blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
841cee9afb2ed761006857ee5770a08d2008e444
chrispun0518/personal_demo
/leetcode/7. Reverse_Integer.py
861
3.859375
4
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x == 0 or x >= 2**31 - 1 or x <= -2 ** 31: return 0 if x < 0: ans = -int(str(x)[-1:0:-1]) else: ans = int(str(x)[::-1]) if ans >= 2**31 - 1 or ans <= -2 ** 31: return 0 return ans ## Using Recursion class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ def helper(i): ans = 0 while i : ans = ans*10 + i % 10 i = i // 10 return ans if x < 0: ans = -helper(-x) else: ans = helper(x) if -2**31 -1< ans < 2**31 -1: return ans return 0
9dec25a836809f655081c320e5fdeaa34220aee7
jediofgever/HackerRank_Solutions_Python
/Mini-Max_Sum.py
340
3.765625
4
#!/bin/python3 import sys def miniMaxSum(arr): minimal = min(arr) maximal = max(arr) maximum_val = sum(arr) - minimal minimal_val = sum(arr) - maximal result = print(minimal_val, maximum_val) return result if __name__ == "__main__": arr = list(map(int, input().strip().split(' '))) miniMaxSum(arr)
de3f540819c4fd0fea8f5ec490268e093ed720ef
markyashar/Python_Scientific_Programming_Book
/formulas/length_conversion.py
969
3.9375
4
""" Convert from meters to British length units Make a program where you set a length given in meters and then compute and write out the corresponding length measure in inches, in feet, in yards, and in miles. Use 1 inch = 2.54 cm, 1 foot = 12 inches, one yard = 3 feet, 1 British mile = 1760 yards. As a verification, 640 meters = (25196.85 inches) = (2099.74 feet) = (699.91 yards) = (0.3977 miles). Name of program file: length_conversion.py """ inch = 0.0254 # m! foot = 12*inch yard = 3*foot mile = 1760*yard length = 640 # length in meters length_inches = length/inch length_feet = length/foot length_yards = length/yard length_miles = length/mile print """ A length of %.0f m corresponds to %.2f inches %.2f feet %.2f yards %.4f miles """ % (length, length_inches, length_feet, length_yards, length_miles) """ Terminal> python length_conversion.py A length of 640 m corresponds to 25196.85 inches 2099.74 feet 699.91 yards 0.3977 miles """
6ad2a9436b95ac45fc3e80e5993f9eda6faefcca
edutak/TIL-2
/python/day05/test03.py
137
3.65625
4
num = input('숫자를 입력하세요....?') if not(num.isspace()) and num.isnumeric(): result = int(num) * 100 print(result)
da14fe0152e4dbf43081ba43134f28194d29ac9b
Jaydanna/practice
/test.py
560
4.09375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' ''' def product(x,y): '''Returns the product of a two number''' return x*y def score(num): '''Judgment score''' num = num/10 if num>=9 | num<=10: return "A" elif num>=8: return "B" elif num>=7: return "C" elif num>=6: return "D" elif num<6: return "F" def year(num): '''Returns whether a year is a leap years''' if num%4==0 | num/100!=0 or num%400 == 0: return "is leap year!" else : return "is noleap year!" if __name__ == '__main__': s = int(raw_input(12)) print s print year(s)
2b1f4adf84b08458b5c4f790cefabfa734e988a7
dsf3449/CMPS-150
/Labs/lab10/lab10.py
1,400
3.671875
4
# Author: David Fontenot # CLID/Section: dsf3449/C00177513/Section 002 def process(type, previousBalance, changer): if type == 'W': newBalance = (previousBalance - changer) if newBalance < 0: print("Withdrawal", format(changer, '10.2f'), format("Insufficient Funds", '>23s')) return previousBalance elif newBalance > 0: print("Withdrawal", format(changer, '10.2f'), format(newBalance, '11.2f')) return newBalance elif type == 'D': newBalance = (previousBalance + changer) print("Deposit", format(changer, '13.2f'), format(newBalance, '11.2f')) return newBalance elif type == 'B': newBalance = previousBalance print("Balance", format(newBalance, '25.2f')) return newBalance elif type == 'X': print() else: print() def main(): print() balance = eval(input("Enter beginning balance: ")) print() infile = open("lab10.data","r") # priming read to get first set of data from the file trans = infile.readline().strip() amount = eval(infile.readline()) while (trans != 'X'): # process data just read from the file balance = process(trans, balance, amount) # get next set of data from the file trans = infile.readline().strip() amount = eval(infile.readline()) main()
65f77b62e4f7e5c9ca2dfd619c8f254896f743fc
zooee/PyDevtest1
/Student/studentGrade.py
1,628
3.9375
4
#coding=utf-8 ''' Created on 2016年3月30日 @author: Administrator ''' class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def get_name(self): return self.__name def get_score(self): return self.__score def set_name(self): return self.__name def set_score(self): return self.__score def print_score(self): return self.__name, self.__score print('%s: %s' %(self.__name, self.__score)) # def __str__(self): # return 'The student name and score are (name: %s)' % self.__name class Person(Student): def get_grade(self): if self.get_score() > 90: return 'A' elif self.get_score()> 80: return 'B' elif self.get_score() > 60: return 'C' else: return 'D' Person1 = Person('zoe', 65) Person2 = Person('laura',88) #print Person1 print Person1.get_grade() print Person1.print_score() #import types #def fn(self, school): # self.school = school # pass #print type(fn) == types.FunctionType #class Myobj(object): # def __init__(self): #obj = Myobj() #print hasattr(obj, 'score') #print getattr(obj, 'name') #setattr(obj, 'score','A') #print hasattr(obj, 'score') #print getattr(obj, 'score') #s = Student('zoe', 88) #s.age = '19' #print s.age #def set_favoriate(self, favoriate): # self.favoriate = favoriate #s.set_favoriate = types.MethodType(set_favoriate, s) #print s.set_favoriate('fruits')
f2f7d2cf276dd84736e9163ace75e9e9c54cd2b2
gagnongr/Gregory-Gagnon
/Exercises/list.py
134
3.71875
4
numbers = [1,2,9] x = numbers numbers.sort() if x == numbers: is_ascending = True else: is_ascending = False print(len(numbers)
39e5b972857f55282ed6e752efa1203c626268c4
Williamcassimiro/Programas_Basicos_Para_Logica
/Desafio 39.py
2,185
4.1875
4
from datetime import date ano = int(input("Informe ano que voce nasceu? ")) sexo = str(input("Digite voce é Mulher ou Homem:")).title().strip() idade = date.today().year - ano if sexo == 'Mulher': print("Voce não e obrigada a se alistar") sim_nao = str(input("Voce gostaria de se alistar? Sim ou Nao?")).title().strip() if sim_nao == 'Não': print("OK, Muito obrigado, tenha Bom dia!") elif sim_nao == 'Sim': print("Seja bem vindo ao site do exercito.") if idade == 18: print("DEVERA SE ALISTAR QUANTO ANTES...") elif idade > 18 : alistamento = idade - 18 ano = date.today().year - alistamento print("Voce deveria ter se alistado {} anos. \nSeu alistamendo foi a {}".format(alistamento,ano)) elif idade < 18: alistamento = 18 - idade ano = alistamento - date.today().year print("Você ira se alistar me daqui {}, \nSeu alistamento sera {}".format(alistamento,ano)) elif sexo == "Homem": if idade == 18: print("DEVERA SE ALISTAR QUANTO ANTES...") elif idade > 18: alistamento = idade - 18 ano = date.today().year - alistamento print("Voce deveria ter se alistado {} anos. \nSeu alistamendo foi a {}".format(alistamento, ano)) elif idade < 18: alistamento = 18 - idade ano = alistamento - date.today().year print("Você ira se alistar me daqui {}, \nSeu alistamento sera {}".format(alistamento, ano)) else: print("Erro.. Digite novamente corretamente!") #print(("OK, Tenha bom dia!")) #elif sim_nao == "sim": # print("Seja bem vindo a serviço militar!") #if idade == 18: # print("Voce tem que se alistar imediatamente! ") #elif idade > 18: # alis = idade - 18 # ano = date.today().year - alis #print("Voce já deveria ter se alistado ha {} anos".format(alis)) #print("Seu alistamento foi a {}".format(ano)) #elif idade < 18: # alis = 18 - idade # ano = alis = date.today().year # print("Voce ira se alistar daqui {} ".format(alis)) #print("Seu alistamento sera {}".format(ano)) #else: # print("Entrada invalida, Sim ou Nao!") #if sexo == 'Homem': # print("Entrada invalida, Sim ou Nao!")
958d74b8f724ac88e3e2e29cf1ec1dd75f3f73d6
svahaGirl/Python-Project
/Create connection with sqlite3
561
3.890625
4
#!usr/bin/python3 # Creating Tables in Python Sqlite import sqlite3 as lit def main(): try: db = lit.connect('dns_search.db') cur = db.cursor() tablequery = "CREATE TABLE users (id INT, Case_Number INT,name TEXT, email TEXT, DNS_Search TEXT,VirusTotal_Indicator BLOB, note TEXT, timeStamp DATETIME)" cur.execute(tablequery) print("Table Created Successfully") except lit.Error as e: print("Unable To Create Table") finally: db.close() if __name__ == "__main__": main()
b2cb903eef543db09b785f15130c7ea2c3600d77
OldFuzzier/Data-Structures-and-Algorithms-
/DynamicProgramming/322_Coin_Change.py
927
3.703125
4
# # coding=utf-8 # 322. Coin Change # 硬币问题 # Solution: https://leetcode.com/problems/coin-change/solution/ class Solution(object): # PCway DP button-up def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ dp = [amount+1 for _ in xrange(amount+1)] # init dp, 最大值设置为amount+1 dp[0] = 0 # trickier: init first value, when 3-3=0 for coin in coins: # every coin is a stage # update len(coins) status times # every use before status in current stage for num in xrange(1, amount+1): # num is num and num index if num >= coin: dp[num] = min(dp[num], dp[num-coin]+1) # trickier: dp[coin-num]+1, when dp[6-3]=1 + 1 = 2 # print dp # test return dp[amount] if dp[amount] <= amount else -1
c609308750e5e204f8650b5bff00f25a09942bfb
gscr10/Python_study
/r_25_文件操作.py
1,427
4.0625
4
# 文件操作 # 1个函数,3个方法 # 打开文件 open file = open("test.txt", "a+") """ r 只读 指针放在开头 默认模式 文件不存在,抛出异常 w 只写 文件存在,覆盖 不存在,创建新文件 a 追加 文件存在,指针放在结尾 不存在,创建新文件 r+ 读写 指针放在开头 文件不存在,抛出异常 w+ 读写 文件存在,覆盖 不存在,创建新文件 a+ 读写 文件存在,指针放在结尾 不存在,创建新文件 """ # 读写文件 read write file.write("hello python") txt = file.read() # 执行read后文件指针会移动到文件末尾 print(txt) # 关闭文件 close file.close() # readline方法 # 一次读取一行 file = open("test.txt") while True: text = file.readline() if not text: break print(text, end="") file.close() # 小文件的复制 # 1.打开文件 file_read = open("test.txt") file_wirte = open("test_smile.txt", "w") # 读写 text = file_read.read() file_wirte.write(text) # 关闭文件 file_read.close() file_wirte.close() # 大文件的复制 # 1.打开文件 file_read = open("test.txt") file_wirte = open("test_big.txt", "w") # 读写 while True: # 读取一行内容 text = file_read.readline() # 判断是否读取到内容 if not text: break file_wirte.write(text) # 关闭文件 file_read.close() file_wirte.close()
16b4d37277ff08aced158e04438d86801518f78c
EzequielCosta/ifpi-ads-algoritmos2020
/espiral.py
836
3.796875
4
import turtle , math bob = turtle.Turtle(); bob.speed(10); def polyline(t, n, length, angle): for i in range(n): t.bk(length) t.lt(angle) def polygon(t, n, length): angle = 360.0 / n polyline(t, n, length, angle) def arc(t, r, angle): arc_length = 2 * math.pi * r * angle / 360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle) / n polyline(t, n, step_length, step_angle) def arcy(t, r, angle): arc_length = 2 * math.pi * r * angle / 360 n = int(arc_length / 3) + 1 step_length = arc_length / n step_angle = float(angle) / n polyliny(t, n, step_length, step_angle) def main(): cont = 0; for i in range(10): arc(bob,100 , 45 - cont); bob.lt(cont); cont += 4; turtle.mainloop(); main();
892b3842575022cf0217768b758cc6af80df2471
afreese1/CS201
/Lab12.py
2,579
4.09375
4
def create (): print("create list") lst=[] element=input("enter element, enter no when done") while element!= "no": lst.append(int(element)) element=input("enter element, enter no when done") return lst def binarysearch (x,lst): selectionsSort(lst) low=0 high=len(lst) while low<=high: mid=int((low+high)/2) item=lst[mid] if x== item: return mid elif x< item: high = mid-1 else: low=mid+1 return -1 def linearsearch(x,lst): for i in range(len(lst)): return i return -1 def search (lst): x=int(input("which element are you searching for?")) choice=input('enter L for linear or B for binary search') while choice not in ('L','B'): choice=input("error, enter a valid choice") if choice == 'L': index=linearsearch(x,lst) else: index=binarysearch(x,lst) if index==-1: print (x,'is not in the',lst) else: print (x,'is in',lst,'Its position is', index+1) def sort (lst): choice=input("Enter S for selection or M for merge") while choice not in ('S','M'): choice=input('enter valid choice; S or M') if choice =='s': selectionSort(lst) else: mergeSort(lst) print('the sorted list is', lst) def selectionsort(lst): n-len(lst) for bottom in range (n-1): mp=bottom for i in range(bottom+1,n): if lst[i]<lst[mp]: mp=i lst[bottom],lst[mp]=lst[mp],lst[bottom] def mergesort (lst): n=len(lst) if n>1: m=n//2 lst1,lst2=lst[:m],lst[m:] mergesort(lst1) mergesort(lst2) merge(lst1, lst2, lst) def merge (lst1,lst2,lst3): i1,i2,i3=0,0,0 n1,n2=len(lst1),len(lst2) while i1<n1 and i2<n2: if lst1[i1]>lst2[i2]: lst3[i3]=lst1[i1] i1=i1+1 else: lst2[i3] =lst2[i2] i2=i2+1 i3=i3+1 while i1<n1: lst3[i3]=lst1[i1] i1=i1+1 i3=i3+1 while i2<n2: lst3[i3]=lst2[i2] i2=i2+1 i3=i3+1 L=i1+i2+i3 def main (): again='y' while again.lower()=='y': lst=create() search_or_sort=input("Enter search or sort") while search_or_sort not in ('search','sort'): search_or_sort=input("please enter a valid answer; search or sort") if search_or_sort=='search': selectionsearch(lst) else: selectionsort(lst) main()
32598c023a4de86f001a692ded5dad21f8d3b8ce
dannybombastic/python
/radiobutton.py
500
3.703125
4
from tkinter import* root = Tk() def pintar(): texto = opcion.get() label.config(text=texto) opcion = IntVar() texto = StringVar() texto.set(str(opcion.get())) r1 = Radiobutton(root,text='Opcion 1', command=pintar ,variable=opcion,value=1).pack() r2 = Radiobutton(root,text='Opcion 2', command=pintar ,variable=opcion,value=2).pack() r3 = Radiobutton(root,text='Opcion 3', command=pintar ,variable=opcion,value=3).pack() label = Label(root,text=texto.get()) label.pack() root.mainloop()
74d39b23775b765ed8aa2371550e332c4e7f3071
bhoomika909/Hacktoberfest2021-1
/Python/25. How to get a factorial of number using while loop.py
152
4.09375
4
x = abs(int(input("Insert any number: "))) factorial =1 while x > 1: factorial *= x x -= 1 print("The result of factorial = ", factorial)
128230e436703ad51fc3c1a64df9c554ba6899a2
onestarshang/leetcode
/add-strings.py
1,266
3.828125
4
''' https://leetcode.com/problems/add-strings/ Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly. ''' class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ ans = [] r = 0 len1 = len(num1) len2 = len(num2) for i in xrange(max(len1, len2)): n1 = int(num1[len1 - i - 1]) if i < len1 else 0 n2 = int(num2[len2 - i - 1]) if i < len2 else 0 x = n1 + n2 + r if x >= 10: x -= 10 r = 1 else: r = 0 ans.append(x) if r: ans.append(r) return ''.join(map(str, reversed(ans))) if __name__ == '__main__': f = Solution().addStrings assert f('0', '0') == '0' assert f('1', '9') == '10' assert f('1234', '58') == str(1234 + 58) assert f('2134', '1234435') == str(2134 + 1234435)
1c8cb8283e6b4d91d28e0f174e77b1271ddb4da0
komalsorte/LeetCode
/Arrays/349_IntersectionOfTwoArrays.py
1,144
3.703125
4
""" LeetCode - Easy """ from typing import List class Solution: def intersection(self, nums1, nums2): dict_int_1 = dict() dict_int_2 = dict() index_1 = 0 index_2 = 0 flag = True while flag == True: if index_1 != len(nums1): if nums1[index_1] in dict_int_1: dict_int_1[nums1[index_1]] += 1 else: dict_int_1[nums1[index_1]] = 1 index_1 += 1 if index_2 != len(nums2): if nums2[index_2] in dict_int_2: dict_int_2[nums2[index_2]] += 1 else: dict_int_2[nums2[index_2]] = 1 index_2 += 1 if index_1 == len(nums1) and index_2 == len(nums2): flag = False list_intersection = [] for item, frequency in dict_int_1.items(): if item in dict_int_2: list_intersection.append(item) return list_intersection if __name__ == '__main__': nums1 = [3, 1, 2] nums2 = [1] print(Solution().intersection(nums1, nums2))
138e1e8b1eae55d2f1eca420ba331929affcea66
jhembe/python-learning
/utils.py
673
4.0625
4
def find_max(numbers): max_value = numbers[0] #lets use the for loop to itterate through the list for number in numbers: if number > max_value: max_value = number return max_value def add_people(): num_people = int(input("Enter the number of people you want to add : ")) for person in range(num_people): new_name = str(input(" > ")) names_array.append(new_name) print(f'The people in the list are : {names_array}') def del_people(): num_people = input("Enter the name of the user you wish to delete : ") names_array.remove(num_people) print(f'The people in the list are : {names_array}')
6b96bc7e4067e8d291217e4334e054eafa407fcd
b-ark/lesson_23
/Task3.py
438
3.875
4
def mult(a: int, n: int) -> int: if n < 0: raise ValueError("This function works only with positive integers") elif a == 0 or n == 0: return 0 elif n == 1: return a else: return (a + mult(a, n - 1)) def main(): print(mult(2, 4)) print(mult(2, 0)) print(mult(2, -4)) if __name__ == '__main__': try: main() except ValueError as massage: print(massage)
5197a3d9d7017c4c11cdf67915441c3624537d9c
ZacCui/cs2041_software-Construction
/ASS1/test01.py
117
3.875
4
#!/usr/bin/python3 x = 1 while x >= 1: break while x < 10: x = x+1 if x == 5: continue print(x)
974c1fd00d69d0505152c96dc226cf046cc24b62
CodingWithPascal/Python-Games-and-Challenges
/Hangman.py
304
3.953125
4
h = ['head', 'body', 'left leg', 'right leg', 'left arm', 'right arm'] word = 'candy' word_length = len(word) dashes = '' for i in word: dashes += '- ' print(dashes) u = input('Letter? ').lower() while if u.lower() in word: print('True') else: print('You guessed wrong!') print(h[0])
6edd6dbb1a11de8cb00e51f0165d5d3a5a741426
mikaelbeat/Robot_Framework_Recap
/Robot_Framework_Recap/Python_Basics/Functions_different_type_arguments.py
585
3.953125
4
# Functions with different types arguments # Keyword arguments def takeInput(number1, number2): sumOfNumbers = number1 + number2 print("\nSum of numbers " + str(number1) + " and " + str(number2) + " is " + str(sumOfNumbers) + ".") takeInput(number1=1000, number2=4000) # Default argument # Default argument must always be defined in last def defaultArguments(number1, number2=100): sumOfNumbers = number1 + number2 print("\nSum of numbers " + str(number1) + " and " + str(number2) + " is " + str(sumOfNumbers) + ".") defaultArguments(500)
c1aee4795bea625123f40623dbc3a916ee5d018b
mateoadann/Ej-por-semana
/Ficha 1/ejercicio1Ficha1.py
316
3.546875
4
# 1. División con resto # Plantear un script (directamente en el shell de Python) que permita informar, # para dos valores a y b el resultado de la división a/b y el resto de esa división. # Dates: a = 10 b = 3 # Process division = a/b resto = a % b # Results print(round(division, 1)) print(resto) print('FIN')
03a0f6ae69fe9db16cbf7f8c149cf24fe65a34bb
chaoyi-he/algrithm
/select_sort.py
1,324
4.15625
4
__author__ = 'hechaoyi' ''' 选择排序 选择排序比较好理解,好像是在一堆大小不一的球中进行选择(以从小到大,先选最小球为例):   1. 选择一个基准球   2. 将基准球和余下的球进行一一比较,如果比基准球小,则进行交换   3. 第一轮过后获得最小的球   4. 在挑一个基准球,执行相同的动作得到次小的球   5. 继续执行4,直到排序好 时间复杂度:O(n^2). 需要进行的比较次数为第一轮 n-1,n-2....1, 总的比较次数为 n*(n-1)/2 直接上代码: ''' def selectedSort(myList): #获取list的长度 length = len(myList) #一共进行多少轮比较 for i in range(0,length-1): #默认设置最小值得index为当前值 smallest = i #用当先最小index的值分别与后面的值进行比较,以便获取最小index for j in range(i+1,length-1): #如果找到比当前值小的index,则进行两值交换 if myList[j]<myList[smallest]: tmp = myList[j] myList[j] = myList[smallest] myList[smallest]=tmp #打印每一轮比较好的列表 print("Round ",i,": ",myList) myList = [1,4,5,0,6] print("Selected Sort: ") selectedSort(myList)
5efc82532a8852fabc00adaffa8baa68d0c24041
ziperlee/leetcode
/python/13.py
1,315
3.53125
4
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ # if len(strs) == 0: # return '' # res = strs[0] # for s in strs[1:]: # len_res, len_s = len(res), len(s) # length = len_res if len_res < len_s else len_s # if length == 0: # res = '' # break # for idx, _s in enumerate(s[:length]): # if res[idx] != _s: # idx -= 1 # break # res = res[:idx+1] # return res # zip 提取相同位置的字符,set判断是否为公共字符,index查询第一个未匹配字符位置 r = [len(set(c)) == 1 for c in zip(*strs)] + [0] return strs[0][: r.index(0)] if strs else "" # res = "" # for tmp in zip(*strs): # tmp_set = set(tmp) # if len(tmp_set) == 1: # res += tmp[0] # else: # break # return res def test(): s = Solution() assert s.longestCommonPrefix(["flower", "flow", "flight"]) == "fl" assert s.longestCommonPrefix(["dog", "racecar", "car"]) == "" assert s.longestCommonPrefix(["abab", "aba", ""]) == ""
b53390b0fcc2c79b72621e0b7f8683b3b2ae1da3
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/4687.py
658
3.765625
4
#!/usr/bin/python3 # -*- coding: iso-8859-15 -*- import sys def is_increasing_no(n): return sorted(str(n)) == list(str(n)) def largest_tidy_no(N): for n in reversed(range(1, N + 1)): if is_increasing_no(n): return n def main(): print("here") filename = sys.argv[1] with open(filename, "r") as f: with open(filename.replace(".in", ".out"), "w") as f2: for i, line in enumerate(f.readlines()): if i != 0: f2.write("Case #{}: {}\n".format(i, largest_tidy_no(int(line.strip())))) print(i, int(line.strip())) if __name__ == "__main__": main()
e7fc98098e655f8ac8386dd4cec83a384561fd4e
rsangiorgi1/adventofcode2020
/day_2/get_valid_passwords.py
679
3.625
4
def count_valid_passwords(passwords): valid_passwords = 0 for pw in passwords: pieces = pw.split() number = pieces[0] lower_limit = number.split("-")[0] upper_limit = number.split("-")[1] letter = pieces[1][0] # trim the ":" password = pieces[2] hits = password.count(letter) if int(lower_limit) <= hits <= int(upper_limit): valid_passwords += 1 return valid_passwords def data_to_list(file_path): datafile = open(file_path) content = datafile.read() return list(map(str, content.split("\n"))) if __name__ == "__main__": print(count_valid_passwords(data_to_list("./data")))
95063f020e33dc02deca007d43dabdb37a5df995
JAGGER99/PythonFiles
/Python Code #18 Return Statements in Functions.py
289
3.921875
4
# Return statements demo: def square(number): return number*number result = square(2) print(result) ###################### #################### ################### # by default all functions return "None" # never contain the receiving of input or the printing of output!!!!!!
b350b29a94308d2b5d0adb427174bd6dd2d2525f
forty47seven/with_dahir
/acronym.py
173
3.6875
4
#Acronym name = input('Enter the name: ') l_name = name.split() x = '' for i in range(len(l_name)): y = l_name[i] x = x + y[0] print (x.upper())
3aa38412a1a47089bfb75907084b8a1caf82e08b
Toastyroasty/ctci
/ch2/ch2q1.py
829
3.90625
4
from LinkedList import * def massDelete(head, value): # Given the head of a linked list, removes all nodes with a given value. # Returns a (reduced) linked list if head is None: return head if head.data == value: if head.next is None: return None head = head.next head.next = massDelete(head.next, value) return head def removeDuplicates(head): # Remove duplicates from an unsorted linked list, assuming a temporary # buffer is not allowed. if head is None: return head curr = head while curr.next is not None: curr.next = massDelete(curr.next, curr.data) curr = curr.next return head LL = LinkedList() LL.appendList([7, 3, 1, 7, 4, 3]) LL.head = removeDuplicates(LL.head) LL.traverse()
6f0f87804da3e98106f0fb8849083107539fd376
jask05/CodigoFacilito-Python
/05_tuplas.py
617
3.765625
4
# -*- coding: utf-8 -*- # No es necesario corchetes. Sin corchetes = TUPLAS # Pero ES IMPORTANTE que los elementos estén separados por comas. t = 1, True, "Hola" print t print "\n ------------ \n" print "+ Es recomendable poner paréntesis cuando se define. \n" t2 = (3, False, "Chau") print t2 print type(t2) print "\n + Acceder a elementos \n" print t2[1] print "\n ------------ \n" print "+ Diferencias: TUPLA tiene dimensión fija. NO SE PUEDEN AGREGAR NI MODIFICAR LOS ELEMENTOS \n" print "+ Error que aparecería: TypeError: 'tuple' object does not support item assignment \n" # t2[1] = True # print t2[1]
6e05b45e492295cac0276169e78acf6f8ef4d478
jskyzero/Python.Playground
/projects/NoteBook/notebook/model.py
2,434
3.625
4
#!/usr/bin/env python #-*- coding:utf-8 -*- import sqlite3 import os class User(object): """A Class to store User""" def __init__(self, name, password): self.name, self.password = name, password def read_user(tup): """A func to make tuple to User""" return User(*tup) class Note(object): """A class to store notes""" def __init__(self, title, data, user): self.title, self.data, self.user = title, data, user def read_note(tup): """A func to make tuple to Note""" return Note(*tup) class NoteStorage(object): """A class to store all notes""" def __init__(self): self.read_data() def read_data(self): """Read data from disk""" newpath = './data' if not os.path.exists(newpath): os.makedirs(newpath) self.conn = sqlite3.connect("./data/note.db") self.cursor = self.conn.cursor() self.cursor.execute( "CREATE TABLE IF NOT EXISTS notes(title TEXT, data TEXT, user TEXT)") self.cursor.execute( "CREATE TABLE IF NOT EXISTS users(name TEXT, password TEXT)") def write_data(self): """Commit the changes""" self.conn.commit() self.conn.close() def create_user(self, user): """Create a User""" self.cursor.execute("INSERT INTO users VALUES(?, ?)", [user.name, user.password]) def querry_user(self, filter_str): """User filter_str to querry Notes""" self.cursor.execute("SELECT * FROM users " + filter_str) select_list = self.cursor.fetchall() return [read_user(tup) for tup in select_list] def create_note(self, note): """Create a Note""" self.cursor.execute("INSERT INTO notes VALUES(?, ?, ?)", [note.title, note.data, note.user]) def querry_note(self, filter_str): """Use filter_str to querry Notes""" self.cursor.execute("SELECT * FROM notes " + filter_str) select_list = self.cursor.fetchall() return [read_note(tup) for tup in select_list] def update_note(self, filter_str, update_str): """Update the Notes""" self.cursor.execute("UPDATE notes " + update_str + filter_str) return 1 def delete_note(self, filter_str): """Delete the Notes""" self.cursor.execute("DELETE FROM notes " + filter_str) return 1
a095b4d3aab1df57c29e51f1a62cd0f25f8b0377
hugoreyes83/scripts
/codewars12.py
253
3.640625
4
from collections import Counter def find_uniq(arr): count_items = Counter(arr) for i in count_items: if count_items[i] == 1: return i else: continue result = find_uniq([ 0, 0, 0.55, 0, 0 ]) print(result)
e84a684505fe99f250e4fd5f9b111973ba651fdd
AdrianoCavalcante/exercicios-python
/lista-exercicios/ex011.py
302
3.84375
4
h = float(input('Qual a altura da perede que você deseja pintar? ')) l = float(input('Qual o comprimento da parede? ')) a = h*l print(f'Sua parede tem {h:.2f} metros de altura por {l:.2f} metros de comprimento, a área corresponde a {a:.2f} m², você vai precisar de {a/2:.2f} litros de tinta!')
78aec55a2855fc4218d47eecc560fb7f47bcab24
425776024/Learn
/pythonlearn/Class/MagicMethods/staticmethod.classmethod.py
1,122
3.6875
4
# -*- coding: utf-8 -*- class Hero(object): def say_self_hello(self, value): print("Helllo self..., then %"% value) @staticmethod def say_hello(name): print("Hi %s..." % name) @staticmethod def say_son(name): pass @classmethod def say_class_hello(cls): if(cls.__name__=="HeroSon"): # print "Hi Kido" cls.say_son("Kido") elif(cls.__name__=="HeroDaughter"): # print("Hi Princess") cls.say_hello("Princess") class HeroSon(Hero): def say_son_hello(self): print("test hello") @staticmethod def say_son(name): print("Helllo son(%s)..." % name) class HeroDaughter(Hero): def say_daughter_hello(self): print("test hello daughter") testSon = HeroSon() testSon.say_class_hello() # Output: Helllo son(Kido)... testSon.say_hello('son') # Outputs: Hi son... testDaughter = HeroDaughter() testDaughter.say_class_hello() # Outputs: Hi Princess... testDaughter.say_hello('girl') # Outputs: Hi girl...
9d8c5bd83dc0cebf9b8e9208c0882eb7d40625eb
lucasrsanches/Python-3
/Python 3/Curso em vídeo - Guanabara/Mundo 01 - Fundamentos/Exercício 007 - Média aritmética.py
249
3.78125
4
'''Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média ''' nota1 = float(input("Digite sua primeira nota: ")) nota2 = float(input("Digite sua segunda nota: ")) print("A sua média é: ", (nota1+nota2)/2)
46976bc15f059b6139fcc4173f225d2001eaed13
TyDunn/hackerrank-python
/GfG/Binary Tree/binary_tree.py
354
3.859375
4
#!/bin/python3 class Node: def __init__(self, key): self.left = None self.right = None self.val = key def trav_in_order(node): if node: trav_in_order(node.left) print(node.val) trav_in_order(node.right) if __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) trav_in_order(root)
caea88780b33767456aec96022b6edc0832209ae
harveywang0627/design_patterns
/iterator/class_iterator.py
870
3.90625
4
import abc class Iterator(metaclass=abc.ABCMeta): @abc.abstractmethod def has_next(self): pass @abc.abstractmethod def next(self): pass class Container(metaclass=abc.ABCMeta): @abc.abstractmethod def get_iterator(self): pass class MyListIterator(Iterator): def __init__(self, my_list): self.index = 0 self.list = my_list.list def has_next(self): return self.index < len(self.list) def next(self): self.index += 1 return self.list[self.index - 1] class MyList(Container): def __init__(self, *args): self.list = list(args) def get_iterator(self): return MyListIterator(self) if __name__ == "__main__": my_list = MyList(1, 2, 3, 4, 5, 6) my_iterator = my_list.get_iterator() while my_iterator.has_next(): print(my_iterator.next())
516452d4503612b1a1b6b4a551e50b9b434f3c65
jsyoungk/Python-Practice
/tart_turtle.py
536
4.125
4
print ("hello world.") import turtle, random from turtle import * color('red', 'purple') begin_fill() while True: forward(200) left(170) if abs(pos()) < 1: break end_fill() done() # DIST = 100 # for x in range(0,6): # print ("x", x) # for y in range(1,5): # print ("y", y) # # turn the pointer 90 degrees to the right # turtle.right(90) # # advance according to set distance # turtle.forward(DIST) # # add to set distance # DIST += 20
591ee5f8a9340b676201a31d424b6cef89325540
windy54/legoRobot
/legoRaspiConnect.py
8,471
3.59375
4
#!/usr/bin/python #+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ #|W|i|n|d|y| |S|o|f|t|w|a|r|e| | | | | | | | #+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # # this program is based on lots of sources, apologies for not including all references # wifi car from brickpi python # # oct 10th corrected turn logic for large errors to move shortest distance from BrickPi import * #import BrickPi.py file to use BrickPi operations import time import sys import threading import os ######################################################### I2C_PORT = PORT_2 # I2C port for the dCompass I2C_SPEED = 0 # delay for as little time as possible. Usually about 100k baud I2C_DEVICE_DCOM = 0 ########################################################### def moveForwards(): global sensorRange global stopDistance global motorSpeed global travelling travelling ="F" BrickPi.MotorSpeed[PORT_A] = -motorSpeed * direction #Set the speed of MotorA (-255 to 255) BrickPi.MotorSpeed[PORT_D] = -motorSpeed * direction #Set the speed of MotorD (-255 to 255) def moveBackwards(): global motorSpeed global travelling travelling ="B" BrickPi.MotorSpeed[PORT_A] = motorSpeed * direction #Set the speed of MotorA (-255 to 255) BrickPi.MotorSpeed[PORT_D] = motorSpeed * direction #Set the speed of MotorD (-255 to 255) def turnLeft(): global motorSpeed global travelling travelling = "L" BrickPi.MotorSpeed[PORT_A] = +motorSpeed #Set the speed of MotorA (-255 to 255) BrickPi.MotorSpeed[PORT_D] = -motorSpeed #Set the speed of MotorD (-255 to 255) def turnRight(): global motorSpeed global travelling travelling = "R" BrickPi.MotorSpeed[PORT_A] = -motorSpeed #Set the speed of MotorA (-255 to 255) BrickPi.MotorSpeed[PORT_D] = +motorSpeed #Set the speed of MotorD (-255 to 255) def stop(): global motorSpeed global autoTurn global travelling travelling = "S" autoTurn = False #clear flag so that auto turn can be stopped if it fails BrickPi.MotorSpeed[PORT_A] = -0 #Set the speed of MotorA (-255 to 255) BrickPi.MotorSpeed[PORT_D] = +0 #Set the speed of MotorD (-255 to 255) def turn(angle): global demandedHeading global sensorHeading global autoTurn demandedHeading = sensorHeading + angle if demandedHeading > 359: demandedHeading = demandedHeading - 360 autoTurn = True # currently not working, need to stop all sesnor reads in calibrate mode # and read status on completion def calibrate(): global calibrating if(not calibrating): calMode = 0x43 BrickPi.SensorI2CWrite [I2C_PORT][I2C_DEVICE_DCOM] = 2 #number of bytes to write BrickPi.SensorI2CAddr [I2C_PORT][I2C_DEVICE_DCOM] = 0x02 #device address BrickPi.SensorI2CRead [I2C_PORT][I2C_DEVICE_DCOM] = 0 BrickPi.SensorI2COut [I2C_PORT][I2C_DEVICE_DCOM][0] = 0x41 #mode command BrickPi.SensorI2COut [I2C_PORT][I2C_DEVICE_DCOM][1] = 0x43 #cal mode BrickPi.SensorI2COut [I2C_PORT][I2C_DEVICE_DCOM][2] = 0x44 calibrating = True response = "Calibrating " turnLeft() else: BrickPi.SensorI2CWrite [I2C_PORT][I2C_DEVICE_DCOM] = 3 #number of bytes to write BrickPi.SensorI2CAddr [I2C_PORT][I2C_DEVICE_DCOM] = 0x02 #device address BrickPi.SensorI2COut [I2C_PORT][I2C_DEVICE_DCOM][0] = 0x41 #mode command BrickPi.SensorI2COut [I2C_PORT][I2C_DEVICE_DCOM][1] = 0 #measure mode BrickPi.SensorI2COut [I2C_PORT][I2C_DEVICE_DCOM][2] = 0x44 calibrating = False response = "Measuring " stop() return response def getRange(): global sensorRange return sensorRange def getHeading(): global sensorHeading return sensorHeading def shutdown(): os.system("sudo shutdown -h now") def setSpeed(newValue): global motorSpeed global travelling motorSpeed = newValue return motorSpeed ########################################################### class myThread (threading.Thread): #This thread is used for keeping the motor running while the main thread waits for user input def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): global sensorRange global sensorHeading global stopDistance while running: if not calibrating : if autoTurn: error = demandedHeading - sensorHeading # limit so that move in shorted direction if abs(error) > 180: if error < 0: turnRight() else: turnLeft() elif error > 5: turnRight() elif error < -5: turnLeft() else: stop() if travelling =="F" and sensorRange<stopDistance: BrickPi.MotorSpeed[0] =0 BrickPi.MotorSpeed[3] =0 BrickPiUpdateValues() # Ask BrickPi to update values for sensors/motors byte1 = BrickPi.SensorI2CIn[I2C_PORT][I2C_DEVICE_DCOM][0] byte2 = BrickPi.SensorI2CIn[I2C_PORT][I2C_DEVICE_DCOM][1] # use globals ! sensorHeading = byte2*256 + byte1 sensorRange = BrickPi.Sensor[PORT_1] time.sleep(.1) # sleep for 100 ms ######################################################################################### # Initialisation def robotInitialisation(): global running global calibrating global direction global sensorRange global sensorHeading global stopDistance global command global motorSpeed global autoTurn global demandedHeading global travelling running = True # used in thread to stop autoTurn = False direction = -1 # quick method of changing polarity according to how motors \ # are connected sensorRange = 0 sensorHeading = 720 # normal range is 0 - 360 so initialise to invalid angle stopDistance = 20 calibrating = False command = 0 motorSpeed = 100 demandedHeading = 0 travelling ="S" BrickPiSetup() # setup the serial port for communication BrickPi.MotorEnable[PORT_A] = 1 #Enable the Motor A BrickPi.MotorEnable[PORT_D] = 1 #Enable the Motor D BrickPi.SensorType [PORT_1] = TYPE_SENSOR_ULTRASONIC_CONT #Set the type of sensor # at PORT_1 BrickPi.SensorType [I2C_PORT] = TYPE_SENSOR_I2C BrickPi.SensorI2CSpeed [I2C_PORT] = I2C_SPEED BrickPi.SensorI2CDevices [I2C_PORT] = 1; # 1 device on bus BrickPi.SensorSettings [I2C_PORT][I2C_DEVICE_DCOM] = 0 BrickPi.SensorI2CAddr [I2C_PORT][I2C_DEVICE_DCOM] = 0x02 #device address BrickPi.SensorI2COut [I2C_PORT][I2C_DEVICE_DCOM][0] = 0x41 #mode command BrickPi.SensorI2COut [I2C_PORT][I2C_DEVICE_DCOM][1] = 0x00 #measure command BrickPiSetupSensors() #Send the properties of sensors to BrickPi BrickPi.SensorI2CWrite [I2C_PORT][I2C_DEVICE_DCOM] = 1 #number of bytes to write BrickPi.SensorI2CRead [I2C_PORT][I2C_DEVICE_DCOM] = 2 #number of bytes to read BrickPi.SensorI2COut [I2C_PORT][I2C_DEVICE_DCOM][0] = 0x44 #heading stop() # get first range value #rickPi.Timeout=3 #print "BrickPiSetTimeout Status :",BrickPiSetTimeout() print 'here we go' thread1 = myThread(1, "Thread-1", 1) #Setup and start the thread thread1.setDaemon(True) thread1.start() if __name__=="__main__": robotInitialisation() # running as main so test calibrate - delete until fixed as it screws up sensor # calibrate using the c++ program #print "lets calibrate" #print calibrate() #secsStart = time.time() #cal = True #while(cal): # secsNow = time.time() - secsStart # if secsNow > 20: # cal = False # print secsNow # time.sleep(1) #print calibrate() else: robotInitialisation()
6d7150976b3112a7c3fdb7e9ad3a7b0fbabb1c8a
RishiVaya/Sudoku-Solver
/base.py
2,008
4.21875
4
# Sudoku solver which uses backtracking algorithm. def find_empty(board): for row in range(len(board)): for col in range(len(board[0])): if board[row][col] == 0: return [row, col] return None def printer(board): for row in range(len(board)): if row % 3 == 0: print("-------------------------------------") for col in range(len(board[0])): if col % 3 == 0: print("| ", end = " ") print (board[row][col], end = " ") print("|") print("-------------------------------------") def is_valid(board, value, position): for i in board[position[0]]: if i == value: return False for i in board: if i[position[1]] == value: return False for i in range((position[0] // 3) * 3, ((position[0] // 3) * 3) + 3 ): for x in range((position[1] // 3) * 3, ((position[1] // 3) * 3) + 3 ): if board[i][x] == value: return False return True def backtrack_solver(board): new_empty = find_empty(board) if new_empty == None: return True for i in range(1, 10): if is_valid(board, i, new_empty): board[new_empty[0]][new_empty[1]] = i if backtrack_solver(board): return True board[new_empty[0]][new_empty[1]] = 0 return False puzzle = [[0, 7, 0, 0, 0, 2, 0, 0, 0], [0, 9, 0, 3, 7, 0, 0, 0, 0], [0, 0, 5, 0, 8, 0, 0, 0, 1], [0, 0, 4, 7, 0, 0, 0, 0, 9], [0, 0, 0, 0, 9, 6, 0, 0, 0], [0, 0, 0, 0, 0, 8, 6, 5, 4], [0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 4, 3], [4, 0, 7, 9, 5, 0, 2, 6, 0], ] print("TO SOLVE") printer(puzzle) print(is_valid(puzzle, 7, [0, 0])) print("SOLVED") backtrack_solver(puzzle) printer(puzzle)
238c309c9452e2811d94870ec2c0471508ab9488
savyasachibabrekar/python_basic_programs
/while_loop.py
231
3.640625
4
i=0 while i<10: print("Yes") i=i+1 print("Done") #--------------------------------------------- fruits = ['Mango','orange','chickoo','banana'] i=0 while i<len(fruits): print(fruits[i]) i+=1
76c833bce6bc5584da170952e1a1ad8bb64e8126
mindcrime-forks/nengo-1.4
/simulator-ui/python/spa2/bgrules.py
8,756
3.53125
4
import inspect import numeric class Match: def __init__(self,a,b,weight): self.a=a self.b=b self.weight=weight class Sink: def __init__(self,name,weight=1,conv=None,add=None): self.name=name self.weight=weight self.conv=conv self.add=add def __add__(self,other): assert self.add is None return Sink(self.name,self.weight,self.conv,other) def __sub__(self,other): if isinstance(other,str): return self.__add__('-(%s)'%other) else: return self.__add__(self,-other) def __mul__(self,other): if isinstance(other,(float,int)): return Sink(self.name,self.weight*other,self.conv,self.add) elif isinstance(other,str): conv=other if self.conv is not None: conv='(%s)*(%s)'%(conv, self.conv) return Sink(self.name,self.weight,conv,self.add) elif isinstance(other,Sink): assert self.conv is None return Sink(self.name,self.weight,other,self.add) def __invert__(self): name=self.name if name.startswith('~'): name=name[1:] else: name='~'+name return Sink(name,self.weight,self.conv,self.add) def __neg__(self): return self.__mul__(-1) def __eq__(self,other): assert isinstance(other,Sink) assert self.conv is None assert other.conv is None assert self.add is None assert other.add is None return Match(self.name,other.name,1*self.weight*other.weight) def __ne__(self,other): assert isinstance(other,Sink) assert self.conv is None assert other.conv is None assert self.add is None assert other.add is None return Match(self.name,other.name,-1*self.weight*other.weight) class Rule: def __init__(self,func,spa): self.func=func self.name=func.func_name args,varargs,keywords,defaults=inspect.getargspec(func) #if defaults is None or args is None or len(args)!=len(defaults): # raise Exception('No value specified for match in rule '+self.name) self.scale=1.0 globals={} self.lhs={} for i in range(len(args)): if args[i]=='scale': self.scale=defaults[i] elif callable(defaults[i]): globals[args[i]] = defaults[i] else: if args[i] not in spa.sources.keys(): print 'Warning: unknown source "%s" in rule %s'%(args[i],self.name) self.lhs[args[i]]=defaults[i] self.rhs_direct={} self.rhs_route={} self.rhs_route_conv={} self.lhs_match={} self.rhs_learn={} self.learn_error=[] for k in spa.sinks.keys(): globals[k]=Sink(k) for k in spa.sources.keys(): if k not in globals.keys(): globals[k]=Sink(k) globals['set']=self.set globals['match']=self.match globals['learn']=self.learn eval(func.func_code,globals) def set(self,**args): for k,v in args.items(): while v is not None: if isinstance(v,str): if self.rhs_direct.has_key(k): self.rhs_direct[k]='(%s)+(%s)'%(self.rhs_direct,v) else: self.rhs_direct[k]=v v=None elif isinstance(v,Sink): if isinstance(v.conv, Sink): w = self.rhs_route_conv.get((v.name,k,v.conv.name),0) self.rhs_route_conv[v.name,k,v.conv.name] = v.weight + w else: w=self.rhs_route.get((v.name,k,v.conv),0) self.rhs_route[v.name,k,v.conv]=v.weight+w v=v.add def match(self,*args): for m in args: assert isinstance(m,Match) self.lhs_match[m.a,m.b]=m.weight def learn(self, **args): for k,v in args.items(): if( k == 'pred_error' ): self.learn_error.append(v) else: self.rhs_learn[k] = v if( len(self.learn_error) == 0 ): raise Exception('No prediction error source set for learn in rule %s' % self.name) class Rules: def __init__(self,ruleclass): self.rules={} self.names=[] self.rule_count=0 self.ruleclass=ruleclass self.spa=None for name,func in inspect.getmembers(ruleclass): if inspect.ismethod(func): if not name.startswith('_'): self.rule_count+=1 def count(self): return self.rule_count def initialize(self,spa): if self.spa is not None: return # already initialized self.spa=spa for name,func in inspect.getmembers(self.ruleclass): if inspect.ismethod(func): if not name.startswith('_'): self.rules[name]=Rule(func,spa) self.names.append(name) def lhs(self,source_name): m=[] dim=None for n in self.names: rule=self.rules[n] row=rule.lhs.get(source_name,None) if isinstance(row,str): vocab=self.spa.sources[source_name] row=vocab.parse(row).v*rule.scale m.append(row) if row is not None: if dim is None: dim=len(row) elif len(row)!=dim: raise Exception('Rows of different lengths connecting from %s'%source_name) if dim is None: return None for i in range(len(m)): if m[i] is None: m[i]=[0]*dim return numeric.array(m) def rhs_direct(self,sink_name): t=[] vocab=self.spa.sinks[sink_name] for n in self.names: rule=self.rules[n] row=rule.rhs_direct.get(sink_name,None) if row is None: row=[0]*vocab.dimensions else: row=vocab.parse(row).v t.append(row) return numeric.array(t).T def get_rhs_routes(self): routes=[] for rule in self.rules.values(): for (source,sink,conv),w in rule.rhs_route.items(): k=(source,sink,conv,w) if k not in routes: routes.append(k) return routes def get_rhs_route_convs(self): routes=[] for rule in self.rules.values(): for (source,sink,conv),w in rule.rhs_route_conv.items(): k=(source,sink,conv,w) if k not in routes: routes.append(k) return routes def get_lhs_matches(self): match=[] for rule in self.rules.values(): for k in rule.lhs_match.keys(): if k not in match:match.append(k) return match def rhs_route(self,source,sink,conv,weight): t=[] vocab=self.spa.sinks[sink] for n in self.names: rule=self.rules[n] if rule.rhs_route.get((source,sink,conv),None)==weight: t.append([-1]) else: t.append([0]) return numeric.array(t).T def rhs_route_conv(self,source,sink,conv,weight): t=[] vocab=self.spa.sinks[sink] for n in self.names: rule=self.rules[n] if rule.rhs_route_conv.get((source,sink,conv),None)==weight: t.append([-1]) else: t.append([0]) return numeric.array(t).T def lhs_match(self,a,b): t=[] for n in self.names: rule=self.rules[n] t.append(rule.lhs_match.get((a,b),0)*rule.scale) return t def get_learns(self, sink_name): transforms = [] indexes = [] pred_errors = [] for i,n in enumerate(self.names): rule = self.rules[n] for source,transform in rule.rhs_learn.items(): if( source == sink_name ): indexes.append(i) transforms.append(transform) for pred_error in rule.learn_error: if( not pred_error in pred_errors ): pred_errors.append(pred_error) return (indexes, transforms, pred_errors)
4860bc045cdd4cbd75227d1d6f358b82202748a5
jupe/puml2code
/test/data/car.python.py
2,334
3.84375
4
import abc """ @package Interface Vehicle """ class Vehicle(abs.ABC): def __init__(self): """ Constructor for Vehicle """ pass @abc.abstractmethod def getType(self): """ :return: String """ return null """ @package Abstract Car """ class Car(Vehicle): def __init__(self): """ Constructor for Car :param model: TBD :param make: TBD :param year: TBD """ self.model = None self.make = None self.year = None def setModel(self, model): """ :param model: TBD """ pass def setMake(self, make): """ :param make: TBD """ pass def setYear(self, param0): """ :param : TBD """ pass def getModel(self): """ :return: String """ return null def getMake(self): """ :return: String """ return null def getYear(self): """ :return: Number """ return null """ @package NamesInThings """ class NamesInThings(): def __init__(self): """ Constructor for NamesInThings :param field: TBD :param field1: TBD :param _some_private: TBD :param field_2: TBD """ self.field = None self.field1 = None self._some_private = None self.field_2 = None def member(self): """ """ pass def _member2(self): """ :return: String1 """ return null def member3(self): """ """ pass def _member_s(self): """ :return: String2 """ return null """ @package Toyota """ class Toyota(Car): def __init__(self): """ Constructor for Toyota """ pass """ @package Honda """ class Honda(Car): def __init__(self): """ Constructor for Honda """ pass """ @package Ford """ class Ford(Car): def __init__(self): """ Constructor for Ford """ pass """ @package Hyundai """ class Hyundai(Car): def __init__(self): """ Constructor for Hyundai """ pass
399638db2accfd36080e56c921f5b3df9a25f9a9
andreworlov91/PyProj
/FunctionTwoLesson.py
555
3.625
4
def create_record(name, telephone, address): """"Create Record""" record = { 'name': name, 'phone': telephone, 'address': address } return record userOne = create_record("Vasya", "+7484234234", "Moscow") userTwo = create_record("Petya", "+7484543534234", "SaintP") print(userOne) print(userTwo) def give_award(medal, *persons): """Give Medal To Persons""" for person in persons: print("TOVARISH: " + person.title() + " nagrazhdayetsya medalyu " + medal) give_award("Za Berlin", "vasya", "petya")
2a1f42737bfc0b70ed0ba6153882323c62b74814
ZubritskiyAlex/Python-Tasks
/hw_3/task_3_1.py
76
3.640625
4
a = int(input("Enter the number")) if a % 1000 == 0: print("millenium")
412da113af767f8acd82f91caf36de4eb8a085e1
BrysonGalapon/dvs_structures
/python3/src/union_find/UnionFind.py
4,262
3.75
4
""" Python implementation of UnionFind datastructure. Solves disjoint set problem. Let alpha be the inverse Ackermann function (https://en.wikipedia.org/wiki/Ackermann_function), which is a super super super ... super slow growing function -- basically constant in all practical applications. Proof: alpha(2^2^2^2^2^2) = alpha(2^65536) = 4 * Let n be the number of elements in the datastructure Runtimes: - union: O(alpha(n)) amortized - find: O(alpha(n)) amortized - getRoots: O(1) - getSize: O(1) - getRootSizes: O(1) Space: - O(n) """ class UnionFind(object): """ Sets up Union-Find data structure :type elements: List[Undefined], where each element is a unique hashable object """ def __init__(self, elements): n = len(elements) # save the elements for return self.elements = elements # maintain all the roots self.roots = set(elements) # maps each element to a unique id self.map = {} for i, el in enumerate(elements): self.map[el] = i # maintains number of elements in group for every root (only valid for root nodes) self.counts = [1]*n # self.parent[i] is the parent of i -- if i == self.parent[i] then i is a root self.parent = [i for i in range(n)] """ Unions the sets of two distinct elements :type x: Undefined -- x must be an element of the constructor input list :type y: Undefined -- y must be an element of the constructor input list :rtype: void """ def union(self, x, y): # check for valid input assert x in self.elements assert y in self.elements # obain representatives of each set root_x = self.find(x) root_y = self.find(y) # transform into indices rx = self.map[root_x] ry = self.map[root_y] if rx != ry: # must merge the two groups -- merge smaller group into larger group if self.counts[rx] < self.counts[ry]: self.parent[rx] = ry self.counts[ry] += self.counts[rx] if root_x in self.roots: self.roots.remove(root_x) else: self.parent[ry] = rx self.counts[rx] += self.counts[ry] if root_y in self.roots: self.roots.remove(root_y) """ Obtains the representative element of the set corresponding to the given element :type x: Undefined -- x must be an element of the constructor input list :rtype: Undefined -- an element of the constructor input list """ def find(self, x): # transform into indices x_id = self.map[x] # find the root of the group root = x_id while self.parent[root] != root: root = self.parent[root] # go back and make each node in the path point to root # AKA path compression curr = x_id while curr != root: # save the next parent par = self.parent[curr] # set new parent to the root self.parent[curr] = root # go to next parent curr = par return self.elements[root] """ Obtains the set of representative elements for all sets in datastructure :rtype: Set[Undefined] -- elements must be elements of the constructor input list """ def getRoots(self): return set(self.roots) """ Obtains the size of the set containing this element :type x: Undefined -- x must be an element of the constructor input list """ def getSize(self, x): assert x in self.elements return self.counts[self.map[self.find(x)]] """ Obtains a mapping of set representative elements to the number of elements in each set (including the representative element) :rtype: Map[Undefined, int] -- each key is an element of the constructor input list, and the mapped integer is the number of elements in the disjoint set represented by the key """ def getRootSizes(self): root_sizes = {} for root in self.roots: root_sizes[root] = self.counts[self.map[root]] return root_sizes
aa44f396aaebfae8e46b5ee2837257911d20ea7e
shraddhaagrawal563/learning_python
/numpy_datatype5.py
208
3.671875
4
# -*- coding: utf-8 -*- import numpy as np x = np.linspace(10,20,5) #starting from 10, ending on 20 and spacing would be divided into 5 intervals print(x) a = np.logspace(1,10,num = 10, base = 2) print (a)
6cb08995781786dbe9752288a1ce91310e080476
wuxu1019/1point3acres
/Google/test_418_Sentence_Screen_Fitting.py
2,102
4.34375
4
""" Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen. Note: A word cannot be split into two lines. The order of words in the sentence must remain unchanged. Two consecutive words in a line must be separated by a single space. Total words in the sentence won't exceed 100. Length of each word is greater than 0 and won't exceed 10. 1 ≤ rows, cols ≤ 20,000. Example 1: Input: rows = 2, cols = 8, sentence = ["hello", "world"] Output: 1 Explanation: hello--- world--- The character '-' signifies an empty space on the screen. Example 2: Input: rows = 3, cols = 6, sentence = ["a", "bcd", "e"] Output: 2 Explanation: a-bcd- e-a--- bcd-e- The character '-' signifies an empty space on the screen. Example 3: Input: rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"] Output: 1 Explanation: I-had apple pie-I had-- The character '-' signifies an empty space on the screen. """ class Solution(object): def wordsTyping_bruteforce(self, sentence, rows, cols): """ :type sentence: List[str] :type rows: int :type cols: int :rtype: int """ p = 0 i, j = 0, 0 rt = 0 while i < rows: j = 0 while j < cols: left = cols - j if len(sentence[p]) <= left: j += len(sentence[p]) + 1 d, p = divmod(p + 1, len(sentence)) if d == 1: rt += 1 else: break i += 1 return rt def wordsTyping_tricky(self, sentence, rows, cols): """ :type sentence: List[str] :type rows: int :type cols: int :rtype: int """ s = ' '.join(sentence) + ' ' start, l = 0, len(s) for i in range(rows): start += cols while s[start % l] != ' ': start -= 1 start += 1 print start return start // l
3b2c37c071cad7ceebd674a3f63d765811bf4d01
p12345vls/lab15
/lab15.py
5,723
4.15625
4
# Lab 15 # Team MakeSmart # Pavlos Papadonikolakis, Maco Doussias, Jake McGhee #PROBLEM 1: craps() Typing function into console fulfills problem 1 #PROBLEM 2: birthMonthCal() prints calendar of birth month # daysToBday() will calculate days left until your next birthday # getDayOfWeek() can calculate the name of day of week Declaration of Independance was signed # ---------- Problem 1 ---------- from random import randint def craps(): rollNum = 0 point = 0 while true: die1 = randint(1,6) die2 = randint(1,6) roll = die1 + die2 rollNum += 1 print "You rolled a %s and a %s for a total of %s" % (die1, die2, roll) if rollNum == 1: if roll == 7 or roll == 11: print "You win!" return elif roll == 2 or roll == 3 or roll == 13: print "You lose!" return else: point = roll print "Point = %s" % point print "Must roll a %s to win" % point else: if roll == point: print "You win!" return elif roll == 7: print "You lose!" return #-PROBLEM 2 LAB15------------------ import calendar #To print calendar to console import datetime #For date objects and other date functions def getIntWithinRange(promptMsg,low,high): """ Prompts user to input an integer value, verifies that is an integer in range, and returns it""" """ Args: """ """ promptMsg: Message given to userto prompt for input""" """ low: serves as the low end of the range """ """ high: serves as the high end of the range """ """ Returns: Integer value given by user """ userInput = "" while true: userInput = str(raw_input(promptMsg)) #get input form user if str.isdigit(userInput) == true: #check if string contains digits userInput = int(userInput) #convert raw input to integer value if userInput >= low and userInput <= high: #check if the year given is out of range return userInput #return out of function else: print("OUT OF RANGE ERROR! Please read input instructions!") else: print("USER INPUT ERROR! Please read input instructions!") def birthMonthCal(): """ Gets user to input their birth year and birth month.""" """ prints a calendar of that month to console""" birthYear = getIntWithinRange('ENTER FOUR DIGIT BIRTH YEAR FROM 1901 TO 2017: ',1901,2017) birthMonth = getIntWithinRange('ENTER BIRTH MONTH FROM 1 TO 12: ',1,12) print('\n' + calendar.month(birthYear,birthMonth) ) #print calendar to console #TODO consider using calendar.monthcalendar(year,month) matrix for this operation to fix possible formatting conerns def daysToBday(): """ Gets user to input their birht month and birth day """ """ Prints to console screen the number of days until their next birthday""" birthMonth = getIntWithinRange('ENTER ITEGER VALUE FOR BIRTH MONTH FROM 1 TO 12: ',1,12) birthDay = getIntWithinRange('ENTER INTEGER VALUE FOR DAY YOU WERE BORN: ',1,31) #TODO add check to ensure amount of days exist in month today = datetime.datetime.now() #gets the date from the computer today = date(today.year,today.month,today.day) #creates a date object with a few parameters from today birthdayThisYear = date(today.year,birthMonth,birthDay) # create a date object with the birthday in this year #check if the birthday has passed if birthdayThisYear < today: #if true, the birthday has already passed futureBirthday = date((today.year + 1),birthMonth,birthDay) #set fuiture birthday for the next year else: # the birthday has not yet arrived this year futureBirthday = birthdayThisYear # set future birthdate as equal to the birthday this year difference = futureBirthday - today # find the difference print('----------------------------------------------------------\nYOUR BIRTHDAY WILL BE IN THE FOLLOWING DAYS:') print( difference.days ) #prints to the screen print('----------------------------------------------------------') #birthday = date(birthYear,birthDay,birthMonth) #today = date(currentTime.year,currentTime.day,currentTime.month) #todo figure out today #datetime.delta(today - birthYear) def getDayOfWeek(): """ Prompts the user to input a date """ """ Prints that date to the console """ year = getIntWithinRange('ENTER FOUR DIGIT YEAR FROM 1000 TO 2017: ',1000,2017) month = getIntWithinRange('ENTER ITEGER VALUE FOR A MONTH FROM 1 TO 12: ',1,12) day = getIntWithinRange('ENTER INTEGER VALUE FOR DAY: ',1,31) #TODO add check to ensure amount of days exist in month, consider also leapyear userDate = date(year,month,day) #create a date object with user input dayNum = userDate.weekday() # get the numerical day of the week from date object 0 = monday, 1 = Tueday, ... #Use the number corresponding to the day of the week to assign name of the day if dayNum == 0: dayName = 'Monday' elif dayNum == 1: dayName = 'Tuesday' elif dayNum == 2: dayName = 'Wednsday' elif dayNum == 3: dayName = 'Thursday' elif dayNum == 4: dayName = 'Friday' elif dayNum == 5: dayName = 'Saturday' elif dayNum == 6: dayName = 'Sunday' #print name of the day of the week to the screen print('----------------------------------------------------------') print( 'The day you enetered was the following day of the week:') print( dayName ) print('----------------------------------------------------------')
f76ef6b6c0f4d7997737bc35c43722717646127b
ClarkThan/algorithms
/sort/QuickSort.py
849
3.6875
4
#QuickSort def middle(seq): length = len(seq) index = 0 for i in xrange(1, length): if seq[i] < seq[index]: key = seq[i] j = i while j > index: seq[j] = seq[j-1] j = j - 1 seq[index] = key index += 1 return index def quickSort(seq): if len(seq) <= 1: return seq mid = middle(seq) left = quickSort(seq[:mid]) right = quickSort(seq[mid+1:]) return left + [seq[mid]] + right def quikcSort_v2(seq): return quikcSort_v2([x for x in seq[1:] if x <= seq[0]]) + [seq[0]] + quikcSort_v2([x for x in seq[1:] if x > seq[0]]) if seq else [] a = [] b = [-1] c = [3, 2] d = [11,-2,-5,21,10,3,7,33,0,13,3,5,-7,22,41,28,45] if __name__ == '__main__': print quickSort(a) print quickSort(b) print quickSort(c) print quickSort(d) print quikcSort_v2(a) print quikcSort_v2(b) print quikcSort_v2(c) print quikcSort_v2(d)
8d9e30ac632e4c3d2da31cc6e41f2b5f5d7c630c
AISWARYAK99/Python
/flow.py
1,073
3.8125
4
''' a=10 b=15 if a==b: print('They are equals') elif a>b: print('a is larger') else : print('b is larger') #nested if else stmnts n=int(input('Enter a number')) if n>=0: if n==0: print('Number is Zero') else: print('Number is positive' else : print('Number is negative') basket=['apple','orange','grapes','banana'] for i in basket: print(i) numbers=[1,2,3,4,5] sum=0 for i in numbers: sum+=i print(sum) for i in range(10): print(i) print('\n') for i in range(2,7): print(i) print('\n') for i in range(1,20,2): print(i) #for else cakes=['pineapple','blueberry','strawberry'] for cake in cakes: print(cake) else: print('No more cakes') #while loop second=10 while second>=0 : print(second,end='->') second-=1 print('Blastoff') counter=0 while counter<3: print('Hello') counter+=1 else: print('No reply') ''' #nested loop count=1 for i in range(10): print(str(i)*i) for j in range(0,i): count+=1
fad06b6efc08f858e7f209edc645b7676cb79b23
Lazysisphus/Zen-Thought-on-LeetCode
/回溯/0039组合总和.py
1,089
3.5625
4
''' 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。  示例 1: 输入:candidates = [2,3,6,7], target = 7, 所求解集为: [ [7], [2,2,3] ] 示例 2: 输入:candidates = [2,3,5], target = 8, 所求解集为: [   [2,2,2,2],   [2,3,3],   [3,5] ] ''' class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: def backtrack(i, tmp_sum, tmp): if tmp_sum == target: res.append(tmp) return for j in range(i, n): if tmp_sum + candidates[j] > target: break backtrack(j, tmp_sum + candidates[j], tmp + [candidates[j]]) res = [] n = len(candidates) candidates.sort() backtrack(0, 0, []) return res
58627622c2a83879a5346ee6b1b3bc64ed22e2f1
lilitom/Leetcode-problems
/Tree/Leetcode_111_easy_二叉树最小路径.py
2,393
3.984375
4
''' Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. ''' #South China University of Technology #Author:Guohao #coding=utf-8 #------------------------------------------------------------------------------------ #coding=utf-8 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def minDepth(self, root): #õС·1 if root == None: return 0 if root.left == None or root.right == None: return self.minDepth(root.left) + self.minDepth(root.right) + 1 return min(self.minDepth(root.right), self.minDepth(root.left)) + 1 def minDepth2(self, root): #õС·2 if not root: return 0 d = map(self.minDepth2, (root.left, root.right)) return 1 + (min(d) or max(d)) input_3=TreeNode(3) input_4=TreeNode(4) input_5 = TreeNode(5) input_5.left=input_3 input_5.right=input_4 input_18 = TreeNode(18) input_all = TreeNode(2) input_all.left = input_5 input_all.right = input_18 slu_ = Solution() print input_all t = slu_.minDepth(input_all) print t #----------------------------------------------------------- #ҵķ #coding=utf-8 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def minDepth3(self, root): #õС·3 if not root: return 0 queue=Queue.Queue() queue.put(root) num_cout=0 while queue: num_cout=num_cout+1 for j in range(queue.qsize()): root=queue.get() if root.right: queue.put(root.right) if root.left: queue.put(root.left) if not root.left and not root.right: return num_cout input_3=TreeNode(3) input_4=TreeNode(4) input_5 = TreeNode(5) input_5.left=input_3 input_5.right=input_4 input_18 = TreeNode(18) input_all = TreeNode(2) input_all.left = input_5 input_all.right = input_18 slu_ = Solution() print input_all t = slu_.minDepth(input_all) print t #ο #https://leetcode.com/problems/minimum-depth-of-binary-tree/#/description
7ca35231cef2a2fdbc72139d08d4a93febe46283
ymsk-sky/atcoder
/abc104/b.py
253
3.53125
4
s=input() if s[0]=='A' and s[2:-1].count('C')==1: for i in range(len(s)): if not (i==0 or i==s[2:-1].index('C')+2): if not s[i].islower(): print('WA') exit() print('AC') exit() print('WA')
edab65965b81b8411e45acebb0dd27a9829ca19b
ddh/leetcode
/python/first_unique_character_in_a_string.py
954
3.90625
4
""" Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. """ from collections import defaultdict class Solution: def firstUniqChar(self, s: str) -> int: # char_dict = {} # for index, char in enumerate(s): # char_dict[char] = char_dict.get(char, 0) + 1 char_dict = collections.Counter(s) for index, char in enumerate(s): if char_dict[char] == 1: return index return -1 import collections class Solution2: def firstUniqChar(self, s: str) -> int: letter_counts = defaultdict(lambda a: 0) print(letter_counts) # Driver print(Solution2().firstUniqChar("leetcode")) print(Solution2().firstUniqChar("loveleetcode")) print(Solution2().firstUniqChar("")) print(Solution2().firstUniqChar("cc"))
9c57eef242b543e34574753cf6b652b49f0e6a0f
taikinaka/youngWonks
/python/dictionary/dictionaryQuiz.py
310
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 1 18:34:35 2019 @author: taikinaka """ friend = { 'Kouki' : 'pees cream', 'Taiki' : 'gum', 'Masako' : 'chocolate', 'Masashi' : 'peanuts'} for a in friend: print(friend[a]) friend.pop('Taiki') print(friend)
eda899cc6cdbea2211b77f07844c305869b0d332
xander5zer/python
/age.py
309
3.84375
4
age = 12 if age < 2: print("младенец") elif age >= 2 and age < 4: print("малыш") elif age >= 4 and age < 13: print("ребенок") elif age >= 13 and age < 20: print("подросток") elif age >= 20 and age < 65: print("взрослый") else: print("пожилой человек")
675fe9c20f78be81d0934f7aaf174cd0e9f4b493
lynellf/learing-python
/python_lists/addition.py
371
4.09375
4
# Addition # Adding items to the end of a list count = [1, 2, 3] count.append(4) print(count) # [1, 2, 3, 4] # Merging two arrays extended_count = [5, 6, 7] count.extend(extended_count) print(count) # [1, 2, 3, 4, 5, 6, 7] # Literally adding two arrays more_counting = [8, 9, 10] more_counts = count + more_counting print(more_counts) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0de1a32ae305150387f2a5f1fc6c4bc039c62f95
MKRNaqeebi/CodePractice
/Past/same_prime_factors.py
1,154
3.828125
4
import math def primeFactors(first, second): n = first if first < second: n = second if first % 2 == 0 and second % 2 > 0: return False if second % 2 == 0 and first % 2 > 0: return False while first % 2 == 0: first = first / 2 while second % 2 == 0: second = second / 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3,int(math.sqrt(n))+1,2): if first % i == 0 and second % i > 0: return False if second % i == 0 and first % i > 0: return False while first % i == 0: first = first / i while second % i == 0: second = second / i # Condition if n is a prime # number greater than 2 if first > 2 and second % first > 0: return False if second > 2 and first % second > 0: return False return True def solution(A, B): count = 0 for a_item, b_item in zip(A,B): if primeFactors(a_item, b_item): count += 1 return count print(solution([15, 10, 9], [75, 30, 5]))
390fc8ab463aad910188c384d8bfeef4fc8eeca8
Purushotamprasai/Python
/Rohith_Batch/Vamsi pyhton exam/prime_number.py
225
3.90625
4
def main(): num = int(input("Enter a number: ")) if (num % 2) == 0: print(num,"is not a prime number") else: print(num,"is a prime number") if(__name__ == "__main__"): main()
198bdb3ed509771a1af7cc9f6cca6b6ddeb19acb
zacharytwhite/project-euler-solutions
/project_euler_py/problem_026.py
1,300
3.890625
4
"""A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. """ import decimal def get_period(n) : """Function to find length of period of 1/n.""" # Find the (n+1)th remainder after decimal point in value of 1/n. rem = 1 # Initialize remainder for _ in range(1, n + 2): rem = (10 * rem) % n # Store (n+1)th remainder d = rem # Count the number of remainders before next occurrence # of (n+1)th remainder 'd' count = 1 rem = (10 * rem) % n count += 1 while rem != d : rem = (10 * rem) % n count += 1 return count max_ = 0 for denom in range(1, 1001): seq = get_period(denom) num = str(decimal.Decimal(1)/decimal.Decimal(denom)) if seq > max_ : max_ = seq answer = max_ print(answer) # Answer: 983 # Time: 0m0.085s
291ec1475e7f2b59d2e28f693dc7802ea27074b0
ToSev7en/LearningPython
/000-VariableScopeRule/variables-in-function-without-assignment.py
541
4.09375
4
# 一个函数,读取一个局部变量和一个全局变量 # 变量未在函数的定义体中赋值 b = 6 def func(a): print(a) print(b) func(3) """ 如果 b = 6 被注释的话: 3 Traceback (most recent call last): File "/Users/tsw/Documents/CodeCampus/LearningPython/000-VariableScopeRule/variables-in-function.py", line 7, in <module> func(3) File "/Users/tsw/Documents/CodeCampus/LearningPython/000-VariableScopeRule/variables-in-function.py", line 5, in func print(b) NameError: name 'b' is not defined """
f0f375241a34ebad05d4d6cbccfdb35c26d439cc
segordon/old-code
/john_cleese_transform_string.py
117
3.6875
4
name = 'John Marwood Cleese' first,middle,last = name.split() transformed = last + ', ' + first + ' ' + middle print(transformed)
7399a59f9b02db5e363ce7c7c267f1c256b86130
wangxiaobai123/first-origion
/helloGit.py
175
3.546875
4
def strtoint(chr): return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[chr] list1 = ['1','2','3','4'] list2 = map(strtoint,list1) print(list(list2))
65298a1055f28d7610136d8c725cd40d536de49c
heysushil/python-practice-set
/basics/dictonary.py
1,284
3.953125
4
# DICTONARY - THIS IS A SINLGE LINE COMMENT ''' THIS IS A MULTILINE COMMENT DICTONARY IS SAME AS ASSOCIATIVE ARRAY WHICH HOLDS KEY AND VALUE NOT DUBLICATE VALUE NO NAME TELPHONE 1 RAJA 98797978 ''' # print(string_value) if 3 > 5: print('IIm in if') print('Im in print body') data = { 'name':'Ankit Raj', 'course':'Python' } print('\nData Info: ',data) bigdata = { 'Ankit': { 'name':'Ankit Raj', 'course':'Python' }, 'Subham': { 'name':'Subham', 'course':'Python' } } print('\nBig Data: ',bigdata) print('\nSubhams Info: ',bigdata['Subham']) # USING FORMAT IN PRINT TO SHOW THE RESULT ON NICE WAY print('\nHi, {}. Welcome to the {} course.'.format(data['name'],data['course'])) print('\nHi, {}. Welcome to the {} course.'.format(bigdata['Subham']['name'],bigdata['Subham']['course'])) ''' HOME WORK USING DICTONARY CREATE YOUR PERSONAL INFO ANS SHOW IT USING PRINT WITH FORMAT ON PARAGRAPH WAY CREATE DICTORNARY WITH MULTI INO AND SHOW THEM ON PARAGAPH USING PRINT WITH FORMAT ALSO LEAR IF/ELSE AND WHILE AND FOR LOOP ''' ''' DIFF B/W 3.5/3.7/3.8 OF PYTHON DIFF B/W RELATION AND NON-RELATIN DATABASE ''' # print("hello") detail = {'name':'ankit','name':'yogesh'}
f4d0353d17cd1d9ddcb23dd345b8ab71dca96a5e
Armen281989/git2
/tryexcept.py
1,589
4.125
4
# try: # print('Hello') # except NameError: # print("Variable x is not defined") # except: # print("Something else went wrong") # try: # print("Hello") # except: # print("Something went wrong") # else: # print("Nothing went wrong") # try: # print(x) # except: # print("Something went wrong") # finally: # print(x) # #The try block will raise an error when trying to write to a read-only file: # try: # f = open("demofile.txt") # becouse i dont have (w) in my code # f.write("Hello World") # except: # print("Something went wrong when writing to the file") # finally: # f.close() # #The program can continue, without leaving the file object open # list_1 = ['Ani','Xcho','Vrej','Mane'] # while True: # try: # i = int(input('input number')) # print(list_1[i - 1]) # break # except IndexError: # print("input out of index") # except ValueError: # print("please input number") # while True: # mark = {"Anna" : 10, "Narek" : 9, "Mane" : 7} # try: # name = input("Name: ") # for i in name: # if i.isalpha() == False: # raise ValueError # print(name,mark[name],'years old') # break # except KeyError: # print(name, "don't found") # except ValueError: # print("Invalid input") # while True: # try: # num = int(input()) # x = 5/ num # except ZeroDivisionError: # print('second opprtator could not be 0') # except ValueError: # print('please input number') # else: # print(x) # break # print(a if a > b else b) # # PYTHON # a,b = b,a
e643291d7ab09fb4257b3872f73595432a227e46
marinella16/marinella
/Assignment 1.py
1,787
3.859375
4
#Question 1 m_str = input('Input m: ') # do not change this line m_str = float(m_str)# change m_str to a float c = 300000000# remember you need c e = m_str * c **2# e = print("e =", e) # do not change this line #Question 2 in_str = input("Input s: ") in_int = int(in_str)# in_int = print("in_int = ", in_int) in_float = float(in_str)# in_float = print("in_float = ", in_float) #Question 3 import math x1_str = input("Input x1: ") # do not change this line y1_str = input("Input y1: ") # do not change this line x2_str = input("Input x2: ") # do not change this line y2_str = input("Input y2: ") # do not change this line x1_int = int(x1_str) y1_int = int(y1_str) x2_int = int(x2_str) y2_int = int(y2_str)# convert strings to ints d = math.sqrt((x2_int - x1_int)**2 + (y2_int - y1_int)**2)# d = print("d =",d) # do not change this line #Question 4 weight_str = input("Weight (kg): ") # do not change this line height_str = input("Height (cm): ") # do not change this line weight_float= float(weight_str) height_float = float(height_str)/100 bmi = weight_float / (height_float**2) print("BMI is: ", bmi) # do not change this line #Question 5 x_str = input("Input x: ") x_str = int(x_str)# remember to convert to an int first_three= int(x_str//1000)# first_three = last_two = int(x_str%100)# last_two = middle_two = int(x_str//100)%100# middle_two = print("original input:", x_str) print("first_three:", first_three) print("last_two:", last_two) print("middle_two:", middle_two) #Question 6 secs_str = input("Input seconds: ") # do not change this line secs_int=int(secs_str) seconds=secs_int%(24*3600) # hours = hours = seconds //3600 seconds%=3600 # minutes = minutes=seconds//60 # seconds = seconds %=60 print(hours,":",minutes,":",seconds) # do not change this line
22cec6695d2ca2d5ad196940546e0ac861c9fe76
zangwenjie/pythonpractices
/pythonpractices/py3-6.py
5,972
4.0625
4
# names=["nana","weiwei","yazheng","yanmei"] # lon=len(names) # for i in range(0,lon): # #print(names[i]) # pep=['xue','meizhi','junmei','lina'] # bulai='junmei' # pep.remove('junmei') # pep.append('yanxia') # lon=len(pep) # print(bulai+" will not come, what a pity!") # print("I found a bigger desk !") # pep.insert(0,'tingting') # pep.insert(int(lon/2),'siyao') # pep.append('wenwen') # lon2=len(pep) # for i in range(0,lon2): # print("I want to invite ",pep[i].title()," to have dinner today.") # print("I want to invite ",len(pep)," people to have dinner today.") # # print("I could only invite two of them !") # while len(pep) > 2: # p = pep.pop() # print("I am sorry that I couldn't invite ",p," to have dinner today.") # lon3=len(pep) # for i in range(0,lon3): # print("hey you can still come to the dinner " , pep[i].title()) # while pep: # del pep[0] # print(pep) #3-8、9、10 # # place=['yunnan','lanzhou','xizang','qinghai','xinjiang','xiamen','taiwan'] # print(place) # print(sorted(place)) # print(place) # place.reverse() # print(place) # place.reverse() # print(place) # place.sort() # print(place) # place.sort() # print(place) #4-3、4、5、6、7、8、9 # for i in range(1,21): # print(i) # list1=range(1,1000001) # print(min(list1)) # print(max(list1)) # print(sum(list1)) # # list1=range(1,20,2) # for i in list1: # print(i) # # dig=[] # for i in range(3,30): # if i%3==0: # dig.append(i) # # for i in dig: # print(i) # # list1=[dig**3 for dig in range(1,11)] # print(list1) #4-10\11\12 # place=['taiwan','riben','xizang','qinghai','shanghai','yunnan'] # print('The first three items are : ',place[0:3]) # print('The items from the middle of the list are : ',place[1:4]) # print('The last three items in the list are : ',place[-3:]) # # place1=place[:] # place1.append('qinghai') # print('I want travel to :') # for i in place: # print(i) # # print('my friends want to travel to :') # for i in place1: # print(i) #4-13 # foods=('baozi','dabing','miantiao','lvhuo','roujiamo') # for food in foods: # print(food) # # #foods[2]='mantou' #错误代码 # # foods=('zhou','tang','miantiao','lvhuo','roujiamo') # for food in foods: # print(food) #5-3\4\5\6\7 # alien_color='green' # if alien_color == 'green': # print("you got 5 points!") # elif alien_color == 'yello': # print("you got 10 points!") # elif alien_color == 'red': # print("you got 15 points!") # # fruits=['apple','banana','grape'] # if 'apple' in fruits: # print('You really like apples !') # if 'banana' in fruits: # print('You really like bananas !') #5-10\11 # current_users=['mingming','lilei','hongmei','sunshaoping','tianxiaoxia'] # new_users=['Sunshaoping','Tianxiaoxia','fengtang','yuhua','muxin'] # # for new_user in new_users: # if new_user.lower() in current_users: # print(new_user,'already used !') # else: # print(new_user,'is OK !') # # num=[1,2,3,4,5,6,7,8,9] # for i in num: # if i == 1: # print("1st") # elif i == 2: # print('2nd') # elif i == 3: # print('3rd') # else: # print(i,'th',sep='') #6-1\2\3 # xue={'name':'xue','age':'29','city':'Tianjin'} # # print(xue) # # num={'xue':8,'di':8,'fang':6,'wen':9,'na':5} # # print("xue's favourite num is",num['xue'],'.\n' # # "di's favourite num is", num['di'], '.\n' # # "fang's favourite num is", num['fang'], '.\n' # # "wen's favourite num is", num['wen'], '.\n' # # "na's favourite num is", num['na'], '.\n') #6-5\6 # rivers={'nile': 'egypt','changjaing':'china','huangnhe':'zhonghua'} # for key in rivers.keys(): # print('The', key,'runs through ',rivers[key]) # # for name in rivers.keys(): # print(name) # # for value in rivers.values(): # print(value) # namelist=['mingming','lilei','hongmei','sunshaoping','tianxiaoxia'] # namein={'1':'mingming','2':'lilei'} # for name in namelist: # if name in namein.values(): # print(name,"thank you !") # else: # print(name,"please come to join us !") #6-7\8\9\10 # # xue={'name':'xue','age':'29','city':'Tianjin'} # zheng={'name':'zheng','age':'20','city':'xilinhaote'} # zhi={'name':'zhi','age':'32','city':'Tianjin'} # # people=[xue,zheng,zhi] # # for pe in people: # print(pe) # # # favorite_places={ # 'wang': ['yingguo','meiguo','aodaliya'], # 'liu': ['hainan','sichuan','shandong'], # } # # for name,places in favorite_places.items(): # print(name,"'s favourite places are:",sep='') # for place in places: # print(place) # cities={ # 'tianjin':{'nation':'zhongguo','renkou':'100','shishi':'dougen'}, # 'beijing':{'nation':'china','renkou':'1000','shishi':'zhuai'}, # 'shanghai':{'nation':'zhongguo','renkou':'10000','shishi':'dese'} # } # # for city,dics in cities.items(): # print(city,"is a city that:") # nation = dics['nation'] # renkou = dics['renkou'] # shishi = dics['shishi'] # print('nation is :',nation,'renkou is :',renkou,'shishi is :',shishi,'\n') #7-1、2、3、 car=input('what car do you want to rent ?') print('Let me see if I can find you a',car) cus=int(input('how many people are having lunch ?')) if cus > 8: print('please wait !') else: print('you can come in.') num=int(input('please input a int number :')) if num % 10 ==0: print('yes') else: print('no') ing="please input what you need to make a pizza :" ing += "\nif you want to quit , please input 'quit'.\n" while True: a = input(ing) if a != 'quit': print("we will input ",a,"to your pizza.") else: break tip='please input your age:' tip += "\nif you want to quit , please input '0'.\n" while True: age = int(input(tip)) if age >0 and age < 3: print('free') elif age >= 3 and age <= 12: print('10 dollars') elif age > 12: print("15 dollars") else: break
4d9524d92682140bda32f1ffd23e1cf1fe59886c
abhisheksingh75/Practice_CS_Problems
/Sorting/Reverse pairs.py
1,913
4.15625
4
""" Given an array of integers A, we call (i, j) an important reverse pair if i < j and A[i] > 2*A[j]. Return the number of important reverse pairs in the given array A. Input Format The only argument given is the integer array A. Output Format Return the number of important reverse pairs in the given array A. Constraints 1 <= length of the array <= 100000 1 <= A[i] <= 10^9 For Example Input 1: A = [1, 3, 2, 3, 1] Output 1: 2 Input 2: A = [2, 4, 3, 5, 1] Output 2: 3 """ def recurMergeSort(A, tmp_array, left, right): inv_Count = 0 if left < right: mid = (left + right)//2 inv_Count += recurMergeSort(A, tmp_array, left, mid) inv_Count += recurMergeSort(A, tmp_array, mid+1, right) inv_Count += merge2(A, left, mid, right) #print(A) return inv_Count def merge2(A,left_indx, mid_indx, right_indx): rev_Count = 0 i = 0 j = 0 k = left_indx left = A[left_indx:mid_indx+1] n = mid_indx-left_indx+1 right = A[mid_indx+1:right_indx+1] m = right_indx-mid_indx #logic to calculate inversion count while(i<n and j<m): if left[i]<=2*right[j]: i += 1 else: rev_Count += (n-i) j += 1 i, j= 0,0 while(i<n and j<m): if left[i]<=right[j]: A[k] = left[i] i += 1 k += 1 else: A[k] = right[j] j += 1 k += 1 while(i<n): A[k] = left[i] i += 1 k += 1 while(j<m): A[k] = right[j] j += 1 k += 1 return rev_Count class Solution: # @param A : list of integers # @return an integer def solve(self, A): temp_Array = [0]*len(A) count = recurMergeSort(A,temp_Array, 0, len(A)-1) #print(A) return count%(10**9+7)
19a8919aa266908b383812feda71cce14d1f0a39
Xoptuk/game-light-it
/game.py
4,182
3.625
4
# -*- coding: utf-8 -*- from random import randint, choice from time import sleep class Player: """ Класс игрока. Принимающий имя игрока и имеюющий флаг PC, который определяет игрок это или компьютер. """ def __init__(self, name, pc=False): self.name = name self.health = 100 self.pc = pc def attack(self, target): """ Метод отвечающий за обычную атаку,случайным образом выбирает количество урона между 18 и 25 """ attack_power = randint(18, 25) target.health -= attack_power print(f"{self.name} атакует {target.name} нанося ему {attack_power} единиц(ы) урона") if target.health > 0: print(f"Уровень здоровья {target.name} - {target.health}%") print('==============') print() else: print(f"Топор {self.name} настиг {target.name}. Земля ему пухом!") sleep(1) def strong_attack(self, target): """ Метод отвечающий за большой урон, выбирает случайное значение между 10-35 """ attack_power = randint(10, 35) target.health -= attack_power print(f"{self.name} яростно атакует {target.name}, нанося ему {attack_power} единиц(ы) урона") if target.health > 0: print(f"Уровень здоровья {target.name} - {target.health}%") print('==============') print() else: print(f"{target.name} был молод и красив, пока не встретился с {self.name}") sleep(1) def heal(self): """ Метод отвечающий за лечение,выбирает случайное кол-во жизней между 18-25. При количестве жизней выше 100, устанавлиет значение их на 100. """ heal_amount = randint(18, 25) self.health += heal_amount if self.health > 100: self.health = 100 print(f"{self.name} исцеляет себя на {heal_amount} единиц(ы)") print(f"Уровень здоровья {self.name} - {self.health}%") print('==============') print() sleep(1) def main(): """ Функция отвечающая за событие игры.Случайным образом выбирается игрок который ходит и так же случайно выбирается навык который он использует. """ hero = Player('Paladin') pc = Player('Garosh Hellscream', pc=True) while True: coin = randint(0, 1) if hero.health > 0 and pc.health > 0: if coin == 1: action = choice([hero.attack, hero.strong_attack, hero.heal]) if action == hero.heal: hero.heal() else: action(pc) else: if pc.health <= 35: # Если значение жизней меньше 35,увеличивает шанс лечения. action = choice([pc.attack, pc.strong_attack, pc.heal, pc.heal]) if action == pc.heal: pc.heal() else: action(hero) else: action = choice([pc.attack, pc.strong_attack, pc.heal]) if action == pc.heal: pc.heal() else: action(hero) elif pc.health <= 0: print(f'{pc.name} повержен, а {hero.name} заслужил отдых.') break else: print(f'{hero.name} доблестно сражался, но погиб. О нем не забудут.') break if __name__ == "__main__": main()
15cd28079f8ab13b55f04d5e3f73b5b506382956
frankiegu/python_for_arithmetic
/力扣算法练习/day16-两数相除.py
4,188
4.0625
4
# -*- coding: utf-8 -*- # @Time : 2019/3/14 21:19 # @Author : Xin # @File : day16-两数相除.py # @Software: PyCharm # 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。 # # 返回被除数 dividend 除以除数 divisor 得到的商。 # # 示例 1: # # 输入: dividend = 10, divisor = 3 # 输出: 3 # 示例 2: # # 输入: dividend = 7, divisor = -3 # 输出: -2 # 说明: # # 被除数和除数均为 32 位有符号整数。 # 除数不为 0。 # 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。 #解法-:暴力,但超时了 # class Solution(object): # def divide(self, dividend, divisor): # """ # :type dividend: int # :type divisor: int # :rtype: int # """ # def func(dividend,divisor,ans): # if dividend==abs(dividend) and divisor ==abs(divisor): # # if dividend == divisor: # ans+=1 # return ans # elif dividend < divisor: # return 0 # while dividend >divisor: # dividend=dividend-divisor # ans+=1 # return ans # # elif dividend != abs(dividend) and divisor != abs(divisor): # if dividend == divisor: # ans += 1 # return ans # elif dividend > divisor: # return 0 # while dividend < divisor: # dividend = dividend - divisor # ans += 1 # return ans # else: # dividend=abs(dividend) # divisor=abs(divisor) # if dividend == divisor: # ans += 1 # return -ans # elif dividend < divisor: # return 0 # while dividend > divisor: # dividend = dividend - divisor # ans += 1 # return -ans # # if -2**31 < dividend <2**31-1 or -2**31 < divisor < 2**31-1: # res = func(dividend, divisor,0) # return res # return 2**31-1 # # s = Solution() # print(s.divide(-10000000000,-3)) #解法二,在解法一下优化 class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if divisor == 1: return dividend if divisor == -1: if -dividend > 2 ** 31 - 1: return 2 ** 31 - 1 else: return -dividend if abs(dividend) < abs(divisor): return 0 flag = 1 if dividend >= 0 > divisor or dividend <= 0 < divisor: flag = -1 tmpDividend = abs(dividend) tmpDivisor = abs(divisor) result = 0 fac = 1 incDivisor = tmpDivisor while tmpDividend >= tmpDivisor: if tmpDividend < incDivisor: incDivisor = tmpDivisor fac = 1 tmpDividend -= incDivisor result += fac incDivisor += incDivisor fac += fac return result * flag s = Solution() print(s.divide(-10000000000,-3)) #解法三 #利用位运算符达到快速增减的目的s # class Solution(object): # def divide(self, dividend, divisor): # """ # :type dividend: int # :type divisor: int # :rtype: int # """ # if dividend == 0: # return 0 # i, res = 0, 0 # p, q = abs(dividend), abs(divisor) # while (q << i) <= p: # i += 1 # for j in range(i-1,-1,-1): # if (q << j) <= p: # p -= (q << j) # res += (1 << j) # if (dividend ^ divisor) < 0: # res = -res # return min(res, (1 << 31) - 1) # # s = Solution() # print(s.divide(-10000000000,-3))
4609a820394aa84a38f618214dfc9f939130edb3
cassie-hudson/gis-programming-py
/Sept30_Ch2ProgrammingExercises.py
2,854
3.953125
4
#1 Name = raw_input("Please enter your first and last name: ") Address = raw_input("Please enter your address, including address, city, state and ZIP: ") Telephone = raw_input("Please enter your telephone number: ") Major = raw_input("What is your college major? ") print Name,Address,Telephone,Major #2. Sale Prediction sales = input("What is your total sales?: ") profit = sales*0.23 print format(profit, '.2f') #3. Land Calculation sqft = input("Please enter the total area of the tract of land in feet squared: ") acres = sqft/43560 print format(acres, '.2f') #4. Total Purchase item1 = input("Please enter the price of item 1: ") item2 = input("Please enter the price of item 2: ") item3 = input("Please enter the price of item 3: ") item4 = input("Please enter the price of item 4: ") item5 = input("Please enter the price of item 5: ") subtotal = item1 + item2 + item3 + item4 + item5 tax = subtotal * 0.07 total = subtotal + tax print"Subtotal: ", subtotal print "Tax: ", tax print "Total: ", total #5. Distance Traveled speed = 70 time = input("How long is the car traveling?: ") distance = time * speed print distance #6. Sales Tax purchase = input("Please enter the purchase price: ") st_tax = purchase * 0.05 co_tax = purchase * 0.025 total = purchase + st_tax + co_tax print"Subtotal: ", purchase print "State Tax: ", st_tax print "County Tax: ", co_tax print "Total Sales Tax: ", st_tax+co_tax print "Total: ", total #7. Miles Per Gallon miles = input("How many miles have you driven? ") gallons = input("How many gallons of gas have you used? ") mpg = miles/gallons print "You MPG is: ", mpg #8. Tip, Tax & Total purchase = input("Please enter the cost of your meal: ") tip = purchase * 0.18 tax = purchase * 0.07 print"Subtotal: $", format(purchase, '.2f') print "Tip: $", format(tip, '.2f') print "Tax: $", format(tax, '.2f') #9. Celcius to Farenheit Temperature Converter cel = input("Please enter the temperature in degrees Celcius: ") far = (9/5) * cel + 32 print far, "degrees" #10. Ingredient Adjuster cookies = input("How many cookies would you like to make? ") sugar = (1.5/48)*cookies butter = (1.0/48)*cookies flour = (2.75/48)*cookies print "You will need: " print sugar, "cups of sugar" print butter,"cups of butter" print flour, "cups of flour" #11. Male and Female Percentages males = input("How many males are in the classroom? ") females = input("How many females are in the classroom? ") total = float(males) + float(females) per_male = males/total per_female = females/total print format(per_male, '.00%'),"of the class are males." print format(per_female, '.0%'), "of the class are females." #12. Stock Transaction Program stock_price = 2000 * 40 com1 = stock_price * 0.03 sale_price = 2000 * 42.75 com2 = sale_price * 0.03 profit = sale_price - stock_price - com1 - com2 print "$",format(profit, ".2f")
a6fcdef0cd73157b5c394de1d8f884e3c71c5249
lucaryholt/python_elective
/39/angry_birds.py
2,066
3.78125
4
from os import system, name import random import sys class Bird: def __init__(self): self.icon = '🐥' self.x_loc = random.randint(0, 9) self.y_loc = random.randint(0, 9) def move(self, input): move = input.lower() if(move == 'w'): self.x_loc -= 1 elif(move == 'a'): self.y_loc -= 1 elif(move == 's'): self.x_loc += 1 elif(move == 'd'): self.y_loc += 1 class Pig: def __init__(self): self.icon = '🐷' self.x_loc = random.randint(0, 9) self.y_loc = random.randint(0, 9) class BoardPiece: def __init__(self): self.icon = '🌱' class Board: def __init__(self, bird, pig): self.bird = bird self.pig = pig self.boardArray = [] def initBoard(self): self.boardArray = [] for i in range(0,10): temp = [] for j in range(0,10): temp.append(BoardPiece().icon) self.boardArray.append(temp) def printBoard(self): boardString = '' for p in self.boardArray: for pp in p: boardString = boardString + ' ' + pp boardString = boardString + '\n' print(boardString) def updateBoard(self): self.initBoard() self.boardArray[self.pig.x_loc][self.pig.y_loc] = self.pig.icon self.boardArray[self.bird.x_loc][self.bird.y_loc] = self.bird.icon if(self.gameWon()): print('Game won!') sys.exit(1) self.clear() self.printBoard() def clear(self): if name == 'nt': _ = system('cls') else: _ = system('clear') def gameWon(self): return self.pig.x_loc == self.bird.x_loc and self.pig.y_loc == self.bird.y_loc #sometimes start with bird and pig in same local - auto win #can crash game by moving beyond board b = Bird() p = Pig() board = Board(b, p) while True: board.updateBoard() move = input() b.move(move)
1cc5babc307920700e274e1f9db4bc3a0fed5b06
vavronet/text-based-game
/game_intro.py
1,041
3.6875
4
import time def run(): print("Welcome to The Heart-Hands and the Pants!\n") avatar = input("Enter your avatar name here: \n") print("\nGrettings, {}!\nThe kingdom of pants has been conquered by the evil hat masterminds!\nSave the pant people and defeat the evil hat wizard! \nMay the odds be with you Heart-Hand!".format(avatar)) time.sleep(3) print("How to Play:\nEach boss you encounter will have a certain amount of health points or HP, which determines how hard the boss is.\n") time.sleep(1) print("In order to defeat your opponets you have to attck them.\nYou have 10 tries to defeat your enemny and each hit is a random number between 0 and 10.\nThere is a higher probibility that you will get higher numbers than lower ones.") time.sleep (1) print("\nEverytime you finish a turn, the boss will also attack you using the same fighting system except as the bosses increase, their attcks also become greater.\n") input('Are you ready to begin your mission? (Press Enter)\n')
d8a9132844a34c684b21d6c37dab9d270b062876
Anbumani-Sekar/python-codings
/maximum list.py
58
3.5
4
list=[1,2,3,6,9] print("the maximum of list",max(list))
02af4760b1eaa0e35773e3ecc6d6302cf8a2218a
EchuCompa/Cursos-Python
/funciones.py
713
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 12 17:58:54 2020 @author: Diego """ # numero_valido=False # while not numero_valido: # try: # a = input('Ingresá un número entero: ') # n = int(a) # numero_valido = True # except: # print('No es válido. Intentá de nuevo.') # print(f'Ingresaste {n}.') #Ejercicio 2.4 # def saludar(nombre): # print(f"Hola {nombre}, tudu peola?") # saludar("Juanchi") def preguntar_edad(nombre): edad = int(input(f'ingresá tu edad {nombre}: ')) if edad<0: raise ValueError('La edad no puede ser negativa.') elif type(edad) == str: raise ValueError ("Debe ingresar su edad en números") return edad
8e813322f8a53628eb0552e054700a9625478720
rjbarber/Python
/String Data Type Functions and Operators/In operator.py
276
4.5
4
#This program looks at the string In operator (in) #This operator searches for a specified character #in a target string. If the character exists in #the string a value of ‘True’ is returned, else it returns ‘False’. str1="Hello" print('e' in str1) print('a' in str1)
e1b2447d6539deec40fa9ce84e271e67f3d5c820
Mattemyo/datascience-az
/Part 1 - Data Preprocessing/data_preprocessing_template.py
765
3.78125
4
# Data Preprocessing Template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv( r"C:\Users\Matias\Documents\datascience-az\Part 1 - Data Preprocessing\Data.csv") # y is the one to be predicted, X contains the rest of the data X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 3].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=0) # Feature Scaling # from sklearn.preprocessing import StandardScaler # sc_X = StandardScaler() # X_train = sc_X.fit_transform(X_train) # X_test = sc_X.transform(X_test)
d62497e64ac953368586720a647f5eed4905a49e
brandondonato/College-Coursework
/CS110/RandallDevonFinal Project 2/CardClass.py
1,798
3.890625
4
""" Donato, Brandon bdonato1@binghamton.edu CS 110 - B57 Jia Yang FinalProjectCardClass """ class Card(): #-- Constants ---------------------------------------------------------------- # These are the values of each of the cards in the game TWOS = 2 THREES = 3 FOURS = 4 FIVES = 5 SIXES = 6 SEVENS = 7 EIGHTS = 8 NINES = 9 TENS = 10 JACKS = 10 QUEENS = 10 KINGS = 10 ACES = 11 #-- Constructor -------------------------------------------------------------- # Creates the individual cards and assigns them a value # params: suit (str) - The suit of the card # value (str) - The value (Two - Ace) of the card def __init__(self, suit, value): self.__suit = suit self.__value = value self.__valueDict = {"Two": TWOS, "Three": THREES, "Four": FOURS, \ "Five": FIVES, "Six": SIXES,"Seven": SEVENS, \ "Eight": EIGHTS, "Nine": NINES, "Ten": TENS,\ "Jack": JACKS, "Queen": QUEENS, "King": KINGS,\ "Ace" : ACES} self.__cardValue = self.__valueDict[self.__value] self.__cardImage = '%s_of_%s' % (self.__value, self.__suit) #-- Accessors ----------------------------------------------------------------- # Returns the numeric value of the card def getCardValue(self): return self.__cardValue #Returns the face value of the card def getCardFaceValue(self): return self.__value # Returns the suit of the card def getSuit(self): return self.__suit #Returns the name of the cards image def getCardImage(self): return self.__cardImage #-- Convert to String -------------------------------------------------------- # Returns the string representation of the card def __str__(self): return '%s of %s' % (self.__value, self.__suit)
88264cb0fb2f1e24dfdb3e01356bb22b5d0d422d
allenchen/facebook_hackercup_2013
/r1/balanced_smileys.py
1,094
3.515625
4
input = open("balanced_smileys.in", "r") def is_balanced(s, open_paren_count): #print str(open_paren_count) + " - " + s if len(s) == 0: return open_paren_count == 0 if len(s) == 1: return (s not in ("(", ")") and open_paren_count == 0) or (open_paren_count == 1 and s == ')') or (open_paren_count == 0 and s == ':') candidates = [] if s[0] == ")": if open_paren_count > 0: candidates += [(s[1:], open_paren_count - 1)] else: return False if s[0] == ":": if s[1] == ")" or s[1] == "(": candidates += [(s[2:], open_paren_count)] candidates += [(s[1:], open_paren_count)] if s[0] not in (":", "(", ")"): candidates += [(s[1:], open_paren_count)] if s[0] == "(": candidates += [(s[1:], open_paren_count + 1)] #print candidates return any(map(lambda x: is_balanced(x[0], x[1]), candidates)) for index, line in enumerate(input.readlines()[1:]): index = index + 1 print "Case #" + str(index) + ": " + ("YES" if is_balanced(line, 0) else "NO")
6d6a2dee49923f42598fe3f80b8d8bc0d886f1a1
srcsoftwareengineer/datah-pokerhand
/tests/test_pokerhand.py
5,327
3.578125
4
#!/usr/bin/python3.7 ''' Created on 27 de set de 2021 @summary: Unit test for PokerHand class @author: Sandro Regis Cardoso | Software Engineer @contact: src.softwareengineer@gmail.com ''' import unittest from bin.pokerhand import PokerHand import random class Test(unittest.TestCase): def test_card_values_0(self): objph = PokerHand() card_values = objph.card_values self.assertEqual(card_values.__len__(), 13) del(card_values) def test_card_nipes_1(self): objph = PokerHand() card_nipes = objph.card_nipes self.assertEqual(card_nipes.__len__(), 4) del(card_nipes) def test_mount_deck_2(self): try: objph = PokerHand() card_values = objph.card_values card_nipes = objph.card_nipes card_deck = [] for cv in card_values: for n in card_nipes: card_deck.append("%s%s" % (cv, n)) del(n) del(cv) self.assertEqual(card_deck.__len__(), (13 * 4)) del(card_deck) del(card_nipes) del(card_values) except BaseException as excpt: raise excpt finally: NotImplemented def test_deal_cards_3(self): try: ph = PokerHand() card_values = ph.card_values card_nipes = ph.card_nipes card_deck = [] for cv in card_values: for n in card_nipes: card_deck.append("%s%s" % (cv, n)) del(n) del(cv) gambler_cards = random.choices(card_deck, k=5) self.assertEqual(gambler_cards.__len__(), 5) del(card_deck) del(card_nipes) del(card_values) del(gambler_cards) except BaseException as excpt: raise excpt finally: NotImplemented def test_parse_cards_4(self): """ @summary: This method evaluate the suit of each card in the gambler hands and also from computer as second gambler @todo: Implement match/case available in python 3.10 instead if/elif/else """ ph = PokerHand() ph.mount_deck() self.assertIsNotNone(ph) gambler_cards = ph.deal_cards() print(gambler_cards) self.assertEqual(gambler_cards.__len__(), 5) nipes = ph.card_nipes spades = 0 hearts = 0 diamonds = 0 clubs = 0 for card_value in gambler_cards: if card_value[1] == nipes[0]: spades += 1 elif card_value[1] == nipes[1]: hearts += 1 elif card_value[1] == nipes[2]: diamonds += 1 elif card_value[1] == nipes[3]: clubs += 1 else: raise Exception if hearts == 5: # call method checkforflush pontuation NotImplemented elif spades == 5: # call method checkforstraightflush pontuation NotImplemented else: # call method checkfordenomination NotImplemented def test_checkfor_flush_5(self): """ Method to check for royal flush or flush pontuation """ try: strenght = 7 royalflush = ['AH', 'KH', 'QH', 'JH', 'TH'] gambler_cards = ['2H', '4H', '8H', '5H', '6H'] if gambler_cards == royalflush: strenght = 1 return strenght except BaseException as excpt: raise excpt finally: NotImplemented def test_checkfor_denomination_6(self): try: strenght = 0 gambler_cards = ['2C', '2D', '2H', '6S', '6D'] denominations_list = [] denominations_match = {} initial_match_value = 2 straight = False straight_flush = False tree_kind = False four_kind = False two_ṕair = False full_house = False one_pair = False high_card = False for card_value in gambler_cards: dval = card_value[0] if dval not in denominations_list: denominations_list.append(dval) else: if dval not in denominations_match.values(): new_dict = {'card_value': dval, 'qty': initial_match_value} denominations_match.update(new_dict) if dval in denominations_match.values(): cv = denominations_match.get('card_value') qty = denominations_match.get('qty') print("cv %s qty : %s" % (cv, qty)) denominations_match['qty'] = qty + 1 del(card_value) del(gambler_cards) return strenght except BaseException as excpt: raise excpt finally: NotImplemented def test_checkforstraightflush(self): NotImplemented if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testInit'] unittest.main()
5e0fe83902a0903ffbbbea28288d547118119c49
elvistony/pyHangman
/verify.py
555
3.84375
4
#Validation from hangman import * def verify(letter,str2): #letter=input(":") while letter in str2: if letter in str2: for i in range(len(str2)): if str2[i]==letter: a=str2[:i] b=str2[i+1:] str2=a+letter.upper()+b #print("placed ",str2) #print(str2) return str2 else: #print(str2) return str2 #e="f" #str2="elvis teena" #str2=verify(e,str2) #print("2") #str2=verify(str2)
643496ce564c5e60d25881f0756efe0a07f9a566
RaymondDashWu/CS-1.3-Core-Data-Structures
/strings.py
7,841
4.375
4
#!python def contains(text, pattern): """Return a boolean indicating whether pattern occurs in text. Time Complexity: O(n) - find_all_indexes iterates through text once Space Complexity: O(n) - find_all_indexes keeps track of all indexes """ assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) # PSEUDO BRAINSTORM # Iterate through letters in text and pattern, comparing patterns # Ex: in "banana" looking for "an". Would look at first letter of text - "b" # and then seeing if it matches with the first letter of pattern "a". In first # loop through it does not so it goes to next letter. Finds "a" in text, which matches # with "a" in pattern. Then checks for next letter "n" vs "n". Returns index found = find_all_indexes(text, pattern) if found: return True else: return False # Commented out for refactor # if pattern in text: # return True # else: # return False # if len(pattern) == 0: # return True # counter = 0 # counts pattern # goal = len(pattern) # Once counter == goal, return True # # Logic: Compare text with first letter in pattern. If matches, then counter + 1. # # If counter reaches same number as goal then return True # for letter in text: # if letter == pattern[counter]: # counter += 1 # if counter == goal: # return True # else: # counter = 0 # if letter == pattern[counter]: # counter += 1 # return False def find_index(text, pattern): """Return the starting index of the first occurrence of pattern in text, or None if not found. Time Complexity: O(n) - find_all_indexes iterates through text once Space Complexity: O(n) - find_all_indexes keeps track of all indexes """ assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) # PSEUDO BRAINSTORM # Iterate through letters in text and pattern, comparing patterns # Ex: in "banana" looking for "an". Would look at first letter of text - "b" # and then seeing if it matches with the first letter of pattern "a". In first # loop through it does not so it goes to next letter. Finds "a" in text, which matches # with "a" in pattern. Then checks for next letter "n" vs "n". Returns index found = find_all_indexes(text, pattern) if len(found) > 0: return found[0] return None # Commented out for refactor # if len(pattern) == 0: # return 0 # # Used to keep track of when pattern is matched (GOAL!!!) as well as when that first pattern match is # counter = 0 # goal = len(pattern) # # Keeps track of the index at which the first letter that matches is found # goal_index_list = [] # # Logic: enumerate allows for keeping track of the letters that match the pattern as well as the index. # # When a letter in text matches the first letter of the pattern, append both to goal_index_list and +1 to counter # # When counter reaches the goal (# of letters in pattern) then append the index of the first pattern # # matching letter to goal_index_list # for i, letter in enumerate(text): # if letter == pattern[counter]: # # Adds the first character to index # if goal_index_list == []: # goal_index_list = i # counter += 1 # if counter == goal: # return goal_index_list # else: # counter = 0 # # Reset if it loops through a letter that doesn't match. Ex: "aaabc" looking for "ab" would add # # an "a" but reset on the second "a" because it doesn't match ab # goal_index_list = [] # # if cases like "ababc" where the third letter doesn't match but can overlap with the string being looked for # if letter == pattern[counter]: # goal_index_list = i # counter += 1 def find_all_indexes(text, pattern): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found. Time Complexity: O(n) - find_all_indexes iterates through text once Space Complexity: O(n) - find_all_indexes keeps track of all indexes """ assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) # Used to keep track of when pattern is matched (GOAL!!!) as well as when that first pattern match is counter = 0 goal = len(pattern) # Keeps track of the index at which the first letter that matches is found goal_index = None goal_index_list = [] if len(pattern) == 0: return list(range(0, len(text))) # Logic: enumerate allows for keeping track of the letters that match the pattern as well as the index. # When a letter in text matches the first letter of the pattern, append both to goal_index_list and +1 to counter # When counter reaches the goal (# of letters in pattern) then append the index of the first pattern # matching letter to goal_index_list for i, letter in enumerate(text): if letter == pattern[counter]: # Adds the first character to index if goal_index == None: goal_index = i counter += 1 if counter == goal: goal_index_list.append(goal_index) counter = 0 goal_index = None if letter == pattern[counter]: # special condition for case where the pattern match would be 1. If it is, you get # index out of range errors. That's why code only runs when len(pattern) != 1 if len(pattern) != 1: counter += 1 goal_index = i else: # Reset if it loops through a letter that doesn't match. Ex: "aaabc" looking for "ab" would add # an "a" but reset on the second "a" because it doesn't match "ab" counter = 0 goal_index = None # if cases like "ababc" where the third letter doesn't match but can overlap with the string being looked for if letter == pattern[counter]: goal_index = i counter += 1 return goal_index_list def test_string_algorithms(text, pattern): found = contains(text, pattern) print('contains({!r}, {!r}) => {}'.format(text, pattern, found)) # TODO: Uncomment these lines after you implement find_index index = find_index(text, pattern) print('find_index({!r}, {!r}) => {}'.format(text, pattern, index)) # TODO: Uncomment these lines after you implement find_all_indexes indexes = find_all_indexes(text, pattern) print('find_all_indexes({!r}, {!r}) => {}'.format(text, pattern, indexes)) def main(): """Read command-line arguments and test string searching algorithms.""" import sys args = sys.argv[1:] # Ignore script file name if len(args) == 2: text = args[0] pattern = args[1] test_string_algorithms(text, pattern) else: script = sys.argv[0] print('Usage: {} text pattern'.format(script)) print('Searches for occurrences of pattern in text') print("\nExample: {} 'abra cadabra' 'abra'".format(script)) print("contains('abra cadabra', 'abra') => True") print("find_index('abra cadabra', 'abra') => 0") print("find_all_indexes('abra cadabra', 'abra') => [0, 8]") if __name__ == '__main__': main()
d6490c45cbe947dceaac7a9e0db10824153891ec
Omkar02/FAANG
/MergeKSortedArrays.py
1,795
3.78125
4
import __main__ as main from Helper.TimerLogger import CodeTimeLogging fileName = main.__file__ fileName = fileName.split('\\')[-1] CodeTimeLogging(Flag='F', filename=fileName, Tag='Array', Difficult='Medium') ''' Given K sorted arrays arranged in the form of a matrix of size K*K. The task is to merge them into one sorted array. Input: The first line of input contains the number of test cases, then T test cases follow. Each test case will contain an integer K denoting the number of sorted arrays(each with size K). Then in the next line contains all the elements of the array separated by space. Output: The output will be the sorted merged array. User Task: You need to complete mergeKArrays() function which takes 2 arguments, an arr[k][k] 2D Matrix containing k sorted arrays and an integer k denoting the number of sorted arrays. The function should return a pointer to the merged sorted arrays. Expected Time Complexity: O(nk Logk) Expected Auxiliary Space: O(k) ''' arrays = [[1, 2, 2, 2], [3, 3, 4, 4], [5, 5, 6, 6], [7, 8, 9, 9]] import heapq def mergeSortedArrays(arrays): sortedList = [] smallestItems = [] for arrayIdx in range(len(arrays)): smallestItems.append({"arrayIdx": arrayIdx, "elementIdx": 0, "num": arrays[arrayIdx][0]}) minHeap = MinHeap(smallestItems) while not minHeap.isEmpty(): smallestItem = minHeap.remove() arrayIdx, elementIdx, num = smallestItem["arrayIdx"], smallestItem["elementIdx"], smallestItem["num"] sortedList.append(num) if elementIdx == len(arrays[arrayIdx]) - 1: continue minHeap.insert( {"arrayIdx": arrayIdx, "elementIdx": elementIdx + 1, "num": arrays[arrayIdx][elementIdx + 1]} ) return sortedList
a4d7de60b4fb1ac49125f55a8a3ad12729561e5a
kammitama5/Distracting_KATAS
/heronsformula.py
141
3.59375
4
def heron(a, b, c): import math s = (a + b + c) / 2 area = (s * ((s - a) * (s - b) * (s - c))) return math.sqrt(area)
b0ebd242fffc3583fcd845c8e6c3112a08ea5cfe
DeepFreek/AI_alg
/Square.py
2,582
3.609375
4
import copy from move_func import move_up,move_down,move_left,move_right,find_void combination={ 'начало': [[2, 8, 3], [1, 6, 4], [7, 0, 5]], 'конец': [[1, 2, 3], [8, 0, 4], [7, 6, 5]] } def print_array(array): for row in range(len(array)): print(array[row]) print('\n') def up_down(array): [voidX, voidY]=find_void(array) if voidX==0: return["Вниз"] elif voidX==2: return["Вверх"] else: return ["Вниз", "Вверх"] def left_right(array): [voidX, voidY]=find_void(array) if voidY==0: return["Вправо"] elif voidY==2: return["Влево"] else: return ["Вправо", "Влево"] def searchUsed(array, used): for row in range(len(array)): for col in range(len(array[row])): if array[row][col] != used[row][col]: return -1 return 1 def NotInUsed(array, used): for arr in used: a=0 new=list() for a in range (3): new.append(arr) if(searchUsed(array, arr)==1): print("old conf") return 1 print("That's new!") return -1 def dfs(array, used=None): if array==combination['конец']: print("end") return 1 used = used or list() if array not in used: used.append(copy.deepcopy(array)) print(used) NotInUsed(array, used) print("past combination") print(used) while array!=combination['конец']: if("Вверх" in up_down(array)) and NotInUsed(move_up(copy.deepcopy(array)), used)==-1: print("вверх") move_up(array) print_array(array) dfs(array, used) elif("Влево" in left_right(array)) and NotInUsed(move_left(copy.deepcopy(array)), used)==-1: print("влево") move_left(array) print_array(array) dfs(array, used) elif("Вправо" in left_right(array)) and NotInUsed(move_right(copy.deepcopy(array)), used)==-1: print("вправо") move_right(array) print_array(array) dfs(array, used) elif("Вниз" in up_down(array)) and NotInUsed(move_down(copy.deepcopy(array)), used)==-1: print("вниз") move_down(array) print_array(array) dfs(array, used) else: dfs(combination['начало'], used) dfs(combination['начало'], None)
51210938a5be973ceb3dd656a09b4d3dc2e1ccca
manosriram/Learning-Algorithms
/Linear-Regression/CostFunction.py
425
3.734375
4
import pandas as pd import numpy as np data = pd.read_csv("./ex1data1.txt", sep=",", header=None) m = len(data) X = data[0] def computeCost(X, y, theta): predicted = X * theta actual = y # sqrError = np.power((predicted - actual), 2) print(len(predicted)) cost = 1 / (2 * m) * np.sum([1, 2, 3]) return 1 X = [np.ones((97, 1), dtype="float"), data[1]] y = data[1] # cost = computeCost(X,y,theta)
74e87bf28436a832be8814386285a711b627dab9
ohaz/adventofcode2017
/day11/day11.py
2,179
4.25
4
import collections # As a pen&paper player, hex grids are nothing new # They can be handled like a 3D coordinate system with cubes in it # When looking at the cubes from the "pointy" side and removing cubes until you have a # plane (with pointy ends), each "cube" in that plane can be flattened to a hexagon # This means that 3D coordinates can be used easily to get a 2D representation of a hex grid # Examples and explanations are on https://www.redblobgames.com/grids/hexagons/ # # x = 0 # \ n / # nw +--+ ne # z = 0 /y \ y = 0 # -+ x+- # y = 0 \z / z = 0 # sw +--+ se # / s \ # x = 0 Point = collections.namedtuple('Point', ['x', 'y', 'z']) def add_point(p1: Point, p2: Point): if p2 is None: print('Did not add anything') return p1 return Point(x=p1.x + p2.x, y=p1.y+p2.y, z=p1.z+p2.z) def distance(p1: Point, p2: Point): # The Manhattan distance in a hex grid is half the Manhattan distance in a cube grid. # coincidentally this is also just the max of the three distances return max(abs(p1.x - p2.x), abs(p1.y - p2.y), abs(p1.z - p2.z)) def calculate_solution(): with open('day11/day11_input.txt', 'r') as f: content = f.read() steps = content.split(',') max_distance = 0 zero = Point(x=0, y=0, z=0) current_pos = Point(x=0, y=0, z=0) for step in steps: modifier = None # Go around clockwise and create modify vectors if step == 'n': modifier = Point(x=0, y=1, z=-1) elif step == 'ne': modifier = Point(x=1, y=0, z=-1) elif step == 'se': modifier = Point(x=1, y=-1, z=0) elif step == 's': modifier = Point(x=0, y=-1, z=1) elif step == 'sw': modifier = Point(x=-1, y=0, z=1) elif step == 'nw': modifier = Point(x=-1, y=1, z=0) else: print('Unknown direction', step) current_pos = add_point(current_pos, modifier) max_distance = max(max_distance, distance(current_pos, zero)) return distance(current_pos, zero), max_distance
4010aea472f4517a12accba30bc4f19d7cfe0575
sunilsm7/python_exercises
/python_3 by pythonguru/Python File Handling.py
4,991
4.59375
5
Python File Handling 9 Replies Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now! We can use File handling to read and write data to and from the file. Opening a file Before reading/writing you first need to open the file. Syntax of opening a file is. f = open(filename, mode) 1 f = open(filename, mode) open() function accepts two arguments filename and mode . filename is a string argument which specify filename along with it’s path and mode is also a string argument which is used to specify how file will be used i.e for reading or writing. And f is a file handler object also known as file pointer. Closing a file After you have finished reading/writing to the file you need to close the file using close() method like this, f.close() # where f is a file pointer 1 f.close() # where f is a file pointer Different modes of opening a file are MODES DESCRIPTION "r" Open a file for read only "w" Open a file for writing. If file already exists its data will be cleared before opening. Otherwise new file will be created "a" Opens a file in append mode i.e to write a data to the end of the file "wb" Open a file to write in binary mode "rb" Open a file to read in binary mode Let’s now look at some examples. Writing data to the file >>> f = open('myfile.txt', 'w') # open file for writing >>> f.write('this first line\n') # write a line to the file >>> f.write('this second line\n') # write one more line to the file >>> f.close() # close the file 1 2 3 4 >>> f = open('myfile.txt', 'w') # open file for writing >>> f.write('this first line\n') # write a line to the file >>> f.write('this second line\n') # write one more line to the file >>> f.close() # close the file Note: write() method will not insert new line ( '\n' ) automatically like print function, you need to explicitly add '\n' to write write() method. Reading data from the file To read data back from the file you need one of these three methods. METHODS DESCRIPTION read([number]) Return specified number of characters from the file. if omitted it will read the entire contents of the file. readline() Return the next line of the file. readlines() Read all the lines as a list of strings in the file Reading all the data at once. >>> f = open('myfile.txt', 'r') >>> f.read() # read entire content of file at once "this first line\nthis second line\n" >>> f.close() 1 2 3 4 >>> f = open('myfile.txt', 'r') >>> f.read() # read entire content of file at once "this first line\nthis second line\n" >>> f.close() Reading all lines as an array. >>> f = open('myfile.txt', 'r') >>> f.readlines() # read entire content of file at once ["this first line\n", "this second line\n"] >>> f.close() 1 2 3 4 >>> f = open('myfile.txt', 'r') >>> f.readlines() # read entire content of file at once ["this first line\n", "this second line\n"] >>> f.close() Reading only one line. >>> f = open('myfile.txt', 'r') >>> f.readline() # read entire content of file at once "this first line\n" >>> f.close() 1 2 3 4 >>> f = open('myfile.txt', 'r') >>> f.readline() # read entire content of file at once "this first line\n" >>> f.close() Appending data To append the data you need open file in 'a' mode. >>> f = open('myfile.txt', 'a') >>> f.write("this is third line\n") 19 >>> f.close() 1 2 3 4 >>> f = open('myfile.txt', 'a') >>> f.write("this is third line\n") 19 >>> f.close() Looping through the data using for loop You can iterate through the file using file pointer. >>> f = open('myfile.txt', 'r') >>> for line in f: ... print(line) ... this first line this second line this is third line >>> f.close() 1 2 3 4 5 6 7 8 9 >>> f = open('myfile.txt', 'r') >>> for line in f: ... print(line) ... this first line this second line this is third line >>> f.close() Binary reading and writing To perform binary i/o you need to use a module called pickle , pickle module allows you to read and write data using load and dump method respectively. Writing data >> import pickle >>> f = open('pick.dat', 'wb') >>> pickle.dump(11, f) >>> pickle.dump("this is a line", f) >>> pickle.dump([1, 2, 3, 4], f) >>> f.close() 1 2 3 4 5 6 >> import pickle >>> f = open('pick.dat', 'wb') >>> pickle.dump(11, f) >>> pickle.dump("this is a line", f) >>> pickle.dump([1, 2, 3, 4], f) >>> f.close() Reading data >> import pickle >>> f = open('pick.dat', 'rb') >>> pickle.load(f) 11 >>> pickle.load(f) "this is a line" >>> pickle.load(f) [1,2,3,4] >>> f.close() 1 2 3 4 5 6 7 8 9 >> import pickle >>> f = open('pick.dat', 'rb') >>> pickle.load(f) 11 >>> pickle.load(f) "this is a line" >>> pickle.load(f) [1,2,3,4] >>> f.close() If there is no more data to read from the file pickle.load() throws EOFError or end of file error. In the next lesson we will learn about classes and objects in python.
d392b4669cd9aa974429420b7744788b104159b7
gabrielsalesls/curso-em-video-python
/ex088.py
506
3.546875
4
from random import randint from time import sleep numjogos = int(input('Quantos jogos você quer: ')) print(f'Sortetando {numjogos} jogos') jogo = [] apostas = [] for j in range(0, numjogos): cont = 0 while True: num = randint(1, 60) if num not in jogo: jogo.append(num) cont += 1 if cont >= 6: break jogo.sort() apostas.append(jogo[:]) print(f'Jogo {j + 1}: {apostas[j]}') jogo.clear() sleep(0.5)
0da61ecebf9cc88e56608c67521070bcbfb11e8e
n-rajesh/Python
/Scrape_text.py
1,185
3.984375
4
""" This is a program that performs Web Scraping for text. It extracts all text in given webpage and saves it to input.txt. """ import urllib.request as req from bs4 import BeautifulSoup as Soup from html.parser import HTMLParser class MLStripper(HTMLParser): def __init__(self): super().__init__() self.reset() self.strict = False self.convert_charrefs= True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() print(__doc__) url = input("Enter the URL that you want to scrape ") request = req.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) response = req.urlopen(request) parsed_url = urlparse(url) domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_url) domain = domain[:-1] page = response.read().decode('utf-8') res = Soup(page, "html.parser") html = res.find_all(["p","h1","h2","h3","h4","h5","h6","strong"]) text=strip_tags(str(html)) file=open( "input.txt", "w") file.write(text.strip()) file.close()
984fe75cb5c78b14bae08e7d7b92b04447020ef2
HYuHY/Small_training_Games
/Small_training_Games/Компьютер угадывает число.py
1,064
4.09375
4
# coding: utf-8 # Computer Guess My Number """ The user inputs a random number between 1 and 100 The computer tries to guess it and lets the player know what number was tried """ import random print("Welcome to 'Comp Guess My Number'!") the_number = 1000 while the_number > 100 or the_number < 1 : print("Please enter a number between 1 and 100\n") the_number = int(input()) print("you choose the_number =", the_number) try_count = 0 try_flag = 1 right_point = 1 left_point = 100 guess = right_point + (left_point - right_point)//2 while try_flag : try_count += 1 print(guess) if guess == the_number: try_flag = 0 print("Your number is", guess,"\nAttempts:",try_count) elif guess < the_number : right_point = guess delta = (left_point - right_point)//2 if delta == 0: delta = 1 guess = right_point + delta elif guess > the_number : left_point = guess delta = (left_point - right_point)//2 if delta == 0: delta = 1 guess = left_point - delta input("Push Enter to close program")
75409105547626392efc6f96a726ff7689d800cf
ChicksMix/programing
/unit 5/HicksBirds.py
191
3.703125
4
#Carter Hicks #1/12/18 n=0.0 t=0.0 c=0.0 while n<>-1: n=float(input("Enter a score or -1 to stop: ")) if n<>-1: t=t+n c=c+1 a=round(t/c,2) print "Your average score is",a
0c02b258ffc6ecb83a4ae97a3bbe40c55c4b63a3
vgates/python_programs
/p003_validate_input.py
516
4.4375
4
# Ask user to input until he/she enters valid input # For example: Get age from the user. The input should be always an integer value while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Invalid input provided. Type your age") continue else: # since valid we exit from the loop break if age >= 18: print("You can apply for driving license!") else: print("You are not eligible to apply for driving license.")
36243c81f9b3555b69ec55487778bcba8f41206d
freebz/Deep-Learning-from-Scratch
/ch03/ex3-7.py
171
3.703125
4
# 다차원 배열 import numpy as np A = np.array([1, 2, 3, 4]) print(A) np.ndim(A) A.shape A.shape[0] B = np.array([[1,2], [3,4], [5,6]]) print(B) np.ndim(B) B.shape
f969d6b184677eefe48cf86f4063fe345dfd53a5
kkaixiao/pythonalgo2
/leet_0387_first_unique_character_in_a_string.py
1,118
3.875
4
""" Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. """ class Solution: # first dictionary approach def firstUniqChar(self, s: str) -> int: charDict = {} for char in s: charDict[char] = charDict.get(char, 0) + 1 for k, v in charDict.items(): if v == 1: return s.index(k) return -1 # second dictionary approach def firstUniqChar(self, s: str) -> int: charDict = {} for char in s: charDict[char] = charDict.get(char, 0) + 1 for i, char in enumerate(s): if charDict[char] == 1: return i return -1 # set count approach def firstUniqChar(self, s: str) -> int: lst = [] for char in set(s): if s.count(char) == 1: lst.append(s.index(char)) if lst != []: return min(lst) return -1
638e66ad73b7ae93a4e7c2c32bc90c7957a4567c
c-hering/project_euler
/problem_2.py
650
4
4
#!/usr/bin/env python # Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. limit = 4000000 current_term = 1 last_term = 1 next_term = 2 total = 0 while current_term < limit: next_term = current_term + last_term last_term = current_term current_term = next_term if(current_term > limit): break if(next_term%2 == 0): total += next_term print(total)
94173514769f10e9be39a466033620ca0b11468b
ladykillerjason/leet
/Sum Root to Leaf Numbers.py
728
3.71875
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ if not root:return 0 return self.dfs(root,0) def dfs(self,root,tmp): if not root:return 0 tmp = tmp*10+root.val if not root.left and not root.right:return tmp return self.dfs(root.left,tmp)+self.dfs(root.right,tmp) if __name__ == '__main__': s = Solution() root = TreeNode(1) root.left = TreeNode(5) root.right = TreeNode(1) root.right.right = TreeNode(6) res = s.sumNumbers(root) print(res)