blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7fb7aa6324e74179d86498a8e575280621df28ca
gwuah/ds-algorithms
/leetcode/search-matrix.py
494
4.03125
4
def search_matrix(matrix, target): for row in matrix: last_element = row[-1] if last_element > target: for element in row: if element == target: return True elif last_element == target: return True return False matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]] matrix_1 = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]] print(search_matrix(matrix, 3)) print(search_matrix(matrix_1, 50))
e2d8f5e804f783e56d281f6c3cb6b6346d18e924
shchrbkv/python-oop
/task5/terminal.py
2,008
3.65625
4
import os import threading from pizza import Pepperoni, BBQ, Seafood from order import Order from handout import Handout class Terminal: menu = [Pepperoni(), BBQ(), Seafood()] def greet(self): os.system("clear") print("{:-^40}".format("Welcome to Pizza Time")) def start(self, code): self.__code = code self.greet() print("{:^40}".format("Is it a takeout? y/n")) current_order = Order(self.__code, True) if input() == ("y" or "Y") else Order(self.__code) while True: self.greet() print(current_order) print("\nChoose your pizza:") for p in range(len(self.menu)): position = self.menu[p] print("{} - ${:.2f} - {}".format(p+1, position.cost, position.title)) print("Enter the id of pizza, or 0 to finish") chosen = int(input()) if chosen in range(len(self.menu)+1): if chosen == 0: break chosen_pizza = self.menu[chosen - 1] try: current_order.add(chosen_pizza) except Exception as e: print(e) print("Press enter to continue to checkout...") input() break baking = threading.Thread(target=chosen_pizza.bake) packing = threading.Thread(target=chosen_pizza.pack, args=(current_order.takeout,)) baking.start() packing.start() else: continue baking.join() packing.join() print("\n1 - Choose another\n0 - Finish the order") if input() == "1": continue else: break self.greet() print(current_order) print("Proceed to checkout...") print("You can pick up your order " + Handout.location_of_pickup) self.__code += 1
ac88240149a6377fedacfc3a157973c287512196
etasycandy/Python
/Workshop5/Project_page165_166/Project_05_page166.py
2,112
4.28125
4
""" Author: Tran Dinh Hoang Date: 16/08/2021 Program: Project_05_page166.py Problem: 5. In Chapter 4, we developed an algorithm for converting from binary to decimal. You can generalize this algorithm to work for a representation in any base. Instead of using a power of 2, this time you use a power of the base. Also, you use digits greater than 9, such as A . . . F, when they occur. Define a function named repToDecimal that expects two arguments, a string, and an integer. The second argument should be the base. For example, repToDecimal("10", 8) returns 8, whereas repToDecimal("10", 16) returns 16. The function should use a lookup table to find the value of any digit. Make sure that this table (it is actually a dictionary) is initialized before the function is defined. For its keys, use the 10 decimal digits (all strings) and the letters A . . . F (all uppercase). The value stored with each key should be the integer that the digit represents. (The letter 'A' associates with the integer value 10, and so on.) The main loop of the function should convert each digit to uppercase, look up its value in the table, and use this value in the computation. Include a main function that tests the conversion function with numbers in several bases. * * * * * ============================================================================================= * * * * * Solution: Display result 10 8 2 16 """ repTable = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15 } def repToDecimal(rep, base): decimal = 0 exp = len(rep) - 1 for digit in rep: decimal += repTable[digit] * base ** exp exp -= 1 return decimal def main(): print(repToDecimal('10', 10)) print(repToDecimal('10', 8)) print(repToDecimal('10', 2)) print(repToDecimal('10', 16)) if __name__ == '__main__': main()
fda54f609aed5dce2c91cdd22eec7cc9868dc9ac
sairajbhise98/Python-Study
/Data Structures in Python/Heap/heap.py
1,041
3.796875
4
''' ------------------------------------------------------------- Code By : Sairaj Bhise Topic : Data Structures and Algorithms (Heap Data Structure) ------------------------------------------------------------- ''' def heapify(arr,n,i) : largest = i l = 2*i + 1 r = 2*i + 2 if l<n and arr[i] < arr[l]: largest = l if r<n and arr[largest] < arr[r]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr,n,largest) def insert(array, newNum): size = len(array) if size == 0: array.append(newNum) else: array.append(newNum) for i in range((size//2)-1,-1,-1): heapify(array,size,i) def deleteNode(array, num): size = len(array) i = 0 for i in range(0,size): if num == array[i]: break array[i], array[size-1] = array[size-1], array[i] array.remove(num) for i in range((size//2)-1,-1,-1): heapify(array,len(array),i) # Driver Code arr = [] insert(arr, 1) insert(arr, 2) insert(arr, 3) insert(arr, 4) insert(arr, 5) insert(arr, 6) print(arr) ''' deleteNode(arr, 6) '''
6a4a679906d5b148b3c94cffca4fec8abdc2f234
Toshiyana/atcoder_study
/ABC/B_problems/150.py
353
3.578125
4
# 自分の回答(なぜかRE) # N = int(input()) # S = input() # count = 0 # for i in range(N): # if S[i] == 'A': # if S[i+1] == 'B': # if S[i+2] == 'C': # count += 1 # print(count) # 他人の模範回答 N = int(input()) S = input() t = 'ABC' count = 0 for i in range(N-2): if S[i:i+3] == t: count += 1 print(count)
149aed7c5a6ccca131683aeecb70beb33c2c1638
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_135/1270.py
1,600
3.53125
4
def magic(case, first_ans, second_ans, first_square, second_square): first_line = first_square[first_ans - 1] second_line = second_square[second_ans - 1] ans = -1 counter = 0 for number in first_line: if number in second_line: counter += 1 ans = number if counter == 1: print_result(case, 1, ans) elif counter > 1: print_result(case, 2, 0) elif counter == 0: print_result(case, 3, 0) def print_result(case, result, line_num): if result == 1: print ("Case #" + str(case) + ": " + str(line_num)) elif result == 2: print ("Case #" + str(case) + ": " + "Bad magician!") elif result == 3: print ("Case #" + str(case) + ": " + "Volunteer cheated!") file_name = "A-small-attempt1.in" with open(file_name) as f: case_num = int(f.readline()) for i in range(1, case_num + 1): first_ans = int(f.readline()) first_square = [] first_square.append(f.readline().strip().split(' ')) first_square.append(f.readline().strip().split(' ')) first_square.append(f.readline().strip().split(' ')) first_square.append(f.readline().strip().split(' ')) second_ans = int(f.readline()) second_square = [] second_square.append(f.readline().strip().split(' ')) second_square.append(f.readline().strip().split(' ')) second_square.append(f.readline().strip().split(' ')) second_square.append(f.readline().strip().split(' ')) magic(i, first_ans, second_ans, first_square, second_square)
8de6b29ba2a3c5462410cbb4bcb48cd9ea7bbfd2
uday4a9/python
/ds/sll_lib.py
2,316
4
4
from functools import wraps import sys def read_value(): a = input("Enter a value to insert in list: ") return a class Node: _value = 123123 __v2 = 321 def __init__(self, val): self._data = val self._next = None self.__v3 = 123 def get_value(self): return self._data def get_next(self): return self._next def set_next(self, new): self._next = new class LinkedList: """ All methods which are going to exposed to user under this class, should use the prefix as `sll_`. """ def __init__(self, front=None): self.front = front def sll_insert_at_begin(self): node = Node(read_value()) node.set_next(self.front) self.front = node self.sll_display() def sll_insert_at_end(self): node = Node(read_value()) if not self.front: self.front = node else: temp = self.front while temp.get_next(): temp = temp.get_next() temp.set_next(node) self.sll_display() def sll_insert_at_end_rec(self): pass def empty_check(self): @wraps def inner(*args, **kwargs): print("inner", self, args, kwargs) return inner def sll_display(self): if not self.front: print("List empty, Nothing to display") return temp = self.front while temp: print(temp.get_value(), end="->") temp = temp.get_next() print("NULL") def sll_delete_at_begin(self): if not self.front: print("List empty, Nothing to delete") return node = self.front self.front = node.get_next() node.set_next(None) del node self.sll_display() def sll_delete_at_end(self): if not self.front: print("List empty, Nothing to delete") return prv = self.front nxt = prv.get_next() if not nxt: del self.front self.front=None self.sll_display() return while nxt and nxt.get_next(): prv = nxt nxt = nxt.get_next() prv.set_next(None) del nxt self.sll_display()
de6f68918689e0312ec0c2c7d6665f70e38d0e98
narutoamu/SPOJSolutions
/BEENUMS.py
177
3.71875
4
import math while(1): x=input() if x == - 1: break x=(4*x-1)/3 if int(math.sqrt(x))**2 == x: print "Y" else: print "N"
39e9261d28102758dc4a4e8249c3a44b3aecfb14
class-yoo/practice02
/practice02.py
2,621
3.734375
4
# 문제2. 다음과 같은 텍스트에서 모든 태그를 제외한 텍스트만 출력하세요. # s = """ # <html> # <body style='background-color:#ffff'> # <h4>Click</h4> # <a href='http://www.python.org'>Here</a> # <p> # To connect to the most powerful tools in the world. # </p> # </body> # </html>""" # # exceptTag =''; # tag=''; # for i in range(0, len(s)): # if s[i] == '<': # exceptTag +=" " # tag = '<' # elif s[i] =='>': # exceptTag +=" " # tag ='' # elif tag == '<': # exceptTag +=" " # else: # exceptTag += s[i] # print(exceptTag,end='') # 문제3. 1)다음 문자열을 모든 소문자를 대문자로 변환하고, # 문자 ',', '.','\n'를 없앤 후에 중복 없이 각 단어를 순서대로 출력하세요. # s = """We encourage everyone to contribute to Python. If you still have questions after reviewing the material # in this guide, then the Python Mentors group is available to help guide new contributors through the process.""" # s = s.replace(',','').replace('.','').replace('\n','') # s = s.upper() # list = s.split(' '); # print(list) # dic = dict() # for voca in list: # if dic.__contains__(voca): # dic[voca] = dic.get(voca)+1 # else: # dic[voca] = 1 # # keyList = dic.keys() # keyList = sorted(keyList) # for key in keyList: # print(key+':'+str(dic.get(key))) # 문제4 반복문을 이용하여 369게임에서 박수를 쳐야 하는 경우의 수를 순서대로 화면에 # 출력해보세요. 1부터 99까지만 실행하세요. # number = int(input('')) # temp = number # clap = '' # while number >= 1: # if (number % 10) % 3 == 0: # clap +='짝' # number /= 10 # number = int(number) # print(temp, clap) # 문제5. 함수 sum 을 만드세요. 이 함수는 임의의 개수의 인수를 받아서 그 합을 계산합니다. # 문제6 숨겨진 카드의 수를 맞추는 게임입니다. # 1-100까지의 임의의 수를 가진 카드를 한 장 숨기고 이 카드의 수를 맞추는 게임입니다. # 아래의 화면과 같이 카드 속의 수가 57인 경우를 보면 수를 맞추는 사람이 40이라고 입력하면 # "더 높게", 다시 75이라고 입력하면 "더 낮게" 라는 식으로 범위를 좁혀가며 수를 맞추고 있습니다. # 게임을 반복하기 위해 y/n이라고 묻고 n인 경우 종료됩니다. # min , max = 1, 100 # while True : # n= random.randrange(max) +min # print(n) # # if n == int(input('수 입력: ')): # break
3a419d704acc510f0b8f967cc19d268596c1527a
airtoxin/mymodule
/stablesort.py
2,706
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from numpy import array def stable_sort_by_column(arr, column_index, element_index=None): u""" stable matrix sorting using column key. input: arr: numpy 2D or (3D) array. If arr is 3D, we assume most inner array as stable element like tuple. column_index: column index of key of stable sort. element_index: If input arr is 3D, sorting key is lambda element: element[element_index] """ arr = array(arr) return array(sorted(arr, key=lambda x: x[column_index][element_index])) def stable_sort_by_row(arr, row_index, element_index=None): u""" stable matrix sorting using row key. imput: arr: numpy 2D or (3D) array. If arr is 3D, we assume most inner array as stable element like tuple. row_index: row index of key of stable sort. element_index: If input arr is 3D, sorting key is lambda element: element[element_index] """ arr = array(arr) return array(sorted(arr.T, key=lambda x: x[row_index][element_index])).T if __name__ == "__main__": a = array([[4, 1, 4, 2, 1, 3], [7, 3, 2, 0, 5, 0], [2, 3, 6, 0, 6, 7], [6, 4, 5, 7, 5, 1], [3, 1, 6, 6, 2, 4], [6, 0, 5, 5, 5, 1]]) b = array([[("a", 1), ("b", 6), ("c", 5), ("p", 0), ("u", 0)], [("i", 3), ("d", 4), ("q", 2), ("e", 7), ("y", 9)], [("s", 2), ("x", 0), ("z", 5), ("b", 6), ("m", 8)], [("r", 6), ("g", 1), ("k", 2), ("f", 4), ("m", 0)], [("h", 0), ("n", 2), ("l", 8), ("e", 5), ("c", 3)]]) print "input array" print a print "" print "stable sort by last column" print "stable_sort_by_column(a, -1)" print stable_sort_by_column(a, -1) print "" print "stable sort by last row" print "stable_sort_by_row(a, -1)" print stable_sort_by_row(a, -1) print "\n" print "input array (3D)" print """[[("a", 1), ("b", 6), ("c", 5), ("p", 0), ("u", 0)], [("i", 3), ("d", 4), ("q", 2), ("e", 7), ("y", 9)], [("s", 2), ("x", 0), ("z", 5), ("b", 6), ("m", 8)], [("r", 6), ("g", 1), ("k", 2), ("f", 4), ("m", 0)], [("h", 0), ("n", 2), ("l", 8), ("e", 5), ("c", 3)]]""" print "" print "3D array stable sort by last column" print "stable_sort_by_column(b, -1, key=lambda x: x[1])" print stable_sort_by_column(b, -1, element_index=1) print "" print "3D array stable sort by last row" print "stable_sort_by_row(b, -1, element_index=1)" print stable_sort_by_row(b, -1, element_index=1) print ""
c6c214a1d26fcdec2f19720aeb4f5f08c774f503
skyeaaron/ICU
/SampleInputs/gzip_file.py
540
3.9375
4
""" Gzip a file. For example, python gzip.file input_file.txt will gzip input_file.txt to input_file.txt.gz """ import gzip, sys def convert_to_gzip(input_filename, output_filename, input_encoding = 'utf-8', output_encoding = 'utf-8'): """ given an input text file gzip it """ with open(input_filename, 'rt', encoding = input_encoding) as f_in, gzip.open(output_filename, 'wt', encoding = output_encoding) as f_out: f_out.writelines(f_in) return None convert_to_gzip(sys.argv[1], sys.argv[1] + '.gz')
2b5ec0059f23938457f4ff2f1a78c21d487e7e29
SachinPitale/Python3
/Python-2021/17.Functions/4.function-with-simple-argument.py
700
3.984375
4
""" def get_result(num): #Parameter and positional argument result=num+10 print(f"final result of num is {result}") return None def main(): num=eval(input("Enter your number: ")) get_result(num) #Argument return None main() """ def get_add(p,q): result=p+q print(f"The addition of {p} and {q} is : {result}") return None def get_sub(m,n): result=m-n print(f"The sub of {m} and {n} is : {result}") return None def main(): a=eval(input("Enter your first number: ")) b=eval(input("Enter your second number: ")) get_add(a,b) get_sub(b,a) get_sub(109,16) x=50 get_add(x,b) get_sub(b,x) return None main()
4dbd7d3735c71513e4344ffaf4fa0cebb320ef35
github641/python-journey
/IpReverse.py
712
3.65625
4
def tranFromIPToInt(strIP): lst = strIP.split(".") if len(lst) != 4: return "error ip" return int(lst[0]) * (256 ** 3) + int(lst[1]) * (256 ** 2) +\ int(lst[2]) * 256 + int(lst[3]) def tranFromIntToIP(strInt): ip1 = 0 ip2 = 0 ip3 = 0 ip4 = 0 ip1 = int(strInt) / (256 ** 3) ip2 = (int(strInt) % (256 ** 3)) / (256 ** 2) ip3 = (int(strInt) % (256 ** 2)) / 256 ip4 = int(strInt) % 256 return str(ip1) + "." + str(ip2) + "." + str(ip3) + "." + str(ip4) c=raw_input( "input 'b' for IP-->INT or 'a' for INT-->IP :") if c=='a': x=raw_input('A int: ') print tranFromIntToIP(x) elif c=='b': y=raw_input('A IP: ') print tranFromIPToInt(y)
f740f11765f2123c78e0c69ed66b27083f69b374
lt910702lt/python
/day05/02 作业讲解.py
6,426
3.640625
4
#######第一题:写代码,有如下列表,按照要求实现每一个功能 #li = ["alex", "WuSir", "ritian", "barry", "wenzhou"] # # 1)、计算列表的长度并输出 # print(len(li)) # # 2)、列表中追加元素“seven”,并输出添加后的列表 # li.append("seven") # print(li) # # 3)、请在列表的第一个位置插入元素“Tony”,并输出添加后的列表 # li.insert(0, "Tony") # print(li) # # 4)、请修改列表的第2个位置的元素为“Kelly”,并输出修改后的列表 # li[1] = li[1].replace("alex", "Kelly") # print(li) # # 5)、请将列表l2 = [1, "a", 3, 4, "heart"]的每一个元素添加到列表li中,一行代码实现,不允许循环添加 # l2 = [1, "a", 3, 4, "heart"] # li.extend(l2) # print(li) # # 6)、请将字符串s = "qwert" 的每个元素添加到列表li中,一行代码实现,不允许循环添加 # s = "qwert" # li.extend(s) # print(li) # # 7)、请删除列表中的元素“alex”,并输出删除后的列表 # li.remove("alex") # print(li) # # 8)、请删除列表中的第二个元素,并输出删除的元素和删除元素后的列表 # e = li.pop(1) # print(e) # print(li) # # 9)、请删除列表中的第2至第4个元素,并输出删除后的列表 # del li[1:4] # print(li) # # 10)、请将列表所有的元素反转,并输出反转后的列表 # li.reverse() # print(li) # # 11)、请计算出“alex”元素在列表中出现的次数,并输出该次数 # print(li.count("alex")) # ######第二题:写代码,有如下列表,利用切片实现每一个功能 # li = [1, 3, 2, "a", 4, "b", 5, "c"] # # 1)、通过对li列表切片形成新的列表l1,l1 = [1, 3, 2] # print(li[:3]) # # 2)、通过对li列表切片形成新的列表l2,l2 = ["a", 4,"b"] # print(li[3:6]) # # 3)、通过对li列表切片形成新的列表l3,l3 = [1, 2, 4, 5] # print(li[::2]) # # 4)、通过对li列表切片形成新的列表l4,l4 = [3, 'a', 'b'] # print(li[1:6:2]) # # 5)、通过对li列表切片形成新的列表l5,l5 = ['c'] # print(li[-1:-2:-1]) # # 6)、通过对li列表切片形成新的列表l6,l6 = ["b", "a", 3] # print(li[-3::-2]) # ######第三题:有如下列表,按照要求实现每一个功能 # lis = [2, 3, "k", ["qwe", 20, ["k1", ["tt", 3, "1"]], 89], "ab", "adv"] # # 1)、将列表中的"tt"变成大写(用两种方式) # lis[3][2][1][0] = lis[3][2][1][0].upper() # lis[3][2][1][0] = lis[3][2][1][0].replace('t', 'T') # lis[3][2][1][0] = "TT" # # # 2)、将列表中的数字3变成字符串"100"(用两种方式) # lis[3][2][1][1] = "100" # lis[3][2][1][1] = str(lis[3][2][1][1] + 97) # # # 3)、将列表中的字符串"1"变成数字101(用两种方式) # lis[3][2][1][2] = 101 # lis[3][2][1][2] = int(lis[3][2][1][2] + "01") # ######第四题:请用代码实现 # li = ["alex", "eric", "rain"] # #利用下划线将列表的每一个元素拼接成字符串"alex_eric_rain" # s = "" # for el in li: # s = s + el + "_" # print(s[:len(s)-1]) # ######第五题:利用for循环和range打印出下面列表的索引 *** # li = ["alex", "WuSir", "ritian", "barry", "wenzhou", ""] # for i in range(len(li)): # print(i) ######第六题:利用for循环和range找出100以内所有的偶数,并将这些偶数插入到一个新的列表中 # li = [] # for n in range(100): # if n % 2 == 0: # li.append(n) # print(li) ######第七题:利用for循环和range找出50以内能被3整除的数,并将这些偶数插入到一个新的列表中。 # li = [] # for n in range(50): # if n % 3 == 0: # li.append(n) # print(li) # ######第八题:利用for循环和rang从100~1,倒叙打印 # for n in range(100, 0, -1): # print(n) ######第九题:利用for循环和rang从100~10,倒叙将所有的偶数添加到一个新的列表中,然后对列表的元素进行筛选,将能被4整出的数留下 # li = [] # for n in range(100, 9, -1): # if n % 2 == 0: # li.append(n) # new_li = [] # for el in li: # if el % 4 == 0: # new_li.append(el) # print(new_li) # ######第十题:利用for循环和range,将1~30的数字一次添加到一个列表中,并循环这个列表,将能被3整出的数改成*。 # li = [] # for n in range(1, 31): # li.append(n) # new_li = [] # for el in li: # if el % 3 == 0: # new_li.append("*") # else: # new_li.append(el) # print(new_li) ######第十一题:查找列表li中的元素,移除每个元素的空格,并找出以"A"或者"a"开头,并以"c"结尾的所有元素,添加到一个新的列表中,最后循环打印这个列表 # li = ["TaiBai ", "ale xC", "AbC ", "egon", " ri TiAn", "WuSir", " aqc"] # lst = [] # for el in li: # el = el.replace(" ", "") # if (el.startswith("A") or el.startswith("a")) and el.endswith("c"): # lst.append(el) # print(lst) # ######第十二题:开发敏感词语过滤程序,提示用户输入评论内容,如果用户输入的内容中包含特殊字符,则将用户输入的内容中的敏感词汇替换成等长度的*。 # li = ["苍老师", "东京热", "武藤兰", "波多野结衣"] # content = input("请输入评论内容: ") # for el in li: # if el in content: # content = content.replace(el, "*"*len(el)) # print("你输入的内容是:" + content) ######第十三题:有如下列表,循环打印列表的每个元素,遇到列表再循环打印出它里面的元素,并将大写变小写! # li = [1, 3, 4, "alex", [3, 7, 8, "TaiBai"], 5, "RiTiAn"] # for el in li: # if type(el) == list: #判断数据类型 # for ell in el: # if type(ell) == str: # ell = ell.lower() # print(ell) # else: # print(ell) # else: # if type(el) == str: # el = el.lower() # print(el) # else: # print(el) ######第十四题:把班级学生数学考试成绩录入到一个表中,并求平均值。要求:录入的时候带着人名录入,例如:张三_44 # lst = [] # while 1: # stu = input("请输入学生的姓名和成绩(姓名_成绩),录入Q退出:") # if stu.upper() == "Q": # break # lst.append(stu) # #求平均值 # sum = 0 # for el in lst: # li = el.split("_") # sum = sum + int(li[1]) # print(sum/len(lst))
1d15d0e9a49b7ef60ba7910fef96b4add5634aa0
chuzyrepo/pythonstudy
/demo20180604/format.py
1,144
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下: print('hello, %s' % 'world') #%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换, # 有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。 print('hi %s,you have $%d'%('张三',100000)) #格式化整数和浮点数还可以指定是否补0和整数与小数的位数: print('%2d-%02d' % (3, 1))#%2d意为以固定的两位位宽来输出展示内容,不足两位在前面补空格,超过两位,则按实际位数输出 print('%.2f' % 3.1415926) #当字符串里面的%是一个普通字符时,这个时候就需要转义,用%%来表示一个%: print('growth rate: %d %%' % 7) #另一种格式化字符串的方法是使用字符串的format()方法,它会用传入的参数依次替换字符串内的占位符{0}、{1}……,不过这种方式写起来比%要麻烦得多: print('Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125))
97718678a848e93cdf447301c113777621aa473c
polly-rm/python_advanced
/4.Exercise-Comprehensions.py
4,781
3.671875
4
# 1.Word Filter # result = [el for el in input().split() if len(el) % 2 == 0] # for word in result: # print(word) # 2.Words Lengths # result = {word: len(word) for word in input().split(', ')} # final = [f'{key} -> {value}' for key,value in result.items()] # print(', '.join(final)) # 3.Capitals # countires = tuple(input().split(', ')) # capitals = tuple(input().split(', ')) # # pairs = list(zip(countires, capitals)) # result = {el[0]: el[1] for el in list(zip(countires, capitals))} # for key, value in result.items(): # print(f'{key} -> {value}') # 4.Number Class # nums = input().split(', ') # positive = [num for num in nums if int(num) >= 0] # negative = [num for num in nums if int(num) < 0] # even = [num for num in nums if int(num) % 2 == 0] # odd = [num for num in nums if int(num) % 2 == 1] # print(f"Positive: {', '.join(positive)}") # print(f"Negative: {', '.join(negative)}") # print(f"Even: {', '.join(even)}") # print(f"Odd: {', '.join(odd)}") # 5.Diagonals # n = int(input()) # matrix = [] # for _ in range (n): # matrix.append([int(el) for el in input().split(', ')]) # # first_d = [matrix[i][i] for i in range(n)] # second_d = [matrix[i][n - i - 1] for i in range(n)] # print(f"First diagonal: {', '.join([str(x) for x in first_d])}. Sum: {sum(first_d)}") # print(f"Second diagonal: {', '.join([str(x) for x in second_d])}. Sum: {sum(second_d)}") # 6.Matrix of Palindromes # rows, cols = [int(el) for el in input().split()] # alfa = "abcdefghijklmnopqrstuvwxyz" # matrix = [] # for r in range(rows): # matrix.append([['a', 'a', 'a'] for _ in range(cols)]) # # for row_i in range(rows): # i = row_i # for col_i in range(cols): # current_el = matrix[row_i][col_i] # current_el[0] = alfa[row_i] # current_el[-1] = alfa[row_i] # current_el[1] = alfa[i] # i += 1 # # for row in matrix: # for col_i in range(len(row)): # str_el = ''.join(row[col_i]) # row[col_i] = str_el # # print(*row) # 7.Flatten List # elements = [int(n) for el in input().split('|')[::-1] for n in el.split()] # print(*elements) # 8.Heroes Inventory 80/100 # names = [name for name in input().split(', ')] # data = input() # people = {} # while not data == "End": # name, item, price = data.split('-') # if not name in people: # people[name] = {item: int(price)} # else: # if not item in people[name]: # people[name].update({item: int(price)}) # data = input() # # for person, item_data in people.items(): # print(f'{person} -> Items: {len(item_data)}, Cost: {sum(item_data.values())}') # 9.Bunker # categories = {category: {} for category in input().split(', ')} # n = int(input()) # for _ in range(n): # data = input().split(' - ') # category = data[0] # item = data[1] # q_q_data = data[2] # quantity_data, quality_data = q_q_data.split(';') # quantity = int(quantity_data.split(':')[1]) # quality = int(quality_data.split(':')[1]) # if item not in categories[category]: # categories[category].update({item: {'quantity': quantity, 'quality': quality}}) # else: # categories[category][item]['quantity'] += quantity # categories[category][item]['quality'] += quality # # total_items = 0 # total_quality = 0 # for category, items_data in categories.items(): # for item, q_q_data in categories[category].items(): # total_items += q_q_data['quantity'] # total_quality += q_q_data['quality'] # # print(f'Count of items: {total_items}') # average_quality = total_quality / len(categories) # print(f'Average quality: {average_quality:.2f}') # items_per_category = [] # for category, items_data in categories.items(): # for item, q_q_data in categories[category].items(): # items_per_category.append(item) # print(f"{category} -> {', '.join(items_per_category)}") # items_per_category.clear() # 10.Matrix Modification # n = int(input()) # matrix = [] # for _ in range (n): # matrix.append([int(el) for el in input().split()]) # # data = input() # while not data == 'END': # command, row_index, col_index, value = data.split() # row_index = int(row_index) # col_index = int(col_index) # value = int(value) # # if row_index < 0 or row_index > n-1 or col_index < 0 or col_index > n-1: # print('Invalid coordinates') # # else: # if command == 'Add': # matrix[row_index][col_index] += value # elif command == 'Subtract': # matrix[row_index][col_index] -= value # # data = input() # # for row in matrix: # print(*row)
a533edf2f91a854679ccddc5226bf56862c2f727
ljrdemail/AID1810
/PythonBasic/Day08/exec6.py
320
3.703125
4
L = list() def input_number(num): return L.append(num) while True: num = int(input("请输入整数,以负数结束:")) if (num < 0): break else: input_number(num) print("列表为:",L) print("最大值为:", max(L)) print("最小值为:", min(L)) print("和为:", sum(L))
8279936b0d5d63ef1827256932f943eec1c2e84e
garciaha/DE_daily_challenges
/2020-07-08/concert.py
1,360
4.375
4
""" Concert Seats Create a function that determines whether each seat can "see" the front-stage. A number can "see" the front-stage if it is strictly greater than the number before it. Everyone can see the front-stage in the example below: FRONT STAGE ------------ [[1, 2, 3, 2, 1, 1], [2, 4, 4, 3, 2, 2], [5, 5, 5, 5, 4, 4], [6, 6, 7, 6, 5, 5]] # Starting from the left, the 6 > 5 > 2 > 1, so all numbers can see. # 6 > 5 > 4 > 2 - so all numbers can see, etc. Not everyone can see the front-stage in the example below: FRONT STAGE ------------ [[1, 2, 3, 2, 1, 1], [2, 4, 4, 3, 2, 2], [5, 5, 5, 10, 4, 4], [6, 6, 7, 6, 5, 5]] The 10 is directly in front of the 6 and blocking its view. The function should return True if every number can see the front-stage, and False if even a single number cannot. """ def can_see_stage(stage): for row in range(1, len(stage)): for seat in range(len(stage[row])): if stage[row][seat] <= stage[row - 1][seat]: return False return True if __name__ == '__main__': assert can_see_stage([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == True assert can_see_stage([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) == True assert can_see_stage([[2, 0, 0], [1, 1, 1], [2, 2, 2]]) == False assert can_see_stage([[1, 0, 0], [1, 1, 1], [2, 2, 2]]) == False print("All cases passed!")
38e71de37925b3bee6c6a8453ea60f8ca1486c3c
casssax/make_ff
/Scripts/sub_scripts.py
2,656
3.578125
4
import csv import sys def fill_zero_length(fields): for e in range(len(fields)): if fields[e] == 0: fields[e] = 10 return fields def max_length(data): first_flag = 1 fields = [] for get_line in data: line = list(get_line) if first_flag == 1: for i in range(len(line)): fields.append(len(line[i])) first_flag = 0 else: for i in range(len(line)): if fields[i] < len(line[i]): fields[i] = len(line[i]) return fields def make_fixed_field(input_file,out_file,lay_out): print 'This program will convert a delimited file to fixed_field' print 'based on the longest value for each field of the file. ' print '(fields with length of zero will be changed to l0.)' get_delim = raw_input("Enter delimiter(enter 't' for tab): ") delim_dict = { ',':',', '|':'|', 't':'\t', 'T':'\t' } delim_type = delim_dict[get_delim] data = csv.reader(input_file, delimiter=str(delim_type)) #data = [row for row in data] #max_len = [max(len(str(x)) for x in line) for line in zip(*data)] max_len = max_length(data) fields = fill_zero_length(max_len) print 'layout: ', str(fields) lay_out.write(str(fields).replace(" ", "")[1:-1]) total = 0 input_file.seek(0) data = csv.reader(input_file, delimiter=str(delim_type)) for get_line in data: line = list(get_line) total = total + 1 count = 0 num_fields = len(line) new = '' pos = 0 for field in line: try: if len(field) > abs(fields[count]): new = new + field[:abs(fields[count])] #truncataes if field longer than layout (for header records) count = count + 1 else: if fields[count] < 1: new = new + field.rjust(abs(fields[count])) #right justify if all digits else: new = new + field.ljust(fields[count]) count = count + 1 except IndexError: print line out_file.write(new + '\n') print 'total records processed: {}'.format(total) # def strip_suffix(name): #strip suffix to create output file name w/'.csv' # return name[:-4] # file_ext = '.ff' # fname = 'newsupps.txt' # with open(fname, 'r') as input_file, open(strip_suffix(fname) + file_ext, 'w') as out_file: # make_fixed_field(input_file, out_file)
82ecc3e32e7940422238046cd7aa788979c51f9c
KurinchiMalar/DataStructures
/Stacks/Stack.py
1,115
4.125
4
from LinkedLists.ListNode import ListNode class Stack: def __init__(self,head=None): self.head = head self.size = 0 def push(self,data): newnode = ListNode(data) newnode.set_next(self.head) self.head = newnode self.size = self.size + 1 def pop(self): if self.head is None: print "Nothing to pop. Stack is empty!" return -1 toremove = self.head self.head = self.head.get_next() self.size = self.size - 1 return toremove def peek(self): if self.head is None: print "Nothing to peek!. Stack is empty!" return -1 return self.head.get_data() def print_stack(self): current = self.head while current != None: print current.get_data(), current = current.get_next() print ''' stack = Stack() stack.push(1) stack.push(2) stack.push(3) stack.push(4) stack.push(5) stack.push(6) stack.print_stack() stack.pop() stack.print_stack() print stack.size print "top: "+str(stack.peek()) print stack.size '''
1664b4e465dee4c24c2274aa04a494b7d7314d1d
ceteongvanness/100-Days-of-Code-Python
/Day 5 - Beginner - Python Loops/3. Adding Even Numbers/main.py
329
4.125
4
total_height = 0 for height in student_heights: total_height += height print(f"total height = {total_height}") number_of_students = 0 for student in student_heights: number_of_students += 1 print(f"number of students = {number_of_students}") average_height = round(total_height / number_of_students) print(average_height)
1ff053604ad0e3d5508dd993f9c47e5d76e1d380
urazbayevr/Pythonchik
/btcmp_self_study/File_IO/CSV_reader.py
1,089
3.90625
4
# THIS DOES READ THE FILE BUT IT DOESN'T PARSE IT! # BAD!!!!!! #with open("fighters.csv") as file: # data = file.read() # Using reader # from csv import reader # with open("fighters.csv") as file: # csv_reader = reader(file) # next(csv_reader) #To skip the headers # for fighter in csv_reader: # # Each row is a list # # Use index to access data # print(f"{fighter[0]} is from {fighter[1]}") # Example where data is cast into a list # from csv import reader # with open("fighters.csv") as file: # csv_reader = reader(file) # data = list(csv_reader) # print(data) # with open("fighters.csv",'w') as file: # csv = file.write("Name,Country,Height (in cm)\nRyu,Japan,175\nKen,USA,175\nChun-Li,China,165\nGuile,USA,182\nE. Honda,Japan,185\nDhalsim,India,176\nBlanka,Brazil,192\nZangief,Russia,214\n") # Reading/Parsing CSV Using a DictReader: from csv import DictReader with open("fighters.csv") as file: csv_reader = DictReader(file) for row in csv_reader: # Each row is an OrderedDict! print(row) #Use keys to access data
b79de13ef7ae6e4a9f469855b8278032fc836a9f
thiago-ximenes/curso-python
/pythonexercicios/ex025.py
138
3.828125
4
nome = str(input('Digite o nome de uma pessoa: ')).strip() print('It is {} that has Silva in the name!'.format('Silva' in nome.title()))
9d75dbf4e1c21a7917d107d2797f7cb91af93b7b
FangyangJz/Black_Horse_Python_Code
/第一章 python基础/02 python基础_days07/function_多值参数求和.py
421
4.09375
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2017/11/13 def sum_numbers(*args): num = 0 print (args) for n in args: num += n return num result = sum_numbers(1,2,3,4,5) print result def sum_numbers_cmp(args): #这里 num = 0 print (args) for n in args: num += n return num result = sum_numbers_cmp((1,2,3,4,5)) #这里 print result
3707aaec786a745c7343f19704b5666a1a001529
pauladam2001/Sem1_FundamentalsOfProgramming
/a4-pauladam2001/src/domain/entity.py
2,995
3.640625
4
""" Domain file includes code for entity management entity = number, transaction, expense etc. """ def set_newValue(contestantNumber, problemNumber, newValue, listOfContestants): """ Sets a new value for a given problem input: contestantNumber - the position of the contestant problemNumber - P1, P2 or P3 newValue - the new value of "problemNumber" listOfContestants - the list of all contestants """ listOfContestants[contestantNumber][problemNumber] = newValue def get_average_score_of_contestants(listOfContestants): """ Used to display the contestants sorted in decreasing order of average score input: listOfContestants - the list of all contestants """ return float((listOfContestants['P1'] + listOfContestants['P2'] + listOfContestants['P3']) / 3) def get_problem1(listOfContestants): """ Used to display the contestants sorted in decreasing order of score from problem 1 input: listOfContestants - the list of all contestants """ return listOfContestants['P1'] def get_problem2(listOfContestants): """ Used to display the contestants sorted in decreasing order of score from problem 2 input: listOfContestants - the list of all contestants """ return listOfContestants['P2'] def get_problem3(listOfContestants): """ Used to display the contestants sorted in decreasing order of score from problem 3 input: listOfContestants - the list of all contestants """ return listOfContestants['P3'] def get_problem1_score(contestant, listOfContestants): """ Returns the score for problem number 1 input: contestant - the position/index of the contestant listOfContestants - the list of all contestants """ return listOfContestants[contestant]['P1'] def get_problem2_score(contestant, listOfContestants): """ Returns the score for problem number 2 input: contestant - the position/index of the contestant listOfContestants - the list of all contestants """ return listOfContestants[contestant]['P2'] def get_problem3_score(contestant, listOfContestants): """ Returns the score for problem number 3 input: contestant - the position/index of the contestant listOfContestants - the list of all contestants """ return listOfContestants[contestant]['P3'] def get_average_score_of_one_contestant(contestant, listOfContestants): """ Returns the average score of a contestant input: contestant - the index of the contestant listOfContestants - the list of all contestants """ problem1 = get_problem1_score(contestant, listOfContestants) problem2 = get_problem2_score(contestant, listOfContestants) problem3 = get_problem3_score(contestant, listOfContestants) return float((problem1 + problem2 + problem3) / 3)
f61ba2fdb135aa17619c1b9832ff764ac554a058
brijkishorsoni1210/library-management-system
/lib_man_sys.py
4,467
3.5
4
import datetime import os class LMS: def __init__(self,list_of_books,library_name): self.list_of_books="List_of_books.txt" self.library_name=library_name self.books_dict={} Id=101 with open(self.list_of_books) as bk: content=bk.readlines() for line in content: self.books_dict.update({str(Id):{"books_title":line.replace("\n",""),"lender_name":"","Issue_date":"","Status":"Available"}}) Id=Id+1 def display_books(self): print("-----------------------List of Books------------------------------") print("Books ID","\t","Title") print("--------------------------------------------------------------------") for key,value in self.books_dict.items(): print(key,"\t\t",value.get("books_title"),"-[",value.get("Status"),"]") def Issue_books(self): books_id=input("Enter books ID:") current_date=datetime.datetime.now().strftime("%Y-%m_%d %H:%M:%S") if books_id in self.books_dict[books_id]["Status"]=="Available": print(f"This book is already issued to {self.books_dict[books_id]['lender_name']} on {self.books_dict[books_id]['lend_date']}") return self.lend_books() elif self.books_dict[books_id]['status']=='Available': your_name=input("Enter Your Name:") self.books_dict[books_id]['lender_name']=your_name self.books_dict[books_id]['lend_date']=current_date self.books_dict[books_id]['status']='Already Issued' print("Book Issued Successfully!!!\n") else: print("Book ID Not Found!!!") return self.Issue_books() def add_books(self): new_books=input("Enter books title:") if new_books=="": return self.add_books() elif len(new_books)> 50: print("Books title length is too lon!!! Title length should be less then 50 characters") return self.add_books() else: with open(self.list_of_books,"a") as bk: bk.writelines(f"{new_books}\n") self.books_dict.update({str(int(max(self.books_dict))+1):{'books_title':new_books,'lender_name':'','lend_date':'', 'status':'Available'}}) print(f"The books '{new_books}'has been added successfully!!!") def return_books(self): books_id=input("Enter Books ID: ") if books_id in self.books_dict.keys(): if self.books_dict[books_id]['status']=='Available': print("This book is already available in library.Please check book id!!!") return self.return_books() elif not self.books_dict[books_id]['status']=='Available': self.books_dict[books_id]['lender_name']='' self.books_dict[books_id]['lend_date']='' self.books_dict[books_id]['status']='Available' print("Successfully Updated !!!\n") else: print("Book ID Not Found !!!") if __name__=="__main__": try: myLMS=LMS("list_of_books.txt","Python's") press_key_list={"D":"Display Books","I":"Issue Books","A":"Add Books","R":"Return Books","Q":"Quit"} key_press=False while not (key_press=="q"): print(f"\n-----------Welcome To {myLMS.library_name} Library management System-----------\n") for key,value in press_key_list.items(): print("Press",key,"To",value) key_press=input("Press Key:").lower() if key_press == "i": print("\nCurrent Selection: ISSUE BOOK\n") myLMS.Issue_books() elif key_press =="a": print("\nCurrent Selection: ADD BOOK\n") myLMS.add_books() elif key_press =="d": print("\nCurrent Selection: DISPLAY BOOKS\n") myLMS.display_books() elif key_press =="r": print("\nCurrent Selection: RETURN BOOKS\n") myLMS.return_books() elif key_press =="q": break else: continue except Exception as e: print("Something went wrong.Please check again!!!") #l=LMS("List_of_books.txt","Python's Library") #print(l.display_books()) #print(LMS("List_of_books.txt","Python's Library"))
ecd07767c66ce60d577f8b82f311eebcd180aabb
nurgalix/CoursePython
/anagrammav2.py
2,021
4.03125
4
import random WORDS = ("пайтоннеговно", "превысокомногорассмотрительствующий", "тысячадевятьсотвосьмидесятидевятимиллиметровый", "водогрязеторфопарафинолечение", "человеконенавистничество", "папич") word = random.choice(WORDS) jumble = "" correct = word attempt = 1 temp = 0 while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] print("Здравствуйте это игра Анаграммы, вам дается 5 попыток для отгадование исходного слово") print("Вот анаграмма >>>> ", jumble) print("Если хотите воспользоваться подсказкой, напишите символ '!'") guess = input("Попробуйте отгадать исходное слово:") while guess != correct and guess != "": if guess == "!": print("Первая буква", correct[0]) temp += 1 print("К сожелею вы ошиблись, попробуйте заново") guess = input("Попробуйте отгадать исходное слово: ") attempt += 1 if guess == correct: continue if attempt == 5: print("К сожелению вы проиграли :(") break if guess == correct: if temp == 0 and attempt == 1: print("ПРЕВОСХОДНО ВЫ ВЫИГРАЛИ, ВАМ НАЧИСЛЯЕТСЯ 10000000000 баллов") elif temp > 0: print("Поздравляю вы справились, но использывали подсказку :/ , поэтому вам начисляется 50 баллов") else: print("Поздравляю вы выиграли, вам начисляется 100 баллов") input("\n\nPress Enter, to exit")
6c4dd0b36ff01e6261f3be4aa5c2f68514926f92
kporcelainluv/1_month_commit
/5_day/5_1.py
237
3.71875
4
def update_dictionary(d, key, value): new_key = int(key)*2 if key in d: d[key] += [value] if key not in d: if new_key not in d: d[new_key] = [value] else: d[new_key] += [value]
010ffd53a3858f3970f476c7029274cbd7145a0f
ivenpoker/Python-Projects
/Projects/Online Workouts/w3resource/Basic - Part-I/program-144.py
1,248
4.5
4
#!/usr/bin/env python3 ####################################################################################### # # # Program purpose: Check if an variable is of integer type or string type. # # Program Author : Happi Yvan <[email protected]> # # Creation Date : September 3, 2019 # # # ####################################################################################### def find_type(someVar=None): if someVar is None: raise TypeError("Invalid argument") typeInfo = str(type(someVar)) if typeInfo.find("str") >= 0: return "str" elif typeInfo.find("int") >= 0: return "int" if __name__ == '__main__': varA = int(1) print(f"Variable type of varA: {find_type(varA)}") varB = str("james") print(f"Variable type of varB: {find_type(varB)}") # OR we could still do this print(isinstance(25, int) or isinstance(25, str)) print(isinstance([25], int) or isinstance([25], str)) print(isinstance("25", int) or isinstance("25", str))
c1a22c939ff90ed3b2dbb566830e7bae7c0c4ecf
laloxxx20/Ant-Colony
/place.py
1,154
3.71875
4
class Place(object): value = 0 position = (0, 0) neighbors = [] value_pheromone = 0 prev_neighbor = None # Place object value_to_up_phero = 0.1 def __init__(self, pos, value, neighbors): self.position = pos self.value = value self.neighbors = neighbors def set_position(self, x, y): self.position = (x, y) def set_value(self, value): self.value = value def add_neighbor(self, value): self.neighbors.append(value) def set_value_pheromone(self, value, prev_neighbor): self.value_pheromone += value if self.prev_neighbor: self.prev_neighbor = prev_neighbor self.prev_neighbor.value_pheromone += value def evaporate(self): self.value_pheromone -= self.value_to_up_phero if self.prev_neighbor: self.prev_neighbor.value_pheromone -= self.value_to_up_phero def print_place(self): print "%s: [%s] -- %s. PHE: %s" % ( self.value, ', '.join(str(n) for n in self.neighbors), str(self.position), str(self.value_pheromone), )
7615bd44ef8f50b0779bf68b1f234d9db6b5d7d5
yang4978/Coding-Interviews
/2 - Basic Knowledge/0013. Implement strStr().py
361
3.640625
4
class Solution: """ @param source: @param target: @return: return the index """ def strStr(self, source, target): if(len(source)==0 and len(target)==0): return 0 result = -1 for i in range(len(source)): if(source[i:i+len(target)]==target): return i return result
2360506764d57b9af4c31f79f3d91a12d9e9baf6
tohanyich/Algorithms-theory-and-practice
/haffman_encoding.py
3,939
3.640625
4
import heapq from collections import Counter class Node: def __init__(self, left=None, right=None, data=None, value=None, code=''): self.left = left self.right = right self.data = data self.value = value self.code = code def __str__(self): return 'Node ['+str(self.data)+']' class Tree: def __init__(self): self.root = None # корень дерева self.encoding_dict = {} def NewNode(self, data): return Node(None, None, data, None) # /* функция для вычисления высоты дерева */ def height(self, node): if node is None: return 0 else: l_height = self.height(node.left) r_height = self.height(node.right) if l_height > r_height: return l_height + 1 else: return r_height + 1 # /* функция для распечатки элементов на определенном уровне дерева */ def print_given_level(self, root, level): if root is None: return if level == 1: print('{} {} {}'.format(root.data, root.value, root.code)) elif level > 1: self.print_given_level(root.left, level - 1) self.print_given_level(root.right, level - 1) # /* функция для распечатки дерева */ def print_level_order(self): h = self.height(self.root) i = 1 while i <= h: self.print_given_level(self.root, i) i += 1 def set_code_given_level(self, root, level, code): if root is None: return if level == 1: root.code = code if len(root.data) == 1: self.encoding_dict.update({root.data: root.code}) elif level > 1: self.set_code_given_level(root.left, level - 1, code + '0') self.set_code_given_level(root.right, level - 1, code + '1') def set_all_codes(self): h = self.height(self.root) i = 1 while (i <= h): self.set_code_given_level(self.root, i, self.root.code) i += 1 def main(): # in_str = input() in_str = 'aaaccc' letters_freq = Counter(in_str) heap = [] for letter, freq in letters_freq.items(): heapq.heappush(heap, [freq, letter]) print(heap) code_tree = Tree() # Если только один символ if len(heap) == 1: root = heapq.heappop(heap) code_tree.root = Node(data=root[1], value=root[0], code='0') else: while heap: if len(heap) > 1: left = heapq.heappop(heap) right = heapq.heappop(heap) if len(left) > 2: l_node = Node(left[2].left, left[2].right, left[1], left[0]) else: l_node = Node(data=left[1], value=left[0]) if len(right) > 2: r_node = Node(right[2].left, right[2].right, right[1], right[0]) else: r_node = Node(data=right[1], value=right[0]) root_node = Node(l_node, r_node, left[1] + right[1], left[0] + right[0]) heapq.heappush(heap, [left[0] + right[0], left[1] + right[1], root_node]) else: code_tree.root = heapq.heappop(heap)[2] code_tree.set_all_codes() # code_tree.print_level_order() # print(code_tree.encoding_dict) # Закодируем строку new_str = '' for l in in_str: new_str += code_tree.encoding_dict[l] print('{} {}'.format(len(code_tree.encoding_dict), len(new_str))) for key, code in sorted(code_tree.encoding_dict.items(), key=lambda t: t[0]): print('{}: {}'.format(key, code)) print(new_str) if __name__ == "__main__": main()
9455a4ec8080467bb93c72bf507dcdbda454fa61
smoil-ali/Word-Order
/Word Order.py
197
3.5
4
from collections import defaultdict d = defaultdict(list) for x in range(int(input())): y=input() d[y].append(1) print(len(d)) for i,j in d.items(): print(sum(j),end=" ")
a6bcda3810e234b407939058dac21d034d8ba114
Zu1uDe1ta/Personal-Project-The-First-Troll-Under-The-Bridge
/exam1/gregorian_cal_utils.py
506
4.34375
4
def is_leap_year(year: int) -> bool: """ Given a year, this function returns a boolean indicating whether or not it is a leap year. :param year: an integer indicating a year. :return: A boolean indicating whether or not the year parameter is a leap year. """ if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False
87d1db6ca9af94a34ba4cdd74311ebd96bfbb15f
anatrevis/xaman
/utils.py
5,296
4.125
4
import datetime import re def extract_date(input, app): """Verify if user input contains one and only one valid date and extracts it from string. :param input: string with input from the user :param app: flask app used for system logging :return: boolean that indicates if date is within range """ app.logger.info('input: ' + input) try: to_find = re.findall('[0-9][0-9][/][0-1][1-9][/][1-2][0-9][0-9][0-9]', input) # Search for a date pattern app.logger.info('to_find: ' + str(len(to_find))) if len(to_find) > 1: app.logger.warning("Input contains more than one date.") return False if len(to_find) < 1: app.logger.warning("Input does not contain a date.") return False if len(to_find) == 1: date = str(to_find[0]) app.logger.info("Date extracted: " + date) return date except Exception as e: app.logger.warning("Error while extracting date.") app.logger.error(e) return None def verify_date_range(date, app): """Check if user entered a date within the API range - which is 5 days from today on the free version. :param date: a datetime object with a date :param app: flask app used for system logging :return: boolean that indicates if date is within range """ start = datetime.datetime.now() end = datetime.datetime.now() + datetime.timedelta(days=5) if end >= date >= start: app.logger.debug("Range check: ok") return True else: app.logger.warning("Range check: fail. The date entered is not within 5 days range.") return False def is_date(input, app): """Checks if the user input contains a valid date in 3 steps: first extracts the date from user input; second try to parse the extracted date in a datetime object - It will throw an exception if it is not valid; third verifies if the date is within the permitted API range. :param input: input from the user :param app: flask app used for system logging :return: boolean that indicates if contains a valid date """ try: app.logger.warning("User input date = " + input) extracted_date = extract_date(input, app) # First: try to extract a date from user input if extracted_date: date = datetime.datetime.strptime(extracted_date, "%d/%m/%Y") # Second: try to parse the extracted date in a datetime object - It will throw an exception if it is not valid if verify_date_range(date, app): # Third: verify if the date is withn the API range - Which is 5 days from today return date else: return False else: return False except Exception as e: app.logger.warning("Error parsing date.") app.logger.error(e) return False def sensation(temp): """Return suggestions of clothing based on the temperature. :param temp: the temperature sensation extracted from the forecast. :return: string containing clothing suggestions. """ if temp <= 4: return "The weather will be very cold. I advise you to take a scarf and a hat with you." elif 4.1 < temp < 8.0: return "The weather will be cold. I advise you to wear a cozy jumper." elif 8.1 < temp < 13.0: return "The weather will be cool. I advise you to take a jacket with you." elif 13.1 < temp < 18.0: return "The weather will be slightly cool. I advise you to carry a jacket with you." elif 18.1 < temp < 23.0: return "The weather will be bland. Wearing a sweatshirt will be fine." elif 23.1 < temp < 24.0: return "The weather will be slightly warm. Wearing a shirt will be fine." elif 24.1 < temp < 27.0: return "The weather will be warm. Take your shorts with you." elif 27.1 < temp < 33.0: return "The weather will be hot. Perfect opportunity to use sandals." elif temp >= 33.1: return ( "The weather will be very hot. Take a bathsuit with you and be prepared if an opportunity to refresh in " "the pool appear.") def suggest_clothes(trip_forecast): """Checks the possibility of other meteorological events such as rain, snow, thunderstorm and drizzle and return additional suggestions of clothing. :param trip_forecast: a dict with the forecast. :return: string containing clothing suggestions. """ temp = trip_forecast.get("temperature_feel") sens = sensation(temp) stat = trip_forecast.get("status") if stat == 'Rain': return sens + " Also, take an umbrella if you can. There is a chance of rain." elif stat == 'Drizzle': return sens + " Also, take an raincoat if you can. There is a chance of drizzle." elif stat == 'Thunderstorm': return sens + " Be careful! There is a high chance of a thunderstorm." elif stat == 'Snow': return sens + " Take your boots with you, because there is a high chance of snow." elif stat == 'Clear': return sens + " Take your sunglasses for the day, because the sky will be clear." else: return sens
01094b8a4268491022850be92d175bb2214ee19c
dg5921096/Books-solutions
/Python-For-Everyone-Horstmann/Chapter6-Lists/P6.18.py
1,577
4.15625
4
# It is a well-researched fact that men in a rest room generally prefer to maximize # their distance from already occupied stalls, by occupying the middle of the longest # sequence of unoccupied places. # For example, consider the situation where ten stalls are empty. # _ _ _ _ _ _ _ _ _ _ # The first visitor will occupy a middle position: # _ _ _ _ _ X _ _ _ _ # The next visitor will be in the middle of the empty area at the left. # _ _ X _ _ X _ _ _ _ # Write a program that reads the number of stalls and then prints out diagrams in the # format given above when the stalls become filled, one at a time. Hint: Use a list of # Boolean values to indicate whether a stall is occupied. # FUNCTIONS def generate_N_stalls(number, list): for i in range(number): list.append("-") return list def occupyStall(list): lenList = len(list) middle = len(list) // 2 for i in range(middle, -1, -1): if list[i] != "X": # occupy list[i] = "X" break else: # occupy half of length till occupied X if list[i // 2] != "X": list[i // 2] = "X" break return print(list) # main def main(): exampleToilet = [] inputN_stalls = int(input("How many stalls do you want your toilet to have: ")) exampleToilet = generate_N_stalls(inputN_stalls, exampleToilet) print("Your amazing, but empty toilet") print(exampleToilet) print("Occupy 2 stalls") occupyStall(exampleToilet) occupyStall(exampleToilet) # PROGRAM RUN main()
cd6d234f6649ebcaca343a782149baf95021fd98
dimitar-daskalov/SoftUni-Courses
/python_advanced/labs_and_homeworks/01_lists_as_stacks_and_queues_exercise/10_cups_and_bottles.py
817
3.59375
4
from collections import deque cups_queue = deque(int(cup) for cup in input().split()) bottles_list = [int(bottle) for bottle in input().split()] wasted_water = 0 are_filled = True current_cup = cups_queue[0] while cups_queue: current_bottle = bottles_list[-1] if current_bottle - current_cup >= 0: wasted_water += current_bottle - current_cup bottles_list.pop() current_cup -= current_bottle if current_cup <= 0: cups_queue.popleft() if cups_queue: current_cup = cups_queue[0] if len(bottles_list) == 0: are_filled = False break if are_filled: print(f"Bottles: {' '.join(str(bottle) for bottle in bottles_list)}") else: print(f"Cups: {' '.join(str(cup) for cup in cups_queue)}") print(f"Wasted litters of water: {wasted_water}")
421879ec85d22de86099aba61df9efcf1df71261
NallamilliRageswari/Python
/Square_of_sorted_array.py
645
4.25
4
''' Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] Constraints: * 1 <= nums.length <= 104 * -104 <= nums[i] <= 104 nums is sorted in non-decreasing order. ''' nums=list(map(int,input().split())) l=[] for i in range(len(nums)): x=nums[i]*nums[i] l.append(x) l.sort() print(l)
fff7795d319f61a550286809925c0c053364f96d
NHTdz/baitapthem
/list_getfirstsecond.py
150
3.5
4
list = [77,53,457,108,98,23,55] list_new = sorted(list) print("First score is:" + str(list_new[-1])) print("First score is:" + str(list_new[-2]))
5d1316339baaa3d3610dbb8ed564ce641756ba9b
jashidsany/Learning-Python
/LCodecademy Lesson 10 Classes/LA10.10_Self.py
1,127
4.125
4
# If we were creating a search engine, and we wanted to create classes for each separate entry we could return. We’d do that like this: # class SearchEngineEntry: # def __init__(self, url): # self.url = url # codecademy = SearchEngineEntry("www.codecademy.com") # wikipedia = SearchEngineEntry("www.wikipedia.org") # print(codecademy.url) # prints "www.codecademy.com" # print(wikipedia.url) # prints "www.wikipedia.org" # Since the self keyword refers to the object and not the class being called, we can define a secure method on the SearchEngineEntry class that returns the secure link to an entry. class Circle: pi = 3.14 def __init__(self, diameter): print("Creating circle with diameter {d}".format(d=diameter)) # Add assignment for self.radius here: self.radius = (diameter/2) def circumference(self): circumference = 2 * Circle.pi * self.radius return circumference medium_pizza = Circle(12) teaching_table = Circle(36) round_room = Circle(11460) print(medium_pizza.circumference()) print(teaching_table.circumference()) print(round_room.circumference())
2f9d8f3eebf4f3b45b4977e673b6a7fd1dbc7e5f
wmmxk/Nuts_bolts_python_programming
/package/basic_pkg/foo/level2/another_mod.py
90
3.546875
4
def add(a, b): print("modify 4") return a+b+1 def multiply(a, b): return a*b
d4717404b1ec9f963765bf1ad9c10d4f63e8617d
commGom/pythonStudy
/알고리즘withPy/카카오기출/2단계_level/뉴스클러스터링.py
774
3.5
4
def solution(str1, str2): answer = 0 str1=str1.lower() str2=str2.lower() str1_=[] str2_=[] for i in range(len(str1)-1): if str1[i].isalpha() and str1[i+1].isalpha(): str1_.append(str1[i]+str1[i+1]) for i in range(len(str2)-1): if str2[i].isalpha() and str2[i+1].isalpha(): str2_.append(str2[i]+str2[i+1]) a1 = str1_.copy(); a2 = str1_.copy() for i in str2_: a2.append(i) if i not in a1 else a1.remove(i) print(a2) common = [] for i in str2_: if i in str1_: str1_.remove(i); common.append(i) print(common) if len(a2)==0: answer=65536 else: answer=int(len(common)/len(a2)*65536) return answer print(solution("FRANCE+","french"))
9d23c5b5bdbff8332c8d169e5f009c4b2cfc928e
rkovrigin/crypto
/task1.py
4,552
3.640625
4
""" Let us see what goes wrong when a stream cipher key is used more than once. Below are eleven hex-encoded ciphertexts that are the result of encrypting eleven plaintexts with a stream cipher, all with the same stream cipher key. Your goal is to decrypt the last ciphertext, and submit the secret message within it as solution. Hint: XOR the ciphertexts together, and consider what happens when a space is XORed with a character in [a-zA-Z]. """ import codecs import os import string from itertools import permutations cyphers = [] cyphers.append("315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764703de0f3d524400a19b159610b11ef3e") cyphers.append("234c02ecbbfbafa3ed18510abd11fa724fcda2018a1a8342cf064bbde548b12b07df44ba7191d9606ef4081ffde5ad46a5069d9f7f543bedb9c861bf29c7e205132eda9382b0bc2c5c4b45f919cf3a9f1cb74151f6d551f4480c82b2cb24cc5b028aa76eb7b4ab24171ab3cdadb8356f") cyphers.append("32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb") cyphers.append("32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa") cyphers.append("3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070") cyphers.append("32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4") cyphers.append("32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce") cyphers.append("315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3") cyphers.append("271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027") cyphers.append("466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83") cyphers.append("32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904") def strxor(a, b): # xor two strings of different lengths if len(a) > len(b): return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)]) else: return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])]) def hexxor(a, b): # xor two strings of different lengths if len(a) > len(b): return ([x ^ y for (x, y) in zip(a[:len(b)], b)]) else: return ([x ^ y for (x, y) in zip(a, b[:len(a)])]) def random(size=16): return os.urandom(size) def encrypt(key, msg): c = strxor(key, msg) return c def get_hex_cyfer(i=0): return codecs.decode(cyphers[i], 'hex') def get_hex_cyfers(): return [get_hex_cyfer(i) for i in range(len(cyphers))] def find_2_cyphers(position_of_code): codes = [] for cypher in get_hex_cyfers(): if position_of_code < len(cypher): codes.append(cypher[position_of_code]) return list(permutations(list(set(codes)), 2)) def main(): latters = string.ascii_letters + " " result = [] for index in range(len(get_hex_cyfer(10))): perm = find_2_cyphers(index) keys = list(range(256)) for p in perm: k = [] for i in keys: if chr(p[0] ^ i) in latters and chr(p[1] ^ i) in latters: k.append(i) print(k, len(k)) if len(k) == 1: keys = k break if len(k) > 0: keys = k # print(keys[0], len(keys)) if len(keys) == 1: result.append(keys[0]) elif len(keys) == 0: result.append(0) else: result.append(0) print(result) result[2] = 110 result[7] = 204 result[21] = 127 for cypher in get_hex_cyfers(): print(''.join(chr(i ^ j) for i, j in zip(result, list(cypher)))) if __name__ == "__main__": main()
e083be8b703974cb33388e739314ef2491cd5ff2
frainfreeze/studying
/home/old/python/014.py
231
3.8125
4
def front_times(str, n): if n>=0: if len(str)<3: return str*n return str[:3]*n print(front_times('Chocolate', 2)) #'ChoCho' print(front_times('Chocolate', 3)) #'ChoChoCho' print(front_times('Abc', 3)) #'AbcAbcAbc'
18348b5ecefe399f7ffa76bb6227ce4e38156413
ShengHow95/basic-algorithm-examples
/palindrome_permutation.py
591
3.90625
4
palin_perm = "Tact Coa" not_palin_perm = "This is not palindrome permutation" def is_panlindrome_permutation(s): s = s.replace(" ", "").lower() ht = dict() for i in s: if i in ht: ht[i] += 1 else: ht[i] = 1 odd_count = 0 for key, value in ht.items(): if value % 2 != 0 and odd_count == 0: odd_count += 1 elif value % 2 != 0 and odd_count != 0: return False else: return True print(is_panlindrome_permutation(palin_perm)) print(is_panlindrome_permutation(not_palin_perm))
6645119540baad9744c0149d2afa2d5f9c13a2a5
pydevjason/Python-VS-code
/class_str_and_repr_methods.py
264
3.71875
4
class Card(): def __init__(self, rank, suit): self.rank = rank self.suit = suit def __str__(self): return f"{self.rank} of {self.suit}" def __repr__(self): return f"Card('{self.rank}', '{self.suit}')" c = Card("Ace", "Spades") print(c) print(repr(c))
3eb72a7054419f9a2374201011fceac231feecf9
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/leetcode/LeetCode/964 Least Operators to Express Number.py
2,708
4.21875
4
#!/usr/bin/python3 """ Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-). For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used. Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations. Note: 2 <= x <= 100 1 <= target <= 2 * 10^8 """ from functools import lru_cache class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: """ x/x is 1 x * x is power 2 target = a_n * x^n + a_{n-1} * x^{n-1} + ... + a_1 * x^1 + a_0 * x/x To make target divisible, it can be target - a0 or target + (x^1 - a0) """ return self.dfs(target, x, 0) - 1 @lru_cache(maxsize=None) def dfs(self, target, x, power): """ power: power, pow(x, power) """ if target == 0: return 0 if target == 1: return self.ops(power) d, r = target // x, target % x ret = r * self.ops(power) + self.dfs(d, x, power + 1) # either -r or +(x-r) if r != 0: ret2 = (x - r) * self.ops(power) + self.dfs(d + 1, x, power + 1) ret = min(ret, ret2) return ret def ops(self, power): """ number of ops required + x/x + x + x * x + x * x * x """ if power == 0: return 2 else: return power if __name__ == "__main__": assert Solution().leastOpsExpressTarget(3, 19) == 5 assert Solution().leastOpsExpressTarget(5, 501) == 8 assert Solution().leastOpsExpressTarget(2, 125046) == 50
720667900e9990fb8af11b7972fe71e37cdc9f5f
adi1201239/b
/Q_1.py
179
3.734375
4
a = 40; b = 10; print("Addition of two number", a+b) print("Subtraction of two number", a-b) print("Multiplication of two number", a*b) print("Division of two number", a/b)
e98685864b2cdddaa2979d9d64fcf61fa07178fb
mozi-h/TicTacToe2
/mode2.py
3,796
3.734375
4
from os import system game = [0, 0, 0, 0, 0, 0, 0, 0, 0] char_lookup = {0: "-", 1: "X", 2: "O"} turn = 1 not_turn = [0, 2, 1] to_check = [ # Combinations of fiels a player needs to own to win [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ] def cls(): system("cls") def game_draw(): """Prints the battlefield and an index lookup.""" game_fancy = list(map(lambda x: char_lookup[x], game)) print("[{0[0]}] [{0[1]}] [{0[2]}] 0 1 2".format(game_fancy)) print("[{0[3]}] [{0[4]}] [{0[5]}] 3 4 5".format(game_fancy)) print("[{0[6]}] [{0[7]}] [{0[8]}] 6 7 8".format(game_fancy)) def win_detection(): """Returns a player's number if they won. 0 otherwise.""" for lst in to_check: check = list(map(lambda x: game[x], lst)) if (check[0] != 0) & (check[0] == check[1] == check[2]): return check[0] return 0 def prod(iterable): """Returns the product of all values of the iterable.""" out = 1 for product in iterable: out *= product return out def draw_detection(): return prod(game) != 0 def turn_swap(): global turn if turn == 1: turn = 2 else: turn = 1 ## AI Functions ## def close_to_winning(player): """ Checks if player is one move away from winning. Returns the index on the move neccecary to win. None wotherwise. """ for lst in to_check: # Get occupieing player of field with index x # if (the player to look for occupies row) & (row is almost claimed) & (missing spot is unclaimed) check = list(map(lambda x: game[x], lst)) if (check[0] == player) & (check[0] == check[1]) & (check[2] == 0): return lst[2] elif (check[1] == player) & (check[1] == check[2]) & (check[0] == 0): return lst[0] elif (check[0] == player) & (check[0] == check[2]) & (check[1] == 0): return lst[1] return None def choose_prefered(): """ Returns the first available prefered index. """ prefer = [4, 0, 2, 6, 8, 1, 3, 5, 7] for index in prefer: if not game[index]: return index class TicTacToeIndexError(Exception): pass cls() ## Main Loop ## while True: print("It's {}'s turn".format(char_lookup[turn])) if turn == 1: # AI's turn winning = close_to_winning(turn) if winning: move = winning else: winning = close_to_winning(not_turn[turn]) if winning: move = winning else: move = choose_prefered() game[move] = turn else: # Human's turn while True: game_draw() try: # Get human move, raise error if neccecary move = int(input()) if move not in range(9): raise ValueError if game[move] != 0: raise TicTacToeIndexError game[move] = turn cls() break except ValueError: # Invalid move cls() print("You may only enter whole numbers from 0 to 8.") except TicTacToeIndexError: # Field occupied cls() print("You may only tick into unoccupied fields.") turn_swap() # Win / Draw detection won = win_detection() if won != 0: game_draw() print("{} has won the game!".format(char_lookup[won])) input("Press enter") exit() if draw_detection(): game_draw() print("The game is a draw!") input("Press enter") exit()
e89251de8d98197ee8dc05a305cb0e9e076fe66e
nikhilmborkar/fsdse-python-assignment-1
/square_of_numbers.py
167
3.578125
4
def squareOfNumbers(n): square_of_numbers = {} for i in range(1, n+1): square = i*i square_of_numbers[i] = square return square_of_numbers
8b21746260ec87df5c12d36f349ad44275f9dcc1
Vadskye/rise-gen
/rise_gen/combat.py
7,564
3.6875
4
#!/usr/bin/env python3 import argparse from rise_gen.creature import Creature import cProfile from pprint import pprint class CreatureGroup(object): """A CreatureGroup is a group of creatures that acts like a single creature """ # TODO: move dead creatures to the end of the array when they die def __init__(self, creatures): self.creatures = creatures def standard_attack(self, group): """Attack the given group of creatures Args: group (CreatureGroup): Creatures to attack """ for c in self.creatures: target = group.get_living_creature() # if all targets are dead, stop attacking if target is None: return else: c.standard_attack(target) def get_living_creature(self): """Return a single living creature Yields: Creature: living creature """ for c in self.creatures: if c.is_alive(): return c return None def refresh_round(self): """Refresh the round for all creatures in the group""" for c in self.creatures: c.refresh_round() def refresh_combat(self): """Refresh the combat for all creatures in the group""" for c in self.creatures: c.refresh_combat() def is_alive(self): """Check whether any creatures in the group are alive Yields: bool: True if any creatures are alive, false otherwise """ for c in self.creatures: if c.is_alive(): return True return None def __str__(self): return 'CreatureGroup({})'.format([str(c) for c in self.creatures]) def run_combat(red, blue): """Simulate a round of combat between the given creatures Args: red (Creature): a creature that attacks first blue (Creature): a creature that attacks second """ results = { 'red is alive': 0, 'blue is alive': 0, 'rounds': 0 } def run_combat_round(): red.standard_attack(blue) blue.standard_attack(red) red.refresh_round() blue.refresh_round() results['rounds'] += 1 while (red.is_alive() and blue.is_alive() and results['rounds'] <= 100): run_combat_round() if red.is_alive(): results['red is alive'] += 1 if blue.is_alive(): results['blue is alive'] += 1 red.refresh_combat() blue.refresh_combat() return results def initialize_argument_parser(): parser = argparse.ArgumentParser( description='Do battle between Rise creatures', ) parser.add_argument( '-b', '--blue', dest='blue', help='creatures on the blue side', type=str, nargs='+', ) parser.add_argument( '-t', '--test', dest='test', type=str, help='perform a specific test', ) parser.add_argument( '-l', '--level', dest='level', help='the level of the characters', default=1, type=int, ) parser.add_argument( '-p', '--print', dest='print', help='if true, print the generated characters', action='store_true', ) parser.add_argument( '-v', '--verbose', dest='verbose', help='if true, print more output', action='store_true', ) parser.add_argument( '--profile', dest='profile', help='if true, profile performance', nargs='?', type=str, ) parser.add_argument( '-r', '--red', dest='red', help='creatures on the red side', type=str, nargs='+', ) parser.add_argument( '--trials', default=10000, dest='trials', help='The number of trials to run', type=int, ) parser.add_argument( '--bl', dest='blue level', help='level of creatures on the blue side', type=int, ) parser.add_argument( '--rl', dest='red level', help='level of creatures on the red side', type=int, ) return vars(parser.parse_args()) def custom_red_modifications(red): """Modify the CreatureGroup for random testing Args: red (CreatureGroup): Group of red creatures """ pass def custom_blue_modifications(blue): """Modify the CreatureGroup for random testing Args: blue (CreatureGroup): Group of blue creatures """ pass def generate_combat_results(red, blue, trials): raw_results = list() for t in range(trials): raw_results.append(run_combat(red, blue)) results = { 'red alive %': int([ True if result['red is alive'] else False for result in raw_results ].count(True) / float(trials) * 100), 'blue alive %': int([ True if result['blue is alive'] else False for result in raw_results ].count(True) / float(trials) * 100), 'average rounds': sum([results['rounds'] for results in raw_results]) / float(trials) } return results def test_training_dummy(level, trials): sample_creature_names = 'barbarian barbarian_greatsword cleric cleric_spells druid druid_spells fighter fighter_dex ranger rogue rogue_str sorcerer warrior warrior_dex warrior_str_dex wizard'.split() sample_creatures = [Creature.from_sample_creature(name, level=level) for name in sample_creature_names] training_dummy = Creature.from_sample_creature('dummy', level=level) results = dict() for creature in sample_creatures: for i in range(trials): rounds_to_defeat_dummy = run_combat(creature, training_dummy)['rounds'] try: results[creature.name] += rounds_to_defeat_dummy except KeyError: results[creature.name] = rounds_to_defeat_dummy results[creature.name] /= trials for key in results.keys(): results[key] = round(results[key], 1) pprint(results) def main(args): blue_creatures = [Creature.from_sample_creature( name, level=args['blue level'] or args['level'] ) for name in args['blue']] blue = CreatureGroup(blue_creatures) red_creatures = [Creature.from_sample_creature( name, level=args['red level'] or args['level'] ) for name in args['red']] red = CreatureGroup(red_creatures) custom_blue_modifications(blue) custom_red_modifications(red) if args.get('verbose'): print("RED:\n{}\nBLUE:\n{}".format(red, blue)) pprint(generate_combat_results(red, blue, args['trials'])) if __name__ == "__main__": cmd_args = initialize_argument_parser() if cmd_args.get('profile'): cProfile.run('main(cmd_args)', sort=cmd_args.get('profile')) elif cmd_args.get('test') == 'dummy': test_training_dummy( level=cmd_args['level'], trials=100 ) elif cmd_args.get('test') == 'levels': cmd_args['trials'] //= 10 for i in range(1, 21): cmd_args['level'] = i print(str(i) + ": ", end="") main(cmd_args) elif cmd_args.get('test') == 'level_diff': cmd_args['trials'] //= 10 for i in range(3, 21): cmd_args['blue level'] = i cmd_args['red level'] = i-2 print(str(i) + ": ", end="") main(cmd_args) else: main(cmd_args)
c2b7874fa24a0c58fa65831b44175de2423401bd
g-hurst/Python-For-Teenagers-Learn-to-Program-Like-a-Superhero-codes
/pygame animation.py
2,753
3.59375
4
import pygame from pygame.locals import * import sys import random pygame.init() # varriables gameQuit = False move_x = 300 move_y = 300 #creating colors stored in tuples colorWHITE = (255, 255, 255) colorBLACK = (0, 0, 0) colorRED = (255, 0, 0) # creates and names the window that is created gameWindow = pygame.display.set_mode((800, 600)) # captions the text in the top of the window pygame.display.set_caption('Box Animator 5000') # game loop while not gameQuit: for event in pygame.event.get(): if event.type == pygame.QUIT: gameQuit = True pygame.quit() sys.exit() # activats esc as a quit button if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: gameQuit = True pygame.quit() sys.exit() # activats q as a quit button if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameQuit = True pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: #moves object left with left arrow if event.key == pygame.K_LEFT: move_x -= 10 # moves object right with right arrow if event.key == pygame.K_RIGHT: move_x += 10 # moves object up with up arrow if event.key == pygame.K_UP: move_y -= 10 # moves object down with down key if event.key == pygame.K_DOWN: move_y += 10 #creates a teleport to a rendom spot when t is pressed if event.type == pygame.KEYDOWN: if event.key == K_t: move_x = int(random.randint(1, 750)) move_y = int(random.randint(1, 550)) pygame.display.set_caption('Gnarly Teleport!') # fill the screen white gameWindow.fill(colorWHITE) # checking for collisions #right collision if move_x > 750: move_x -= 50 pygame.display.set_caption('Right Collision!') # left collision if move_x <1: move_x += 50 pygame.display.set_caption('Left Collision!') # bottom colision if move_y > 550: move_y -= 50 pygame.display.set_caption('Bottom Collision!') # top colision if move_y < 1: move_y += 50 pygame.display.set_caption('Top Collision!') # blit a black rectangle on the screen pygame.draw.rect(gameWindow, colorBLACK, [move_x, move_y, 50, 50]) # update the screen pygame.display.update()
dd1199d0424531068d907ac702239bcb8cf5fbbd
zjwyx/python
/day05/02_字典.py
2,383
3.84375
4
# dic = { # '太白':{'name':'太白金星','age':18,'sex':'男'}, # 'python22期':['主管梁','大壮'] # } # 键必须是不可变的数据类型 int str # 值可以是任意数据类型,对象 # 字典在3.5之前时无序的 # 字典在3.6版本初建字典的顺序排列 # 字典的优点:查询速度非常快,存储关联型的数据 # 字典的缺点:以空间换时间 # 字典的创建方式 # 方式一: # dic = dict((('one',1),('two',2),('three',3))) # print(dic) # 方法二: # dic = dict(one = 1,two=2,three=3) # print(dic) # 方法三: # dic = dict({"one":1,"two":2,"three":3}) # print(dic) # 增删改查 dic = {"name":"太白","age":18,"hobby_list":['直男',"开车"]} # 增 # 直接增加,键是唯一的 # 有则改之,无则增加 # dic["sex"] = "男"; # print(dic) # setdefault() # 有则不变,无则增加 # dic.setdefault("hoddy","打游戏") # print(dic) # update() 增 里面的参数是字典,有则改之无则增加 # 删 # pop() 按照键删除键值对 有返回值 *** # 设置第二个参数则无论字典中有无此键都不会报错 # dic.pop('age') # print(dic) # ret = dic.pop('hoddy','没有此键') # print(ret) # print(dic) # clear() 清空 # dic.clear(); # print(dic) # del() # del dic["age"] # print(dic) # 改 # dic['name'] = "alex" # print(dic) # 查 # print(dic['hobby_list']) # get() *** # li = dic.get('hobby_list'); # print(li) # 三个特殊的 # keys() values() items() # print(dic.keys()) # 可以转化成列表 # print(list(dic.keys())) # for key in dic.keys(): # print(key) # values() # print(dic.values()) # items() 所有的键值对 # print(dic.items()) # for i in dic.items(): # print(i) # 元祖的拆包 # a,b = ("name","太白") # print(a,b) # 面试题 # a = 18 # b = 12 # a,b = b,a # print(a,b) dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]} # 请在字典中添加一个键值对,"k4": "v4",输出添加后的字典 # dic["k4"] = "v4" # print(dic) # dic.setdefault("k4","v4"); # print(dic) # 请在修改字典中 "k1" 对应的值为 "alex",输出修改后的字典 # dic["k1"] = "alex" # print(dic) # 请在k3对应的值中追加一个元素 44,输出修改后的字典 # dic["k3"].append(444); # print(dic) # 请在k3对应的值的第 1 个位置插入个元素 18,输出修改后的字典 dic["k3"].insert(1,18); print(dic)
b2ae20973445522b94b71212cd975c1b2b469663
ShiinaMashiro1314/Project-Euler
/Python/381.py
294
3.734375
4
import math def is_prime(x): if(x <= 1): return False if(x == 2): return True for i in xrange(2,int(math.floor(math.sqrt(x)))+1): if(x % i == 0): return False return True result = 0 for i in xrange(5,100): if(is_prime(i)): result += i - 101%i print (i - 101%i) print result
609e12af50ebea7535ac2665ae93079a2a08b6fd
daisyang/data_structure_and_algorithm
/Merge2sortedlist.py
466
4
4
# You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. def Merge(a,b,m,n): if b is None: return a ind1 = m -1 ind2 =n -1 ind = ind1+ind2+1 while (ind>=0): if ind1 >=0 and a[ind1] > b[ind2]: a[ind]=a[ind1] ind1-=1 else: a[ind]=b[ind2] ind2-=1 ind-=1 return a def test(): a=[-2,2,3,4,5,0,0,0,0] b=[-4,-3,-2,10] a=Merge(a,b,5,4) print a test()
033293c5486cb0a55c3debbe50afcea74c3a947f
manuelcerdas/python_projects
/PlotMovies/classifier.py
1,135
3.53125
4
import numpy as np def classify0 (newPoint, dataSet, labels, k): # Get the ammount of rows in the data set numRows = dataSet.shape[0] #Create a matrix the same size as the data set, but in this case all the rows are the new point newSet = np.tile (newPoint,(numRows,1)) # we use Euclid to obtain the distance # if the point are (a,d) and (b,c) then the distance is ((a-b)**2 + (d-c)**2) **0.5 #Calulating the (a-b)**2 firstStep = (newSet - dataSet) ** 2 #Now add the results in the previous step (adding the squares) secondStep = firstStep.sum(axis=1) # get the square root distances = secondStep ** 0.5 # get the sorted indexes of the distances sortedDistancesIndexes = distances.argsort() #Create a dictionary to store the results labelCount = {} for i in range(k): voteLabel = labels[sortedDistancesIndexes[i]] labelCount[voteLabel] = labelCount.get(voteLabel,0)+1 sortedLabelCount = sorted(labelCount,key=lambda item:item[1]); return (sortedLabelCount[0])
83a2faad463d579002f7c673a90ac9d4b65fb36b
amani021/python100d
/day_39.py
214
4.0625
4
#-------- DAY 39 "exercise1" -------- def rec(num, power): if power > 0: result = num * rec(num, power-1) else: result = 1 return result print('The result of 5 x 5 x 5 is:', rec(5, 3))
ba8cd9b8cf699e00ae7865fab95cdc16a20dac93
julienemo/exo_headfirst
/11-jeu_de_vie.py
593
3.75
4
def set_grid(length, width): grid = [0] * length for i in range(length): grid[i] = [0] * width return grid # def count(): def decide_next(n, count): if n == 0: if count == 3: n = 1 else: n = 0 else: if (count > 3) or (count < 2): n = 0, else: n = 1 return n def draw_next(): global grid global height global width for i in height: for i in width: grid[height][width] = decide_next() height = 10 width = 10 grid = set_grid(height, width)
38aa843a83904894f86e1c447fcdb138b281a370
luckeyme74/tuples
/tuples_practice.py
2,274
4.40625
4
# 12.1 # Create a tuple filled with 5 numbers assign it to the variable n n = ('2', '4', '6', '8', '10') # the ( ) are optional # Create a tuple named tup using the tuple function tup = tuple() # Create a tuple named first and pass it your first name first = tuple('Jenny',) # print the first letter of the first tuple by using an index print first[0] # print the last two letters of the first tuple by using the slice operator (remember last letters means use # a negative number) print first[3:] # 12.2 # Given the following code, swap the variables then print the variables var1 = tuple("hey") var2 = tuple("you") var1, var2 = var2, var1 print var1 print var2 # Split the following into month, day, year, then print the month, day and year date = 'Jan 15 2016' month, day, year = date.split(' ') print month print day print year # 12.3 # pass the function divmod two values and store the result in the var answer, print answer answer = divmod(9, 2) print answer # 12.4 # create a tuple t4 that has the values 7 and 5 in it, then use the scatter parameter to pass # t4 into divmod and print the results t4 = (7, 5) result = divmod(*t4) print result # 12.5 # zip together your first and last names and store in the variable zipped # print the result first = "Jenny" last = "Murphy" zipped = zip(first, last) print zipped # 12.6 # Store a list of tuples in pairs for six months and their order (name the var months): [('Jan', 1), ('Feb', 2), etc months = [('October', 10), ('January', 1), ('March', 3), ('May', 5), ('July', 7), ('December', 12)] # create a dictionary from months, name the dictionary month_dict then print it month_dict = dict(months) print month_dict # 12.7 # From your book: def sort_by_length(words): t = [] for word in words: t.append((len(word), word)) t.sort(reverse=True) res = [] for length, word in t: res.append(word) return res # Create a list of words named my_words that includes at least 5 words and test the code above # Print your result my_words = ('hacienda', 'empathetic', 'harmonious', 'allegorical', 'totalitarianism', 'harpsichord', 'embellishment', 'lassitude', 'mysticism') print sort_by_length(my_words)
aa1b08d0d82a7865d94fd06f9b98c4b8468923d5
MeganathanR/Mega
/case44.py
97
3.609375
4
def num(n): if n in range(1,10): print( "yes") else : print("no") num(9)
183ff08e72916b817864d350e9ed850ccc983162
dnth/Malaysia_License_Plate_Generator
/main.py
2,511
3.546875
4
from fake_plate_generator import Generator import argparse import os ''' Parameters for generators: 1. state (string) = The first alphabets for car plate based on state and territory, must enter full state name Example: "Perak": "A", "Selangor": "B", "Pahang": "C", "Kelantan": "D", "Putrajaya": "F", "Johor": "J", "Kedah": "K", "Malacca": "M", "Negeri Sembilan": "N", "Penang": "P", "Perlis": "R", "Kuala Lumpur(1)": "W", "Kuala Lumpur(2)": "V", "Sarawak": "Q", "Sabah": "S" 2. plate_type (string) = The type of plate Example: "single", "double", "putrajaya 3. variant_plate (boolean) = add a random alphabet at back 4. total_plate (integer) = number of plate generated 5. alphabet_num (integer) = number of alphabet in plate (1 - 3) 6. number_num (integer) = number of numerical number in plate (1 -4) 7. font_type (string) = Example: "Arial_Bold", "Charles_Wright 8. display (boolean) = display result ''' # parser parser = argparse.ArgumentParser() parser.add_argument("--plate_type", type=str, help="type of plate. Eg: 'single', 'double', 'putrajaya'", default="single") parser.add_argument("--total_plate", required=True, type=int, help="number of plate generated") parser.add_argument("--variant", type=bool, default=False, help="add a random alphabet at back") parser.add_argument("--state", type=str, default="Penang", help= "The first alphabets for car plate based on state and territory, must enter full state name Example: 'Perak': 'A', 'Selangor': 'B', 'Pahang': 'C', 'Kelantan': 'D', 'Putrajaya': 'F', 'Johor': 'J', 'Kedah': 'K', 'Malacca': 'M', 'Negeri Sembilan': 'N', 'Penang': 'P', 'Perlis': 'R', 'Kuala Lumpur(1)': 'W', 'Kuala Lumpur(2)': 'V', 'Sarawak': 'Q', 'Sabah': 'S'") parser.add_argument("--alphabet_num", type=int, default=3, help="number of alphabet in plate (1 - 3)") parser.add_argument("--number_num", type=int, default=4, help="number of numerical number in plate (1 -4)") parser.add_argument("--font_type", type=str, default="Arial_Bold", help="The font type. There are 'Arial_Bold', 'Charles_Wright'") parser.add_argument("--display", type=bool, default=False, help="display result") args = parser.parse_args() # Main cwd = os.getcwd() destination = cwd + '/data/generated_plates' # Create directory if not exist if not os.path.exists(destination): os.mkdir(destination) gen = Generator() gen.generatePlates(args.plate_type, args.total_plate, args.variant, args.state, args.alphabet_num, args.number_num, args.font_type, args.display)
d91b59ab8550ee5cc7f2d2c6c5e88da53ed7144d
steview-d/practicepython-org-exercises
/practice_python_org/18_cows_bulls.py
815
3.546875
4
from random import randint def compare(guess, answer): bullcow = [0, 0] for x in range(4): if guess[x] == answer[x]: bullcow[0] += 1 else: bullcow[1] += 1 return bullcow if __name__ == "__main__": answer = ''.join([str(randint(0,9)) for x in range(4)]) count = 0 while True: guess = str(input("Guess the 4 digit number > ")) if guess == "cheat": print(answer) continue count += 1 bullcow = compare(guess, answer) if bullcow[0] == 4: print("Well Done! You have correctly identified all 4 numbers.\nIt took you a total of {} guesses".format(count)) break else: print("You have {} bulls and {} cows.".format(bullcow[0], bullcow[1]))
b3ea8d3797a5c55700589cf590a320e8111a4cb4
hgdsraj/pqueue
/pqueue/pqueue/cli.py
570
3.609375
4
import click import sqlite3 conn = sqlite3.connect('queue.db') c = conn.cursor() @click.command() @click.argument('command', default='world', required=False) @click.option('-m', required=False, prompt='Your name', help='The message to push.') @click.command() @click.argument('w', default='world', required=False) @click.option('-c', required=False, prompt='wit', help='www message to push.') def main(command, m): """A command line priority queue for organizing your life!""" click.echo('{0}, {1}.'.format(command, m)) if __name__ == '__main__': main()
389a0eeb65e984713ab701e46474ab7d26ca55b5
nickxu/firstPython
/字符串重复多次.py
144
3.875
4
# coding:utf-8 print("words"*3) word = "it's a looooooong loop" num = 12 bang_str = 'bang!' total_result = bang_str * (len(word) - num) print(total_result)
896f1275f4ec13ba74bfd476ff2f38df11bc0d85
ruthlee/combo_opto
/digraph_class.py
2,009
4.0625
4
# goal: implement an adjacency list class for a digraph given a list of inputs that connect two vertices. # We want methods for adding edges by inputting two integers, i.e., 1, 2 means that vertices 1 and 2 are connected. # since class edge: def __init__(self, v, w, weight): self.v = v self.w = w self.weight = weight class Digraph: ''' Note that the edge will always be represented in the adjacency list as a tuple with (end_vertex, weight). ''' def __init__(self, V): # V is the number of vertices self.V = V self.adj_list = [[] for i in range(V)] # placeholder adjacency list # add edge def add_edge(self, e): # v, w in V, we will add a tuple to the adjacency list. e is an instance of the edge class if e.v > self.V or e.w > self.V: raise ValueError('The vertex labels must be between ' + str(0) + ' and ' + str(self.V)) self.adj_list[e.v].append((e.w, e.weight)) def remove_edge(self, e): if e.v > self.V or e.w > self.V: raise ValueError('The vertex labels must be between ' + str(0) + ' and ' + str(self.V)) self.adj_list[e.v].remove((e.w, e.weight)) def add_edges(self, edges): # takes in a list of edge instances and puts them in D. for i in range(len(edges)): self.add_edge(edges[i]) def remove_edges(self, edges): for i in range(len(edges)): self.remove_edge(edges[i]) def print_digraph(self, long = False): # returns a summary of the digraph, with optional boolean input "long" for a more descriptive output if long: for i in range(len(self.adj_list)): print('Vertex ' + str(i) + ' is adjacent to vertices ', end="") print(*self.adj_list[i]) else: for i in range(len(self.adj_list)): print(str(i) + '->', end='') print(*self.adj_list[i], sep = '->')
c8a52b0cd1fe28e74acccc900e884187715b1961
YeoYeJi0430/Python
/chap5_3.py
1,007
3.921875
4
""" a,b=10,20 print("swap 전", end="") print("a",a,"b",b) a,b=b,a print("swap 후", end="") print("a",a,"b",b) """ """ def call_10_times(func): for i in range(10): func() def print_hello(): print("Hello World") call_10_times(print_hello) """ """ # def power(item): # return item*item #power = lambda item : item * item # def under_3(item): # return item<3 under_3 = lambda item : item < 3 lists = [1, 2, 3, 4, 5] output = map(lambda item: item * item ,lists) print(output) print(list(output)) output_b = filter(lambda item:item<3, lists) print(list(output_b)) """ #파일열고 f = open("./data/basic.txt","w") #파일쓰고 f.write("Hello Python Programming...!!") #파일닫기 f.close() f1 = open("./data/basic.txt","a") f1.write("\nAdded documents") f1.close() with open("./data/tset.txt","a") as f3: # a 는 계속 추가됨 f3.write("\nWith sentence document") content = "" with open("./data/tset.txt","r") as f4: content = f4.read() print(content)
0883c8ac348f0edfae849927c0e466c5e8c2aa7c
RameezFridie/Python-String-manip
/amazon.py
2,485
4.40625
4
# ================= BONUS Optional Task ================== # Create a Python file called "amazon.py" in this folder. # Write code to read the content of the text file input.txt. # For each line in input.txt, write a new line in the new text file output.txt that computes the answer to some operation on a list of numbers. # If the input.txt has the following: # Min: 1,2,3,5,6 # Max: 1,2,3,5,6 # Avg: 1,2,3,5,6 # Your program should generate output.txt as follows: # The min of [1, 2, 3, 5, 6] is 1. # The max of [1, 2, 3, 5, 6] is 6. # The avg of [1, 2, 3, 5, 6] is 3.4. # Assume that the only operations given in the input file are min, max and avg, and that the operation is always followed by a list of comma separated integers. # You should define the functions min, max and avg that take in a list of integers and return the min, max or avg of the list. # Your program should handle any combination of operations and any length of input numbers. # You can assume that the list of input numbers are always valid integers and that the list is never empty. the_file = open('input.txt','r') the_lines = the_file.readlines() the_file.close() temp_line_1 = the_lines[0].split(':') temp_line_1 = temp_line_1[1].split(',') x = (int(i) for i in temp_line_1) x = min(x) temp_1 = the_lines[0].replace('min:','').split() # Did this so that in the file it just prints ['1,2,3,4,5,6'] temp_line_2 = the_lines[1].split(':') temp_line_2 = temp_line_2[1].split(',') y = (int(i) for i in temp_line_2) y = max(y) temp_2 = the_lines[1].replace('max:','').split() # Did this so that in the file it just prints ['1,2,3,4,5,6'] count = 0 total = 0 temp_line_3 = the_lines[2].split(':') temp_line_3 = temp_line_3[1].split(',') for i in temp_line_3: #Checks each position for a number count += 1 # For each i in the loop will add the counter by 1 total += int(i) # Casts the string value at i into an integer then adds it average = total/count temp_3 = the_lines[2].replace('avg:','').split() # Did this so that in the file it just prints ['1,2,3,4,5,6'] out_file = open('output.txt','w') out_file.write('The min of ' + str(temp_1) + ' is ' + str(x) + '\n') out_file.write('The max of ' + str(temp_2) + ' is ' + str(y) + '\n') out_file.write('The avg of ' + str(temp_3) + ' is ' + str(average)) out_file.close()
3f81f6e2490fcc4e6f7f1f0a40830a8941561a88
PeteMcNie/Playground-Typescript-React-Python
/freeCodeCamp2.py
4,949
3.5
4
from flask import Flask app = Flask(__name__) @app.route('/') def python(): myFile = open('data.txt') for each_line in myFile: print(each_line) a_file = open('data.txt') line_count = 0 for new_line in a_file: line_count += 1 print('Line count', line_count) the_file = open('data.txt') a_string = the_file.read() # ONLY READ WHOLE FILES IF THEY ARE SMALL < 200,000 characters print('Number of characters is file', len(a_string)) # prints whole length as file returned as a string print('Only first 30 characters', a_string[:30]) # uses slice to print only first 30 characters search_for = open('data.txt') for each_new_line in search_for: if each_new_line.startswith('Poseidon'): print(each_new_line) #WILL DEFAULT PRINT A NEW LINE (WHICH YOU PROBABLY DONT WANT) search_with_no_new_line = open('data.txt') for no_new_line in search_with_no_new_line: no_new_line = no_new_line.rstrip() # new lines (\n) count as white space so can strip away if no_new_line.startswith('Poseidon'): print(no_new_line) using_in_operator = open('data.txt') for line in using_in_operator: line = line.rstrip() if not 'Athena' in line: # searches for lines WITH Athena in continue print('Only print lines with Athena', line) # file_name = raw_input('Enter a file name to search through: ') # try: # file_handle = open(file_name) # except: # print('File cannot be opened:', file_name) # quit() # Stop executing the rest of this file. We need to provide our own error message above as there will be no traceback # count2 = 0 # for line in file_handle: # if 'Poseidon' in line: # count2 += 1 # print('Lines with Poseidon', count2) #LISTS [] like arrays in JS # LISTs ARE mutable print(['blue', 'red', 'yellow', 24, 89.6]) print(['Dan', 'Steve', [1, 'Snow'], 'Kim']) friends = ['Sam', 'Ari', 'Jake', 'Zac', 'Kim', 'Rikke'] for friend in friends: # This loop is fine if you don't need to know your position in the loop print('Happy Birthday:', friend) print('The end') print(friends[1]) # ari print(len(friends)) # Number of items in a list ie: 6 print(range(3)) # range gives us a list upto that number ie: [0, 1, 2] print(range(len(friends))) # range combined with len give us each index of the list ie: [0, 1, 2, 3, 4, 5] for index in range(len(friends)): # This for statement uses index to find the data stored at each location in the list friend = friends[index] # SAME AS ABOVE LOOP BUT USES INDEX print('Happy New Year:', friend) #You can add lists together like this: a = [1, 2, 3] b = [5, 6, 7] c = a + b print('Two lists added together', c) #LIST SLICING my_list = [3, 94, 75, 63, 7, 800, 19, 10, 151, 812, 1, 14] print(my_list[1:3]) print(my_list[:4]) print(my_list[5:]) print(my_list[:]) #LIST METHODS stuff = list() # makes an empty list stuff.append('book') stuff.append(56) print(stuff) print(94 in my_list) print(10 in my_list) print(24 not in my_list) print('Pre-sort', my_list) my_list.sort() print('Sorted', my_list) print(len(my_list)) print(max(my_list)) print(min(my_list)) print(sum(my_list)) print(sum(my_list)/len(my_list)) # total = 0 # Create a for loop to add up the values of numbers input into the computer, the find average # count = 0 # while True: # inputt = input('Enter a number: ') # if inputt == 0 : # break # value = float(inputt) # total += value # count += 1 # average = total / count # print('Average is:', average) # Create a list to add numbers to, then find average # new_list = list() # while True: # inputt2 = input('Enter a number: ') # if inputt2 == 0 : break # new_list.append(inputt2) # print(sum(new_list)/len(new_list)) #SPLIT METHOD abc = 'Here are the words' stuff = abc.split() print(stuff) print(len(stuff)) print(stuff[1]) for word in stuff: print(word) print('done') spaces = 'Here is a ton of spaces ' lets_split = spaces.split() print(lets_split) #Ignores extra spaces text = 'Posiedon;Athena;Zeus;Apollo' # attemp_to_split = text.spilt() # Does not work as no spaces to 'split' between. # print(attemp_to_split) actual_split = text.split(';') print(actual_split) email_line = 'From: [email protected] Fri Jan 6 03:45:34 2008' split_email_line = email_line.split() print(split_email_line) print(split_email_line[2]) email = split_email_line[1] part_of_email = email.split('@') print(part_of_email[1]) return 'and here we go'
6cf271f3348e29d6d89ba9c33fc8399472ac0cb2
alinasansevich/hello-world
/black_friday_must_do.py
785
3.9375
4
# Inspired by the book "Automate the boring stuff with Python" def print_list(items_dict, left_width, right_width): print('SHOPPING LIST'.center(left_width + right_width, '-')) for k, v in items_dict.items(): print(k.title().ljust(left_width, '.') + str(v).rjust(right_width, ' ')) black_friday_wish_list = {'electronics': 2200, 'for the house': 250, 'toys': 320, 'clothes': 180, 'shoes': 130, 'hobbies': 190} def how_much_is_it(items_dict, left_width, right_width): total = 0 for v in items_dict.values(): total += v print('\nTotal'.ljust(left_width, '.') + str(total).rjust(right_width, ' ')) print_list(black_friday_wish_list, 20, 5) how_much_is_it(black_friday_wish_list, 21, 5) print("\n\t...and that's when I decide not to buy anything!")
0e8ddff2f59cf42b6d27c89f8832c33dd3aaab86
USCO-CO/test
/guess.py
717
3.859375
4
from random import randint def getRandomNumber (): return (randint(0,100)) def askUser (): num = raw_input("Give me a number: ") return int(num) def compGetNum (): return (randint(0,100)) count = 1 correct = False print "Welcome to the guessing game. Try to pick a number between 1 and 100 before the computer does" answer = getRandomNumber() print answer while correct != True: guess = askUser() compGuess = compGetNum() if guess < answer: print "Your guess of %s is too low" % guess count = count + 1 elif guess > answer: print "Your guess of %s is too high" % guess count = count + 1 else: print "Correct! %s was the number and it took you %s guesses" % (guess, count) correct = True
107497743ad5d5edb4f1183e32f90b50166abbc9
JaimePazLopes/dailyCodingProblem
/problem047.py
2,338
3.84375
4
# Problem #47 [Easy] # Given a array of numbers representing the stock prices of a company in chronological order, # write a function that calculates the maximum profit you could have made from buying and selling that stock once. # You must buy before you can sell it. # # For example, given [9, 11, 8, 5, 7, 10], you should return 5, # since you could buy the stock at 5 dollars and sell it at 10 dollars. # instantly went for this n² time solution, but after i could see a linear one def maximum_profit(array): biggest_profit = 0 # take one price for outer_index in range(len(array[0:])): buy_price = array[outer_index] # and compare to all other prices for inner_index in range(outer_index + 1, len(array)): sell_price = array[inner_index] # check for profit profit = sell_price - buy_price # if the profit is bigger, update it if profit > biggest_profit: biggest_profit = profit return biggest_profit assert maximum_profit([9, 11, 8, 5, 7, 10]) == 5 assert maximum_profit([9, 11, 8, 10, 7, 10]) == 3 assert maximum_profit([6, 11, 8, 10, 7, 1]) == 5 assert maximum_profit([]) == 0 assert maximum_profit([1]) == 0 assert maximum_profit([5, 2]) == 0 def maximum_profit_linear(array): biggest_profit = 0 if not array: return biggest_profit # take one price price_check = array[0] # and compare with the next price for price in array[1:]: # calculate profit profit = price - price_check # if profit increased, update if profit > biggest_profit: biggest_profit = profit # if there is lower price, update if price_check > price: price_check = price return biggest_profit assert maximum_profit_linear([9, 11, 8, 5, 7, 10]) == 5 assert maximum_profit_linear([9, 11, 8, 10, 7, 10]) == 3 assert maximum_profit_linear([6, 11, 8, 10, 7, 1]) == 5 assert maximum_profit_linear([]) == 0 assert maximum_profit_linear([1]) == 0 assert maximum_profit_linear([5, 2]) == 0 # easy problem, the first solution came instantly, the second one i need to iterate on the first some times to see that # nested loops are not necessary. 30 minutes to do everything
7cbd4fcf8326f01a51def77e8dc8584b5a98d4a1
serg-myst/GEEK_Lessons
/Lesson 3/korzhov_sergey_lesson_3_task_3.py
844
3.8125
4
def my_func(*args): my_dict = {} for name in args: """Отбираем имена по первой букве в цикле filter(lambda el: el[:1] == name[:1]""" my_dict.update({name[:1]: list(filter(lambda el: el[:1] == name[:1], args))}) return my_dict result = my_func('Марья', 'Иван', 'Света', 'Петя', 'Марсель', 'Павел', 'Илларион', 'Прошка', 'Сергей') print(result) # Отсортируем словарь по ключам. Воспользуемся встроенной функцией sorted() # Полученный результат - новый объект Список. Обернем его обратно в словарь dict() print('Отсортированный по ключам словарь') print(dict(sorted(result.items())))
4389e4edd9797bb6584988b59d17f7acb51983a1
TheIrresistible/Python_Advanced_ITEA
/5/3.py
593
3.796875
4
class File: def __init__(self, name, action): self.name = name self.action = action self.status = 1 def __enter__(self): self.file = open(f'{self.name}', f'{self.action}') if self.status == 1: return self.file raise ValueError def __exit__(self, exc_type, exc_val, exc_tb): print(exc_type, exc_val, exc_tb) if exc_val == ValueError: print('You did something wrong with values') self.file.close() self.status = 0 with File('file.txt', 'w') as f: f.write('Hello world!')
a51bf5a90f3b187283e95a7eb6a693ee07ab2524
dipo7/gitload
/rough2.py
392
3.734375
4
def number_palondrome(x, y=0, z=0): steps = 1 y = str(x) y = y[::-1] z = x + int(y) end_sum = True while end_sum: if z == int(str(z)[::-1]): end_sum = False return(steps, z) else: x, y, z = z, str(x)[::-1], x + int(y) number_palondrome(x, y, z) steps += 1 x = number_palondrome(195) print(x)
9ac3559f256fad5ff6b2e750bcad512fbcc5c5cc
imzeki/coconut
/maths.py
1,279
4.03125
4
""" Stores math equations and formulas inside """ class EMC2Error(BaseException): """ Error called when EMC2 gone wrong """ pass pi = 3.1415926535897932385 e = 2.7182818284590452354 sqrt2 = 1.4142135623730950488 sqrt5 = 2.2360679774997896964 phi = 1.6180339887498948482 ln2 = 0.69314718055994530942 ln10 = 2.302585092994045684 euler = 0.57721566490153286061 catalan = 0.91596559417721901505 khinchin = 2.6854520010653064453 apery = 1.2020569031595942854 logpi = 1.1447298858494001741 def mean(*l: int or float) -> int or float: """ Returns the average of the numbers full of integers and floats, any other types will be discluded. """ l = list(l) average = sum([i for i in l if type(i) in [int, float]]) average = average / len(str(average)) if average.is_integer(): return int(average) else: return average def median(*l): return l[min(range(len(l)), key=lambda i: abs(l[i] - mean(l)))] def EMC2(M: int or float): """ Calculates the famous equation from Einstein E = MC2 """ if type(M) in [int, float]: return M * ((3 * (10 ** 8)) ** 2) else: raise EMC2Error("E = mc2 went wrong as M is not an integer or float")
d5290cdf0322731aeb02562035ba6f84246b4f7c
treasureb/Python
/day9/map.py
274
3.890625
4
#-*- coding: utf-8 -*- #map()接收一个函数f和一个list #通过f一次作用在list的每个元素上 def f(x): return x*x print map(f,[1,2,3,4,5,6,7,8,9]) def format_name(s): return s[0].upper()+s[1:].lower() print map(format_name,['adma','LISA','barT'])
786e1e1e027f3e01cebd46dd3154e935e5d83e64
hanhuyeny2k/holbertonschool-web_back_end
/0x0D-NoSQL/11-schools_by_topic.py
267
3.625
4
#!/usr/bin/env python3 """function that returns the list of school having a specific topic""" import pymongo def schools_by_topic(mongo_collection, topic): """query documents in collection""" return mongo_collection.find( {"topics": topic} )
12a76639711736e8a773560a8d96ea6d91455884
avinash-rath/pythonlab
/numpat.py
120
3.734375
4
n = 1 while n <= 9: k = 1 while k <= n: print(n, end='') k = k+1 print(end='\n') n = n+1
ab94061b34a40e4df6d9cbc5e5c4af5db50a417c
papayetoo/StudyinPython
/LeetCode/repeated_substring_pattern.py
487
3.5
4
class Solution: def repeatedSubstringPattern(self, s: str) -> bool: halfLength = len(s) // 2 + 1 for i in range(halfLength, 0, -1): subStr = s[:i] if subStr * (len(s) // len(subStr)) == s: return True return False def repeatedSubstringPattern2(self, s: str) -> bool: ss = (s + s)[1:-1] return ss.find(s) != -1 if __name__ == '__main__': s = Solution() s.repeatedSubstringPattern2('aba')
64a2aa835d7e892ad7f278b36377fe6de42f5d82
agabhi017/Algortihmic-Toolbox
/Week 3/q7_max_salary_v2.py
643
4.0625
4
import os import numpy as np def compare_numbers(num1, num2) : combo1 = num1 + num2 combo2 = num2 + num1 if combo1 >= combo2 : return num1 else : return num2 def largest_number(numbers) : largest_numb = [] while len(numbers) > 0 : largest_val = numbers[0] for vals in numbers : largest_val = compare_numbers(largest_val, vals) largest_numb.append(largest_val) numbers.remove(largest_val) return int("".join(largest_numb)) if __name__ == "__main__" : n = int(input()) numbers = input().split() print(largest_number(numbers))
779c28f0f3eca0b3c840d5c3aa5456721c82369d
ofirn21-meet/meet2019y1lab5
/lab_5.py
118
3.859375
4
x,y,z = (3,4,5) print(x+y+z) my_tuple = (3,4,5) print(my_tuple+my_tuple) my_tuple[0]=17 print(my_tuple) x=17 print(x)
9e812ec9ca55fd853f83cd7c375734184c918520
iamrishap/PythonBits
/IVCorner/iress/string_change.py
2,877
4
4
''' You will be given 2 strings and need to make the changes below based on the words “nice” and “niece” and others. String 1- if its nice = insert because you’re putting in an extra e to make niece String 2- niece to nice = delete the extra e String 3: form to from = swap String 4: if its identical String 5: impossible ''' def solution(S, T): # write your code in Python 3.6 if S == T: return "NOTHING" elif abs(len(S) - len(T)) > 1: return "IMPOSSIBLE" else: swap_str = None if len(S) == len(T): # Try swapping a character skip_i = len(S) # RISHAP ADDED LATER. SKIP I. for i in range(len(S)): if S[i] != T[i] and skip_i != i: # All values can't be same. So we are just considering the different values # RISHAP ADDED LATER. SKIP I. if i < len(S)-1 and S[i+1] == T[i] and swap_str is None and S[i] == T[i+1]: # Check limits of array swap_str = "SWAP " + S[i] + " " + S[i+1] skip_i = i+1 # RISHAP ADDED LATER. SKIP I. else: return "IMPOSSIBLE" return swap_str elif len(S) > len(T): # Try deleting a character chance = 0 # Only one chance to reedem(delete) j = 0 for i in range(len(S)): if j < len(S): # Checking that j is still in bounds of array length if S[j] == T[i]: j += 1 elif S[j] != T[i] and S[j+1] == T[i] and chance == 0: c_del = S[j] j += 2 chance = 1 else: return "IMPOSSIBLE" return "DELETE " + c_del # If so far it hasn't been impossible, it is possible with deletion else: # Try inserting a character chance = 0 # Only one chance to reedem(insert) j = 0 for i in range(len(S)): if j < len(S): if S[i] == T[j]: if i == len(S) - 1: return "INSERT " + T[i+1] # To handle cases like 'nice' -> 'nicee' j += 1 elif S[j] != T[i] and S[j] == T[i + 1] and chance == 0: c_ins = T[i] j += 2 chance = 1 else: return "IMPOSSIBLE" return "INSERT " + c_ins # If so far it hasn't been impossible, it is possible with insertion return "IMPOSSIBLE" print(solution('form', 'from')) print(solution('form', 'format')) print(solution('front', 'font')) print(solution('alex', 'alexa')) print(solution('olx', 'olax')) print(solution('olax', 'olax'))
79634e67a479e3f268b9061c6174a21919d55ad0
26tanishabanik/Interview-Coding-Questions
/Arrays/MergeTwoSortedArraysWithoutExtraSpace.py
507
4.125
4
""" Given two sorted arrays sort them accordingly with out extra space i.e O(1) Input: ar1[] = {1, 5, 9, 10, 15, 20}; ar2[] = {2, 3, 8, 13}; Output: ar1[] = {1, 2, 3, 5, 8, 9} ar2[] = {10, 13, 15, 20} """ def Merge(a1, a2, n1, n2): for i in range(n1): if a1[i] > a2[0]: a1[i], a2[0] = a2[0], a1[i] key = a2[0] j = 1 while j < n2 and key > a2[j]: a2[j-1] = a2[j] j += 1 a2[j-1] = key
076aba45a5bc725ea97ff099a9a100e079512fec
vunguyenq/adventofcode2019
/00.Code_Template.py
777
3.578125
4
import datetime exec_part = 1 # which part to execute exec_test_case = 1 # 1 = test input; 0 = real puzzle input # Puzzle input INPUT_TEST = ''' ''' INPUT = ''' ''' def parse_input(input): return input.split('\n') def part1(input): result = 0 return result def part2(input): result = 0 return result if __name__ == "__main__": if(exec_test_case == 1): input = INPUT_TEST else: input = INPUT input = parse_input(input) start_time = datetime.datetime.now() if (exec_part == 1): result = part1(input) else: result = part2(input) end_time = datetime.datetime.now() print('Part {} time: {}'.format(exec_part, end_time - start_time)) print('Part {} answer: {}'.format(exec_part, result))
515edaf757665263225289c6415b48417bc9eb5c
stefifm/parciales
/p4_aed_bruera_stefania_59149_1k10/registro.py
2,034
3.578125
4
""" Registro del tipo Mueble """ class Mueble: """ Registro del tipo Mueble """ def __init__(self, cod, nom, pre, tip_mu, mat_pri): self.codigo = cod self.nombre = nom self.precio = pre self.tipo_mueble = tip_mu self.mat_prima = mat_pri def cadena_tipo_mueble(cod_mueble): """ Transforma un número del tipo de mueble en cadena de caracteres :param cod_mueble: la codificación del tipo de mueble :return: La cadena ya transformada """ if cod_mueble < 0 and cod_mueble > 9: return "Valor no válido" tipo_muebles = ("Sillas", "Mesas", "Sofá", "Camas", "Escritorios", "Cómodas", "Biblioteca", "Colchones", "Literas", "Mini Bar") return tipo_muebles[cod_mueble] def cadeba_mat_prima(cod_mat_prima): """ Transforma el código de materia prima en cadena :param cod_mat_prima: la codificación de la materia prima :return: La cadena ya transformada """ if cod_mat_prima < 0 and cod_mat_prima > 14: return "Valor no válido" materias_primas = ("Algarrobo", "Roble", "Metal", "Mármol", "Ébano", "Nogal", "Caoba", "Castaño", "Fresno", "Haya", "Pino", "Plástico", "Cuero", "Tableros MDF", "Aglomerado") return materias_primas[cod_mat_prima] def to_string(mueble): """ Transforma un registro del tipo Mueble en cadena de caracteres :param mueble: el registro de tipo Mueble :return: La cadena del tipo Mueble ya transformada """ r = " " r += "Código: " + str(mueble.codigo) r += " - Nombre: " + mueble.nombre r += " - Precio: " + "$" + str(mueble.precio) r += " - Tipo de Mueble: " + str(mueble.tipo_mueble) + "." + \ cadena_tipo_mueble(mueble.tipo_mueble) r += " - Materia Prima: " + str(mueble.mat_prima) + "." + \ cadeba_mat_prima(mueble.mat_prima) return r
8f8bacb7c0238db9768c9b6c8d460e44621c3cef
ramwin/leetcode
/reshape_the_matrix.py
1,554
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Xiang Wang @ 2017-05-24 16:42:05 import unittest class Solution(object): def matrixReshape(self, nums, r, c): if len(nums) == 0: # nums = [] if c == 0: return [[]] * r else: return [] if len(nums[0]) == 0: if c == 0: return [[]] * r else: return [] if len(nums) * len(nums[0]) != r * c: return nums num_rows = len(nums) num_columns = len(nums[0]) results = [] row_start = -1 column_start = -1 for row in range(r): # print("正在生成矩阵第{0}行".format(row)) tmp = [] for column in range(c): # print("正在生成举证第{0}列".format(column)) column_start = (column_start + 1) % num_columns if column_start == 0: row_start += 1 # print("正在读取原来举证的第{0}行第{1}列".format(row_start, column_start)) tmp.append(nums[row_start][column_start]) results.append(tmp) return results class Test(unittest.TestCase): def testsolution(self): print('1') a = Solution() nums = [[1,2],[3,4]] self.assertEqual(a.matrixReshape(nums, 1, 4),[[1,2,3,4]]) nums = [[1.2],[3,4]] self.assertEqual(a.matrixReshape(nums, 2, 4),[[1.2],[3,4]]) if __name__ == '__main__': unittest.main()
2c5842ca2ba75871738a8da5f46bb3edb75a5c72
pymft/mft-vanak
/S09/methods/string_methods.py
438
3.8125
4
text = """April is the cruellest month, breeding Lilacs out of the dead land, mixing Memory and desire, stirring Dull roots with spring rain.""" # res = "hello".capitalize() # res = "hello".upper() res = text.title() print(res) num = text.count("the") print(num) indx = text.find("the", 10) print(indx) words = text.lower().split() print(len(words)) uniques = set(words) print(len(uniques)) value = " hello ".strip() print(value)
9ff069b3a4beb61919870a1a1298122de3aa1717
RubennCastilloo/master-python
/10-sets-diccionarios/sets.py
231
3.53125
4
""" SET es un tipo de dato, para tener una colección de valores, pero no tiene ni indice ni orden """ personas = { "Ruben", "Abisai", "Alexandra" } personas.add("Nayelli") personas.remove("Abisai") print(personas)
954c274b8b2a4e673fbdb551220e8521db297820
suganthicj/gangac
/gangac.py
176
3.671875
4
from datetime import datetime s1 = '10:04:00' s2 = '11:03:11' # for example format = '%H:%M:%S' time = datetime.strptime(s2, format) - datetime.strptime(s1, format) print time
cbbd4370df7fe13e72d8a6cd2ee4149b4a7ad950
Breynerr/taller-30-abril
/ejercicio#14.py
264
3.8125
4
#calcular la velocidad final aceleracion=float(input("introduce la aceleracion en m/s = ")) tiempo=float(input("introducel el tiempo deseado en segundos = ")) velocidadfinal= (0 + aceleracion)*tiempo print("la velocidad final es = ", velocidadfinal, str ("m/s"))
f3c36f1e46acf5365a1f56da2b14668181551f73
ChrisBentley/cl-draw
/canvas.py
2,554
4.34375
4
""" A canvas class that allows the user to create a canvas of size x,y and draw on it. """ class Canvas(object): def __init__(self, w, h): self.width = w self.height = h # Initialize a canvas of size x by y, filled with spaces self.canvas = [[' ' for x in range(w + 2)] for y in range(h + 2)] # Fill in the borders of the canvas for y in range(h + 2): for x in range(w + 2): if (x == 0 or x == (w + 1)): self.canvas[y][x] = '|' if (y == 0 or y == (h + 1)): self.canvas[y][x] = '-' def draw_line(self, x1, y1, x2, y2): # Check if drawing a vertical line if (x1 == x2): # Switch y values so it always draws in one direction if y1 > y2: y1, y2 = y2, y1 for y in range(y1, (y2+1)): self.canvas[y][x1] = 'x' # Check if drawing a horizontal line if (y1 == y2): # Switch y values so it always draws in one direction if x1 > x2: x1, x2 = x2, x1 for x in range(x1, (x2+1)): self.canvas[y1][x] = 'x' def draw_rectangle(self, x1, y1, x2, y2): # Draw the top horizontal line self.draw_line(x1, y1, x2, y1) # Draw the bottom horizonal line self.draw_line(x1, y2, x2, y2) # Draw the left side vertical line self.draw_line(x1, y1, x1, y2) # Draw the right side vertical line self.draw_line(x2, y1, x2, y2) def fill_area(self, x, y, c): self.colour = c self.coordinates_stack = [] self.coordinates_stack.append([x,y]) while (len(self.coordinates_stack) > 0): for coords in self.coordinates_stack: self.check_coords(coords) self.coordinates_stack.remove(coords) def check_coords(self, coords): x = coords[0] y = coords[1] if (x < 1 or x > self.width): return if (y < 1 or y > self.height): return if (self.canvas[y][x] != '-' and self.canvas[y][x] != '|' and self.canvas[y][x] != 'x' and self.canvas[y][x] != self.colour): self.canvas[y][x] = self.colour self.coordinates_stack.append([(x+1),y]) self.coordinates_stack.append([(x-1),y]) self.coordinates_stack.append([x,(y+1)]) self.coordinates_stack.append([x,(y-1)]) return
dc81c69446ec8cb8475dd6b3c411f5baefe8258d
romanvoiers/Python
/WorkingWithNumbers.py
860
4.375
4
from math import * # imports more math functions. Also called a module my_num = 27 my_abs_num = -10 print(1, 2, 3, 4) print(5 + 5) # Don't need variables to do math print(10 * (5 + 5)) print(10 * 5 + 5) # Order of operations print(10 % 3) # Spits out the remainder print(my_num) # Prints out the variable print(str(my_num)) # Converts number into a string print(str(my_num) + " is my Favorite number.") # in order to add strings to a number you need to convert print(abs(my_abs_num)) # Gives the absolute value print(pow(5, 2)) # Pow takes two values. First: num Second: Power of print(max(5, 10)) # Max outputs largest number print(min(5, 10)) # Min outputs lowest number print(round(3.2)) # Rounds the number print(floor(3.945)) # outputs base number print(ceil(3.2)) # Always rounds up print(sqrt(36)) # Squares the number
46d14590841b11c7f56d9f64ada98b4674ef4198
grumpy13/python-foundations
/cashier.py
538
3.90625
4
items = [] item_name = input("Item (enter 'done' when finished): ") while item_name != 'done': price = float(input("Price: ")) quantity = int(input("Quantity: ")) items.append({"name": item_name, "price": price, "quantity": quantity}) item_name = input("Item (enter 'done' when finished): ") print("\nReceipt:\n") total = 0 for i in items: print(str(i["quantity"]) +" "+ i["name"] +" "+ str(i['quantity']*i['price']) + " KD") total = total + i["price"]*i["quantity"] print("\nYour total is %s" %str(total) + " KD")
1d2ac5721b98c046aa30f33ce73977f866e6434d
isensen/PythonBasic
/Tutorials/29_0_常用内建模块(collections).py
2,366
3.78125
4
#coding=utf-8 ''' Python之所以自称“batteries included”,就是因为内置了许多非常有用的模块,无需额外安装和配置,即可直接使用。 ''' __author__ = 'isenen' #--------------------------[collections]----------------------------- # collections是Python内建的一个集合模块,提供了许多有用的集合类 # 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: p = (1, 2) # 但是,看到(1, 2),很难看出这个tuple是用来表示一个坐标的。 # 定义一个class又小题大做了,这时,namedtuple就派上了用场: from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print p.x, p.y, isinstance(p, Point), isinstance(p, tuple) #---------------------------[deque]---------------------------------- # 使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储, # 数据量大的时候,插入和删除效率很低。 # deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈: from collections import deque q = deque(['a', 'b', 'c']) q.append('x') q.appendleft('y') print q #---------------------------[defaultdict]------------------------------ # 使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict: # 除了在Key不存在时返回默认值,defaultdict的其他行为跟dict是完全一样的。 from collections import defaultdict dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' dd['key1'] # key1存在 dd['key2'] #---------------------------[OrderedDict]------------------------------ # 使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。 # 如果要保持Key的顺序,可以用OrderedDict: from collections import OrderedDict d = dict([('a', 1), ('b', 2), ('c', 3)]) print d # dict的Key是无序的 od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) print od # OrderedDict的Key是有序的 #----------------------------[Counter]---------------------------------- # Counter是一个简单的计数器,例如,统计字符出现的个数: from collections import Counter c = Counter() for ch in 'programming': c[ch] = c[ch] + 1 print c
697ba3aa40a21e1b0e9fb4eb24f8c9171c2a93ff
zz-zhang/some_leetcode_question
/source code/257. Binary Tree Paths.py
751
3.59375
4
from utils import TreeNode from typing import List, Optional class Solution: def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: self.res = [] self.dfs(root, '') self.res = [s[2:] for s in self.res] return self.res def dfs(self, node, path): new_path = f'{path}->{node.val}' if not (node.left or node.right): self.res.append(new_path) return if node.left: self.dfs(node.left, new_path) if node.right: self.dfs(node.right, new_path) if __name__ == '__main__': sol = Solution() root_str = '[1,2,2,3,3,null,null,4,4]' root = TreeNode.build_by_str(root_str) print(sol.binaryTreePaths(root))
7f9b1e1f2167291c7c4339916a940cbd0289124c
ChemelAA/scientific_python
/scientific_python/d_scipy/optimize.py
3,894
3.515625
4
#!/usr/bin/env python3 # This file contains examples of usage of scipy.optimize module from __future__ import division import numpy as np from numpy.testing import assert_allclose from scipy import optimize # -- root -- # `root` is a function that solves a vector equation f(x) = 0. It providing # interface to various root-finding methods. All of them perfroms numerical # iteration, so `root` needs an initial approach to a solution. # - 1-D example - def parabola(x): """Equation with a solution of +-sqrt(2)""" return x**2 - 2 result = optimize.root(parabola, 1) # 1 is an initial guess assert isinstance(result, optimize.OptimizeResult) assert result.success assert_allclose(np.sqrt(2), result.x[0]) # .x is an array even in 1-D case # In some cases the optimization will not be success: # Using the default method (at least for scipy v. 1.0): result = optimize.root(parabola, 0, method='hybr') assert not result.success # The optimization can be speeded up by providing Jacobian of the function: def parabola_jac(x): """Jacobian of parabola()""" return 2*x result_w_jac = optimize.root(parabola, 1e-5, jac=parabola_jac, tol=1e-9) assert result_w_jac.success result_wo_jac = optimize.root(parabola, 1e-5, tol=1e-9) assert result_wo_jac.success assert_allclose(result_wo_jac.x[0], result_w_jac.x[0]) # Compare number of function calls: assert result_w_jac.nfev < result_wo_jac.nfev # But call of Jacobian also takes some time! assert result_w_jac.nfev + result_w_jac.njev < result_wo_jac.nfev # - 2-D example - # Let's find a solution of an equation $x^2 + bx + c = 0$. Of course, the right # way to do it is using of polynomial root finding algorithm, but think about # it as an simple example. # Vieta's formulas give $x_0 + x_1 = -b$ and $x_0 x_1 = c$: def vieta(x, b, c): return [x[0] + x[1] + b, x[0] * x[1] - c] def vieta_jac(x, b, c): return [ [1, 1], [x[1], x[0]] ] b, c = -1, -1 result = optimize.root(vieta, [0, 1], args=(b, c), jac=vieta_jac) assert result.success # `numpy.roots(p)` provides roots of polynomial # `p[0] * x**(len(p)-1) + p[1] * x**(len(p) - 2) ... + p[-1]`: roots = np.roots((1, b, c)) assert_allclose(np.sort(roots), np.sort(result.x)) # -- minimize -- # `minimize` provides a common interface to a collection of minimization # methods. See `lmfit` package that provides prettier interface to augmented # collection of methods: https://lmfit.github.io/lmfit-py/ # - Multivariate function - def func(x, a, b): """Negative Gaussian function with argument a*x+b and sigma=10""" y = np.dot(a, x) + b return -np.exp(-np.sum(np.square(y))/200) a = np.array([[1, 2, 3], [1, 1, 1], [0, 0, 1]]) b = np.array([3, 2, 1]) result = optimize.minimize(func, np.ones_like(b), args=(a, b)) assert result.success x = np.linalg.solve(a, -b) assert_allclose(x, result.x, rtol=1e-3) # - Various optimization problems - # A lot of optimization problems can be solved using machine learning methods. # Our days there are a lot of machine learning libraries and frameworks, e.g. # see `scikit-learn` and `TensorFlow`: # http://scikit-learn.org # https://www.tensorflow.org # # Here we solve a simple problem of cluster analysis using the most simple # # approach. Let's consider that we have two comparable sets of objects in # # N-dimensional space and we search the best separating hyperplane between # # them. # from scipy.stats import multivariate_normal as m_normal # mean1 = np.array([1, 2,3]) # mean2 = np.array([-3,-3,5]) # cov1 = np.diag([1.5, 2.0, 2.5]) # cov2 = np.array([ # [ 1.0, -0.3, 0.3], # [-0.3, 2.5, 0.3], # [ 0.3, -0.3, 3.0], # ]) # size = 100 # random_state = np.random.RandomState(13) # Lucky number # y1 = m_normal.rvs(mean=mean1, cov=cov1, random_state=random_state) # y2 = m_normal.rvs(mean=mean2, cov=cov2, random_state=random_state)
9b329683a0fc0f7a011ed5b9face2803e3732b2a
TiborUdvari/Python
/src/Exercice1/conversionTemperatureLigneCommande.py
563
3.71875
4
import sys if(len(sys.argv)!=3): sys.exit("Not the good argument count ... Read the man page, oh wait there isn't one :)") try: temperature = float(sys.argv[1]) conversionVers = str(sys.argv[2]) except ValueError: sys.exit("Should be program.py {NUMBER} {F or C}") if conversionVers != 'C' and conversionVers != 'F' : sys.exit("Second arg must be C or F") if conversionVers == 'C' : resultat = 5/9 * (temperature - 32) elif conversionVers == 'F': resultat = 9/5 * temperature + 32 print('Résultat {0:.2f}'. format(resultat))
cd262b3a03ed06bd03854ac921739a7de64fa178
lalitsharma16/python
/cowANDbulls.py
1,321
3.828125
4
#!/usr/bin/python import random def compare_num(number, user_guess): cowbull = [0,0] # cow , bull for i in range(len(number)): if number[i] == user_guess[i]: cowbull[1] += 1 else: cowbull[0] += 1 return cowbull if __name__=="__main__": playing = True number = str(random.randint(1000,9999)) guesses = 0 print("Let's play a game of Cowbull!") #explanation print("I will generate a number, and you have to guess the numbers one digit at a time.") print("For every number in the wrong place, you get a cow. For every one in the right place, you get a bull.") print("The game ends when you get 4 bulls!") print("Type exit at any prompt to exit.") while playing: user_guess = raw_input("Give me your best guess in 4 digit number like 1234 : ") if user_guess == "exit": break cowbullcount = compare_num(number, user_guess) guesses+=1 print("You have "+ str(cowbullcount[0])+" cows, and " + str(cowbullcount[1]) + " bulls.") if cowbullcount[1]==4: playing = False print("You win the game after "+ str(guesses)+ "! The number was "+str(number)) break else: print("Your guess isn't quite right, try again.")
5285ee882c0ac51baaf71eb222045b12cc08b0b7
GuilhermoCampos/Curso-Python3-curso-em-video
/Pythonteste/test/calculadoradeporcentagem.py
269
3.828125
4
valor = float(input('Digite o Valor que quer aplicar o desconto: R$')) desci = float(input('Digite o desconto que quer aplicar: ')) descf = desci / 100 final = valor - (descf * valor) print('O valor R${} com {}% de desconto será R${:.2f}'.format(valor, desci, final))
4e2c1ab074a704f63ffc452f74fb02956c142595
Dohyun-l/python_basic
/test/test18.py
953
3.625
4
def open_account(): print("새로운 계좌가 생성되었습니다.") open_account() def deposit(balance, money): print("입금이 완료되었습니다. 잔액은 {}원 입니다.".format(balance + money)) return balance + money def withdraw(balance, money): if balance >= money: # 잔액이 출금보다 많으면 print("출금이 완료되었습니다. 잔액은 {}원 입니다.".format(balance-money)) return balance - money else: print("출금이 완료되지 않았습니다. 잔액은 {}원 입니다.".format(balance)) return balance def withdraw_night(balance, money): # 저녁에 출금 commision = 100 return commision, balance - money - commision balance = 0 # 잔액 balance = deposit(balance, 1000) balance = withdraw(balance, 1000) commision, balance = withdraw_night(balance, 500) print("수수료는 {}원이며, 잔액은 {}원입니다.".format(commision, balance))