text
stringlengths
37
1.41M
class Person: name = '' age = 110 def __init__(self,name,age): self.name = name self.age = age one = Person('zhankeqing',25) f = getattr(one,'name') print(f)
def generator(k): i = 1 while True: yield i ** k i += 1 gen_1 = generator(1) gen_3 = generator(3) print(gen_1) print(gen_3) def get_sum(n): sum_1 , sum_3 = 0,0 for i in range(n): next_1 = next(gen_1) next_3 = next(gen_3) print('next_1={},next_3={}'.format(next_1,next_3)) sum_1 += next_1 sum_3 += nex...
#原始字符串 s1 = "D:\codes\pythonlearn\fenpythonbook\2\2.4" print(s1) s2 = "D:\\codes\\pythonlearn\\fenpythonbook\\2\\2.4" print(s2) raws = r"D:\codes\pythonlearn\fenpythonbook\2\2.4" print(raws) raws2 = r'"Let\'s go",said Charlie' print(raws2) raws3 = r'Good Morning' '\\' print(raws3)
user = "Charli" age = 8 #格式化字符串吕有两个占位符,第三部分也应该提供两个变量 print("%s is a %s years old boy"%(user,age)) ''' num=28 #当中的 6 表示 输出宽度,也可理解 除输出外用0填充 #i/d,转换为带符号的十进制整数 print("num is: %6i" % num) print("num is: %06d" % num) #o 八进制整数 print("num is: %6o" %num) #x/X 转换为带符号的十六进制形式的整数 print("num is: %6x" %num) print("num is: %6X" %nu...
src_list = [12,45,3.4,13,'a',4,56,'crazyit',109.5] my_sum = my_count = 0 for ele in src_list: #如果元素是整数或是浮点数 if isinstance(ele,int) or isinstance(ele,float): print(ele) #累加该元素 my_sum += ele #数值元素的个数加 1 my_count += 1 print("总和:",my_sum) print("平均数",my_sum / my_count)
s = "talk is cheap".title() print(s) ''' sq = ["1","2"] sp='+' print(sp.join(sq)) title="money python" re = title.find('fy') print(re) print('s5'.center(5,'*')) width = int(input('please enter width: ')) #35 price_width=10 item_width=width-price_width #25 header_fmt = '{{:{}}},{{:>{}}}'.format(item_width,pri...
s_max = input("请输入您想计算的阶乘:") mx = int(s_max) result = 1 #使用for in 循环 for num in range(1,mx+1): result *= num print(result)
#关于生成器函数使用 def even_number(max): n=0 while n< max: yield n n += 2 for i in even_number(10): print(i) break
class User: def __init__(self,name="ddds"): self.name=name def walk(self,content="d"): print(self,"正在慢慢地走",content) u= User() User.walk(u) #u.walk("fkit") class Person: '这是一个学习Python定义的一个Person类' hair = "black" def __init__(self,name="Charlie"): #定义实例变量 self.name = name #定义一个s...
lst = [1,2,3,4] it = iter(lst) for x in it: print(x,",")
cars = {"bmw":8.5,"bens":"44a","audi":442} #返回所有的k-v dict_items 对象 ims = cars.items() print(ims) #将dict_items转换成列表 print(list(ims)) print(tuple(ims)) #访问第二个key-v 对 print(list(ims)[1]) #获取字典中所有的key,返回一个dict_keys对象 kys = cars.keys() print(kys) #访问第二个key print(list(kys)[1]) #获取字典中所有的values,返回一个dict_values vals = cars.valu...
''' class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) try: raise MyError('oops') except MyError as e: print('My exception occurred, value:', e.value) ''' with open("myfile.txt") as f: for line in f: print(line) #r...
#统计各元素出现的次数 src_list = [12,45,3.4,12,"fkit",45,3.4,"fkit",45,3.4] statistis = {} for ele in src_list: #如果字典中包含ele代表的key if ele in statistis: statistis[ele] += 1 else: statistis[ele] = 1 for ele,count in statistis.items(): print("%s 出现的次数为:%d" % (ele,count))
class Cat: def __init__(self,name): self.name = name #这个定义本身是为类使用的,且是为类当中有name属性才可用 def walk_func(self): print("{}慢慢地走过一片草地".format(self.name)) d1 = Cat("Garfield") d2 = Cat("Kitty") #为类赋属性 Cat.walk = walk_func Cat.params = "good job"#添加属性 #这挺神奇的,定义后的类实例,还能使用类之后 生成的动态方法与变量 d1.walk() d2.walk() print(d1.param...
a_tuple=("crazyit",20,-1.2) b_tuple=(127,"crazyit","fkit",3.33) #元组相加 sum_tuple=a_tuple+b_tuple print(sum_tuple) print(a_tuple+(2,)) a_list=["crazyit",20,-1.2] b_list=[127,"crazyit","fkit",3.33] sum_list = a_list+b_list print(sum_list) #相等 print('a'==('a'))
class InConstructor: def __init__(self): # 在构造方法里定义一个foo变量(局部变量) foo = 0 # 使用self代表该构造方法正在初始化的对象 # 下面的代码将会把该构造方法正在初始化的对象的foo实例变量设为6 self.foo = 6 #所有使用InConstructor创建的对象的foo实例变量将被设为6 print(InConstructor().foo)
def check_index(key): if not isinstance(key,int):raise TypeError if key < 0: raise IndexError class ArithmeticSequence: def __init__(self,start=0,step=1): self.start = start self.step = step self.changed = {} def __getitem__(self, item): check_index(item) try:r...
import sort_4 def permutate(array: list): result = [] if len(array) == 1: return [array[:]] for i in range(len(array)): val = array.pop(0) perms = permutate(array) for j in perms: j.append(val) result.extend(perms) array.append(val) retur...
def decorator_function(orignal_function): def wrapper_function(*args, **kwargs): print(f'wrapper fn executed before {orignal_function.__name__}') return orignal_function(*args, **kwargs) return wrapper_function @decorator_function def display(): print('display fn running..') ### for class ...
#!/usr/bin/env python3 import re from sympy import isprime DEBUG = True def istrunc(n): for d in range(1, len(str(n))): if not isprime(int(str(n)[d:])) or not isprime(int(str(n)[:d])): return False return True n, f = 11, 1 bag = [] while len(bag) < 11: n += 3-f f = -f # if...
def getFirstNonRepeatingChar(inputString): foundChar = "" for index in range(0, len(inputString)): currentChar = inputString[index] subStringToSearch = inputString[0: index] + inputString[index + 1: len(inputString) - 1] if (not currentChar in subStringToSearch): foundChar ...
# simple dictionary alien = {'color': 'green', 'points': 5} # accessing a value skin = alien['color'] print(f"The alien's color is {skin}") # getting the value with get dog = {'color': 'red'} dog_color = dog.get('color') dog_points = dog.get('points', 0) print(dog_color) print(dog_points) # adding a new key-value ...
bikes = ['trek', 'redline', 'giant'] # get the first element of bikes first = bikes[0] # get the second element of bikes second = bikes[1] # get the last element of bikes last = bikes[-1] # changing an element bikes[0] = 'valerie' bikes[-2] = 'robby' # loop through a list for bike in bikes: print(bike) # or f...
class Polynomial: "Polynomial([]) -> a polynomial" def __init__ (self,poly): self.poly = poly def __add__(self,poly_new): "return self+poly_new" ...
class Polynomial(): def __init__(self,coeffs,powers=[0]): self.c=coeffs[:] self.p=powers[:] if(len(self.p)!=len(self.c)): self.p.pop() for i in range(len(self.c)): self.p.insert(0,i) def __str__(self): ...
class Polynomial(): def __init__(self,s): self.d = { } for i in range(len(s)): if s[i] != 0: self.d[len(s)-i-1] = s[i] def __str__(self): s = "" for i in self.d: if self.d[i] != 0: s = s + "+" + str(self.d[i]) + "x^" + str(i) s = s[1:] return s ...
class Polynomial(): def __init__(self,List = []): self.dict = {} for key in range(len(List)): self.dict[len(List)-key-1] = List[key] def __str__(self): ...
class Polynomial(): pass def __init__(self,poly=[0]): self.poly = poly self.coefficient = self.poly[:] self.power = [0]*len(self.poly) for i in range(0, len(self.poly)): self.power[i] = i self.power = list(reversed(self.power)) self.coefficient = list((self.coefficie...
\ \ \ \ class Polynomial(): def __new__(self): self={0:0} def __init__(self): self={0:0} def __getitem__(self,x): self={0:0} i=0 while(i<len(x)): self[i]=x[len(x)-1-i] i+=1 def __add__(sel...
class Polynomial(): def __init__(self,poly=[0]): self.dict = {} for i in range (0, len(poly)): self.dict[(len(poly)-1-i)] = poly[i] def __getitem__(self, index): if index in (self.dict): return(self.dict[index]) else: return(0) def __setitem__(self, index, value)...
import random for x in range(10): print(random.randint(10,100)) for x in range(10): print(random.randint(100,1000)) for x in range(5): print(random.randint(1000,10000)) for x in range(5): print(random.randint(10**90, 10**100))
class Tree(object): def __init__(self): self.left = None self.right = None self.dim = None self.val = None self.parent = None def build_kd_tree(vecs, dim, d): if(len(vecs) == 0): return None if(len(vecs) == 1): ret = Tree() ret.val = vecs[0] return ret vals = sorted(vecs, key=lambda v: v[dim]) m...
#!/usr/bin/python3 """Create the module""" import json def save_to_json_file(my_obj, filename): """Function that writes an Object to a text file""" with open(filename, 'w', encoding="utf-8") as myfile: return json.dump(my_obj, myfile)
def stolen_lunch(note): result = "" code_dict = { "a": "0", "b": "1", "c": "2", "d": "3", "e": "4", "f": "5", "g": "6", "h": "7", "i": "8", "j": "9", "0": "a", "1": "b", "2": "c", "3": "d", "4": "e", "5": "f", "6": "g", "7": "h", "8": "i", "9": "j", } chars = list(note) ...
def almost_increasing_sequence(array): count = 0 for i in range(len(array) - 1): if (array[i] <= array[i - 1]): count += 1 if ((array[i] <= array[i - 2]) and (array[i + 1] <= array[i - 1])): return False return count <= 1 # Test print(almost_increasing_seq...
import re def digits_prefix(string): numbers = re.findall(r'\d+', string) return max(numbers) # Test print(digits_prefix("123aa1")) # 123
def check_palindrome(inp_str): inp_str = inp_str.lower() rvsd_str = inp_str[::-1] return inp_str == rvsd_str # Test print(check_palindrome("aabaa")) # True print(check_palindrome("abac")) # False print(check_palindrome("a")) # True
def cip(input_string): input_string = input_string.lower() reversed_str = input_string[::-1] return input_string == reversed_str # Test print(cip("AaBaa")) # True print(cip("abac")) # False
def first_not_repeating_char(s): for i in range(len(s)): repeat = False for j in range(len(s)): if (s[i] == s[j]) and i != j: repeat = True if not repeat: return s[i] return "_" # Test print(first_not_repeating_char("abacabad")) # c print(firs...
def launch_sequence(system_names, steps): sequence = {} for i in range(len(system_names)): sequence[system_names[i]] = [] for j in range(len(steps)): sequence[system_names[j]].append(steps[j]) for _, value in sequence.items(): for i in range(len(value) - 1): if val...
""" Checking out the Wikipedia API You're doing so well and having so much fun that we're going to throw one more API at you: the Wikipedia API (documented here). You'll figure out how to find and extract information from the Wikipedia page for Pizza. What gets a bit wild here is that your query will return nested JSON...
class Number(): def __init__(self, number=0): self.value = float(number) def __str__(self): return "Your number = {}".format(self.value) def add(self, number=0): self.value += float(number) def sub(self, number=0): self.value -= float(number) def mult(self, number...
import bisect class TestBisect: def test_bisect_left(self): A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] # -10 is at index 1 assert bisect.bisect_left(A, -10) == 1 # First occurrence of 285 is at index 6 assert bisect.bisect_left(A, 285) == 6 def test_bisect_rig...
""" Given two sorted arrays, A and B, determine their intersection. What elements are common to A and B? SIMPLE SOLUTION: res = set(A).intersection(B) Though the above solution works just fine even with unsorted arrays, but the solution given below is efficient. Ass...
""" PROBLEM: Given a string, find the first occurrence of an uppercase letter and return the index of that letter. If no uppercase letters return None. Algorithm: 1. Iterate through the string and check if the current character is uppercase. If so, return the tuple wi...
def create_db_and_tables(cnx, cursor, tables_sql, db_name): ''' Use database or create it if not exist; create tables :param cnx: pymysql connection object :param cursor: pymysql cursor object :param tables_sql: dict of SQL to create tables :return: None ''' try: cursor.execute...
#!/usr/bin/env python # USAGE: day_11_01.py # Michael Chambers, 2015 file = "day_11_input.txt" movements = open(file,'r').read().rstrip() movements = movements.split(',') def calcDist(x,y): return(abs(x) + abs(y)) posx = 0 posy = 0 maxdist = 0 for m in movements: # print(m) if m == "n": posy += 1 elif m == "s...
#!/usr/bin/env python # USAGE: day_02_01.py # Michael Chambers, 2015 class RecKeyPress(object): def __init__(self, startpos): self.keys = [[1,4,7],[2,5,8],[3,6,9]] self.pos = startpos def move(self, mdir): if mdir == "U": newpos = (self.pos[0], self.pos[1] - 1) elif mdir == "D": newpos = (self.pos[0...
def fibonacci (int1): x = 0 alist = [0,1,2] for i in range(int1+1): if int1<3 : break if i<3: continue else: alist.append(alist[i-1]+alist[i-2]) continue else: print "range is" , len(alist) re...
#!/usr/bin/python3 import math def distance(point1, point2): return math.sqrt((point2[0]-point1[0])**2 + (point2[1]-point1[1])**2 + (point2[2]-point1[2])**2) def sphere_coords(center, radius, point): if distance(center, point) > radius: return [] else: res = [] xDist = math.sqrt(ra...
# Task 7 # Write a password generator in Python. Be creative with how you generate passwords - # strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. # The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time cod...
import random first_names = ['Róisín', 'Ciara', 'Amy', 'Aoife'] last_names = ['Murphy', 'Finan', 'Monahan', 'Whelan'] chosen_name = random.choice(first_names) + ' ' + random.choice(last_names) print(chosen_name)
import turtle turtle.speed(1) turtle.color('aqua', 'yellow') def triangle(side_length): angle=120 for side in range(3): turtle.forward(side_length) turtle.right(angle) triangle(50) turtle.forward(50) triangle(75)
#Prompt: # Write an efficient function that checks whether any permutation ↴ of an input string is a palindrome. ↴ # You can assume the input string only contains lowercase letters. # Examples: # "civic" should return True # "ivicc" should return True # "civil" should return False # "livci"...
def one_away(word1, word2): count = 0 difference = 0 length1 = len(word1) length2 = len(word2) if (abs(length1 - length2) <= 1): while (count < length1) & (count < length2) & (difference < 2): if word1[count] != word2[count]: count += 1 ...
""" Написать функцию, которая будет проверять счастливый билетик или нет. Билет счастливый, если сумма одной половины цифр равняется сумме второй. """ def is_lucky(ticket_num): pass assert is_lucky(1230) is True assert is_lucky(239017) is False assert is_lucky(134008) is True assert is_lucky(15) is Fal...
import numpy as np #NumPy incorporated for typical sin or cosines def f(x): #Define the Function return (np.cos(x)) def gc(a, b, n): #Define the Rule quadrature = 0 #Set the loop for sub-intervals for i in range (1, n+1): ...
import re def statistics_upper_words(text): upper_count = 0 for token in text.split(): if re.search(r'[A-Z]', token): upper_count += 1 return upper_count def statistics_unique_words(text): words_set = set() for token in text.split(): words_set.add(token) return le...
# # @lc app=leetcode.cn id=206 lang=python3 # # [206] 反转链表 # # https://leetcode-cn.com/problems/reverse-linked-list/description/ # # algorithms # Easy (57.57%) # Total Accepted: 35.2K # Total Submissions: 60.6K # Testcase Example: '[1,2,3,4,5]' # # 反转一个单链表。 # # 示例: # # 输入: 1->2->3->4->5->NULL # 输出: 5->4->3->2->1->N...
# # @lc app=leetcode.cn id=114 lang=python3 # # [114] 二叉树展开为链表 # # https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/description/ # # algorithms # Medium (60.73%) # Likes: 108 # Dislikes: 0 # Total Accepted: 6.8K # Total Submissions: 11.2K # Testcase Example: '[1,2,5,3,4,null,6]' # # 给定一个二叉树,原地...
# # @lc app=leetcode.cn id=187 lang=python3 # # [187] 重复的DNA序列 # # https://leetcode-cn.com/problems/repeated-dna-sequences/description/ # # algorithms # Medium (42.75%) # Likes: 30 # Dislikes: 0 # Total Accepted: 3.7K # Total Submissions: 8.7K # Testcase Example: '"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"' # # 所有 DNA 由...
# # @lc app=leetcode.cn id=33 lang=python3 # # [33] 搜索旋转排序数组 # # https://leetcode-cn.com/problems/search-in-rotated-sorted-array/description/ # # algorithms # Medium (36.04%) # Total Accepted: 18.3K # Total Submissions: 50.8K # Testcase Example: '[4,5,6,7,0,1,2]\n0' # # 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 # # ( 例如,数组 [0,1,...
# # @lc app=leetcode.cn id=475 lang=python3 # # [475] 供暖器 # # https://leetcode-cn.com/problems/heaters/description/ # # algorithms # Easy (26.72%) # Total Accepted: 1.9K # Total Submissions: 7.1K # Testcase Example: '[1,2,3]\n[2]' # # 冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。 # # 现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半...
# # @lc app=leetcode.cn id=105 lang=python3 # # [105] 从前序与中序遍历序列构造二叉树 # # https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ # # algorithms # Medium (57.84%) # Likes: 158 # Dislikes: 0 # Total Accepted: 12.8K # Total Submissions: 22.1K # Testcase Example: '[3,...
# # @lc app=leetcode.cn id=147 lang=python3 # # [147] 对链表进行插入排序 # # https://leetcode-cn.com/problems/insertion-sort-list/description/ # # algorithms # Medium (58.06%) # Likes: 63 # Dislikes: 0 # Total Accepted: 7.5K # Total Submissions: 12.8K # Testcase Example: '[4,2,1,3]' # # 对链表进行插入排序。 # # # 插入排序的动画演示如上。从第一个元...
# # @lc app=leetcode.cn id=129 lang=python3 # # [129] 求根到叶子节点数字之和 # # https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/description/ # # algorithms # Medium (56.98%) # Likes: 60 # Dislikes: 0 # Total Accepted: 5.9K # Total Submissions: 10.4K # Testcase Example: '[1,2,3]' # # 给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每...
# # @lc app=leetcode.cn id=92 lang=python3 # # [92] 反转链表 II # # https://leetcode-cn.com/problems/reverse-linked-list-ii/description/ # # algorithms # Medium (42.49%) # Likes: 137 # Dislikes: 0 # Total Accepted: 10.4K # Total Submissions: 23.8K # Testcase Example: '[1,2,3,4,5]\n2\n4' # # 反转从位置 m 到 n 的链表。请使用一趟扫描完成...
# # @lc app=leetcode.cn id=387 lang=python3 # # [387] 字符串中的第一个唯一字符 # # https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/ # # algorithms # Easy (35.49%) # Total Accepted: 21.3K # Total Submissions: 59.4K # Testcase Example: '"leetcode"' # # 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 #...
# # @lc app=leetcode.cn id=204 lang=python3 # # [204] 计数质数 # # https://leetcode-cn.com/problems/count-primes/description/ # # algorithms # Easy (25.80%) # Total Accepted: 12.4K # Total Submissions: 47.4K # Testcase Example: '10' # # 统计所有小于非负整数 n 的质数的数量。 # # 示例: # # 输入: 10 # 输出: 4 # 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5...
class Node: def __init__(self, name): self.name = name self.children = [] def add_child(self, node): self.children.append(node) def build_orbit(node, object_dictionary): if node.name not in object_dictionary.keys(): return node for child in object_dictionary[node.name...
#!/usr/bin/python #-*-coding:utf-8-*- '''@Date:18-10-13''' '''@Time:下午10:01''' '''@author: Duncan''' money_dic = {'美元':7,'日元':0.06,'香港元':0.88,'欧元':8,'瑞士法郎':7,'加元':5.31,'新加坡元':5.02,'丹麦克朗':1.07,"人民币元":1} # 数据预处理,将币种统一 def convert(x): if x in money_dic.keys(): return money_dic[x] else: return x ...
# FileName : Chapter8_5.py ''' 类中封装实例的私有数据: python中没有访问控制,所以可以通过一定的属性、方法命名规则来达到这个目的: '_name'、'__name'和'__name__'的区别 ''' if __name__ == '__main__': class A: def __init__(self): self.value = 'value' self._value = '_value' self.__value = '__value' self.__value__ = '__value__' def method(self): print...
# FileName : Chapter3_8.py ''' 分数操作: 通过fractions模块定义分数 ''' if __name__ == '__main__': from fractions import Fraction a = Fraction(5, 4) b = Fraction(7, 16) c = a * b print(a + b) print(a * b) print(c.numerator) print(c.denominator) print(float(c)) print(c.limit_denominator(8)) x = 3.75 print(Fraction(*x.as...
# FileName : Chapter2_5.py ''' 字符串搜索、替换(大小写敏感): 简单替换:str.replace(ori, new) 负责替换:re.sub(ori, new), re.subn(ori, new),可以指定替换模式或者通过回调函数指定替换方式 ''' import re if __name__ == '__main__': text = 'yeah, but no, but yeah, but no, but yeah' print(text.replace('yeah', 'yep')) text = 'Today is 11/27/2012. PyCon starts 3/13/201...
""" Written by Nicolette Lewis at University of Washington for CESG 505: Engineering Computing Date: October 15, 2019 Homework 2 Problem 1 - baseconverter.py Program Description: basecheck(base,inval,pr=0): Checks to see if the input string is a valid expression of an integer in the provided base ...
""" Calculates and storyes x,y coordinates for an item that bounces up and down based on sinusiodal curve. It does not hold the graphical item to be animated. """ """ Begun 5 April by Jason Cisarano. Included complete setBounce, getCoord, and isBouncing functions. """ from math import sin, pi import pygame ...
""" SongChooserMenu displays a list of songs appropriate for the player's current status in the game and allows her to choose a song to play. It takes a GameInfo item as input and returns a song file. this class is usable with both freeplay and challenge mode levels. """ """ 6 April -- Begun by Jas...
# https://github.com/EricCharnesky/CIS2001-Winter2021/blob/f7f628db35c8af29024460713d8e06c3dd5b0be9/Lab3/main.py class Queue: DEFAULT_CAPACITY = 10 def __init__(self, initial_size = DEFAULT_CAPACITY): self._data = [None] * initial_size self._front = 0 self._back = 0 self._numbe...
class DoublyLinkedList: class Position: def __init__(self, container, node): self._container = container self._node = node def data(self): return self._node.data def __eq__(self, other): return type(other) is type(self) and other._node is ...
# Write the Python code that takes two integer values and returns the first value raised to the power of the second value. number = int(input()) power = int(input()) squared = lambda number, power: number**power print(squared(number, power))
# days = int(input("How many days:")) # years = days // 365 # weeks = (days % 365) // 7 # days = days - ((years * 365) + (weeks * 7)) # print("Years:", years) # print("Weeks:", weeks) # print("Days:", days) user_input = input() number = int(user_input) binary = bin(number) print(binary)
# JSON = JavaScript Object Notation # json.dumps() method is used for JSON encoding, ex: converting dictionaries to JSON objects import json sample = { 'name': 'Bert Bertie', 'age': 24 } sample_json = json.dumps(sample) print(sample_json) print(type(sample_json)) # the output type is a str object # If you wa...
import random def random_number_generator(l): output = [] for i in range(l): output.append(random.randint(1, 5)) return output print(random_number_generator(1))
import csv output = [] # creating csv file with names and hours worked columns with open('input.csv', 'r') as f: mock_data_reader = csv.reader(f) output_data = [] line_count = 1 for row in mock_data_reader: if line_count != 1: # iterates through the file and multiplies the int(hours worked) by ...
# creating a file f = open('myfile.txt', 'w') # writing something to the new file we just created print(f.write('Hello, World\n')) print(f.write('Hello, world again')) # closing the file f.close() # if we want to add need to re-open (this is an append version) f = open('myfile.txt', 'a') f.write('More content') f.cl...
height = float(input("What is your height in meters?: ")) weight = int(input("What is your weight in Kg?: ")) bmi = weight / (height * height) if bmi < 30: if bmi >= 25: print("Overweight") if bmi >= 18.5: print("Normal") if bmi < 18.5: print("Underweight") else: print("Obesity"...
numbers = [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10] # 'i' is the singular item in the 'numbers' list for num in numbers: square = num * num print(num, "squared is ", square)
## union() a = {1,2,3,4,5,6} b = {1,2,3,7,8,9,10} print(a.union(b)) ## another syntax for union is: print(a | b) ## intersection of sets is what they have in common a = {1,2,3,4,5,6} b = {1,2,3,7,8,9,10} print(a.intersection(b)) ## other syntax example: print(a & b) ## difference, self explanatory a = {1,2,3,4,5,6} ...
import os import csv import time import units def rule_god(cell: bool, neighbors: int) -> bool: """ godmode """ return True """ cell: cell state; True or False neighbors: number of alive neighbor cells, 0<=int<=9 """ def rule_underpopulation(cell: bool, neighbors: int) -> bool: """ Any li...
## 기본 출력을 위한 print 함수 import sys print(1) print('hello', 'world') # sep 파라미터 x = 0.2 s = "hello" print(x) print(s) # 기본적으로 ',' 로 구분이 되면 separator가 ' '로 동작한다 print(x, s, sep=' ') print(x, s) # 기본적인 print() 함수 호출 print('abc', 'des', sep=' ', end='\n') # file 파라미터를 지정 print('Hello World', file=sys.stdout) print('Erro...
class lesson: def inputgrades(self, m, f, p): self.grades["midterm"]=m self.grades["final"]=f self.grades["project"]=p def lettergrade(self): a = ((self.grades["midterm"] * self.percent["midterm"]) + (self.grades["final"] * self.percent["final"]) + (self.grades["project"] * self...
# Python program to print the file extension in a given file name #Ex: Hello.java should output java file_name = input('Please enter a file name: ') print(str(file_name.split('.')[-1]))
""" stringjumble.py Author: Jackson Lake Credit: https://www.youtube.com/watch?v=u1jdar3WADY https://www.youtube.com/watch?v=OFSELeMx2nE Assignment: The purpose of this challenge is to gain proficiency with manipulating lists. Write and submit a Python program that accepts a string from the user and prints it back...
a=eval(input('a=')) b=eval(input('b=')) eps=eval(input('eps=')) x=a y=b while abs(x-y)>=eps: z=(x+y)/2 x=y y=z print('Limita este:',z)
x=0 prog=[] while True: x=int(input('x=')) if x>-1: prog.append(x) else: break r=prog[1]-prog[0] este_prog=True for i in range(len(prog)-1, 1, -1): if prog[i]-prog[i-1]!=r: este_prog=False print('Sirul nu este o progresie aritmetica') break if este_prog==True: prin...
from math import sqrt def radical(a, eps): x = a y = 0.5*(x+a/x) while abs(x-y) >= eps: x = y y = 0.5*(x+a/x) return y while True: a=eval(input()) if a>0: break eps=eval(input('eps=')) print('Radicalul aproximativ=', radical(a,eps)) print('Rezultatul cu functia sqrt este...
p=int(input("p=")) q=int(input("q=")) d=p i=q r=1 while r!=0: r=d%i d=i i=r print(p,"/",q," ",p//d,"/",q/d)
"""Description Write a computer program to implement SVM method. (i)preprocessthe data instances:if data instances have categorical features, then call the subroutine convert(X). (ii) given the training data instances, your program should be able to compute the w, b, alpha, margin. (iii) when a new data instance is pr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 8 09:46:56 2018 @author: denisvrdoljak """ import random class Card: possiblesuits = ('Spade', 'Heart', 'Diamond', 'Club') suitsymbols = {text: symbol for text, symbol in zip(('Spade', 'Heart', 'Diamond', 'Club'), ['\u2660', '\u2665', '\...
import numpy as np import math as m import pytest class Point: """A point. Inputs: Point = list of points ex: Point((0,0,0)) Methods: add = sum of point and vector radd = sum of vector and point sub = subtraction of point from point ...