blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8fbf109d75f7dc1d0f0cfb81187c7d650249ff7e
Allan-Ai/study-python
/sample100/sample100-4.py
806
4
4
# sample 4 # -*- coding: UTF-8 -*- ''' 题目:输入某年某月某日,判断这一天是这一年的第几天? 程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天: ''' year = int(raw_input('year:\n')) month = int(raw_input('month:\n')) day = int(raw_input('day:\n')) increase = 0 days_in_month = (0, 31, 59, 90, 120, 151, 181, 212, 242, 273, 303, 334) if (year < 0) or ( month < 1) or (month > 12) or (day < 1) or (day > 31): print "input year, month, day are invalid" if (year % 4 == 0) and (year % 100 != 0) and (year % 400 == 0): increase = 1 day_in_month = days_in_month[month-1] + day + increase print "It is the {}th day.".format(day_in_month)
c7ebfb6561c949f8a97aec88009c9729542bc7b3
rakib1521/Automatic-Email-Sender
/email_send.py
1,940
3.71875
4
from tkinter import * import smtplib def sendmail(username,password,reciver,message,count): session = smtplib.SMTP('smtp.gmail.com', 587) #server location ,port number # start TLS for security session.starttls() #TSL = Transport layer security # Authentication session.login(username,password) # message to be sent #message = message # sending the mail session.sendmail(username, reciver, message) #print("{} mail done".format(count)) # terminating the session session.quit() def show(): username=s_email_input.get() password=s_password_input.get() reciver=r_email_input.get() message=text_input.get() count=int(no_email_input.get()) for i in range(count): sendmail(username,password,reciver,message,i) print(i) auto_mail = Tk() auto_mail.geometry('500x500') auto_mail.title("Email Info") s_email_label = Label(auto_mail, text="Sender's Email",width=20,font=("bold", 10)) s_email_label.place(x=80,y=130) s_email_input = Entry(auto_mail) s_email_input.place(x=240,y=130) s_password_label = Label(auto_mail, text="Sender's Password",width=20,font=("bold", 10)) s_password_label.place(x=80,y=180) s_password_input = Entry(auto_mail,show="*") s_password_input.place(x=240,y=180) r_email_label = Label(auto_mail, text="Reciver's Email",width=20,font=("bold", 10)) r_email_label.place(x=80,y=230) r_email_input = Entry(auto_mail) r_email_input.place(x=240,y=230) text = Label(auto_mail, text="Text",width=20,font=("bold", 10)) text.place(x=80,y=280) text_input = Entry(auto_mail) text_input.place(x=240,y=280) no_email_label = Label(auto_mail, text="Number of Email",width=20,font=("bold", 10)) no_email_label.place(x=80,y=330) no_email_input = Entry(auto_mail) no_email_input.place(x=240,y=330) Button(auto_mail, text='send',width=20,bg='red',fg='white',command=show).place(x=180,y=380) auto_mail.mainloop()
2793b3899d52b1cfae33e711f3964644e5c6ab8c
nimiew/python-oodp
/tutorial_3_class_and_static_methods.py
1,162
3.84375
4
""" Python OODP Tutorial 3: Class methods and Static methods """ class Employee: raise_amount = 1.04 # class variable; num_of_emps = 0 def __init__(self, first, last, pay): # constructor self.first = first self.last = last self.email = "{}.{}@company.com".format(first, last) self.pay = pay Employee.num_of_emps += 1 def fullname(self): # method; remember to put self return "{} {}".format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay * self.raise_amount) # Employee.raise_amount works too; pending on the situation, choose appropriately @classmethod def set_raise_amt(cls, amount): # instead of taking the instance as the first parameter, take the class as the first parameter cls.raise_amount = amount @classmethod # using classmethod as alternative constructor def from_string(cls, emp_str): first, last, pay = emp_str.split("-") return cls(first, last, pay) @staticmethod # neither class nor instance is used as the first parameter def is_workday(day): return day.weekday() != 5 and day.weekday() != 6
726d23155e341ea0bea3db6dac0bcae2280db959
pythoningLearning/python_start
/chap2_1.py
109
3.796875
4
print "%s is number %d!" % ("python", 1) user = raw_input('Enter login name: ') print 'You login is:', user
cafd91d2cbfc86833df6e1c36cd2955a69549f4f
gadolinis/Basic_exercises
/Calculator.py
758
4.25
4
# simple expample #num1 = input("Enter first number: ") #num2 = input("Enter another number: ") #result = float(num1) + float(num2) # float - realus skaiciai; int - sveiki skaičiai #print(result) # More advanced calculator ### q_simbolis = "a" while (q_simbolis != "q"): num1 = float(input("Enter first number: ")) op = input("Enter operator: ") num2 = float(input("Enter second number: ")) if op == "+": print(num1 + num2) elif op == "-": print(num1-num2) elif op == "/": print(num1 / num2) elif op == "*": print(num1 * num2) elif op == "^": print (num1 ** num2) else: print("Invalid operator") print("Tęsiame") q_simbolis = input("Nutraukti? (q) ")
a890295e711802c733b0e8df88c3b5830eb977bf
OH1107/SSAFY
/APS_기본/06_Stack/02_practice_stack.py
363
3.84375
4
def push(item): s.append(item) def pop(): if len(s) == 0: # underflow return else: return s.pop(-1) s = [] # s = ['a'] push('a') print(s) # s = ['a', 'b'] push('b') print(s) # s = ['a', 'b', 'c'] push('c') print(s) # s = ['a', 'b'] pop() print(s) # s = ['a'] pop() print(s) # s= [] pop() print(s) # None print(pop())
c55643304f85bcfb3ae17f91773d8314524f4687
Anirudh-Swaminathan/DSA
/Python/huffman_encoding.py
2,110
3.921875
4
#This is python implementation for Huffman encoding of input string. # The input is the string to be encoded. # THe outputs:- # 1. The number of distinct letters for the code # 2. The frequency of each distinct letter. # 3. The code for each distinct letter. # 4. The encoding of the input string __author__ = "Anirudh Swaminathan" import Queue code = [""]*128 # The data to be in the tree class data: def __init__(self,data1,freq1): self.left = None self.right = None self.data = data1 self.freq = freq1 def __cmp__(self,other): return cmp(self.freq,other.freq) q = Queue.PriorityQueue() # The function that recursively generates the hash for the characters def encodeIt(root,ch): if root is None: return if root.data != "@#$": print root.data+" : "+ch code[ord(root.data)] = ch encodeIt(root.left,ch+"0") encodeIt(root.right,ch+"1") # The function that builds the tree def executeTree(dataHe,freqHe,n): for i in range(n): q.put(data(dataHe[i],freqHe[i])) while(q.qsize() !=1): lefty = q.get() righty = q.get() top = data("@#$",lefty.freq+righty.freq) top.left = lefty top.right = righty q.put(top) temp = q.get() q.put(temp) # Call the function that generates the hash for the code encodeIt(temp,"") if __name__ == '__main__': a = raw_input("Enter a string\n") p = len(a) t=[0]*128 count = 0 for i in range(p): t[ord(a[i])]+=1 for i in range(128): if t[i]!=0: count+=1 print "The number of distinct characters used is "+str(count)+"\n" letter = [] freq=[] n = count for i in range(128): if t[i]!=0: letter.append(chr(i)) freq.append(t[i]) for i in range(n): print "Frequency of "+str(letter[i])+" : "+str(freq[i]) print "The codes are \n" executeTree(letter,freq,n) final = "" print "The encoded string for "+a+" is " for i in range(p): final+=code[ord(a[i])] print final
62aa2924834752616649062b1d4f4cb861b55207
s-c-vaz/GoogleCodeJam
/CaptainHammer.py
367
3.515625
4
import math if __name__ == '__main__': G = 9.8 testcases = int(raw_input()) for testcase in xrange(1, testcases+1): V, D = raw_input().split(' ') V = float(V) D = float(D) theta = math.degrees(0.5 * math.asin(min(1,(G*D)/(V*V)))) print 'Case #'+ str(testcase) + ': ' + str(theta)
480fc771ee4f8c0ef11bbb4dd2463907f3cb1042
EscapeB/LeetCode
/Integer to Roman.py
2,236
3.734375
4
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. # # Symbol Value # I 1 # V 5 # X 10 # L 50 # C 100 # D 500 # M 1000 # For example, two is written as II in Roman numeral, just two one's added together. # # 12 is written as, XII, which is simply X + II. # The number 27 is written as XXVII, which is XX + V + II. # # Roman numerals are usually written largest to smallest from left to right. # However, the numeral for four is not IIII. Instead, the number four is written as IV. # # Because the one is before the five we subtract it making four. # The same principle applies to the number nine, which is written as IX. # There are six instances where subtraction is used: # # I can be placed before V (5) and X (10) to make 4 and 9. # X can be placed before L (50) and C (100) to make 40 and 90. # C can be placed before D (500) and M (1000) to make 400 and 900. # Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. import math class Solution: def intToRoman(self, num: int) -> str: mapping = { 1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M' } outputStr = '' for i in range(3, -1, -1): divider = math.pow(10, i) char = mapping[divider] remain = math.floor(num / divider) if remain == 4: outputStr += mapping[divider] + mapping[divider * 5] elif remain == 9: outputStr += mapping[divider] + mapping[divider * 10] else: if remain >= 5: outputStr += mapping[divider * 5] remain -= 5 for j in range(remain): outputStr += char num = num % divider return outputStr # print(outputStr) solution = Solution() print(solution.intToRoman(1)) print(solution.intToRoman(3)) print(solution.intToRoman(4)) print(solution.intToRoman(58)) print(solution.intToRoman(1994)) print(solution.intToRoman(3999))
007119277f7ad6550ffa2bce8f508d5da69ceb40
ymjrchx/myProject
/pythonStudy/python-demo/Day03/grade.py
252
3.90625
4
score = float(input("输入成绩: ")) if score >=90: grade='A' elif score >= 80: grade="B" elif score >=70: grade="C" elif score>=60: grade='D' else: grade="E" print('对应的等级是: ',grade) if __name__ == '__main__': pass
de469886f89425daaed57f3f8b58e61007213e56
xiaomi388/LeetCode
/iter1/1430.py
740
3.515625
4
from contextlib import ExitStack class Solution: def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool: p = [] def dfs(node, i): with ExitStack() as stack: p.append(node.val) stack.callback(lambda : p.pop()) if node.val != arr[i]: return False if node.left is None and node.right is None and i == len(arr)-1: return True elif i == len(arr)-1 or (node.left is None and node.right) is None: return False if node.left and dfs(node.left, i+1): return True if node.right and dfs(node.right, i+1): return True return False return dfs(root, 0)
115dfe17d44393cd826c4a22ef1b7b660d0a9b69
echo001/Python
/python_for_everybody/exer12.10.3.py
790
4.03125
4
#Exercise 3 Use urllib to replicate the previous exercise of () retrieving the # document from a URL, () displaying up to 3000 characters, and () # counting the overall number of characters in the document. Don’t worry # about the headers for this exercise, simply show the first 3000 # characters of the document contents. import urllib.request, urllib.parse, urllib.error userUrl = input('Enter a url: ') try: fhand = urllib.request.urlopen(userUrl).read() except: print('Can not connect this URL,please try agin.') exit() doc = '' count = 0 for line in fhand: if line is None: break count = count + line doc = doc + line pos = doc.find('\r\n\r\n') print(doc[pos+4:3005]) print(count)
31cb49be8ecb40a4f432f26c1e323284e3431929
dydwnsekd/coding_test
/baekjoon/python/1181.py
282
3.703125
4
import sys n = int(sys.stdin.readline()) word_list = [] for _ in range(n): word_list.append(sys.stdin.readline().strip()) word_list = list(set(word_list)) word_list = sorted(word_list, key=lambda word_list: [len(word_list), word_list]) for word in word_list: print(word)
674a4ad993dc21e8523e06a9268dd54456bbb8ec
Bzan96/python-stuff
/Intermediate/everything_be_true.py
2,063
4.0625
4
''' Check if the predicate (second argument) is truthy on all elements of a collection (first argument). In other words, you are given an array collection of objects. The predicate pre will be an object property and you need to return true if its value is truthy. Otherwise, return false. In JavaScript, truthy values are values that translate to true when evaluated in a Boolean context. Remember, you can access object properties through either dot notation or []notation. ''' def truthCheck(collection, pre): falsyValues = [None, 0, ""] for i in collection: for key in i.keys(): if pre not in i.keys(): return False else: for value in i.values(): if key == pre and value in falsyValues: return False return True print(truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") ) ##should return true. print(truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") ) ##should return false. print(truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age") ) ##should return false. print(truthCheck([{"name": "Pete", "onBoat": True}, {"name": "Repeat", "onBoat": True}, {"name": "FastFoward", "onBoat": None}], "onBoat") ) ##should return false print(truthCheck([{"name": "Pete", "onBoat": True}, {"name": "Repeat", "onBoat": True, "alias": "Repete"}, {"name": "FastFoward", "onBoat": True}], "onBoat") ) ##should return true print(truthCheck([{"single": "yes"}], "single") ) ##should return true print(truthCheck([{"single": ""}, {"single": "double"}], "single") ) ##should return false print(truthCheck([{"single": "double"}, {"single": None}], "single") ) ##should return false print(truthCheck([{"single": "double"}, {"single": None}], "single") ) ##should return false
3f24cce0bbc96cb30d38489de5fcc99de95831ea
Joe132000/Phyton
/ordenarlista2.py
683
3.734375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 17 11:22:39 2020 @author: JOSEPH """ import random from time import sleep Listacreada=[] a=0 n = int(input("Ingrese el tamaño de su matriz: ")) for i in range(n): Listacreada.append(random.randint(0,99)) print('El valor en la posicion ',i+1,'es: ',Listacreada[i]) sleep(1) x=Listacreada[:] for i in range(n): x.sort() x.reverse() print('El valor ordenado en la posicion ',i+1,'es: ',x[i]) sleep(1) print('La lista creada es: ') print('A= ',Listacreada) Listacreada.sort() Listacreada.reverse() print('La lista ordenada de menor a mayo es: ') print('A= ',Listacreada)
9604f9ee0421638a18c94a9a58925a369991186a
chenggang0815/algo
/LeetCode/_0326_Power_of_Three/Power_of_Three.py
2,001
4.34375
4
import math """ 326. Power of Three Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. Example 1: Input: n = 27 Output: true Example 2: Input: n = 0 Output: false Example 3: Input: n = 9 Output: true Example 4: Input: n = 45 Output: false 思路: 方法一:循环迭代 方法二:换底公式 2.1 若n是3的幂,那么log3(n)一定是个整数 => 只需要判断log3(n)是不是整数即可 2.2 由于java中没有log3(n)这个库函数,由换底公式可以的得到log3(n) = log10(n) / log10(3) 方法三:3的最大幂次方 """ class Solution: # time:o(log(n)) def isPowerOfThree1(self, n: int) -> bool: while n != 0 and n % 3 == 0: n = n / 3 if n == 1: return True else: return False def isPowerOfThree2(self, n: int) -> bool: while n > 1: n = n / 3 if n == 1: return True else: return False def isPowerOfThree3(self, n: int) -> bool: if n == 1 or n == 3 or n == 9 or n == 27 or n == 81 or n == 243 or n == 729 or n == 2187 or n == 6561 or n == 19683 or n == 59049 or n == 177147 or n == 531441 or n == 1594323 or n == 4782969 or n == 14348907 or n == 43046721 or n == 129140163 or n == 387420489 or n == 1162261467: return True else: return False # 换底公式 def isPowerOfThree4(self, n: int) -> bool: return n > 0 and 3 ** n == round(math.log(27, 3)) # math.log 函数得到的数据可能不够精确,可以使用 round 取整 def isPowerOfThree5(self, n: int) -> bool: return n > 0 and 1162261467 % n == 0 # 递归 def isPowerOfThree6(self, n: int) -> bool: return n > 0 and ( n == 1 or (n % 3 == 0 and self.isPowerOfThree(n / 3))) if __name__ == '__main__': s = Solution() print(s.isPowerOfThree6(28))
c8bb23258f582838374b28d60840fc5a297483ef
jeandy92/Python
/ExerciciosCursoEmVideo/Mundo_3/ex078.py
693
3.65625
4
valores = [] posicaomaior = [] posicaomenor = [] menor = maior = 0 for c in range(0, 5): valores.append(int(input(f'Digite um valor para a posicao {c}: '))) if c == 0: maior = menor = valores[c] else: if valores[c] < menor: menor = valores[c] if valores[c] > maior: maior = valores[c] print('=-' * 30) print(f'VOCE DIGITOU OS VALORES:{valores}') print(f'O MAIOR VALOR: {maior} NA POSIÇÃO', end='') for i, v in enumerate(valores): if v == maior: print(f' {i}...', end='') print(f'O MENOR VALOR:{maior} NA POSIÇÃO', end='') for i, v in enumerate(valores): if v == menor: print(f' {i}...', end='') print()
bec686973f02abaa3c27e34e30b0866f02c10678
lshpaner/python-datascience-cornell
/Writing Custom Python Functions, Classes, and Workflows/Compound Interest Calculations/exercise.py
4,502
4.34375
4
""" Compound Interest Calculations Author: Leon Shpaner Date: August 17, 2020 """ # Examine the starter code in the editor window, and run that code in the # interpreter. What this code is describing is the growth of a pot of money, # which started at $100, and which grows over time at a rate of 3% per year. The # balance at the end of a given year is equal to balance*rate from the year # before. The current balance is rounded to the nearest two decimal places # (i.e.,$0.01), and is printed out each year for a total period of 10 years. # (The balance at year 0 is just the initial principal invested.) balance = 100.0 rate = 0.03 print(0, round(balance,2)) for n in range(1,11): balance = round(balance * (1 + rate), 2) print(n, round(balance,2)) # This is the sort of calculation that we would probably like to do repeatedly, # so let’s write a function to capture the basic logic. # In the code editor, write a function named compound that takes three inputs: # balance, rate, and num_periods. That function should take the initial balance, # a fixed interest rate, and the number of time periods over which the balance # is to be compounded. (If the interest rate represents a yearly interest rate, # then num_periods would correspond to the number of years; if it is a monthly # interest rate, it would reflect the number of months.) You’ll want your # function to return the current balance (i.e., the total of the principal plus # all accrued interest) at the end of the function so that you know how much # money you have if you would like to reinvest it. def compound(balance, rate, num_periods): Amount = round(balance * ((1 + rate) ** num_periods),2) return Amount # Your function is useful, but maybe you’d like to have a record of what the # balance was at the end of each year, rather than just a print out of it on the # screen. So let’s create another function that takes care of that. Write a new # function named compound_by_period that takes the same three inputs as before; # instead of writing it from scratch, you can copy the previous function # definition, paste a new function definition below, and then change the name of # the function. In this new function, you don’t want to just update and print # the balance each year, but keep a list of what those yearly balances are that # you can return at the end. Initialize an empty list at the start of the # function, and then append the yearly balance to the end of the list each time # through the loop. Instead of returning just the current balance at the end, # return the entire list of yearly balances (the last element of which will be # the current balance). def compound_by_period(balance, rate, num_periods): Amounts = [] for i in range(num_periods+1): Amounts.append(round(balance * ((1 + rate) ** i),2)) return Amounts # Since we now have our yearly balances stored in a list, it is easy for us to # write other functions to process that data. Write a new function named # change_per_period that takes a list of yearly balances and returns a new list # that contains the change in account value from year to year. So the first # element of this new list will contain the difference between the year 1 and # year 0 balances, the second element will contain the difference between year 2 # and year 1, etc. Since you are calculating the difference between two # consecutive years, the list that is returned by this new function will have # one element less than the list of yearly balances that you input. def change_per_period(Amounts): Difference = [] for i, _ in enumerate(Amounts): if i == len(Amounts)-1: continue Difference.append(round(Amounts[i+1]-Amounts[i],2)) return Difference # With your function compound_by_period in hand, we can apply it to a very # different problem in compound interest: the wheat on a chessboard problem. # First read (https://en.wikipedia.org/wiki/Wheat_and_chessboard_problem/) if # you are unfamiliar with the story. In this problem, the initial investment of # 1 grain of wheat is compounded for each square on the chessboard, leading to a # staggering amount of wheat by the time the chessboard is filled. Your function # compound_by_period is just what we need to compute how much wheat will # actually end up on the chessboard. wheat = [] for i in range(0,64): wheat.append(compound(1,1,i)) #print(wheat) total_wheat = sum(wheat)
738398ab05b06ad727b871fb1a0ef807c5af604d
mandarborkar/hello-world
/.idea/avent3a.py
829
3.796875
4
def numberoftrees (mylist, slope): addtotree = 0 for i in range (1,len(mylist)): if mylist[i][(i*slope)] == "#": addtotree += 1 print (mylist[i][(i*slope)] + " found tree on " + str(i) + ";" + str(addtotree)) else: print (mylist[i][(i*slope)] + " no tree on " + str(i) + ";" + str(addtotree)) return (int(addtotree)) f1 = open("/Users/mborkar/PycharmProjects/hello-world/avent3input.txt", "r") mylist = f1.readlines() rowcount=len(mylist) columncount=len(mylist[0]) duplicatecount=int(rowcount/columncount) # populate additional columns to traverse for i in range (0,len(mylist)): mylist[i] = mylist[i].replace("\n","") for j in range (0,duplicatecount-1): mylist[i] += mylist[i] print ("Trees for slope 3 = " + str(numberoftrees(mylist,3)))
7fe8d4c845fb51c9247ac44fd2b2507f9a634202
mahim23/DSA
/lab4/SpellChecker.py
1,346
3.84375
4
from lab2.LinkedList import * hashTable = [None for i in range(30)] def hashCode(key): x = 1 hash = 0 for i in range(len(key)): hash += ord(key[i])*x x *= 33 return hash def hashMap(hash): index = hash % 30 return index def insert(key, val=None): index = hashMap(hashCode(key)) if not hashTable[index]: l = LinkedList() l.insertAtIndex((key, val), 0) hashTable[index] = l else: l = hashTable[index] l.insertAtIndex((key, val), 0) def search(key): index = hashMap(hashCode(key)) if hashTable[index]: l = hashTable[index] node = l.search((key, None)) if node: return True else: return False def keys(): k = [] for i in hashTable: if i: tmp = i.head while tmp.next: k.append(tmp.next.val[0]) tmp = tmp.next return k file = open("ispell.dict", "r") words = file.readlines() for word in words: insert(word[:-1]) print("\n\tSPELL CHECKER\n") while True: word = input("Enter word to be checked (0 to exit): ") if word != "0": if search(word): print("Correct Spelling\n") else: print("Incorrect Spelling\n") else: print("Exiting...") break
89b11a6f57c045bd3b784c8a0bb9a1d8a51d7758
Atlantt/repozitor
/Z1.py
540
4.1875
4
# -*- coding: cp1251 -*- import math print " This program is designed to solve quadratic equations, such as a*x^2+b*x+c=0 " a = input( " Enter the number a " ) b = input( " Enter the number b " ) c = input( " Enter the number c " ) d=b**2-4*a*c if d < 0: print " The discriminant is equal to less than zero ", d elif d == 0: x=-b/2*a print " equation has a root and it is equal to ", x else: print " equation has two roots " x1=(-b+math.sqrt(d))/2*a x2=(-b-math.sqrt(d))/2*a print " x1=",x1 print " x2=",x2
230936d07ce0bd0a56c468402a0635fd544439ed
shabbirnayeem/spotify-playlist
/main.py
2,427
3.828125
4
from bs4 import BeautifulSoup import requests import spotipy from pprint import pprint date = input("Which year do you want to travel to? Type the date in this format YYYY-MM--DD: ") # https://www.billboard.com/charts/{date}?rank=1 # Getting the billboard.com html page response = requests.get(url=f"https://www.billboard.com/charts/hot-100/{date}") # saving HTML data to data data = response.text # using Beautiful Soup to scrape the HTML data soup = BeautifulSoup(data, "html.parser") # parsing to get the song titles song_title = soup.find_all("span", class_="chart-element__information__song text--truncate color--primary") # using spotipy to authenticate to spotify headers = spotipy.oauth2.SpotifyOAuth(client_id="[YOUR ID]", client_secret="[YOUR SECRET]", redirect_uri="http://example.com", scope="playlist-modify-private", cache_path=".cache") # getting current user information spotipy_user = spotipy.Spotify(auth_manager=headers) # getting hold of the user ID, need to create the play list user_id = spotipy_user.current_user()["id"] # authenticating to spotify using the headers data sp = spotipy.client.Spotify(auth_manager=headers) # getting hold of the year from the user input YYYY = date.split("-")[0] # creating a list of song uri song_uri = [] for song_name in song_title: try: # using the search function from spotipy to search for each song title result = sp.search(f"track:{song_name.getText()} year:{YYYY}") # getting hold of each song uri uri = result['tracks']['items'][0]['uri'] except IndexError: # if song not found in spotify skip and continue to the next continue else: # append each uri to song_uri list song_uri.append(uri) # print(len(song_uri)) # Creating a private playlist in spotify playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public=False, collaborative=False, description="Creating playlist with python code") play_list_id = playlist["id"] # adding all the songs from the billboard to the playlist # note items take a list tracks sp.playlist_add_items(playlist_id=play_list_id, items=song_uri, position=None)
5e49f9155f7732426ce8f170e951394252b0e27b
anujram178/ICS-31
/Project 5/dungeonGame.py
6,681
3.5625
4
#Ramaswamy, Anuj DungeonDict = dict() playerInv = [] class Room: '''This is the class Room which helps create and maintain the Dungeon dictionary.''' def __init__(self, roomNumber, desc, north, south, east, west): '''This is the constructor which initializes the class Room.''' self.desc = desc self.north = int(north) self.south = int(south) self.east = int(east) self.west = int(west) self.roomNumber = int(roomNumber) self.roomInv = [] def loaddungeon(filename): '''This function loads the layout of allrooms and places the player in the first room.''' f = open(filename) flag = 1 roomNumberList = [] fileContent = f.readlines() for line in fileContent: lineItems = line.split() roomNumberList.append(lineItems[0]) room = Room(lineItems[0], getDesc(line), lineItems[-4], lineItems[-3], lineItems[-2], lineItems[-1]) if flag == 1: playerStartPosition = room.roomNumber flag = 0 DungeonDict[room.roomNumber] = room print(getDesc(fileContent[0])) return int(playerStartPosition) def getDesc(line): '''This function helps in extracting the description for each room.''' res = "" i = 0 while i < len(line): if line[i] == "\"": i += 1 while line[i] != "\"": res += line[i] i += 1 break else: i += 1 return res def north(playerPosition): '''This function moves the player to the room immediately to its north.''' if DungeonDict[playerPosition].north == -1: print("You can't go there") return playerPosition else: playerPosition = DungeonDict[playerPosition].north print(DungeonDict[playerPosition].desc) return playerPosition def south(playerPosition): '''This function moves the player to the room immediately to its south.''' if DungeonDict[playerPosition].south == -1: print("You can't go there") return playerPosition else: playerPosition = DungeonDict[playerPosition].south print(DungeonDict[playerPosition].desc) return playerPosition def east(playerPosition): '''This function moves the player to the room immediately to its east.''' if DungeonDict[playerPosition].east == -1: print("You can't go there") return playerPosition else: playerPosition = DungeonDict[playerPosition].east print(DungeonDict[playerPosition].desc) return playerPosition def west(playerPosition): '''This function moves the player to the room immediately to its west.''' if DungeonDict[playerPosition].west == -1: print("You can't go there") return playerPosition else: playerPosition = DungeonDict[playerPosition].west print(DungeonDict[playerPosition].desc) return playerPosition def loaditems(filename): '''This function loads the items and adds them to the players inventory.''' f = open(filename) fileContent = f.read() global playerInv playerInv = fileContent.split(',') playerInv[-1] = playerInv[-1][0:-1] for i in range(len(playerInv)): playerInv[i] = playerInv[i].strip() def pinventory(): '''This function displays what the player holds in his/her inventory.''' pItems = '' global playerInv for item in playerInv: pItems += item +', ' if pItems == '': print("You have: nothing") else: print(f"You have: {pItems[:-2]}.") def rinventory(playerPosition): '''This function displays the items in the room that the player is currently in.''' rItems = '' for item in DungeonDict[playerPosition].roomInv: rItems += item + ', ' if rItems == '': print("This room contains: nothing") else: print(f"This room contains: {rItems[:-2]}.") def take(item, playerPosition): '''This function helps the player take the item he/she wishes to take and adds it to his inventory.''' global playerInv if item in DungeonDict[playerPosition].roomInv: DungeonDict[playerPosition].roomInv.remove(item) playerInv.append(item) else: print("That item is not in this room.") def drop(item, playerPosition): '''This function drops the item that is given as the argument and removes it from the player inventory and adds to the room's inventory.''' global playerInv if item in playerInv: playerInv.remove(item) DungeonDict[playerPosition].roomInv.append(item) else: print("You don't have that item.") def adventure(): '''This function is the main function which takes the user input and processes it.''' program = 1 playerPosition = None allCommandsList = [] while program == 1: userInput = input("$ ") commandList = userInput.split() if len(commandList)>1: allCommandsList.append(commandList[0]) if commandList[0] == "loaddungeon": if len(commandList) == 1: continue else: if allCommandsList.count("loaddungeon")>1: print("Dungeon already loaded") else: playerPosition = loaddungeon(commandList[1]) elif commandList[0] == "loaditems": if len(commandList) == 1: continue else: if allCommandsList.count("loaditems")>1: print("Items already loaded") else: loaditems(commandList[1]) elif commandList[0] == "north": playerPosition = north(playerPosition) elif commandList[0] == "south": playerPosition = south(playerPosition) elif commandList[0] == "east": playerPosition = east(playerPosition) elif commandList[0] == "west": playerPosition = west(playerPosition) elif commandList[0] == "pinventory": pinventory() elif commandList[0] == "rinventory": rinventory(playerPosition) elif commandList[0] == "take": if len(commandList) == 1: continue else: take(commandList[1], playerPosition) elif commandList[0] == "drop": if len(commandList) == 1: continue else: drop(commandList[1], playerPosition) elif commandList[0] == "quit": program = 0 print("you ended the program") adventure()
91cc8a2af35d4cbe374662c9a5e4edaf8200b430
yamscha/repo_class
/UCB_Python/Python1_UCB/netflix_mysolution.py
541
3.75
4
import csv import os video=input("What movie you are lokking for?") #set path for file csvpath = os.path.join("Resources","netflix_ratings.csv") found = False #open the csv file with open(csvpath,newline="") as csvfile: csvreader = csv.reader(csvfile,delimiter=",") for row in csvreader: if row[0]==video: print(row[0]+ " is rated "+ row[1] + " with a rating of " + row[6]) found = True if found == False: print("Sorry about this, we don't seem to have what you are looking for!")
0a3a79a65ae12366c9090914e9e2f63b8d718cd4
Faryab/UROP_Sandbox
/mpactgeometry.py
3,364
3.828125
4
import math class MeshParams: """ Parameters for a Mesh (for a Geometry) """ def __init__(self, nrad=1): self.nRad = nrad class Geom: """ A Geometry object (an attribute of a Level). Can be any elementary shape. Sub-Classes devolve into the different shapes possible. """ def __init__(self, name=None): self.Name = name class CircleGeom(Geom): """ Inherits from Geom. Defines a Circle in MPACT. """ def __init__(self, r=0, centroid=(0,0), startangl=0.0, stopangl=2*math.pi, meshparams=None): Geom.__init__(self) self.Name = "CircleGeom" self.Radius = r self.Centroid = centroid # the circles center self.StartAngle = startangl # where the circle starts (anticlockwise) 0 = 1st quadrant +x-axis self.StopAngle = stopangl # where the circle stops (anticlockwise) pi = 2nd quadrant -x axis self.MeshParams = meshparams # TODO: Should Mesh Params be a list? Yes. There are different parameters (e.g. for box brendan will send) class BoxGeom(Geom): """ Inherits from Geom. Defines a Box (quadrilateral) in MPACT. """ # TODO: Ask Brendan about Squares again done def __init__(self, cornerpt=(0,0), vector1=None, vector2=None, extent=None, meshparams=None): Geom.__init__(self) self.Name = "BoxGeom" self.CornerPoint = cornerpt self.Vector1 = [1, 0] if vector1 is None else vector1 self.Vector2 = [0, 1] if vector2 is None else vector2 self.Extent = extent self.MeshParams = meshparams # TODO: Should Mesh Params be a list? done class Level: """ Attribute of a GeneralMeshType Object. Contains a geometry as a sub-object on a specific level. Each level can have different numbers of geometries (for now we assume each level will only have a single geometry). Each level itself is unique """ def __index__(self, ngeom=0, geoms=None, name=None): self.name = name # The level number self.nGeom = ngeom self.geoms = [] if geoms is None else geoms def add_geom(self, geom): if geom in self.geoms: print("Error: Geometry is already in the list of geometries for this level.") else: self.geoms.append(geom) self.nGeom += 1 class GeneralMeshType: """ General Mesh Type class for defining MPACT Geometry. Contains the entire geomety as its sub-objects. Acts as the root of the XML tree. """ def __init__(self, name="GenPinMeshType", id=None, nlevels=0, xpitch=0.0, ypitch=0.0, zpitch=0.0, split=0, levels=None): self.name = name self.ID = id self.NLevels = nlevels self.XPitch = xpitch self.YPitch = ypitch self.ZPitch = zpitch self.Split = split self.Levels = {} if levels is None else levels def add_level(self, level): if level.name in self.Levels: print("Error: Level Number already added") return else: self.Levels[level.name] = level self.NLevels += 1 def remove_level(self, level_num): if level_num in self.Levels: print("Error: Specified level is not in the model") return else: del self.Levels[level_num]
0cbd2741cac4b681f2986e70f7ecff463ddd8918
yodo-im/answers_of_some_tasks_python
/3.py
307
3.59375
4
m = int(input("Введите массу\n")) h = int(input("Введите высоту\n")) G = 6.67 * 10**(-11) M = 6*10**24 R = 6371 * 10**3 Ft = G * ((M * m)/((R + h)**2)) Ft = str(Ft) for i in range(0,len(Ft)): if Ft[i] == '.': break print(Ft[0:i]," - сила тяжести")
9183c9bbfc66a4d18f5d8600d49e0cdaaa5cc6b4
madsonviana/miniflow
/miniflow_test.py
758
3.703125
4
# -*- coding: utf-8 -*- import unittest from nodes.node import Node from nodes.add import Add from nodes.input import Input class TestNodes(unittest.TestCase): """ Classe de teste para implementação dos nós da rede neural """ def test_node_interface(self): """ Testa se não tem implementação de forward na classe Node """ node = Node() with self.assertRaises(NotImplementedError): node.forward() def test_add_node(self): """ Testa o nó de adição """ input1 = Input() input1.forward(1) input2 = Input() input2.forward(2) add = Add(input1, input2) add.forward() self.assertEqual(3, add.value)
614e4b11663f259c4a3034ec24a57c27b9927d4c
mcgridles/neuromatic
/interface/buttons.py
5,595
3.6875
4
import tkinter class GenericButton(object): def __init__(self, root, button_label, passed_function, assigned_row=0, assigned_col=0, sticky='nsew', logger=None, main_window=None): """ Parent class to the drag and drop buttons. Contains functionality to assign a function to the button and assign the widget position. :param root: Tkinter.Widget - The Tkinter parent widget in which this class is encapsulated. :param button_label: str - The string displayed on the button. :param passed_function: function - The function executed on the button click. :param assigned_row: int - The row on which the button will exist on root. :param assigned_col: int - The column on which the button will exist on root. :param sticky: str - The sides of root to which the widget will adhere and expand. :param logger: funciton - The function to which status strings can be passed. :param main_window: Tkinter.Tk - The main window of the application. Used to manage application data. """ self.root = root self.passed_function = passed_function self.b = tkinter.Button(self.root, text=button_label, command=self.button_callback) self.b.grid(row=assigned_row, column=assigned_col, sticky=sticky) self.log = logger self.main_window = main_window def button_callback(self): """ Run the function passed by through the constructor. :return: None """ self.passed_function() class LayerButton(GenericButton): def __init__(self, root, button_label, passed_function, layer_type='Blank', assigned_row=0, assigned_col=0, sticky='nsew', logger=None, main_window=None): """ The LayerButton adds the drag and drop methods to the GenericButton. :param root: Tkinter.Widget - The Tkinter parent widget in which this class is encapsulated. :param button_label: str - The string displayed on the button. :param passed_function: function - The function executed on the button click. :param assigned_row: int - The row on which the button will exist on root. :param assigned_col: int - The column on which the button will exist on root. :param sticky: str - The sides of root to which the widget will adhere and expand. :param logger: funciton - The function to which status strings can be passed. :param main_window: Tkinter.Tk - The main window of the application. Used to manage application data. """ super(LayerButton, self).__init__(root=root, button_label=button_label, passed_function=passed_function, assigned_row=assigned_row, assigned_col=assigned_col, sticky=sticky, logger=logger, main_window=main_window) # Track the button's layer type self.layer_type = layer_type # The layer buttons are made draggable for canvas design. self.make_draggable() def make_draggable(self): """ Bind events to the button so that the drag and drop methods will be called. :return: None """ # A single click will signify the start of drag and drop self.b.bind('<Button-1>', self.on_start) self.b.bind('<B1-Motion>', self.on_drag) # Releasing the click will end drag and drop self.b.bind('<ButtonRelease-1>', self.on_drop) # Change the cursor while positioned over the widget self.b.configure(cursor='hand2') def on_start(self, event): """ Store the layer type in the main window so that a different widget, that is part of the main window, can inherit the layer type on drop. :param event: Tkinter.target - A Tkinter variable that represents a user's interaction with the GUI. :return: None """ self.main_window.current_layer_type = self.layer_type def on_drag(self, event): """ Change the cursor to signify the drag event. :param event: Tkinter.target - A Tkinter variable that represents a user's interaction with the GUI. :return: None """ self.b.configure(cursor='middlebutton') def on_drop(self, event): """ Check the cursor's position at the end of a drag and drop. This will return the target widget at that position and trigger a Tkinter event which will run a method of that widget class. :param event: Tkinter.target - A Tkinter variable that represents a user's interaction with the GUI. :return: None """ self.b.configure(cursor='hand2') # Get the location of the cursor x, y = self.root.winfo_pointerx(), self.root.winfo_pointery() # Get the widget at that location target = event.widget.winfo_containing(x, y) try: # Generate the <<Inherit>> event that could trigger a method in the target widget target.event_generate('<<Inherit>>', when='tail') except: pass
90c387abe0f043e92806fbc85ed9dd01ea23b759
MinwooRhee/unit_six
/d4_unit_six_warmups.py
123
3.9375
4
numbers = [3, 4, 5, 6, 7] squares = [] for x in numbers: square = x * x squares.append(square) print(squares)
cf755b348868e1726c4707567ad58c724de5ecb9
kimurakousuke/MeiKaiPython
/chap09/column0905.py
222
3.828125
4
# 函数名作为变量名 a, b, c = 3, 7, 5 max = max(a, b, c) # 第一次执行:OK (max = 7) print('a、b和c中的最大值是', max, '。') max = max(a, b, c) # 第二次执行:错误(max = 7(a, b, c))
5d1328b3946c203be14310692eb019b3e5df8287
markoschalaalx/bootcampschool-low_level_programming
/0x16-doubly_linked_lists/dev/palindrome.py
535
3.625
4
#!/usr/bin/python3 def sumofthreedignums(thesum, themin): a = 999 while a > 99: b = 999 while a * b > themin: b -= 1 if a * b == thesum: return True a -= 1 return False def main(): thesum = 999 * 999 themin = 999 * 100 - 1 while thesum > themin: if str(thesum) == str(thesum)[-1::-1]: if sumofthreedignums(thesum, themin): break thesum -= 1 print(thesum) if __name__ == "__main__": main()
8e536b3346713429ce7a629964540b92fb3af5a7
nandakishore723/cspp-1
/video_files/m2/nestedConds.py
1,465
3.875
4
# # -*- coding: utf-8 -*- # """ # Created on Wed Jun 8 11:07:33 2016 # @author: ericgrimson # """ # if x%2 == 0: # if x%3 == 0: # print('Divisible by 2 and 3') # else: # print('Divisible by 2 and not by 3') # elif x%3 == 0: # print('Divisible by 3 and not by 2') # import operator # t = () # print(t) # t = ('me','u') # print(t) # print(t) # s= set([1,2,2,3,4,4,5,'me',6]) # print(s) # d = {} # print(d) # d = dict([(1, 'me'),(2,'u')]) # print(d) # d = {1:'me',2:'u'} # print(d) # d = {1:'me',2:'u',3:{1:'me',2:'u'}} # print(d) # d1 = d.copy() # print(d1) # #type(d1) # print(type(d1)) # x = 100 # y = 4000 # x, y = y, x # print(x,y) # a = 4; b =2 # print(a+b) # print(a*b) # print(a>b) # print(a<b) # print(a==b) # print(a/b) # print(a//b) # print(a%b) # print(a is not b) # max = a if a>b else b # print(max) # print(any ([False,False])) # print(any ([False,False,True])) # print(any ([True,False,False])) # print(all ([False,False])) # print(all ([False,False,True])) # print(all ([True,True])) # print(operator.add(a, b)) # print(operator.sub(a, b)) # print(operator.mul(a, b)) # print(operator.truediv(a, b)) # print(operator.floordiv(a, b)) # print(operator.mod(a, b)) # import array # count = 0 # arr1 = array.array('i', [1,2,2,3,5,8]) # print(arr1.count(2)) # for _ in range(0,6): # print(arr1[_], end = " ") import re p = re.compile('\d+') print(p.findall("rabcdeefgyYhFjkIoomnpOeorteeeeet 11 22222-1256-226-1-0-2"))
f491475339de7bc125353ba588c186673bf21697
giri110890/python_gfg
/Functions/decorators.py
2,790
4.625
5
''' In Python, functions are the first class objects, which means that – Functions are objects; they can be referenced to, passed to a variable and returned from other functions as well. Functions can be defined inside another function and can also be passed as argument to another function. # Syntax for decorator @gfg_decorator def hello_decorator(): print("GFG") Above code is equivalent to def hello_decorator(): print("GFG") hello_decorator = gfg_decorator(hello_decorator)''' # Decorator can modify the behaviour def hello_decorator(func): # inner1 is a Wrapper function in which the argument is called # inner function can access the outer local functions like in this # case func def inner1(): print("Heelo, this is before function execution") # calling the actual function now inside the wrapper function func() print("This is after function execution") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print("This is inside the function !!") # passing 'function_to_be_used' inisde the decorator to control its # behaviour function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used() # program to find out the execution time of a function using a decorator # importing libraries import time import math # decorator to calculate duration taken by any function def calculate_time(func): # added arguments inside the inner1, if function takes any arguments # can be added like this def inner2(*args, **kwargs): # storing time before function execution begin = time.time() func(*args, **kwargs) # storing time after function execution end = time.time() print("Total time taken in : ", func.__name__, end - begin) return inner2 # this can be added to any function present, in this case to # calculate a factorial @calculate_time def factorial(num): # sleep 2 seconds because it takes very less time so that you can # see the actual difference time.sleep(2) print(math.factorial(num)) # calling the function factorial(10) # What if a function returns something def hello_decorator_new(func): def inner_new(*args, **kwargs): print("before Execution") # getting the return value returned_value = func(*args, **kwargs) print("After execution") # return the value to the original frame return returned_value return inner_new # adding decorator to the function @hello_decorator_new def sum_two_number(a, b): print("Inside the function") return a + b a, b = 1, 2 # getting the value through return of the function print("Sum =", sum_two_number(a, b))
74d72cd5850e77f80647cf7c3ccb24b133ca30a9
obaid147/python_ds_algos
/String/FirstLetterOfString.py
119
3.9375
4
inp = input("Enter a String: ") if 'A' <= inp[0] <= 'Z': inp = inp.upper() else: inp = inp.lower() print(inp)
53afe431107abee7e5609507e5faa54bcfddbd30
pu-bioinformatics/python-exercises-henrick-aduda
/src/02.py
1,823
3.859375
4
#Module2 trna='AAGGGCTTAGCTTAATTAAAGTGGCTGATTTGCGTTCAGTTGATGCAGAGTGGGGTTTTGCAGTCCTTA' #defining trna as a string #CK The trna should be initialized before usage -1 A_count=trna.count('A') C_count=trna.count('C') G_count=trna.count('G') T_count=trna.count('T') print("The length of the trna sequence is %i" % len (trna), "nucleotides") #showing the total number of bases in the sequences C_count=trna.count('C') #counting the total number of G's in the trna sequence G_count=trna.count('G') #counting the total number of C's in the trna sequence print("There are %d 'G' and %d C's in the trna sequence" % (trna.count('G'),trna.count('C'))) #showing the number of G's and C's in the trna sequence. GC_percent=(trna.count('G')+trna.count('C'))/len (trna)*100 print("The GC percentage of the trna sequence is %.3f" %GC_percent, "%") #This is the calculation for GC content for the trna sequence #Exercise_2 Finding the positions of amino acids in a given sequence. Amino1_seq="MNKMDLVADVAEKTDLSKAKATEVIDAVFA" #Defining the given amino acid sequence as a string. print("The first amino acid in the sequence is", Amino1_seq[0]) #Printing output for the first amino acid in the sequence. print("The fifth amino acid in the sequence is", Amino1_seq[4]) #Printing output for the second amino acid in the sequence. print("The last amino acid in the sequence is ", Amino1_seq[len (Amino1_seq)-1]) #Printing output for the last amino acid in the sequence. print("The 'MDL' motif is found at index " , Amino1_seq.find("MDL")) DNA1_seq="AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA" print ("'TCCGGA'restriction site is at index %d to" % DNA1_seq.find("TCCGGA"),\ DNA1_seq.find("TCCGGA")+len ("TCCGGA"), "of the given DNA sequence") # Try and figure out how many times the restriction site is repeated.
5c8b5b06478ceaa0bf407f79c6a64c02e6228548
br7roy/py_work
/basic/错误、调试和测试/debug.py
2,667
4.0625
4
#调试 def foo(s): n = int(s) print('>>> n = %d' %n) return 10 / n def main(): foo('0') #main() """ 用print()最大的坏处是将来还得删掉它,想想程序里到处都是print(),运行结果也会包含很多垃圾信息。 所以,我们又有第二种方法。 """ #断言 """ 凡是用print()来辅助查看的地方,都可以用断言(assert)来替代: """ def foo(s): n = int(s) assert n != 0, 'n is zero!' return 10 / n def main(): foo('0') #main() """ 程序中如果到处充斥着assert,和print()相比也好不到哪去。不过,启动Python解释器时可以用-O参数 来关闭assert: 关闭后,你可以把所有的assert语句当成pass来看。 """ #logging """ 把print()替换为logging是第3种方式,和assert比,logging不会抛出错误,而且可以输出到文件: logging.info()就可以输出一段文本。运行,发现除了ZeroDivisionError,没有任何信息。怎么回事? 别急,在import logging之后添加一行配置再试试: """ import logging logging.basicConfig(level=logging.INFO) s = '0' n = int(s) logging.info('n = %d' % n) #print(10 / n) """ 这就是logging的好处,它允许你指定记录信息的级别,有debug,info,warning,error等几个级别, 当我们指定level=INFO时,logging.debug就不起作用了。同理,指定level=WARNING后,debug和info就不起作用了。这样一来,你可以放心地输出不同级别的信息,也不用删除,最后统一控制输出哪个级别的信息。 logging的另一个好处是通过简单的配置,一条语句可以同时输出到不同的地方,比如console和文件。 """ #pdb """ 第4种方式是启动Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态。我们先准备好程序: """ # err.py s = '0' n = int(s) #print(10 / n) #pdb.set_trace() """ 这种通过pdb在命令行调试的方法理论上是万能的,但实在是太麻烦了,如果有一千行代码,要运行到第999行得敲多少命令啊。还好,我们还有另一种调试方法。 """ # err.py import pdb s = '0' n = int(s) pdb.set_trace() # 运行到这里会自动暂停 print(10 / n) #这个方式比直接启动pdb单步调试效率要高很多,但也高不到哪去。 #IDE """ 如果要比较爽地设置断点、单步执行,就需要一个支持调试功能的IDE。目前比较好的Python IDE有: Visual Studio Code:https://code.visualstudio.com/,需要安装Python插件。 PyCharm:http://www.jetbrains.com/pycharm/ 另外,Eclipse加上pydev插件也可以调试Python程序。 """
a36f4b6a081be0ed3f88f0e1cfce2a244bf23f61
cinnamennen/Advent2020
/src/02/a.py
845
3.796875
4
import pprint import re from typing import List pp = pprint.PrettyPrinter(indent=4) def read_input(): file = "input.txt" with open(file) as f: return f.readlines() def parse_input(data: str = None): if not data: data = read_input() else: data = data.splitlines() data = [_.strip() for _ in data] return data def solve(data=None): data = parse_input(data) regex = r"(\d+)-(\d+) (\w): (\w+)" count = 0 for d in data: char: str password: str low, high, char, password = re.match(regex, d).groups() low = int(low) high = int(high) amount = password.count(char) valid = low <= amount <= high if valid: count += 1 return count def main(): print(solve()) if __name__ == "__main__": main()
fed7b3fd11e18a0cd069e15fd381abb2772b8b5d
chkaradimitriou/MyPythonLessons
/Lesson1/LessonOne.py
501
4.09375
4
# 1. Exercise print to console # 2. String properties # 3. Primitive types import math # Strings | Print name length, upper & lower letters. x = "name" name = "Christos" print(len(name)) print(name.upper()) print(name.lower()) name = " Christos " print(name.strip()) # String | Print greeting + name + add space greeting = "Hello" print(greeting + " " + name) #Int | float y = 5 c = float(y) print(y) print(c) # Int | complex d = complex(c) print(d) # if else + ex lesson 2 defterova9mia exisosh
2e56781006ea5f2249a8d9f44942533ffc2948fd
guogander/python100
/lesson_73.py
200
4.09375
4
# 题目:反向输出一个链表。 l1 = [int(input("please input a number:\n")) for i in range(5)] l2 = l1[::-1] l1.reverse() print(l1) print(l2) for i in range(len(l2)): print(l2[i])
afaa12d698bd6756c40497d893101acf08329500
Gowthini/gowthini
/numberreverse.py
113
3.640625
4
x=int(input("enter the number")) rev=0 while(x>0): dig=x%10 rev=rev*10+dig x=x//10 print(rev)
7d481b424be7bce96fef0782f8725be293d11265
changchingchen/leetcode
/725_SplitLinkedListInParts/solution.py
1,001
3.65625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]: new_list = [None] * k if not root: return new_list size = 0 node = root while node: size += 1 node = node.next quotient = size // k remainder = size % k node = root for i in range(k): sublist_size = quotient if remainder > 0: sublist_size += 1 remainder -= 1 size -= sublist_size new_list[i] = node while sublist_size > 1: node = node.next sublist_size -= 1 next_node = node.next node.next = None node = next_node if size <= 0: break return new_list
3207873c9f688251f60ff30a97049d2c5660d14f
Kzshii/aulas
/revisao_6f.py
131
3.90625
4
a=int(input("Insira um valor: ")) b=int(input("Insira outro valor: ")) temp=a a=b b=temp print("Os valores trocados são",a,"e",b)
843f872bcc086a7cb930268579ac185de83e5469
trishajjohnson/python-fundamentals
/python-syntax/words.py
483
4.5
4
def print_upper_words(words, must_start_with): """takes word in words and prints word capitalized For example: print_upper_words(['hello', 'goodbye']) should print: HELLO GOODBYE """ # utilizing python's built in function capitalize() for word in words: if word[0] in must_start_with: print(word.upper()) print_upper_words(["hello", "hey", "goodbye", "yo", "yes", "yellow"], must_start_with = {'h', 'y'})
10c35fbf192aa93632d777ab8c60ece05018b943
nycowboy04/PythonProjects
/Practice exercises/divisors.py
137
4
4
a = int(input("Please enter a number: ")) x = range(2, a) for item in x: if a%item == 0: print(item, "is a divisor of", a)
0199f10d3fe8eb9b93f185e978721bfa5693e50f
adyadyat/pyprojects
/shultais_courses/data_types/string_methods_string_conditions/string_conditions.py
997
3.921875
4
domain1 = "www.yandex.ru" domain2 = "www.youtube.com" domain3 = "www.rutracker.org" domain4 = "yandex.ua" print(domain1.endswith(".ru")) print(domain2.endswith(".ru")) print(domain3.endswith(".ru")) print(domain4.endswith(".ru")) print("*" * len(domain4)) print(domain1.startswith("www.")) print(domain2.startswith("www.")) print(domain3.startswith("www.")) print(domain4.startswith("www.")) print("*" * len(domain4)) print(domain1.islower()) print(domain2.islower()) print(domain3.isupper()) print(domain4.isupper()) # МЕТОДЫ СТРОК: СОСТОЯНИЕ СТРОК # Методы возвращают True Falce # S.endswith(str) Заканчивается ли строка S шаблоном str # S.startswith(str) Начинается ли строка S с шаблона str # S.islower() Состоит ли строка из символов в нижнем регистре # S.isupper() Состоит ли строка из символов в верхнем регистре
a7e34d6ea180417cbf1b8c7e829a1e0a774ec9b6
james-dietz/advent-of-code-2020
/challenges/day02/solutions/part2.py
1,110
4.28125
4
from challenges.day02.solutions.part1 import Policy, parse_policy def is_valid_toboggan_password(policy: Policy, password: str) -> bool: """ Test if the password conforms to Toboggan's version of the password policy. The policy is interpreted as: - the required character must exist in exactly one of the two 1-indexed indices from the policy. :param policy: the password policy :param password: the password to test :return: whether the password is valid or not """ character, i1, i2 = policy first = password[i1 - 1] == character second = password[i2 - 1] == character return first != second def solve_part2(input_filename: str) -> int: with open(input_filename, "r") as input_file: # parse each line's policy and extract the password lines = [parse_policy(line.rstrip("\n")) for line in input_file.readlines()] # count the number of valid passwords return sum([is_valid_toboggan_password(policy, password) for policy, password in lines]) if __name__ == '__main__': print(solve_part2("../inputs/input.txt"))
8729b50117f1b83a84bca8d5823e104da58741d1
504703038/Linux
/study/大二下/Python/实验/实验4/习题4.3.py
314
3.84375
4
# 习题4.3 def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def lcm(a, b): return a * b / gcd(a, b) x, y = eval(input("请输入两个整数(用逗号隔开):")) print("{}和{}的最大公约数是{},最小公倍数是{:.0f}".format(x, y, gcd(x, y), lcm(x, y)))
a6ff98936c5fa00aebf16a44a90ea1e9d373524b
enriqueaf/UniProyectos
/Circulo.py
265
4.15625
4
from math import sqrt def distancia(x,y): return sqrt(x**2+y**2) def Circulo(r): for y in range(2*r): for x in range(2*r): if distancia(r-x,r-y) <= r-1: print '*', else: print ' ', print print 'Introuzca un numero' a = input('>>> ') Circulo(a)
3195d8c879900d8e7bb047db4f566fd6910b7229
jingwen-z/python-playground
/leetcode/1323.maximum-69-number.py
874
3.984375
4
# Easy # # Given a positive integer num consisting only of digits 6 and 9. # # Return the maximum number you can get by changing at most one digit # (6 becomes 9, and 9 becomes 6). # # # Example 1: # # Input: num = 9669 # Output: 9969 # Explanation: # Changing the first digit results in 6669. # Changing the second digit results in 9969. # Changing the third digit results in 9699. # Changing the fourth digit results in 9666. # The maximum number is 9969. # # Example 2: # # Input: num = 9996 # Output: 9999 # Explanation: Changing the last digit 6 to 9 results in the maximum number. # # Example 3: # # Input: num = 9999 # Output: 9999 # Explanation: It is better not to apply any change. # # # Constraints: # # 1 <= num <= 10^4 # num's digits are 6 or 9. class Solution: def maximum69Number (self, num: int) -> int: return int(str(num).replace('6', '9', 1))
b203a0f35c12e477f30849af6cf8afa844c3b145
szyszprzemek/Advent_Callendar
/4/4_2.py
798
3.671875
4
def uniqueElements(arg): '''Find unique elements in list''' b = set(arg) return list(b) def check(arg): ''' Checking conditions ''' a_old = 0 flag = False allNr = [] for a_str in str(arg): a = int(a_str) if (a < a_old): return False if (a == a_old): flag = True allNr.append(a) a_old = a if(flag): for element in uniqueElements(allNr): if (str(arg).count(str(element)) == 2): return True return False if __name__ == "__main__": start = 353096 end = 843212 counter = 0 for i in range(start, end): if (check(i)): print(i) counter += 1 print("Counter: ", counter)
b7db6cb2269a41492e4e0668c3da42648a56d22f
pepitooo/python-wd40
/wd40/expire_fifo.py
3,149
3.6875
4
import arrow class ExpireArrow(arrow.Arrow): def is_expired(self) -> bool: return self < arrow.utcnow() def expiration(self, seconds): return self.replace(seconds=seconds) class ExpireFifo: def __init__(self, expire_s=None): """ :param expire_s: expiration date delta en seconds all objects inserted will use this delta to set their own expiration date :return: """ self._list = [] self.expire_s = expire_s self.arrow_factory = arrow.ArrowFactory(ExpireArrow) def append(self, p_object, expire_s=None) -> None: """ Append new object in the list :param p_object: object to add to the list :param expire_s: (optional) if you want to use a different expiration date in seconds """ if expire_s is None: expire_s = self.expire_s expiration_date = self.arrow_factory.now().expiration(seconds=expire_s) self._list.append((expiration_date, p_object)) def pop(self) -> object: """ :return: first element stored in the list (FIFO) :raise: ExpireFifo.ExpiredValueError if the data is expired """ # list.pop(0) = take first element stored while not self.is_empty(): expiration_date, p_object = self._list.pop(0) if not expiration_date.is_expired(): return p_object del expiration_date del p_object raise KeyError def is_empty(self): """ :return: true is the ExpireFifo is empty """ return 0 == len(self._list) class ExpiredValueError(TimeoutError): """ raise this when data is expired on pop() """ pass class ExpireDict(dict): def __init__(self, expire_s=None): """ :param expire_s: expiration date delta en seconds all objects inserted will use this delta to set their own expiration date :return: """ super().__init__() self.expire_s = expire_s self.arrow_factory = arrow.ArrowFactory(ExpireArrow) def add(self, key, value, expire_s=None): if not expire_s: expire_s = self.expire_s expiration_date = self.arrow_factory.now().expiration(seconds=expire_s) super().__setitem__(key, (value, expiration_date)) def __setitem__(self, key, value): self.add(key, value) def get(self, k, d=None): self.clean_up() p_object, expiration_date = super().get(k, d) return p_object def pop(self, k, d=None): self.clean_up() p_object, expiration_date = super().pop(k, d) return p_object def __getitem__(self, key): return self.get(key) def __contains__(self, item): self.clean_up() return super().__contains__(item) def clean_up(self): for key in list(super().keys()): val = super().get(key) p_object, expiration_date = val if expiration_date.is_expired(): super().__delitem__(key)
92dd469943e90ab8caa822eea316f03b5050248c
computingForSocialScience/cfss-homework-AlyssaBlack
/Assignment5/fetchArtist.py
1,264
3.78125
4
import sys import requests import csv import re def fetchArtistId(name): """Using the Spotify API search method, take a string that is the artist's name, and return a Spotify artist ID. """ url = "https://api.spotify.com/v1/search?q=" +name+ "&type=artist" r = requests.get(url).json() artist = r["artists"] #print artist items = artist['items'] pick = items[0] id = pick['id'] #print id return id #fetchArtistId('Robyn') def fetchArtistInfo(artist_id): """Using the Spotify API, takes a string representing the id and ` returns a dictionary including the keys 'followers', 'genres', 'id', 'name', and 'popularity'. """ url = "https://api.spotify.com/v1/artists/"+artist_id r = requests.get(url).json() artistinfo = {} followers = r['followers'] followers = followers['total'] artistinfo['followers'] = followers genres = r['genres'] artistinfo['genres'] = genres id = r['id'] artistinfo['id'] = id name = r['name'] artistinfo['name'] = name popularity = r['popularity'] artistinfo['popularity'] = popularity #print artistinfo return artistinfo #fetchArtistInfo('6UE7nl9mha6s8z0wFQFIZ2')
c2fc2112d1c6268c5294d89a14dce45bd184202b
PythonBuffalo/unit-testing
/1_unittest/2_setup_teardown.py
1,320
3.953125
4
import unittest class SetupTeardownTest(unittest.TestCase): @classmethod def setUpClass(self): """This is run before any of the test methods are run @classmethod is required """ self.data = {'not': 'what', 'we': 'want'} @classmethod def tearDownClass(self): """This is run after all the test methods have been run @classmethod is required """ self.data = None def setUp(self): """This is run before each and every test """ self.data = {'some': 'data'} def tearDown(self): """This is run after each and every test """ self.data = None def test_data(self): """Test and make sure that setUp is run before this test method and we get the data we expect """ self.assertIsNotNone(self.data, 'self.data is None') self.assertEqual(self.data, {'some': 'data'}, 'self.data is not what we expected') def test_again(self): """Same as the test above just to prove that setUp is run again before this test method """ self.assertIsNotNone(self.data, 'self.data is None') self.assertEqual(self.data, {'some': 'data'}, 'self.data is not what we expected') if __name__ == '__main__': unittest.main()
fa7086071de733ae130fbd29fa9dd8258dc7fc13
juniorsmartins/Aulas-Python
/Aula12.py
578
3.953125
4
# -*- coding: utf-8 -*- print('') print('Estudo de Python') print('Livro: Python para desenvolvedores - Luiz Eduardo Borges') print('') nome = input('Qual teu nome? ') nota1 = float(input('Qual tua primeira nota? ')) nota2 = float(input('Qual tua segunda nota? ')) nota3 = float(input('Qual tua terceira nota? ')) nota_media = (nota1 + nota2 + nota3)/3 if nota_media < 0: print('Nota c/ Erro!') elif 0 <= nota_media < 7: print('Reprovado!') elif 7 <= nota_media < 9: print('Aprovado!') elif 9 <= nota_media <= 10: print('Aprovado com louvor!') else: print('Nota inexistente!')
bfa9b3b8116b062cd7838d2a3b8b2509b319c840
kitianFresh/flask-study
/Decorator/realworldDecorator/building-sys/smartbuilder/graphlib.py
3,037
3.515625
4
# -*- coding: utf-8 -*- from collections import defaultdict class Graph: """ 一个关于构建任务之间关系的有向图. 一个任务是通过 hash 值直接获取的, 这里使用 python 的 dictionary key. """ sort_key = None def __init__(self): # 使用 defaultdict 而不是 dict 的原因是, dict 对不存在 key 的访问 dict['key'] 访问会抛出 KeyError # defaultdict 当 key 不存在时, 会输出 空集合 set(). 这样代码会更加简练, Pythonic # 这里采用了同时存储 出度和入度 的冗余 hash 链表 self._inputs_of = defaultdict(set) self._consequences_of = defaultdict(set) def sorted(self, nodes, reverse=False): nodes = list(nodes) try: nodes.sort(key=self.sort_key, reverse=reverse) except TypeError: pass return nodes def add_edge(self, input_task, consequence_task): """ 添加一条边: `consequece_task` 使用 `input_task` 的输出. """ self._consequences_of[input_task].add(consequence_task) self._inputs_of[consequence_task].add(input_task) def remove_edge(self, input_task, consequence_task): self._consequences_of[input_task].remove(consequence_task) self._inputs_of[consequence_task].remove(input_task) def inputs_of(self, task): """ 按顺序返回 `task` 的所有输入 """ return self.sorted(self._inputs_of[task]) def clear_inputs_of(self, task): input_tasks = self._inputs_of.pop(task, ()) # 删除所有的该任务的入度 # 删除该任务在出度的贡献 for input_task in input_tasks: self._consequences_of[input_task].remove(task) def edges(self): """ 返回所有的边, 结果是 由 ``(input_task, consequence_task)`` 组成的 tuples.""" return [(a, b) for a in self.sorted(self._consequences_of) for b in self.sorted(self._consequences_of[a])] def tasks(self): """返回图中所有的任务.""" return self.sorted(set(self._inputs_of).union(self._consequences_of)) def immediate_consequences_of(self, task): """Return the tasks that use `task` as an input.""" return self.sorted(self._consequences_of[task]) def recursive_consequences_of(self, tasks, include=False): def visit(task): visited.add(task) consequences = self._consequences_of[task] for consequence in self.sorted(consequences, reverse=True): if consequence not in visited: visit(consequence) stack.insert(0, task) def generate_consequences_backwards(): for task in self.sorted(tasks, reverse=True): visit(task) if include is False: stack.remove(task) visited = set() stack =[] generate_consequences_backwards() return stack
dceddc8ff404b9fd05393aeeb18c1f24eaebfed0
moriakh/zoo
/zoo.py
3,174
4.03125
4
from animal import Frog, Tiger, Bear, Peacock class Zoo: def __init__(self, zoo_name): self.animals = [] self.name = zoo_name self.animal_class = '' self.regular_food = '' self.max_qty_food = '' self.gender = '' self.random_attribute = '' def add_animal(self): self.animal_class = '' self.regular_food = '' self.max_qty_food = '' self.gender = '' while self.animal_class == '': print('According to the following list:') print('1 : Amphibia') print('2 : Reptiles') print('3 : Birds') print('4 : Mammals') animal_class = input('Please insert the animal class: ') if animal_class == '1': self.animal_class = 'Amphibia' elif animal_class == '2': self.animal_class = 'Reptiles' elif animal_class == '3': self.animal_class = 'Birds' elif animal_class == '4': self.animal_class = 'Mammals' else: self.animal_class = '' while self.regular_food == '': self.regular_food = input('How many kilograms eat daily? ') while self.max_qty_food == '': self.max_qty_food = input('Max kilograms/day? ') # hacer validador para que max sea mayor que regular while self.gender == '': self.gender = input("Enter 'F' for Female or 'M' for Male: ") return self def add_frog(self, name): self.add_animal() self.random_attribute = input(f"Insert {name}'s jumps: ") self.random_attribute = float(self.random_attribute) self.animals.append(Frog(name, self.animal_class, self.regular_food, self.max_qty_food, self.gender, self.random_attribute)) def add_tiger(self, name): self.add_animal() self.random_attribute = input(f"Insert {name}'s bites: ") self.random_attribute = float(self.random_attribute) self.animals.append(Tiger(name, self.animal_class, self.regular_food, self.max_qty_food, self.gender, self.random_attribute)) def add_bear(self, name): self.add_animal() self.random_attribute = input(f"Insert {name}'s roars: ") self.random_attribute = float(self.random_attribute) self.animals.append(Bear(name, self.animal_class, self.regular_food, self.max_qty_food, self.gender, self.random_attribute)) def add_peacock(self, name): self.add_animal() self.random_attribute = input(f"Insert {name}'s flies: ") self.random_attribute = float(self.random_attribute) self.animals.append(Peacock(name, self.animal_class, self.regular_food, self.max_qty_food, self.gender, self.random_attribute)) def print_all_info(self): print("-"*30, self.name, "-"*30) for animal in self.animals: if animal.state == "'I'm died'": # tb puede ser un animal.health == 0 pass # limpiar lista else: animal.display_info() print("\n") return self
6908555b3aef9de0709bc6c1e40733bb407de0e5
KruZZy/coderdojo-python
/16.11.2019/challenge_6.py
126
3.78125
4
def divizori (n): for i in range (1,n//2+1): if n%i ==0: print (i) print (n) n=int(input("n= ")) divizori (n)
662c25c5eb58c442466ee5a0fd37262381bf65ad
cosmo-developer/qcore
/quadnative/home/py_command.py
1,248
3.59375
4
__globals__ = globals() # Don't erase it import hashlib def MyName(c=4, d=44): return c + c * c + d def E(x): return [5, 5, 5, 5] def Factorial(n): if n == 0: return 1 else: return n * Factorial(n - 1) def GiveMyName(yourname): return yourname def SayHelloToUser(username): print("Hello User:", username) def Max(n): if n == 0: return 1 else: return n * Max(n - 1) def Eval(exp): return eval(exp) def Hash(data): return hashlib.sha3_512(data.encode('utf-8')).hexdigest() def Execute(python_code): return exec(python_code) def Something(): return BACKUP.self + ' ' + ARRAY.index1 + '\n' def Login(username, password): if username == DB.username and password == DB.password: return 'Logined Successfully' else: return 'Login Unsuccess' def LaptopDetail(): print('___Laptop Details____') print("Name:", LAPTOP.self) print("Type:", LAPTOP.type) print("Processor Inside:", LAPTOP.processor) print("Processor Speed:", LAPTOP.processor_speed) print("Storage Type:", LAPTOP.internal_type) print("Storage Capacity:", LAPTOP.internal_capacity) print("Price:", LAPTOP.price) return LAPTOP.self
6579f140a88c6d6e79a5baa447cf9725dbe1162e
ritik1457/python-codes
/paladroem.py
169
3.609375
4
n=int(input("enter a number")) m=n sum=0 while(n>0): rem=n%10 sum=sum*10+rem n=n//10 if(sum==m): print("paledrome",+sum) else: print("non")
4468b3ce4eeda8e7de5fa1033d66fd4c8e55cf6a
hoang2109/leetcode-practice
/Map/136.py
718
3.671875
4
# 136. Single Number # Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. # Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory? # Example 1: # Input: nums = [2, 2, 1] # Output: 1 # Example 2: # Input: nums = [4, 1, 2, 1, 2] # Output: 4 # Example 3: # Input: nums = [1] # Output: 1 class Solution(object): def singleNumber(self, nums): dic = {} for _, val in enumerate(nums): if val in dic: dic[val] += 1 else: dic[val] = 1 for k, v in dic.items(): if v == 1: return k return -1
74a438e30aff480dc4ed629529188de767bcf07e
baballev/DailyCode
/18-03-2020-num53.py
1,178
3.8125
4
# Implement a FIFO with two LIFO. class Stack: def __init__(self): self.content = [] def pop(self): if not self.content: return None else: return self.content.pop() def add(self, x): self.content.append(x) def isVoid(self): return not self.content def length(self): return len(self.content) class Queue: def __init__(self): self.stack1 = Stack() self.stack2 = Stack() def enqueue(self, x): if self.stack2.isVoid: self.stack1.add(x) else: for _ in range(self.stack2.length()): self.stack1.add(self.stack2.pop()) self.stack1.add(x) def dequeue(self): if (not self.stack2.isVoid()): return self.stack2.pop() else: for _ in range(self.stack1.length()): self.stack2.add(self.stack1.pop()) return self.stack2.pop() test1 = Queue() test1.enqueue(1) test1.enqueue(2) test1.enqueue(3) print(test1.stack1.content) print(test1.stack2.content) print(str(test1.dequeue())) print(test1.stack1.content) print(test1.stack2.content)
405babd22a37ce158c1df71dd4470790e2b7c0a1
sreeaurovindh/code_sprint
/recursion/simple_recursion/1-recursive_print.py
207
3.984375
4
def recursive_print(num): if num < 1: return else: print("Prev Line: Test",num) recursive_print(num-1) print("End Line: Test",num) return recursive_print(3)
2d354aebeab6c27bcd9795f7e704b03a283706f1
dgreeott/Blackjack_Python
/business.py
6,137
4.25
4
#!/usr/bin/ env python3 # 04/26/2020 # @uthor Drake Greeott # Design and implement an object-oriented program for a simple game of # blackjack that provides for one player and a dealer (the computer). from db import Card, Deck, Hand #Creating the game class Blackjack(): def __init__(self): pass #function to display and play the game def play_game(self): print("Blackjack") print() game = True #while loop for the start of the game while game: #creating the deck variable self.deck = Deck() self.deck.shuffle_cards() #creating the players hand and dealers hand self.player_hand = Hand() self.dealer_hand = Hand(dealer=True) #deal two cards to each player and dealer for i in range(2): self.player_hand.add_card(self.deck.deal_cards()) self.dealer_hand.add_card(self.deck.deal_cards()) #showing one card of the dealers hand and both cars of the players print("DEALER'S SHOW CARD:") self.dealer_hand.display_start() print() print("YOUR CARDS:") self.player_hand.display_start() print() game_over = False #while loop for the rest of the game while not game_over: player_points = self.player_hand.get_points() dealer_points = self.dealer_hand.get_points() #determining of the player of dealer has blackjack blackjack_player, blackjack_dealer = self.blackjack_check() #if statement to determine what text should be printed to the screen if blackjack_player or blackjack_dealer: game_over = True self.show_blackjack(blackjack_player, blackjack_dealer) continue #creating the choice variable and question to want to hit or stand choice = input("Hit or stand? (hit/stand): ").lower() print() #if statment on if choice = "hit" if choice == "hit": #add a card to the players hand self.player_hand.add_card(self.deck.deal_cards()) #display the cards on the screen print("YOUR CARD'S: ") self.player_hand.display_start() print() #if statment to run the player over function if self.player_over(): self.show_points(player_points, dealer_points) print("You have busted!") game_over = True #else if statement for choice = "stand" else: if dealer_points < 17: #to check the function to see if the dealer shoud hit or stand self.dealer_hand.add_card(self.deck.deal_cards()) elif dealer_points >= 17: if self.dealer_over(): #to display the dealers whole hand on the screan print("DEALER'S CARD'S: ") self.dealer_hand.display_end() self.show_points(player_points, dealer_points) print("You have busted!") game_over = True else: #to display the dealers whole hand on the screan print("DEALER'S CARD'S: ") self.dealer_hand.display_end() self.show_points(player_points, dealer_points) self.decide_winner(player_points, dealer_points) game_over = True #to determine of the player wants to play again print() again = input("Play Again? (y/n) ") while again.lower() not in ["y", "n"]: if again.lower() == "n": print("Come back soon!") playing = False else: game_over = False #checking for blackjack for both the player and dealer def blackjack_check(self): player = False dealer = False if self.player_hand.get_points() == 21: player = True if self.dealer_hand.get_points() == 21: dealer = True return player, dealer #showing the text on if either or both the player and deal have 21 def show_blackjack(self, blackjack_player, blackjack_dealer): if blackjack_player and blackjack_dealer: print("Both players have blackjack! Draw!") elif blackjack_player: print("You have blackjack! You win!") elif blackjack_dealer: print("Dealer has blackjack! Dealer wins!") #to show the end points of both the player and dealer def show_points(self, player_points, dealer_points): print() print("YOUR POINTS: ", player_points) print("DEALER'S POINTS:", dealer_points) print() #to determine if the player wins, ties, or the dealer wins def decide_winner(self, player_points, dealer_points): if player_points > dealer_points: print("You Win!") elif player_points == dealer_points: print("Tie!") else: print("Dealer Wins!") game_over = True #to determine if the players hand is over 21 def player_over(self): return self.player_hand.get_points() > 21 #to determine if the dealers hand is over 21 def dealer_over(self): return self.dealer_hand.get_points() > 21
681936b24a2021c507f8db6bf6bcecbf4d685031
shubhamTeli/PythonAutomationMachineLearning
/Assignment2_10.py
266
3.609375
4
import sys; def main(no): i=0; Digitsum=0; while (no != 0): Digitsum += no % 10; no = no // 10; i+=1; print("Addition of digits in no are: ",Digitsum); if (__name__ == '__main__'): main(int(sys.argv[1]));
b07cdb347a801c503ac6c1075ff1966daece249d
thanhtd32/advancedpython_part1
/Exercise13.py
2,941
4.0625
4
#Coder: Tran Duy Thanh #Email: thanhtd@uel.edu.vn #Phone: 0987773061 #Blog for self-study: https://duythanhcse.wordpress.com #Facebook for solving coding problem: https://www.facebook.com/groups/communityuni #Description: #These codes I improved from Exercise 12. #1.use 2d array dimension to improve program #2.give any postion to user guess (use randomn position) #eg: [2, 4, 6, ?], [13, ?, 19, 22], [?, 3, 5, 7, 11],... #3.use try..exception to catch user problem input import random #pattern 2D array to stored all pattern patterns=[ [2, 4, 6, 8],[13, 16, 19, 22], [2, 3, 5, 7, 11],[1, 1, 2, 3, 5, 8], [31, 28, 31, 30] ] #this function use to check matching value between pattern and guessing value #it will return True (right) or False (wrong) def patternmatch(pattern): #variable to store right or wrong guessing number correctAns=False #get the len of pattern (1D array) lenOfPattern = len(pattern) #random a postion guessPosition = random.randint(0, lenOfPattern-1) #user has to guess value at this position valueAtQuestionMark = pattern[guessPosition] for i in range(lenOfPattern): if i == guessPosition: print("?", end=" ")#print ? mark, user must guess this number else: print(pattern[i],end=" ") while True:#user must enter valid value try:#use try except guessAns = int(input("What is the value at ? position:")) break except ValueError: print("Value input is not valid! please enter an integer number") if guessAns == valueAtQuestionMark: correctAns = True print("Well done! Congratulations") else: correctAns = False print("You are wrong, the correct answer is %d " %valueAtQuestionMark) return correctAns #this function pass the 2D pattern array #it will iterate all data in 2D to ask user give guessing number def playQuiz(patterns): # variable to count correct or wrong guessing number correctAns = 0 wrongAns = 0 lenOfPattern=len(patterns) for i in range(lenOfPattern): #get an 1D array pattern to resuse the patternmatch function above pattern=patterns[i] result= patternmatch(pattern) if result == True: correctAns = correctAns + 1 else: wrongAns = wrongAns + 1 print("%d patterns, correct %d, wrong %d."%(lenOfPattern,correctAns,wrongAns)) #this function will use while loop to ask user re-play Quiz Game: def playQuizLoop(): while True: print("Welcome to Quiz Game!") playQuiz(patterns) confirm=input("Do you want to re-play Quiz Game?[y,n]:") if confirm == 'n' or confirm == 'N': break print("Thank you so much for your playing the Quiz Game!") #call playQuizLoop functioin: playQuizLoop()
52f38ad2d50b787cfdcec4b1f4f82a9ebe73fc35
FaustoXLopez/PROYECTOS
/PYTHON/For.py
200
3.890625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 25 14:23:54 2021 @author: Fausto López """ x=int(input("Ingrese un número: ")) y=1 while True: print(y) y=+1 if y> x: break
863c95ab25b10acda3a7ad3a28e572cd26723e0c
zadraleks/Stepik.Python_3.First_steps
/Lesson 1-5/1-5-1.py
245
3.8125
4
#Напишите программу, которая считает сумму трёх целых чисел. Данные находятся на разных строках. a = int(input()) b = int(input()) c = int(input()) print(a + b + c)
6ee1435c673f32f20776f31ccecf3d74ef38ee21
KansasCityWomeninTechnology/games1
/variables.py
221
3.8125
4
# using number variables x = 5 print(x) x = 6 print(x) x = x + 2 print(x) y = 7 z = x - y print(z) # using word variables word1 = "Coding " word2 = "and " word3 = "Cupcakes" message = word1 + word2 + word3 print(message)
24e3c0060ec35b9871918ec37a8b7202386b09b6
shyheng/Python
/Python-OutTime/shy/1.py
648
3.9375
4
# != 不等于 命令 = "" 出发 = False while True: 命令 = input(">").lower() if 命令 == "开始": if 出发: print("滚") else: 出发 = True print("准备停车") elif 命令 == "stop": if not 出发: print("大哥,车已经停sb") else: 出发 = False print("停了") elif 命令 == "help": print(""" # 保持装换 开始- 开始停车 stop- 为了停车 quit- 老子不玩了 """) elif 命令 == "quit": break#直到输入 quit结束 else: print("老子不玩了")
54439e4a63ccb8d5fac06ee240863eda6b0146d8
NutthanichN/grading-helper
/week_6/6210545475_lab6.py
10,580
4.09375
4
# exercise 1 def ll_sum(t): """ takes a list of lists of integers and adds up the elements from all of the nested lists. >>> t = [[1, 2], [3], [4, 5, 6]] >>> ll_sum(t) 21 >>> t = [[1], [2], [3]] >>> ll_sum(t) 6 >>> t = [[0], [1], [2, 3, 4]] >>> ll_sum(t) 10 >>> t = [[-1, -7], [-9], [-5, -6]] >>> ll_sum(t) -28 >>> t = [[5], [5], [5]] >>> ll_sum(t) 15 """ number = [] for i in t: number += i return sum(number) # exercise 2 def cumulative_sum(t): """ takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. >>> t = [1, 2, 3] >>> cumulative_sum(t) [1, 3, 6] >>> t = [4, 5, 6] >>> cumulative_sum(t) [4, 9, 15] >>> t = [1000000, 999999.9999, 3636353] >>> cumulative_sum(t) [1000000, 1999999.9999000002, 5636352.9999] >>> t = [-1, -2, -3] >>> cumulative_sum(t) [-1, -3, -6] >>> t = [a, b, c] >>> cumulative_sum(t) Traceback (most recent call last): ... NameError: name 'a' is not defined """ summary = [] num = [] for i in t: num.append(i) summary.append(sum(num)) return summary # exercise 3 def middle(t): """ function called middle that takes a list and returns a new list that contains all but the first and last elements. >>> t = [1, 2, 3, 4] >>> middle(t) [2, 3] >>> t = [1, 2, 3, 4, 5, 6] >>> middle(t) [2, 3, 4, 5] >>> t = [0] >>> middle(t) [] >>> t = [] >>> middle(t) [] >>> t = [[1, 2],[3],[4, 5, 6],[7]] >>> middle(t) [[3], [4, 5, 6]] """ new_list = [] removed_string = [] count = 0 for i in t: if count == 0 or count == (len(t) - 1): removed_string.append(i) count += 1 else: new_list.append(i) count += 1 print(f"{new_list}") # exercise 4 def chop(t): """ takes a list, modifies it by removing the first and last elements, and returns None. >>> t = [1, 2, 3, 4] >>> chop(t) >>> t [2, 3] >>> t = [1, 2, 3, 4, 5, 6] >>> chop(t) >>> t [2, 3, 4, 5] >>> t = [0] >>> chop(t) >>> t [] >>> t = [] >>> chop(t) >>> t [] >>> t = [[1, 2],[3],[4, 5, 6],[7]] >>> chop(t) >>> t [[3], [4, 5, 6]] """ count = 0 for i in t: if count == 0 or count == (len(t) - 1): t.remove(i) count += 1 else: count += 1 # exercise 5 def is_sorted(list): """ takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise. >>> is_sorted([1, 2, 2]) True >>> is_sorted([1, 2, 3, 4, 0]) False >>> is_sorted(["a","b","c"]) True >>> is_sorted(["b","a"]) False >>> is_sorted([b,a]) Traceback (most recent call last): ... NameError: name 'b' is not defined """ if list == sorted(list): return True else: return False # exercise 6 def front_x(l): """ Returns a list with the strings in sorted order, except group all the strings that begin with 'x' first. >>> l = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] >>> front_x(l) ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] >>> l = ['b', 'd', 'e', 'a', 'x', 'c'] >>> front_x(l) ['x', 'a', 'b', 'c', 'd', 'e'] >>> l = ['xxx', 'xxxxx', 'x', 'xx', 'xxxx'] >>> front_x(l) ['x', 'xx', 'xxx', 'xxxx', 'xxxxx'] >>> l = ['xz', 'x3', 'x1', 'xa'] >>> front_x(l) ['x1', 'x3', 'xa', 'xz'] >>> l = ['x%', 'x*', 'x!', 'x&', 'x#'] >>> front_x(l) ['x!', 'x#', 'x%', 'x&', 'x*'] """ x_string = [] list_string = [] for i in l: if i[0] == "x": x_string.append(i) else: list_string.append(i) return sorted(x_string) + sorted(list_string) # exercise 7 def even_only(list): """ Take a list of integers, and return a new list with only even numbers. >>> even_only([3,1,4,1,5,9,2,6,5]) [4, 2, 6] >>> even_only([3,1,1,5,9,5]) [] >>> even_only([7,8,0,1,9,4,3]) [8, 0, 4] >>> even_only(1+1,2+2,3+6,4+9,5+7) Traceback (most recent call last): ... TypeError: even_only() takes 1 positional argument but 5 were given >>> even_only([[2],2,3,4]) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for %: 'list' and 'int' """ even_num = [] for i in list: if i % 2 == 0: even_num.append(i) else: pass return even_num # exercise 8 def love(text): """ Change the second last word of the text to “love”. >>> love("I like Python") "I love Python" >>> love("I really like XiaoZhan") "I really love XiaoZhan" >>> love("I hate Physics") "I love Physics" >>> love(I like Python) File "C:/Gift/6210545475_lab6.py", line 267 ... SyntaxError: invalid syntax >>> love("IlikePython") Traceback (most recent call last): IndexError: pop index out of range """ text_list = text.split() text_list.pop(-2) text_list.insert(-1, "love") return " ".join(text_list) # exercise 9 def is_anagram(text1, text2): """ Takes two strings and returns True if they are anagrams. >>> is_anagram('arrange', 'Rear Nag') >>> True >>> is_anagram('arrange', 'Rear Nig') >>> False >>> is_anagram('Undertale', 'deltarune') >>> True >>> is_anagram('ah Nazi ox', 'Xiao Zhan') >>> True >>> is_anagram('13', '31') >>> True """ list_1 = [] list_2 = [] for i in text1: if i == " ": pass else: list_1.append(i.lower()) for i in text2: if i == " ": pass else: list_2.append(i.lower()) return sorted(list_1) == sorted(list_2) # exercise 10 def has_duplicates(list): """ Takes a list and returns True if there is any element that appears more than once. It should not modify the original list. >>> has_duplicates([1, 2, 3, 4, 5]) False >>> has_duplicates([1, 2, 3, 4, 5, 2]) True >>> has_duplicates(["a", "b", "d", "e"]) False >>> has_duplicates(["a", "b", "d", "e", "b"]) True >>> has_duplicates([a,b,c,a]) Traceback (most recent call last): ... NameError: name 'a' is not defined """ new_list = [] for i in list: if i in new_list: return True else: new_list.append(i) return False # exercise 11 def average(nums): """ Returns the mean average of a list of numbers. >>> average([1, 1, 5, 5, 10, 8, 7]) 5.285714285714286 >>> average([1,2,3,4,5,6]) 3.5 >>> average([[1], 1, 5, 5, 10, 8, 7]) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +: 'int' and 'list' >>> average([a, 1, 5, 5, 10, 8, 7]) Traceback (most recent call last): ... NameError: name 'a' is not defined >>> average([5,5,5,5]) 5.0 """ return (sum(nums))/(len(nums)) # exercise 12 def centered_average(nums): """ returns a "centered" average of a list of numbers, which is the mean average of the values that ignores the largest and smallest values in the list. If there are multiple copies of the smallest/largest value, pick just one copy. >>> centered_average([1, 1, 5, 5, 10, 8, 7]) 5.2 >>> centered_average([1,2,3,4,5,6]) 3.5 >>> centered_average([1,1,1,1]) 1.0 >>> centered_average([1,10]) Traceback (most recent call last): ZeroDivisionError: division by zero >>> centered_average([]) Traceback (most recent call last): ValueError: min() arg is an empty sequence """ nums.remove(min(nums)) nums.remove(max(nums)) return (sum(nums))/(len(nums)) # exercise 13 def reverse_pair(text): """ Two sentences are a “reverse pair” if each is the reverse of the other. Write a function reverse_pair that returns the reverse pair of the input sentence. >>> reverse_pair("May the fourth be with you") "you with be fourth the May" >>> reverse_pair("LanWangji and WeiWuxian friends forever") "forever friends WeiWuxian and LanWangji" >>> reverse_pair("Love you") "you Love" >>> reverse_pair(123) Traceback (most recent call last): ... AttributeError: 'int' object has no attribute 'split' >>> reverse_pair("Mo,dao,zu,shi") "Mo,dao,zu,shi" """ split_text = text.split() return " ".join(split_text[::-1]) # exercise 14 def match_ends(list): """ returns the count of the number of strings where the string length is 2 or more and the first and last chars of the string are the same. >>> match_ends(["Gingering", "hello","wow"]) 2 >>> match_ends(["loL", "papapa","Uwu", "blaB"]) 3 >>> match_ends(["in", "on","at"]) 0 >>> match_ends(["Aa", "Bb","Cc"]) 3 >>> match_ends(["A", "a","b"]) 0 """ match = 0 for i in list: if len(i) >= 2: if i[0].lower() == i[-1].lower(): match += 1 return match # exercise 15 def remove_adjacent(list): """ Returns a list where all adjacent elements have been reduced to a single element. >>> remove_adjacent([1, 2, 2, 3]) [1, 2, 3] >>> remove_adjacent([1, 2, 3, 1, 4]) [1, 2, 3, 4] >>> remove_adjacent(["a", "b", "c", "a", "c", "d"]) ['a', 'b', 'c', 'd'] >>> remove_adjacent([1]) [1] >>> remove_adjacent([1+0,1,0+1]) [1] """ new_list = [] for i in list: if i in new_list: pass else: new_list.append(i) return new_list
5db39a472399c2ebd5b93c9f2032f05b6577825f
platypusjerry/gpt3-web-tool
/gpt3.py
9,728
3.578125
4
"""Creates the Example and GPT classes for a user to interface with the OpenAI API.""" import openai import uuid from operator import itemgetter import requests import json #def set_openai_key(key): # """Sets OpenAI key.""" # openai.api_key = key class Example: """Stores an input, output pair and formats it to prime the model.""" def __init__(self, inp, out): self.input = inp self.output = out self.id = uuid.uuid4().hex def get_input(self): """Returns the input of the example.""" return self.input def get_output(self): """Returns the intended output of the example.""" return self.output def get_id(self): """Returns the unique ID of the example.""" return self.id def as_dict(self): return { "input": self.get_input(), "output": self.get_output(), "id": self.get_id(), } class GPT: """The main class for a user to interface with the OpenAI API. A user can add examples and set parameters of the API request. """ def __init__(self, engine, temperature, max_tokens, top_p, frequency_penalty, presence_penalty, stop = None, input_prefix="", input_suffix="\n", output_prefix=" ", output_suffix="\n\n", append_output_prefix_to_query=False): self.examples = {} self.engine = engine self.temperature = temperature self.top_p = top_p self.max_tokens = max_tokens self.frequency_penalty = frequency_penalty self.presence_penalty = presence_penalty self.input_prefix = input_prefix self.input_suffix = input_suffix self.output_prefix = output_prefix self.output_suffix = output_suffix self.append_output_prefix_to_query = append_output_prefix_to_query self.stop = stop def add_example(self, ex): """Adds an example to the object. Example must be an instance of the Example class. """ assert isinstance(ex, Example), "Please create an Example object." self.examples[ex.get_id()] = ex def delete_example(self, id): """Delete example with the specific id.""" if id in self.examples: del self.examples[id] def get_example(self, id): """Get a single example.""" return self.examples.get(id, None) def get_all_examples(self): """Returns all examples as a list of dicts.""" return {k: v.as_dict() for k, v in self.examples.items()} def get_prime_text(self): """Formats all examples to prime the model.""" return "".join( [self.format_example(ex) for ex in self.examples.values()]) def get_engine(self): """Returns the engine specified for the API.""" return self.engine def get_temperature(self): """Returns the temperature specified for the API.""" return self.temperature def get_top_p(self): """returns the top_p specified for the api""" return self.top_p def get_max_tokens(self): """Returns the max tokens specified for the API.""" return self.max_tokens def get_frequency_penalty(self): """returns the frequency penalty specified for the api""" return self.frequency_penalty def get_presence_penalty(self): """returns the presence penalty specified for the api""" return self.presence_penalty def craft_query(self, prompt): """Creates the query for the API request.""" q = self.get_prime_text( ) + self.input_prefix + prompt + self.input_suffix if self.append_output_prefix_to_query: q = q + self.output_prefix return q def update_temp(self, new_temp): self.temperature = new_temp return self.temperature def submit_request(self, prompt, new_temp): """Calls the OpenAI API with the specified parameters.""" response = openai.Completion.create(engine=self.get_engine(), prompt=self.craft_query(prompt), max_tokens=self.get_max_tokens(), temperature=self.update_temp(new_temp), top_p=self.get_top_p(), frequency_penalty=self.get_frequency_penalty(), presence_penalty=self.get_presence_penalty(), n=1, stream=False, stop=self.stop) return response def get_top_reply(self, prompt): """Obtains the best result as returned by the API.""" response = self.submit_request(prompt) return response['choices'][0]['text'] def format_example(self, ex): """Formats the input, output pair.""" return self.input_prefix + ex.get_input( ) + self.input_suffix + self.output_prefix + ex.get_output( ) + self.output_suffix class Semantic(): def __init__(self, engine, documents): self.engine = engine self.documents = documents def get_engine(self): return self.engine def get_query(self, query): return query def get_documents(self): return self.documents def get_score(self, query): search_response = openai.Engine(self.get_engine()).search( query = self.get_query(query), documents = self.get_documents() ) data_search_response = dict(search_response) intents_list = self.documents.copy() scores = [] for a,b in data_search_response.items(): if a == 'data': data_list = list(data_search_response.values()) document_list = data_list[1] for i,j in zip(document_list, intents_list): document = dict(i) intent_score = dict((k, document[k]) for k in ['document', 'score'] if k in document) intent_score.update(text = j) scores.append(intent_score) return scores def intent_filtering(self, raw_score): data = sorted(raw_score, key=itemgetter('score'), reverse=True) for a in range(len(data)): if data[a]["score"] < 0: data[a]["score"] = 0 max = 0 top_int = [] for i in range(len(data)-1): if data[i]["score"] - data[i+1]["score"] > max: max = data[i]["score"] - data[i+1]["score"] top_int.append(data[i]) return_list = [] for a in range(len(top_int)): return_list.append(top_int[a]["text"]) if len(return_list) > 4: return return_list[0:3] str_ = ", ".join(return_list) return(str_) class Jurassic(): def __init__(self, primer, suffix, numresult, temp, stopseq): self.primer = primer self.suffix = suffix self.numresult = numresult self.temp = temp self.stopseq = stopseq def get_prompt(self, prompt): q = self.primer + prompt + self.suffix return q def get_numresult(self): return self.numresult def get_temp(self): return self.temp def get_stopseq(self): return self.stopseq def encoder_test(self, testing): if isinstance(testing, Jurassic): return {'primer' : testing.primer, 'suffix' : testing.suffix, 'numresult' : testing.numresult, 'temp' : testing.temp, 'stopseq' : testing.stopseq} raise TypeError(f'Object {testing} is not of type Jurassic.') def submit_req(self, prompt, testing): resp = requests.post( "https://api.ai21.com/studio/v1/j1-large/complete", headers={"Authorization": "Bearer Ro2nbCuaQXhR6AH2rXysLXfzcAR17FbY"}, json={ "prompt": self.get_prompt(prompt), "numResults": self.get_numresult(), "maxTokens": 10, "stopSequences": self.get_stopseq(), "topKReturn": 0, "temperature": self.get_temp() } ) resp = resp.json() testJSON = json.dumps(resp, default=self.encoder_test(testing), indent=4) testObj = json.loads(testJSON) return testObj["completions"][0]["data"]["text"]
1ad1685d4cb8cff4eae645649a19e4644aa6eae9
gautam4941/Python_Basics_Code
/IfElse/Prog4.py
1,333
4.15625
4
#Calculate the attendance of a student by taking input of class_held and class_attended. #attendance = (class_attended/class_held) * 100. If attendace is less than 75 then, ask student for any #medical certifiate. If medicate certificate is there. Print Student can sit in exam. If attendace is less #than 75 and student doesn't have medical certifcate then print student can't sit in exam. #If student percentage is greater thn 75. Then, student is allowed to sit in exam. class_held = int( input("Enter the number of class held = " )) class_attended = int( input("Enter the number of class attended = " )) if( class_attended > class_held ): print("Wrong Input") else: attendance = (class_attended/class_held) * 100 if( attendance >= 75 ): print(f"Student is allowed to sit in class and attendance% = {attendance}") else: medical_issue = input("Do you have any medical problem : Y/N = ") if(medical_issue == 'Y'): print(f"Student is allowed to sit in class and attendance% = {attendance}") elif( medical_issue == 'N' ): print(f"Student is not allowed to sit in class and attendance% = {attendance}") else: print("Wrong Input") #Note : This is nested if-else program. if inside outer if or outer else.
b4fa4424669bb8964a580d7a50337ae41dc3b9d4
jvano74/advent_of_code
/2022/day_05_test.py
7,784
4
4
import re from collections import defaultdict class Puzzle: """ --- Day 5: Supply Stacks --- The expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged. The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack. The Elves don't want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark. They do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input). For example: [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2 In this example, there are three stacks of crates. Stack 1 contains two crates: crate Z is on the bottom, and crate N is on top. Stack 2 contains three crates; from bottom to top, they are crates M, C, and D. Finally, stack 3 contains a single crate, P. Then, the rearrangement procedure is given. In each step of the procedure, a quantity of crates is moved from one stack to a different stack. In the first step of the above rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this configuration: [D] [N] [C] [Z] [M] [P] 1 2 3 In the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a time, so the first crate to be moved (D) ends up below the second and third crates: [Z] [N] [C] [D] [M] [P] 1 2 3 Then, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a time, crate C ends up below crate M: [Z] [N] [M] [D] [C] [P] 1 2 3 Finally, one crate is moved from stack 1 to stack 2: [Z] [N] [D] [C] [M] [P] 1 2 3 The Elves just need to know which crate will end up on top of each stack; in this example, the top crates are C in stack 1, M in stack 2, and Z in stack 3, so you should combine these together and give the Elves the message CMZ. After the rearrangement procedure completes, what crate ends up on top of each stack? --- Part Two --- As you watch the crane operator expertly rearrange the crates, you notice the process isn't following your prediction. Some mud was covering the writing on the side of the crane, and you quickly wipe it away. The crane isn't a CrateMover 9000 - it's a CrateMover 9001. The CrateMover 9001 is notable for many new and exciting features: air conditioning, leather seats, an extra cup holder, and the ability to pick up and move multiple crates at once. Again considering the example above, the crates begin in the same configuration: [D] [N] [C] [Z] [M] [P] 1 2 3 Moving a single crate from stack 2 to stack 1 behaves the same as before: [D] [N] [C] [Z] [M] [P] 1 2 3 However, the action of moving three crates from stack 1 to stack 3 means that those three moved crates stay in the same order, resulting in this new configuration: [D] [N] [C] [Z] [M] [P] 1 2 3 Next, as both crates are moved from stack 2 to stack 1, they retain their order as well: [D] [N] [C] [Z] [M] [P] 1 2 3 Finally, a single crate is still moved from stack 1 to stack 2, but now it's crate C that gets moved: [D] [N] [Z] [M] [C] [P] 1 2 3 In this example, the CrateMover 9001 has put the crates in a totally different order: MCD. Before the rearrangement process finishes, update your simulation so that the Elves know where they should stand to be ready to unload the final supplies. After the rearrangement procedure completes, what crate ends up on top of each stack? """ with open("day_05_input.txt") as fp: RAW_INPUT = fp.read() SAMPLE_RAW = """ [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2""" def split_raw_input(raw): raw_board, raw_moves = raw.split("\n\n") board = defaultdict(list) for row in reversed(raw_board.split("\n")): if row[:2] == " 1": continue for col, value in enumerate(row): if col % 4 == 1: idx = (col + 3) // 4 if value != " ": board[idx].append(value) moves = [ [int(n) for n in re.findall("(\d+)", move_str)] for move_str in raw_moves.split("\n") ] return dict(board), moves def test_split(): board, moves = split_raw_input(SAMPLE_RAW) assert board == { 1: ["Z", "N"], 2: ["M", "C", "D"], 3: ["P"], } assert moves == [[1, 2, 1], [3, 1, 3], [2, 2, 1], [1, 1, 2]] # Now for full puzzle board, moves = split_raw_input(RAW_INPUT) assert board == { 1: ["Z", "T", "F", "R", "W", "J", "G"], 2: ["G", "W", "M"], 3: ["J", "N", "H", "G"], 4: ["J", "R", "C", "N", "W"], 5: ["W", "F", "S", "B", "G", "Q", "V", "M"], 6: ["S", "R", "T", "D", "V", "W", "C"], 7: ["H", "B", "N", "C", "D", "Z", "G", "V"], 8: ["S", "J", "N", "M", "G", "C"], 9: ["G", "P", "N", "W", "C", "J", "D", "L"], } assert len(moves) == 503 assert moves[-1] == [5, 5, 8] assert moves[12] == [11, 1, 4] def update_board(board_state, desired_move, rev=True): number, from_col_idx, to_col_idx = desired_move from_col = board_state[from_col_idx] board_state[from_col_idx], boxes = from_col[:-number], from_col[-number:] board_state[to_col_idx] += reversed(boxes) if rev else boxes return board_state def test_update_board(): board, moves = split_raw_input(SAMPLE_RAW) for move in moves: board = update_board(board, move) assert "".join(col[-1] for col in board.values()) == "CMZ" board, moves = split_raw_input(SAMPLE_RAW) for move in moves: board = update_board(board, move, rev=False) assert "".join(col[-1] for col in board.values()) == "MCD" # Now for full puzzle board, moves = split_raw_input(RAW_INPUT) top_strings = { # 0: 'GMGWMCVCL', # 1: 'GMGWVCVCL', # 2: 'BMGWVCHCL', # 3: 'BMGWVCHCL', } for cnt, move in enumerate(moves): if cnt in top_strings: print(f"\n\ncnt={cnt} move={move}") print(board) assert ( "".join(col[-1] if len(col) > 0 else "-" for col in board.values()) == top_strings[cnt] ) board = update_board(board, move) # print(f"\n\n\nfinal state of board\n{board}") assert ( "".join(col[-1] if len(col) > 0 else "-" for col in board.values()) == "CWMTGHBDW" ) board, moves = split_raw_input(RAW_INPUT) for cnt, move in enumerate(moves): board = update_board(board, move, rev=False) assert ( "".join(col[-1] if len(col) > 0 else "-" for col in board.values()) == "SSCGWJCRB" )
1f5e46792d87c622855dd6ddac1153cb7cc25222
Aasthaengg/IBMdataset
/Python_codes/p02730/s766687739.py
333
3.5625
4
S = input() def kaibun(x): N = len(x) flag = True for i in range(N // 2): if x[i] != x[-i - 1]: flag = False return flag tmp1 = kaibun(S) tmp2 = kaibun(S[:(len(S) - 1) // 2]) tmp3 = kaibun(S[(len(S) + 3) // 2 - 1:]) if tmp1 and tmp2 and tmp3: print('Yes') else: print('No')
c1f48934bc6749ccddbd69c0e848312456035e82
Zmontague/PythonSchoolWork
/fortuneCookie.py
2,024
4.0625
4
""" Author: Zachary Montague Date: 4/27/2021 Description: Program to provide the user with a fortune and magic number, prompting the user until they state no in the prompt. """ # Import statements import random # Variable declaration fileName = "fortunes.txt" randomFortune = "" randomMagicNumber = 0 # if num shows up as 0, error with program userInput = "" # List declaration fortunes = [] # Dictionary declaration usedFortunesAndMagicNums = {} # Open provided fortune file with open(fileName, 'r') as f: # Read file into list for line in f: fortunes.append(line) # Begin looping and randomly selecting magic numbers and fortunes and testing if the user wishes to continue getting # fortunes. while True: # Select random fortune from the fortunes list. randomFortune = random.choice(fortunes) # Remove random fortune from the list fortunes.remove(randomFortune) # Strip white spaces from the fortune randomFortune = randomFortune.strip() # Generate random magic number randomMagicNumber = random.randint(1, 100) # Add magic number and fortune to dictionary usedFortunesAndMagicNums.update({randomFortune : randomMagicNumber}) # Print fortune and magic number print("Fortune: ", randomFortune) print("Magic number: ", randomMagicNumber) # Check if the user wishes to continue userInput = input("Would you like another fortune cookie (Y/N)? ") # If user enters 'n' or 'N' or the fortunes list runs out of fortunes, the program will print the recieved # fortune and magic number before ending the program. if userInput.lower() == 'n' or len(fortunes) == 0: print("Here are all the fortunes you received: ") for key, value in usedFortunesAndMagicNums.items(): print(key, " Magic Number: ", value) break # Sanity check to prevent any strange occurrences where the program may end. Not required, but nice to have. else: continue
5f8c67000df9a083fe1653b692b1979610960694
vsoch/gpg-verify
/verify.py
12,856
3.53125
4
#!/usr/bin/env python3 # Copyright 2021 Vanessa Sochat # Copyright 2011 Trevor Bentley # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys from struct import unpack, calcsize import sys import struct import math from Crypto.Hash import SHA from Crypto.Cipher import DES3 import getpass import zlib import tempfile # keep a list of packets packets = [] def read_bytes(filey, fmt, number=None): """just read a number of bytes from an open file. Parameters ========== filey: an open file object number: the number of bytes to read fmt: an optional format string """ if number == None: number = calcsize(fmt) return filey.read(number) def unpack_bytes(filey, fmt, number=None): """read AND unpack a number of bytes from an open file. If a format is provided, convert to utf-8 and return the string. If fmt is None, assume a character string of the same length. Parameters ========== filey: an open file object number: the number of bytes to read fmt: an optional format string """ byte_values = read_bytes(filey, fmt, number) return unpack(fmt, byte_values) def load_packets_file_to_list(fd): global packets # Create a Packet, including reading in the packet header while True: # The binary information is made of packets. Each packet has: # 1. a packet header (of variable length) # 2. followed by the packet body. packet = Packet() if not packet.load_file(fd): break packets.append(packet) def main(gpgfile): """ Given a gpgfile, verify the signature """ gpgfile = os.path.abspath(gpgfile) if not os.path.exists(gpgfile): sys.exit("%s does not exist." % gpgfile) # Read binary information with open(gpgfile, "rb") as fd: load_packets_file_to_list(fd) packet = packets[0] print("TODO: how to process signature?") import IPython IPython.embed() global packetList packetList = [] class PacketHeader: """Represents the header of a PGP packet""" packetTagStrings = { 0: "Reserved", 1: "PUB ENC Session", 2: "Signature", 3: "SYM ENC Session", 4: "One-Pass Signature", 5: "Secret Key", 6: "Public Key", 7: "Secret Subkey", 8: "Compressed Data", 9: "SYM ENC Data", 10: "Marker", 11: "Literal Data", 12: "Trust", 13: "User ID", 14: "Public Subkey", 17: "User Attribute", 18: "SYM ENC INTEG Data", 19: "Modification Detection Code", } """Packet tag identifies the type of packet""" def __init__(self): self.raw_packet_tag_byte = None self.new_format = None self.tag = None self.header_length = None self.length = None self.is_partial = None def load_from_file(self, fd): """ Load the packet header from an open file """ # The first octet of the packet header is called the "Packet Tag". It # determines the format of the header and denotes the packet contents. # The remainder of the packet header is the length of the packet. tagByte = fd.read(1) # It must be defined, otherwise cut out early if len(tagByte) == 0: return False # The most significant bit is the leftmost bit, called bit 7 # A mask for this bit is 0x80 in hexadecimal. # https://tools.ietf.org/html/rfc4880#section-4.2 tagByte = ord(tagByte) if not (tagByte & 0x80): sys.exit("Invalid tag byte: 0x%x" % tagByte) self.raw_packet_tag_byte = tagByte # There is a new and and old format self.new_format = tagByte & 0x40 if self.new_format: self.tag = tagByte & 0x1F else: self.tag = (tagByte >> 2) & 0x0F self.read_header_length(fd) return True def read_header_length(self, fd): """Read the packet header variable length""" if self.new_format: self.length = self.load_new_length(fd) else: # https://tools.ietf.org/html/rfc4880#section-4.2.1 lentype = self.raw_packet_tag_byte & 0x03 # header is 2 octets long if lentype == 0: self.header_length = 2 # header is 3 octets long elif lentype == 1: self.header_length = 3 # header is 5 octets long elif lentype == 2: self.header_length = 5 # 3, undeterminable length. If the packet is in a file, it extends to end. else: self.header_length = 1 self.length = 0 return self.length = self.load_old_length(fd) def load_new_length(self, fd): """Read a new header length For new-style packets, value of each byte tells us how many more to read We can keep reading by calling this function until is_partial is False. """ self.is_partial = False bytes = fd.read(1) val = ord(bytes[0]) # one byte length if val <= 191: self.header_length = 2 return val # two byte length if val >= 192 and val <= 223: self.header_length = 3 bytes += f.read(1) val = ((val - 192) << 8) + ord(bytes[0]) + 192 return val # 4 byte length if val == 255: self.header_length = 6 bytes = f.read(4) val = ( ord(bytes[0]) << 24 | ord(bytes[1]) << 16 | ord(bytes[2]) << 8 | ord(bytes[3]) ) # val = ord(bytes[0])<<0 | ord(bytes[1])<<8 | ord(bytes[2])<<16 | ord(bytes[3])<<24 return val # This is partial length header self.header_length = 2 self.is_partial = True bytes = 1 << (val & 0x1F) return bytes def load_old_length(self, fd): """Read an old header length For old style packets, bits in tag tell us how many bytes to read """ numbytes = self.header_length - 1 bytes = fd.read(numbytes) val = 0 for i in range(numbytes): val <<= 8 val += bytes[i] return val def tagString(self): """Print string description of header tag""" try: return PacketHeader.packetTagStrings[self.tag] except KeyError: return "UNKNOWN" def __str__(self): """Print formatted description of this header""" return "HEADER TYPE (%s) HEADER SIZE (%d) DATA LEN (%d)" % ( self.tagString(), self.header_length, self.length, ) class Packet: """Stores content of a PGP packet, and a copy of its header""" algorithmStrings = { 1: "RSA", 2: "RSA Encrypt-Only", 3: "RSA Sign-Only", 16: "Elgamal", 17: "DSA", 18: "Elliptic Curve", 19: "ECDSA", 20: "Elgamal OLD", 21: "Diffie-Hellman", } """Asymmetric ciphers""" encryption_strings = { 0: "Plaintext", 1: "IDEA", 2: "TripleDES", 3: "CAST5", 4: "Blowfish", 7: "AES-128", 8: "AES-192", 9: "AES-256", 10: "Twofish", } """Symetric ciphers""" hashStrings = { 1: "MD5", 2: "SHA-1", 3: "RIPE-MD/160", 8: "SHA256", 9: "SHA384", 10: "SHA512", 11: "SHA224", } """Hash algorithms""" compressedStrings = {0: "Uncompressed", 1: "ZIP", 2: "ZLIB", 3: "BZip2"} def __init__(self): """ Create empty packet with an empty header. """ self.header = PacketHeader() self.data = None def __str__(self): return str(self.header) def __repr__(self): return str(self) def load_file(self, fd): """ Load the packet header, and then the rest of the content. """ if not self.header.load_from_file(fd): return False # keep reading until is_partial is false (we've read the whole thing) if self.header.length > 0: self.data = fd.read(self.header.length) while self.header.is_partial: bytes = self.header.load_new_length(fd) self.header.length += bytes self.data += fd.read(bytes) # old type header, packet is inderminable length else: self.data = fd.read(1024 * 1024 * 1024) print(self.header) # These are the kinds of packets (by tag) # https://tools.ietf.org/html/rfc4880#section-4.3 # secret key or secret subkey packet if self.header.tag == 5 or self.header.tag == 7: self.load_secret_key_packet(self.data) # Public key encrypted session key package elif self.header.tag == 1: self.load_session_key(self.data) # Sym. Encrypted and Integrity Protected Data Packet elif self.header.tag == 18: self.load_encrypted_data_packet(self.data) # Compressed Packet elif self.header.tag == 8: self.load_compressed_packet(self.data) # Literal Data Packet elif self.header.tag == 11: self.load_literal_data_packet(self.data) return True def load_literal_data_packet(self, data): print("Literal Data packet") idx = 0 self.format = data[idx] idx += 1 print(data) def load_compressed_packet(self, data): print("Compressed packet") idx = 0 self.algo = data[idx] idx += 1 print(self.compressed_string()) uncompressed = None # ZIP if self.algo == 1: # Magic "wbits=-15" means do a raw decompress without ZIP headers uncompressed = zlib.decompress(data[idx:], -15) # ZLIB elif self.algo == 2: uncompressed = zlib.decompress(data[idx:]) if uncompressed != None: tfile = tempfile.TemporaryFile() tfile.write(uncompressed) tfile.seek(0) load_packets_file_to_list(tfile) def load_encrypted_data_packet(self, data): sys.exit("Loading an encrypted data packet is not supported.") def load_session_key(self, data): sys.exit("Loading a session key is not supported.") def load_secret_key_packet(self, data): """ Load contents of a secret key -- decrypt encrypted contents. See gist with repository for link to original code (that needs work). """ sys.exit("Loading and decrypting secret key contents is not supported.") def read_mpi_from_buffer(self, data): """Reads a multi-precision integer from a buffer of bytes.""" # First two bytes are number of bits to read bits = struct.unpack(">H", data[0:2])[0] # print " * MPI bits: %d" % bits # Convert bits to bytes, add 2 for the header bytes = int((bits + 7) / 8) + 2 return data[0:bytes] def algo_string(self): """Convert asymmetric algorithm index to string""" try: return Packet.algorithmStrings[self.algo] except Exception: return "UNKNOWN - %d" % self.algo def encryption_string(self): """Convert symmetric algorithm index to string""" try: return Packet.encryption_strings[self.encryption] except Exception: return "UNKNOWN - %d" % self.encryption def hash_string(self): """Convert hash algorithm index to string""" try: return Packet.hashStrings[self.hash] except Exception: return "UNKNOWN - %d" % self.hash def compressed_string(self): """Convert asymmetric algorithm index to string""" try: return Packet.compressedStrings[self.algo] except Exception: return "UNKNOWN - %d" % self.algo if __name__ == "__main__": if len(sys.argv) == 1: sys.exit("Please provided a *.gpg file to verify") main(sys.argv[1])
782a7913f096898dd806bf0478fc9cf764bec1ff
WayneRocha/Desafios_python-CeV
/7 - Repetições (for e while)/desafio63.py
330
3.8125
4
# O úsuario digita quantos termos da sequencia de fibonacci quer ver n1 = n2 = 0 fib = 1 cont = int(input('Quantos termos da \033[34mSequência de Fibonacci\033[m quer ver?: ')) while cont != 0: print(f'\033[34m{fib}\033[m', end=' | ') n2 = n1 + fib n1 = fib fib = n2 cont -= 1 print('\n\nFim da sequencia')
9e1e1b40c25317b622229348f7d41106fe0fac71
mohammedtoumi007/core-of-python
/CoreOfPython.py
3,789
4
4
# *******exemple output******* print("Hello world") ############################### print("The numbers are : %5d: %010d" %(5,-20)) ############################### name = "sam" score = 90 print("Total score for %s is %s"%(name,score)) ############################### print ("{:3} {:6} {:10} {:12}".format("a", "bc","def","gh")) ############################### word = 'word' sentence ="This is a sentance" paragraph = """This is a paragraph. iT is made up of miltiple lines and sentences,""" print(word, sentence, paragraph) # *******exemple intput******* age = input("Age?") print(age) ############################### Names = input("Please enter the names") print(Names) # *******If Conditional******* a,b=1,10 if a>b: print("a>b") elif a<b: print("a <b") else : print("a = b") ############################### a,b = 1,10 max = a if (a>b) else b print(max) ############################### if 'a' in ['b','c','a']: print ("a in the list") else: print ("a not in the list") # *******loops******* i=0 while i<4 : print(i) i+=1 ############################### while True: a= input('>') if a=="exit": break print(a) ############################### for a in range(3): print(a) ############################### for a in range(1,6,2): print(a) ############################### for item in ['jordan','US','UK']: print(item) # *******Lambda, filtering & Mapping******* # Lambda : Inline anonymous function (Not bounded to a name) # Filter : Filter out all the elements of a sequence # Map : Applies a function to all teh items in a sequence sum = lambda x,y : x+y print(sum(56,7)) ############################### MyList = [0,1,2,3,4,10,13,22,25,100,120] odd_numbers = list(filter(lambda x: x % 2, MyList)) print(odd_numbers) even_numbers = list(filter(lambda x: x % 2 == 0, MyList)) print(even_numbers) ############################### sentence = "university USA" print(list(map(lambda word: len(word), sentence.split()))) # *******Reduce******* product = 1 list = [1,2,3,4] for num in list : product = product * num print(product) ############################### from functools import reduce product = reduce((lambda x, y: x*y),[1,2,3,4]) print(product) # *******Generators******* def generator_function(): for i in range(10): yield i for item in generator_function(): print(item) ############################### def fibon(n): a = b = 1 for i in range(n): yield a a, b = b,a+b for x in fibon(120): print(x) # *******Exceptions Handling******* while True: try: n = input("Please enter an integer :") n = int(n) break except ValueError : print("No valid integer! Please try again...") print("Great, you successfully entered an integer !") ############################### try: x = float(input("your number:")) inverse = 1.0/x except ValueError : print("You should have given either en int or a float") except ZeroDivisionError : print("Infinity") finally : print("There may or may not have been an exceptions.") # *******Recursive Functions******* def factorial(n): if n==1: return 1 else : return n * factorial(n-1) factorial(10) # *******String******* var1 = "Hello world!" var2 = "Python programming" print("var1[0]:", var1[0]) print("var2[1:5]:", var2[1:5]) print("count(n) :" , var2.count("m")) for c in "Hello": print(c) print("len(var1) : ", var1, len(var1)) str1 = "Hello" + " "+ var2 print("str1",str1) str2 = "%s %s %d" ("Hello", str1,12) print("str2:",str2) ############################### s="Hello" print("s.capitalize() :", s.capitalize()) print("s.upper()",s.upper()) print("s.center()", s.center(20)) print("s.replace():", s.replace("l","(ell)")) print("strip():","world".strip())
f3d051116c294af67ad9cf90b216d5eb15a988a3
devjjinii/python_
/01/practice.py
230
3.78125
4
''' 숫자 자료형 ''' print(5) print(3*6) print(3*(3+1)) ''' 문자열 자료형 ''' print('풍선') print("나비") print("z"*9) ''' boolean 자료형 ''' print(5 > 10) print(not True) print(not (5 > 10))
d789206f7b0e49f79d4036ef2370cef1fda5b694
shadowdevcode/car-game
/game.py
9,724
3.859375
4
# Code by -Vijay Sehgal import pygame import time import random pygame.init() # In order to use sound for crash funtionality crash_sound = pygame.mixer.Sound("sounds/crash.wav") # For car game play we use car.wav sound while playing pygame.mixer.music.load("sounds/car.wav") # For Screen Display width and height of the screen used to display the game display_width = 800 display_height = 600 # Different color coding used in the program. black = (0, 0, 0) white = (255, 255, 255) red = (200, 0, 0) green = (0, 200, 0) blue = (0, 0, 255) bright_red = (255, 0, 0) bright_green = (0, 255, 0) block_color = (53, 115, 255) # This variable car_width = 73 is used in the rest of the program to know where both edges of the car are. # The car's location really just means the location of the top left pixel of the car. # Because of this, it is helpful to also know where the right side is. car_width = 73 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Car Game') clock = pygame.time.Clock() carImage = pygame.image.load('racecar.png') # Declared paused variable globally pause = False def things_dodged(count): """ It is used to increament the counter called Score to run and for display we use blit. :param count: """ font = pygame.font.SysFont(None, 25) text = font.render('Score: ' + str(count), True, black) gameDisplay.blit(text, (0, 0)) def things(thingx, thingy, thingw, thingh, color): """ This function takes x, y starting points, width and height variables and finally a color. we use pygame.draw.rect() to draw the polygon to our specifications. The parameters to this function are : where, what color and then the x,y location followed by the width and the height. :param thingx: :param thingy: :param thingw: :param thingh: :param color: """ pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh]) def car(x, y): gameDisplay.blit(carImage, (x, y)) # "Blit" basically just draws the image to the screen def text_objects(text, font): textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() # def message_display(text): # largeText = pygame.font.Font('freesansbold.ttf', 80) # TextSurf, TextRect = text_objects(text, largeText) # TextRect.center = ((display_width/2),(display_height/2)) # gameDisplay.blit(TextSurf, TextRect) # # pygame.display.update() # # time.sleep(2) # # gameLoop() def crash(): pygame.mixer.music.stop() pygame.mixer.Sound.play(crash_sound) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.QUIT() quit() gameDisplay.fill(white) largeText = pygame.font.Font('freesansbold.ttf', 90) TextSurf, TextRect = text_objects("You Crashed", largeText) TextRect.center = ((display_width / 2), (display_height / 2)) gameDisplay.blit(TextSurf, TextRect) button("Play Again", 150, 400, 100, 50, green, bright_green, gameLoop) button("QUIT", 550, 400, 100, 50, red, bright_red, quitgame) pygame.display.update() clock.tick(15) def button(msg, x, y, w, h, ic, ac, action=None): """ :param msg: What do you want the button to say on it :param x: The x location of the top left coordinate of the button box. :param y: The y location of the top left coordinate of the button box. :param w: Button width. :param h: Button height. :param ic: Inactive color (when a mouse is not hovering). :param ac: Active color (when a mouse is hovering) :param action: """ mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x + w > mouse[0] > x and y + h > mouse[1] > y: pygame.draw.rect(gameDisplay, ac, (x, y, w, h)) if click[0] == 1 and action != None: action() else: pygame.draw.rect(gameDisplay, ic, (x, y, w, h)) smallText = pygame.font.Font("freesansbold.ttf", 18) textSurf, textRect = text_objects(msg, smallText) textRect.center = ((x + (w / 2)), (y + (h / 2))) gameDisplay.blit(textSurf, textRect) def quitgame(): # Quit Button functionality pygame.quit() quit() def unpause(): pygame.mixer.music.unpause() global pause pause = False def paused(): """ Sometimes, a player needs to pause for various reasons. One method is to freeze the frame and write Pause over it with some instructions on how to play again. Another is to have the window cleared and have the Pause and instructions on that. If you think your players might be inclined to cheat by pausing to slow things down, then you might want to clear the screen. """ pygame.mixer.music.pause() # Pause the already playing music. while pause: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.QUIT() quit() gameDisplay.fill(white) # Created for displaying on the screen "Paused" largeText = pygame.font.Font('freesansbold.ttf', 90) TextSurf, TextRect = text_objects("Paused", largeText) TextRect.center = ((display_width / 2), (display_height / 2)) gameDisplay.blit(TextSurf, TextRect) # Button size and dimensions followed by Resume text on button and Quit on the other one. button("RESUME", 150, 400, 100, 50, green, bright_green, unpause) button("QUIT", 550, 400, 100, 50, red, bright_red, quitgame) # Gonna update the display everytime any function is called for specific events. pygame.display.update() clock.tick(15) def game_intro(): # Gonna run one time """ here, we're just defining a variable of "intro" as True, and calling a while loop to run until the variable is no longer true. Within that loop, we have created a mini-pygame instance, which is currently just displaying a title at 15 frames per second. From here, we can, and will, add some actual functional buttons for the player to use and click to play or quit. """ intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.QUIT() quit() gameDisplay.fill(white) largeText = pygame.font.Font('freesansbold.ttf', 90) TextSurf, TextRect = text_objects("Let's Race Over", largeText) TextRect.center = ((display_width / 2), (display_height / 2)) gameDisplay.blit(TextSurf, TextRect) button("START", 150, 400, 100, 50, green, bright_green, gameLoop) button("QUIT", 550, 400, 100, 50, red, bright_red, quitgame) pygame.display.update() clock.tick(15) def gameLoop(): global pause pygame.mixer.music.play(-1) # -1 for infinity loop for music x = (display_width * 0.45) y = (display_height * 0.80) x_change = 0 thing_startx = random.randrange(0, display_width) thing_starty = -600 thing_speed = 4 thing_width = 100 thing_height = 100 dodged = 0 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 # Move 5 times left of current pos if event.key == pygame.K_RIGHT: x_change = 5 # Move 5 times right of current pos if event.key == pygame.K_p: # add a check if the P key is pressed in the KEYDOWN event if-statement: pause = True paused() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 # No change in position x += x_change # "x" is used to position our car image in the car function. gameDisplay.fill(white) # Paint the window white along with the car. # things(thingx, thingy, thingw, thingh, color) things(thing_startx, thing_starty, thing_width, thing_height, black) thing_starty += thing_speed car(x, y) things_dodged(dodged) if x > display_width - car_width or x < 0: # Also include car width in order to check it really crashed at edges crash() if thing_starty > display_height: thing_starty = 0 - thing_height # Blocks to show up at once thing_startx = random.randrange(0, display_width) dodged += 1 thing_speed += 1 # Increase Speed of blocks thing_width += (dodged * 1.2) # Increase size of the blocks # if y < thing_starty + thing_height: we're asking if y, the car's top left, has crossed the object's y + height, meaning the bottom left. # If it has, then, for logic sake, we print that y crossover has occurred. # Now, this doesn't mean there's necessarily overlap, maybe the x coordinates are vastly different and # we're on opposite sides. So, then we need to ask if the objects are anywhere within each other's boundaries. if y < thing_starty + thing_height: print('y crossover') if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx + thing_width: print('x crossover') crash() pygame.display.update() clock.tick(60) game_intro() gameLoop() pygame.quit() quit()
2176f43ebdedadcd91ea603087be5b2572a092b7
Novandev/pythonprac
/functional_programming/functions.py
226
3.578125
4
def yell(text): return f'{text.upper()}!' bark = yell del yell # this wil delete yell and the pointers for it if __name__=="__main__": print(yell('hello')) print(bark("yell")) print(bark("puppy"))
e09173e3d50035fbf9acb6ebfa1c64ca5723f952
arora0508/hell
/addition.py
101
3.75
4
def addition (): a=input("enter a number") b=input("enter a number") c=a+b return(c)
8e8b41af59fe8f85b63619f5f3299fe596a9d0d7
laughouw10/stanCode
/bouncing_ball.py
1,819
3.6875
4
""" File: bouncing ball Name: Peter ------------------------- TODO: """ from campy.graphics.gobjects import GOval from campy.graphics.gwindow import GWindow from campy.gui.events.timer import pause from campy.gui.events.mouse import onmouseclicked VX = 5 DELAY = 10 GRAVITY = 1 SIZE = 20 REDUCE = 0.9 START_X = 30 START_Y = 40 n = 0 V = 0 time = 0 end = 0 window = GWindow(800, 500, title='bouncing_ball.py') def main(): """ This program simulates a bouncing ball at (START_X, START_Y) that has VX as x velocity and 0 as y velocity. Each bounce reduces y velocity to REDUCE of itself. """ ball = GOval(SIZE, SIZE) ball.filled = True window.add(ball, START_X, START_Y) onmouseclicked(bounce) pass def bounce(m): global n, V, time, end if (time < 3) and (end == 0): window.clear() end = 1 X = START_X Y = START_Y ball = GOval(SIZE, SIZE) ball.filled = True window.add(ball, X, Y) while X < 800: while Y < 500: n += 1 pause(DELAY) window.clear() window.add(ball, X, Y) pause(DELAY) X = X + VX V = GRAVITY * n Y = Y + V V = V * 0.9 n = 0 while V > 0: n += 0.1 X = X + VX V = V - GRAVITY * n Y = Y - V pause(DELAY) window.clear() window.add(ball, X, Y) pause(DELAY) window.add(ball, START_X, START_Y) time += 1 end = 0 if __name__ == "__main__": main()
18f5bd98c58bd470350929931c4e27e3ab9c86a0
Pilip88/Rocket
/rocket.py
1,948
3.984375
4
from math import sqrt from random import randint from sys import exit class Rocket: def __init__(self, name = "Rocket", x = 0, y = 0): self.x = x self.y = y self.name = name print "-"*80 print "%s is ready for liftoff!" % self.name def liftoff(self): if self.x == 0: print "-"*80 print "Press Enter to activate main engine hydrogen burnoff system..." user_input = raw_input("----> ") if user_input == "": print "-"*80 print "Press any key to start countdown!" user_input = raw_input("----> ") if user_input == "": print "-"*80 countdown = range(0, 11) countdown.sort(reverse = True) for n in countdown: print n print "WRROOOOOOOOOMMMMMM!!!!" print "Liftoff successful!!!!" self.x = 1 self.y = 1 else: print "-"*80 print "You pressed the wrong key!" return self.liftoff() else: print "-"*80 print "You pressed the wrong key!" return self.liftoff() else: print "-"*80 print "%s is already launched!" % self.name def curent_position(self): print "-"*80 print "Rocket is curently at position (%s,%s)" % (self.x, self.y) def move_rocket(self, x, y): self.x += x self.y += y if self.x <= 0: number_of_people = randint(4, 40) print "-"*80 print "%s collapsed!" % self.name print "You have just killed %s innocent people" % number_of_people exit(0) else: print "-"*80 print "Rocket have moved to position (%s, %s)" % (self.x, self.y) def get_distance(self, other_rocket): x_distance = self.x - other_rocket.x y_distance = self.y - other_rocket.y distance = sqrt((x_distance ** 2) + (y_distance ** 2)) if x_distance != 0 and y_distance != 0: print "-"*80 print "Distance between rockets is %s units." % self.distance else: print "-"*80 print "BOOOOOOM!!!!" print "%s and %s have collided!" % (self.name, other_rocket.name) exit(0)
06061280a8333db9d6b3aa747fd98ac8456c02e7
poojithayadavalli/codekata
/word after article.py
257
3.5625
4
h=['the','a','an','A','An','The'] x=input().split() y=[] for i in range(len(x)): if x[i] in h: if (i+1)<len(x) and x[i]=='The': y.append(x[i+1].capitalize()) elif (i+1)<len(x): y.append(x[i+1]) print(' '.join(y))
ab736f3a2ec54e19a65e0bf1542bc022512927ec
dtchou802/python-practice
/algo1.py
1,923
4.0625
4
import math def numbPrimes(): nump = input("How many primes do you want?") curNum=2 pCount=0 primes=[] #loop till you get required numbers of primes while pCount<nump: isPrime = True #check to see if curNum is prime for x in range(2,int(math.sqrt(curNum))+1): if(curNum % x ==0 and x !=curNum): isPrime = False break if(isPrime): primes.append(curNum) pCount+=1 #check next number curNum+=1 print(primes) numbPrimes() def primesUnder(): nMax = input("All primes under?") curNum=2 pCount=0 primes=[] #loop under prime exceed certain number while curNum<nMax: isPrime = True #check to see if curNum is prime for x in range(2,int(math.sqrt(curNum))+1): if(curNum % x ==0 and x !=curNum): isPrime = False break if(isPrime): primes.append(curNum) pCount+=1 #check next number curNum+=1 print(primes) primesUnder() def primeFactors(): fac=[] n = input("Number for prime factorization?") #get all 2 prime factors while n % 2 == 0: fac.append(2) n = n / 2 #check if next numbers are prime, are for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: fac.append(i) n = n / i if n > 2: fac.append(n) print(fac) powC=1 if(len(fac)==1): print (fac) else: for x in range(1,len(fac)): if(fac[x]==fac[x-1] and x==len(fac)-1): powC=powC+1 print str(fac[x-1])+"^"+str(powC) elif(fac[x]!=fac[x-1] or x==len(fac)-1): print str(fac[x-1])+"^"+str(powC) powC=1 elif(fac[x]==fac[x-1]): powC=powC+1 primeFactors()
68cd3c60d1d7db49bed77d17c09c1fef74bc1058
shi429101906/python
/06_高级数据类型/hm_06_元祖基本使用.py
316
3.796875
4
info_tuple = ("zhangsan", 18, 1.75, "zhangsan") # 1、取值和取索引 print(info_tuple[1]) # 已经知道数据的内容, 希望知道该数据在元祖中的索引 print(info_tuple.index(18)) # 2、统计技术 print(info_tuple.count('zhangsan')) # 统计元祖中包含元素的个数 print(len(info_tuple))
18664d2610240b59d073212203612d8a7f795636
8gm/python_ballgame
/ball_game.py
6,889
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 16 21:27:57 2020 @author: Barry """ from tkinter import * class MyGameObject(object): #初始設定 def __init__(self, mycanvas, item): self.canvas = mycanvas self.item = item def position(self): return self.canvas.coords(self.item) #移動的座標位置 def move(self, c_x, c_y): self.canvas.move(self.item, c_x, c_y) def delete(self): self.canvas.delete(self.item) #MyBall繼承MyGameObject類別 class MyBall(MyGameObject): def __init__(self, canvas, x, y): self.radius = 10 self.direction = [1, -1] self.speed = 10 #用canvas建立圓球 item = canvas.create_oval(x-self.radius, y-self.radius, x+self.radius, y+self.radius, fill = "red") super(MyBall, self).__init__(canvas, item) def (self): coords = self.position() width = self.canvas.winfo_width() #撞到左有兩邊方向會相反 if coords[0] <= 0 or coords[2] >= width: self.direction[0] *= -1 if coords[1] <= 0: self.direction[1] *= -1 x = self.direction[0] * self.speed y = self.direction[1] * self.speed self.move(x, y) def ball_collide(self, game_objects): coords = self.position() x = (coords[0] + coords[2]) * 0.5 if len(game_objects) > 1: self.direction[1] *= -1 elif len(game_objects) == 1: game_object = game_objects[0] coords = game_object.position() if x > coords[2]: self.direction[0] = 1 elif x < coords[0]: self.direction[0] = -1 else: self.direction[1] *= -1 for game_object in game_objects: if isinstance(game_object, MyBrick): game_object.hit() #MyPaddle繼承MyGameObject類別 class MyPaddle(MyGameObject): def __init__(self, canvas, x, y): self.width = 80 self.height = 10 self.ball = None item = canvas.create_rectangle(x - self.width / 2, y - self.height / 2, x + self.width / 2, y + self.height / 2, fill = 'green') super(MyPaddle, self).__init__(canvas, item) def set_ball(self, ball): self.ball = ball def move(self, offset): coords =self.position() width = self.canvas.winfo_width() if coords[0] + offset >= 0 and coords[2] + offset <= width: super(MyPaddle, self).move(offset, 0) if self.ball is not None: self.ball.move(offset, 0) #MyBrick繼承MyGameObject類別 class MyBrick(MyGameObject): COLORS = {1: '#aaaaaa', 2: '#888888', 3: '#000000'} def __init__(self, canvas, x, y, hits): self.width = 75 self.height = 20 self.hits = hits color = MyBrick.COLORS[hits] item = canvas.create_rectangle(x - self.width / 2, y - self.height / 2, x + self.width / 2, y +self.height / 2, fill=color, tags='brick') super(MyBrick, self).__init__(canvas, item) def hit(self): self.hits -= 1 if self.hits == 0: self.delete() else: self.canvas.itemconfig(self.item, fill=MyBrick.COLORS[self.hits]) class MyGame(Frame): def __init__(self): master = Tk() master.title("Ball Game!!") super(MyGame, self).__init__(master) self.lives = 3 self.width = 650 self.height = 580 self.items = {} self.canvas = Canvas(self, bg='#aa11aa', width=self.width, height=self.height) self.canvas.pack() self.pack() self.ball = None #將Paddle物件分配給paddle成員屬性 self.paddle = MyPaddle(self.canvas, self.width/2, 500) self.items[self.paddle.item] = self.paddle #增加磚塊 for x in range(5, self.width -5, 75): self.addBrick(x + 37.5, 50, 2) self.addBrick(x + 37.5, 70, 1) self.addBrick(x + 37.5, 90, 1) self.hud = None self.setupGame() self.canvas.focus_set() self.canvas.bind('<Left>', lambda _: self.paddle.move(-30)) self.canvas.bind('<Right>', lambda _: self.paddle.move(30)) def setupGame(self): self.addBall() self.ball_update_lives_text() self.text = self.draw_text(300, 200, 'press space to start') self.canvas.bind('<space>', lambda _: self.start_game()) def addBall(self): if self.ball is not None: self.ball.delete() paddle_coords = self.paddle.position() x = (paddle_coords[0] + paddle_coords[2]) * 0.5 #新增MyBall物件並將它分配給成員屬性ball self.ball = MyBall(self.canvas, x, 310) self.paddle.set_ball(self.ball) def addBrick(self, x, y, hits): brick = MyBrick(self.canvas, x, y, hits) self.items[brick.item] = brick def draw_text(self, x, y, text, size='55'): font = ('Arial', size) return self.canvas.create_text(x, y, text=text, font=font) def ball_update_lives_text(self): text = 'ball: %s' % self.lives if self.hud is None: self.hud = self.draw_text(320, 20, text, 25) else: self.canvas.itemconfig(self.hud, text=text) def start_game(self): self.canvas.unbind('<space>') self.canvas.delete(self.text) self.paddle.ball = None self.game_loop() def game_loop(self): self.checkCollisions() num_brick = len(self.canvas.find_withtag('brick')) if num_brick == 0: self.ball.speed = None self.draw_text(300, 200, "you win!!") elif self.ball.position()[3] >= self.height: self.ball.speed = None self.lives -= 1 if self.lives <0: self.draw_text(300, 200, 'game over!!') else: self.after(1000, self.setupGame) else: self.ball.ball_update() self.after(50, self.game_loop) def checkCollisions(self): ball_coords = self.ball.position() items = self.canvas.find_overlapping(*ball_coords) objects = [self.items[x] for x in items if x in self.items] self.ball.ball_collide(objects) if __name__ == '__main__': game= MyGame() game.mainloop()
47758ad094e8cd5ce8dc25b2e1e22abaf864c485
vnatesh/Code_Eval_Solutions
/Moderate/reverse_groups.py
1,052
4.125
4
""" REVERSE GROUPS CHALLENGE DESCRIPTION: Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is. INPUT SAMPLE: Your program should accept as its first argument a path to a filename. Each line in this file contains a list of numbers and the number k, separated by a semicolon. The list of numbers are comma delimited. E.g. 1,2,3,4,5;2 1,2,3,4,5;3 OUTPUT SAMPLE: Print out the new comma separated list of numbers obtained after reversing. E.g. 2,1,4,3,5 3,2,1,4,5 """ import sys,math test_cases=open(sys.argv[1],'r') for i in test_cases.read().split('\n'): if i!='': a=int(i.split(';')[1]) b=i.split(';')[0].split(',') x=0 s=[] while x<len(b): if len(list(reversed(b[x:x+a])))==a: s.append(','.join(reversed(b[x:x+a]))) else: s.append(','.join(b[x:x+a])) x+=a print ','.join(s)
3f69fb3ee6502d9a3934ac4062f494bcf78c3d5a
ejkaplan/PacmanCTF
/PacmanCTF/pacman_ctf.py
8,665
3.75
4
from copy import deepcopy import random import time from location import * from maze_gen import maze_gen from random_pacman import Random_Pacman class Pacman_CTF_Game(object): ''' This is the class for making a game! Scroll to the bottom to see how to run a game. ''' def __init__(self, size=31, turn_limit=1800, time_limit=1, log=False, seed=None): ''' Create a new game object. Takes 5 arguments: size - the board is always a square - what are the side lengths? turn_limit - how many turns before the game is over? time_limit - how long in seconds does a bot have to decide what to do? (The director will have 8 turns worth of time for setup code.) log - should a log file be created for eventual replay? seed - do you want to seed the random number generator? (mostly used to ensure that the same map is generated over multiple runs.) ''' if size % 2 == 0: size -= 1 if not seed: seed = random.random() self.seed = seed random.seed(self.seed) self.turn = 0 self.turn_limit = turn_limit self.time_limit = time_limit # Build the maze self.passages = maze_gen(size, size, 20, 4, 6) red_cells = [Location(r, c) for r in range(len(self.passages)) for c in range(len(self.passages[r])) if self.passages[r][c] == 1] random.shuffle(red_cells) n_dots = round(len(red_cells) * 0.5) # Set the spawn points self.spawns = [[], []] for agent_num in range(3): i = 0 while red_cells[i].row > size//4 or not (agent_num*size//3 < red_cells[i].col < (agent_num+1)*size//3): i += 1 red_spawn = red_cells.pop(i) blue_spawn = red_spawn.get_mirror(size) self.spawns[0].append(red_spawn) self.spawns[1].append(blue_spawn) self.spawns[0].sort() self.spawns[1].sort() # Place the dots self.dots = [[], []] for _ in range(n_dots): dot = red_cells.pop() self.dots[1].append(dot) self.dots[0].append(dot.get_mirror(size)) self.dots[0].sort() self.dots[1].sort() # Set up the players self.agents = deepcopy(self.spawns) self.eaten_dots = [[[] for _ in range(3)] for _ in range(2)] self.directors = [] self.scores = [0, 0] # Set up the logfile if log: self.logfile = open("logs/pacman_{}.csv".format(int(time.time())), "w") self.logfile.write("{}\n".format(len(self.passages))) for row in self.passages: for cell in row: self.logfile.write("{},".format(cell)) self.logfile.write("x\n") for team in self.spawns: for coord in team: self.logfile.write("{},{},".format(coord.row, coord.col)) self.logfile.write("x\n") self.log_state() else: self.logfile = None def play_game(self): ''' Run this function to play out the game. Returns the winning director object. ''' for player in self.directors: with timeout(seconds=8*self.time_limit): try: player.start() except: pass while True: for agent in range(3): for player in range(len(self.directors)): with timeout(seconds=self.time_limit): try: move = self.directors[player].get_move(agent) except: move = None newLoc = self.agents[player][agent].get_loc_in_dir(move) if newLoc.isLegal(self.passages) and self.passages[newLoc.row][newLoc.col] > 0: self.agents[player][agent] = newLoc self.eat_dots() self.capture_agents() self.score_points() self.turn += 1 if self.logfile: self.log_state() if self.turn > self.turn_limit: if self.logfile: self.logfile.flush() self.logfile.close() return self.directors[self.scores.index(max(self.scores))] def update(self): self.eat_dots() self.capture_agents() self.score_points() def eat_dots(self): for team_i in range(len(self.agents)): for agent_i in range(len(self.agents[team_i])): loc = self.agents[team_i][agent_i] if loc in self.dots[team_i]: self.dots[team_i].remove(loc) self.eaten_dots[team_i][agent_i].append(loc) def capture_agents(self): conflicts = [coord for coord in self.agents[0] if coord in self.agents[1]] for conf in conflicts: remove = 2 - self.passages[conf.row][conf.col] for i in range(len(self.agents[remove])): if self.agents[remove][i] == conf: self.agents[remove][i] = self.spawns[remove][i] for dot in self.eaten_dots[remove][i]: self.dots[remove].append(dot) self.eaten_dots[remove][i].clear() def score_points(self): for team in range(len(self.agents)): for i in range(len(self.agents[team])): agent = self.agents[team][i] space = self.passages[agent.row][agent.col] - 1 if space == team: self.scores[team] += len(self.eaten_dots[team][i]) * (len(self.eaten_dots[team][i])+1) // 2 self.eaten_dots[team][i].clear() def log_state(self): line = "" for team in self.agents: for agent in team: line += "{},{},".format(agent.row,agent.col) for score in self.scores: line += "{},".format(score) for team in self.dots: for dot in team: line += "{},{},".format(dot.row,dot.col) line += "x\n" self.logfile.write(line) def add_director(self, director): if len(self.directors) < 2: self.directors.append(director) def get_number(self, director): return self.directors.index(director) + 1 def get_passages(self): return deepcopy(self.passages) def get_dots(self, number): return [loc.get_tuple() for loc in self.dots[number - 1]] def get_agents(self, number): return [loc.get_tuple() for loc in self.agents[number - 1]] def get_enemy_agents(self, number): enemies = self.agents[1 - (number - 1)] friends = self.agents[number - 1] out = [] for enemy in enemies: found = False for friend in friends: if friend.manhattan_distance(enemy) <= 5: found = True break out.append(enemy.get_tuple() if found else None) return out def radar(self, number, agent_number): random.seed(self.seed + self.turn) enemies = self.agents[1 - (number - 1)] agent = self.agents[number - 1][agent_number] max_diff = max(agent.row, len(self.passages) - agent.row - 1) + max(agent.col, len(self.passages[0]) - agent.col - 1) out = [] for enemy in enemies: dist = enemy.manhattan_distance(agent) out.append(random.randint(max(0, dist - 6), min(dist + 6, max_diff))) return out import signal class timeout: def __init__(self, seconds=1, error_message='Timeout'): self.seconds = seconds self.error_message = error_message def handle_timeout(self, signum, frame): raise TimeoutError(self.error_message) def __enter__(self): signal.signal(signal.SIGALRM, self.handle_timeout) signal.alarm(self.seconds) def __exit__(self, type, value, traceback): signal.alarm(0) if __name__ == "__main__": ''' You'll set up your game here. ''' game = Pacman_CTF_Game(log=True) #create the game. Random_Pacman(game) #Create the two directors and pass the game in as objects. Random_Pacman(game) game.play_game() #Play the game.
488f3289c8d2214cc0d53a303aa8d4f961d22c30
burakbayramli/books
/Introduction_to_numerical_programming_using_Python_and_CPP_Beu/Ch06/Python/P06-Iter.py
467
3.765625
4
# Real root of a real function by the method of successive approximations from math import * from roots import * def func(x): return x - exp(-x) # main a = -1e10; b = 1e10 # search interval x = 0e0 # initial approximation (x,ierr) = Iter(func,a,b,x) if (ierr == 0): print("x = {0:8.5f} f(x) = {1:7.0e}".format(x,func(x))) else: print("No solution found !")
5ca65136d315c78f083ef8eb9985c45f2201c463
mtawaken/AlgoSolutions
/project-euler/pe010.py
509
3.59375
4
''' Summation of primes Problem 10 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. ''' __author__ = 'SUN' if __name__ == '__main__': prime = [True] * 2000000 prime[0] = prime[1] = False for i in range(2, int(2000000 ** 0.5)): if prime[i]: for j in range(i * i, 2000000, i): prime[j] = False primeSum = 0 for i in range(2000000): if prime[i]: primeSum += i print(primeSum)
9c908df2116ae90014bc5b97ed83619c734e9030
rafaelperazzo/programacao-web
/moodledata/vpl_data/27/usersdata/135/8830/submittedfiles/divisores.py
375
3.8125
4
# -*- coding: utf-8 -*- from __future__ import division import math n= input ('digite a quantidade de divisores desejados: ') a= int(input('digite o valor de a: ')) b= int(input('digite o valor de b:' )) multiplo= 1 contador= 0 while contador <n: if multiplo %a==0 or multiplo %b==0: print (multiplo) contador= contador + 1 multiplo= multiplo+ 1
0331f461b6a68d76c2e6fc753fd43a70ae191125
surfjam6/Thinkful
/Functions/bar.py
1,594
3.9375
4
import random import bar_data def get_customer_name(): """Asks customer for name""" name = str.capitalize(input("Please enter your name: ")) return name def customer_lookup(name, customer_preferences_list): if name in customer_preferences_list: use_previous = str.lower(input("Would you like to use your previous preferences ? {}\n".format(customer_preferences_list[name]))) if use_previous in "y": return True def drink_preferences(questions): preferences = [] """Asks customer preferences and created preferences dictionary""" for taste in questions: print(questions[taste]) while True: answer = str.lower(input("Please enter your response: (y/n)")) if answer in "yn": break else: print("""Incorrect entry, please enter "y" or "n".""") if answer == "y": preferences.append(taste) return preferences def construct_drink(preferences, ingredients): """Constructs and returns a drink""" drink = [] for taste in preferences: drink.append(random.choice(ingredients[taste])) return drink def bar(ingredient, inventory): inventory[ingredient] -= 1 if inventory[ingredient] < bar_data.supply_count/2: restock = str.lower(input("Inventory of {} is low, should I restock?(y/n)\n".format(inventory[ingredient]))) if restock not in "n": bar_data.inventory[ingredient] = bar_data.supply_count print("I am restocking {}".format(inventory[ingredient]))
25cd17217fb871f164a6b813173f3cc66eb21aa0
fagan2888/Leetcode-2
/Arrays_and_Strings.md/Unique Characters in String(1).py
793
3.921875
4
# coding: utf-8 # In[25]: #To check if string has unique characters s=input('Enter the string you want to check') mylist=[] check=True for i in range(len(s)): if s[i] in mylist: check=False print(check) break else: mylist.append(s[i]) if (check): print(check) # In[12]: #Assuming ASCII character set #Returns true if all characters are unique, else returns False. def isunique(str): if(len(str)>128): return False char_bool=[False for _ in range(128)] for char in str: #Get ASCII code for character a=ord(char) if(char_bool[a]): return False char_bool[a]=True return True st=input('Enter the string') isunique(st) # In[10]:
08704bdc6b7d0152369b8788a6a818c4f5a99b76
2016b093005/hackerrank_python
/08_list.py
815
4
4
if __name__ == '__main__': N = int(input()) my_list = list() for i in range(int(N)): input_data = input() input_data = input_data.split() if input_data[0] == 'insert' or input_data[0] == 'append': if len(input_data) == 3: my_list.insert(int(input_data[1]), int(input_data[2])) else: my_list.append(int(input_data[1])) elif input_data[0] == 'print': print(my_list) elif input_data[0] == 'remove': my_list.remove(int(input_data[1])) elif input_data[0] == 'sort': my_list.sort() elif input_data[0] == 'pop': my_list.pop() elif input_data[0] == 'reverse': my_list.reverse() else: print('Given wrong input')
4b65aefb74d8703e4b446d145ce27bf1380fb70b
Stocastico/AI_MOOC
/Exercises/Exercise_1/src/solver.py
8,286
3.828125
4
from collections import deque from queue import PriorityQueue from node import Node from board import Board from time import process_time class Solver(object): """Solves a puzzle using one of the following methods: BFS --> Breadth First Search DFS --> Depth First Search AST --> A-star search IDA --> Ida-star search """ def __init__(self, method, initialState): self.method = method # method used to solve puzzle self.state = Node(initialState) # instance of State class #self.tree = self.state # tree starting from initial configuration if self.method == 'bfs': self.frontier = deque([self.state], None) elif self.method == 'dfs': self.frontier = [self.state] # list of states to be explored elif self.method == 'ast': self.frontier = PriorityQueue() self.frontier.put(self.state) elif self.method == 'ida': self.frontier = [self.state] self.threshold = 1; self.initialState = Node(initialState) self.explored = set() # list of states already explored self.goal = Node(list(range(len(initialState.split(','))))) self.pathToGoal = [] # something like ['Up', 'Left', 'Left'] self.costOfPath = 0 self.nodesExpanded = 0 self.fringeSize = 1 self.maxFringeSize = 0 self.searchDepth = 0 self.maxSearchDepth = 0 self.runningTime = 0.0 self.maxRamUsage = 0.0 self.start = process_time() def solve(self): """Main method for solving puzzle""" if self.method == 'bfs': retVal = self.bfs() elif self.method == 'dfs': retVal = self.dfs() elif self.method == 'ast': retVal = self.ast() elif self.method == 'ida': retVal = self.ida() while retVal is not True: self.threshold = self.threshold + 1 self.frontier = [self.initialState] self.explored = set() self.nodesExpanded = 0 self.fringeSize = 1 retVal = self.ida() else: raise ValueError('Possible methods are dfs, bfs, ast, ida') if not retVal: raise RuntimeError('Solver didn\'t reach final state') self.runningTime = process_time() - self.start self.maxRamUsage = 0; #resource.getrusage(resource.RUSAGE_SELF).ru_maxrss def bfs(self): while len(self.frontier) > 0: self.state = self.frontier.popleft() #print("Current State: " + str(self.state.board.values)) self.fringeSize -= 1 self.explored.add(str(self.state.board.values)) if self.state.testEqual(self.goal): self.searchDepth = self.state.depth self.costOfPath = self.state.depth self.pathToGoal = self.getPathToGoal() return True for neighbour in self.state.neighbours(): #if not neighbour.belongs(self.frontier) and not neighbour.belongs(self.explored): if str(neighbour.board.values) not in self.explored: self.frontier.append(neighbour) self.explored.add(str(neighbour.board.values)) self.fringeSize += 1 if neighbour.depth > self.maxSearchDepth: self.maxSearchDepth = neighbour.depth self.nodesExpanded += 1 if self.fringeSize > self.maxFringeSize: self.maxFringeSize = self.fringeSize def dfs(self): while len(self.frontier) > 0: self.state = self.frontier.pop() #print("Current State:\n" + str(self.state)) self.fringeSize -= 1 self.explored.add(str(self.state.board.values)) if self.state.testEqual(self.goal): self.searchDepth = self.state.depth self.costOfPath = self.state.depth self.pathToGoal = self.getPathToGoal() return True neighbours = reversed(self.state.neighbours()) for neighbour in neighbours: #if not neighbour.belongs(self.frontier) and not neighbour.belongs(self.explored): if str(neighbour.board.values) not in self.explored: self.frontier.append(neighbour) self.explored.add(str(neighbour.board.values)) self.fringeSize += 1 if neighbour.depth > self.maxSearchDepth: self.maxSearchDepth = neighbour.depth self.nodesExpanded += 1 if self.fringeSize > self.maxFringeSize: self.maxFringeSize = self.fringeSize def ast(self): while self.frontier.qsize() > 0: self.state = self.frontier.get() #print("Current State:\n" + str(self.state)) self.fringeSize -= 1 self.explored.add(str(self.state.board.values)) if self.state.testEqual(self.goal): self.searchDepth = self.state.depth self.costOfPath = self.state.depth self.pathToGoal = self.getPathToGoal() return True neighbours = self.state.neighbours() for neighbour in neighbours: if str(neighbour.board.values) not in self.explored: neighbour.heuristics = neighbour.depth + neighbour.board.manhattanDist() self.frontier.put(neighbour) self.explored.add(str(neighbour.board.values)) self.fringeSize += 1 if neighbour.depth > self.maxSearchDepth: self.maxSearchDepth = neighbour.depth self.nodesExpanded += 1 if self.fringeSize > self.maxFringeSize: self.maxFringeSize = self.fringeSize def ida(self): while len(self.frontier) > 0: self.state = self.frontier.pop() #print("Current State:\n" + str(self.state)) self.fringeSize = len(self.frontier) self.explored.add(str(self.state.board.values)) if self.state.depth > self.maxSearchDepth: self.maxSearchDepth = self.state.depth if self.state.testEqual(self.goal): self.searchDepth = self.state.depth self.costOfPath = self.state.depth self.pathToGoal = self.getPathToGoal() return True neighbours = reversed(self.state.neighbours()) for neighbour in neighbours: #if not neighbour.belongs(self.frontier) and not neighbour.belongs(self.explored): if str(neighbour.board.values) not in self.explored: neighbour.heuristics = neighbour.depth + neighbour.board.manhattanDist() if neighbour.heuristics <= self.threshold: self.frontier.append(neighbour) self.explored.add(str(neighbour.board.values)) self.fringeSize = len(self.frontier) self.nodesExpanded += 1 if self.fringeSize > self.maxFringeSize: self.maxFringeSize = self.fringeSize def writeResults(self): f = open('output.txt', 'w') s = "path_to_goal: " + str(self.pathToGoal) + "\n" s += "cost_of_path: " + str(self.costOfPath) + "\n" s += "nodes_expanded: " + str(self.nodesExpanded) + "\n" s += "fringe_size: " + str(self.fringeSize) + "\n" s += "max_fringe_size: " + str(self.maxFringeSize) + "\n" s += "search_depth: " + str(self.searchDepth) + "\n" s += "max_search_depth: " + str(self.maxSearchDepth) + "\n" s += "running_time: " + str(self.runningTime) + "\n" s += "max_ram_usage: " + str(self.maxRamUsage) f.write(s) #print(s) f.close() def getPathToGoal(self): cState = self.state path = [] while cState.action is not None: path.append(cState.action) cState = cState.parent return path[::-1]
d121d13553d88124e8f30512d1f1ed597c6dd3c4
rezabayu/sedati
/kattis-tripletext.py
242
3.921875
4
s = input() char = len(s) // 3 coll = [] for a in range(0, len(s)+1, char): word = s[a:a+char] coll.append(word) if coll[1] == coll[0] or coll[0] == coll[2]: text = coll[0] elif coll[1] == coll[2]: text = coll[1] print(text)
f42333b5c1e2b44b8ee7f080afb78f918b4180f1
Vilard/rzd_payday
/payday.py
1,380
3.96875
4
class Tax: def __init__(self): self.income_tax = 13 self.union_deductions = 1 self.pension_fund = 2.5 def get_income_tax(self): return round(self.value / 100 * self.income_tax, 2) def get_union_deductions_tax(self): return round(self.value / 100 * self.union_deductions, 2) def get_pension_fund_tax(self): return round(self.value/100 * self.pension_fund, 2) def get_tax(self): return round(self.get_income_tax() + self.get_union_deductions_tax() + self.get_pension_fund_tax(), 2) @property def get_tax_percent(self): return self.income_tax + self.union_deductions + self.pension_fund class Payday(Tax): def __init__(self, value): super().__init__() self.value = round(value, 2) if __name__ == '__main__': t = Payday(21070.31-7110) print(f'Налогооблагаемая база: {t.value}') print(f'Профсоюз: {t.get_union_deductions_tax()}') print(f'Подоходный налог: {t.get_income_tax()}') print(f'Пенсионный фонд: {t.get_pension_fund_tax()}') print(f'Общий налог: {t.get_tax()}') print(f'Выплота на карту: {round(21070.31 - t.get_tax()-6316.8-7110, 2)}') print(f'удерживаеться ежемесячно: {t.get_tax_percent}%')
83195a63fa1ff24c27580a35fc862f929cd9f6a1
komal-kharche/python-test
/staticlist.py
226
4
4
name = [] n = 10 value="" for i in range(n): value =raw_input("enter your name: ") name.append(value) for i in range(len(name)): print "my name is",name[i] print "all students name added successfully"