blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3c9d353b622b33ced30f2d68c00928ef1f6c1394
thenol/Leetcode
/Search/79. Word Search.py
1,602
3.90625
4
''' Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false. ''' class Solution: def exist(self, board: List[List[str]], word: str) -> bool: # Search algorithm # dynamic programming m=len(board) n=len(board[0]) visited=[[0 for _ in range(n)]for _ in range(m)] def dp(s,i,j): nonlocal m,n,board,visited if not s: # boundary condition at the first place return True if not visited[i][j]==0: return False if board[i][j]==s[0]: visited[i][j]=1 if not s[1:]: visited[i][j]=0 return True ans= (dp(s[1:],i+1,j) if i+1<m else False) or (dp(s[1:],i-1,j) if i-1>=0 else False)\ or (dp(s[1:],i,j+1) if j+1<n else False) or (dp(s[1:],i,j-1) if j-1>=0 else False) visited[i][j]=0 # end of visiting return ans if not word: return True for i in range(m): for j in range(n): if board[i][j]==word[0]: if dp(word,i,j): return True return False
fd4e26a6f688c13b6c401f639867310aa1ac8c3e
privateOmega/coding101
/hackerearth/CodeMonk/Basic Programming/Basics of IO/seating-arrangement.py
2,177
4.03125
4
def calculate_seat(addOperation, seatNumber, operand, seatType): if addOperation: return '{} {}'.format(seatNumber + operand, seatType) else: return '{} {}'.format(seatNumber - operand, seatType) def get_seating_arrangement(seatNumber): workableValue = seatNumber % 12 switcher = { 0: calculate_seat(False, seatNumber, 11, 'WS'), 1: calculate_seat(True, seatNumber, 11, 'WS'), 2: calculate_seat(True, seatNumber, 9, 'MS'), 3: calculate_seat(True, seatNumber, 7, 'AS'), 4: calculate_seat(True, seatNumber, 5, 'AS'), 5: calculate_seat(True, seatNumber, 3, 'MS'), 6: calculate_seat(True, seatNumber, 1, 'WS'), 7: calculate_seat(False, seatNumber, 1, 'WS'), 8: calculate_seat(False, seatNumber, 3, 'MS'), 9: calculate_seat(False, seatNumber, 5, 'AS'), 10: calculate_seat(False, seatNumber, 7, 'AS'), 11: calculate_seat(False, seatNumber, 9, 'MS') } return switcher.get(workableValue, lambda: 'Invalid') def main(): noOfTestCases = int(input()) testCases = [] if noOfTestCases < 1: return for iterator in range(noOfTestCases): testCases.append(int(input())) for iterator in range(noOfTestCases): print(get_seating_arrangement(testCases[iterator])) if __name__ == '__main__': main() """ Akash and Vishal are quite fond of travelling. They mostly travel by railways. They were travelling in a train one day and they got interested in the seating arrangement of their compartment. The compartment looked something like So they got interested to know the seat number facing them and the seat type facing them. The seats are denoted as follows : Window Seat : WS Middle Seat : MS Aisle Seat : AS You will be given a seat number, find out the seat number facing you and the seat type, i.e. WS, MS or AS. INPUT First line of input will consist of a single integer T denoting number of test-cases. Each test-case consists of a single integer N denoting the seat-number. OUTPUT For each test case, print the facing seat-number and the seat-type, separated by a single space in a new line. """
4874a015b6257229d709e97e80e71651edc190eb
haifeng-jin/codejam
/2016/r1b/a.py
710
3.609375
4
for case_num in range(int(input())): print('Case #%d: ' % (case_num + 1), end='') st = input() letter_count = {chr(char): st.count(chr(char)) for char in range(ord('A'), ord('Z') + 1)} words = ['ZERO', 'SIX', 'SEVEN', 'FIVE', 'EIGHT', 'THREE', 'TWO', 'FOUR', 'NINE', 'ONE'] letters = ['Z', 'X', 'S', 'V', 'G', 'H', 'T', 'F', 'I', 'O'] numbers = [0, 6, 7, 5, 8, 3, 2, 4, 9, 1] ans = [] for index, word in enumerate(words): number_num = letter_count[letters[index]] ans.extend(numbers[index] for i in range(number_num)) for char in word: letter_count[char] -= number_num ans.sort() print(''.join(map(lambda x: str(x), ans)))
f02eb979185ccfc5e078b165d485444383e30b34
The-Radiant-Sun/Cypher_Playground
/Codes/Vigenere.py
1,924
3.78125
4
# Vigenere cypher class VigenereCypher: def __init__(self, message, key): """Save char_set, message and key as self variables""" self.char_set = [char for char in (chr(i) for i in range(32, 127))] self.message = message self.key = self.check_error(key) @staticmethod def history(): """Return history for Keyword""" history = '''The Vigenère Cipher is a polyalphabetic substitution cipher. The method was originally described by Giovan Battista Bellaso in his 1553 book La cifra del. Sig. Giovan Battista Bellaso; However, the scheme was later misattributed to Blaise de Vigenère in the 19th century, and is now widely known as the Vigenère Cipher. ''' return history def cypher(self, encrypt_decrypt): """Return altered text based on encrypt_decrypt input""" # Empty base result = '' for i, char in enumerate(self.message): # Adding all characters outside the char_set if char not in self.char_set: result += char else: # Enacting the different encryption and decryption if encrypt_decrypt == 'encrypt': char_alter = self.char_set.index(char) + self.char_set.index(self.key[i % len(self.key)]) else: char_alter = self.char_set.index(char) - self.char_set.index(self.key[i % len(self.key)]) result += self.char_set[char_alter % len(self.char_set)] return result def encrypt(self): """Return result from cypher function with encrypt input""" return self.cypher('encrypt') def decrypt(self): """Return result from cypher function with decrypt input""" return self.cypher('decrypt') def check_error(self, key): checked = '' for char in key: checked += char if char in self.char_set else '' return checked
3ee95c61df1d7d8561cf9c444ae169862c266a07
BboyZander/CodeWars
/[6kyu]/[6kyu] create_phone_number.py
566
4.125
4
# Функция, которая записывает номер телефона в определенном формате def create_phone_number(n): m = [str(i) for i in n] elements = [m[:3],m[3:6],m[6:]] first = '(' + ''.join(elements[0]) + ') ' second = ''.join(elements[1])+'-' third = ''.join(elements[2]) return first + second + third def create_phone_number2(n): return "({}{}{}) {}{}{}-{}{}{}{}".format(*n) print(create_phone_number([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) print(create_phone_number2([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
54ebc9083b70a98db8a70fc1a6541885e6f5eaf4
MarieDon/Cloud
/samples.py
468
3.875
4
def miles_to_feet(miles): print (5280*miles) miles_to_feet(13) def total_seconds(hours,minutes,seconds): print (hours *3600 + minutes *60 +seconds) total_seconds(7, 21, 37) def is_even(number): if number % 2 == 0: print("True") else: print("False") is_even(5) def name_and_age(name,age): if age <= 0 : print("invalid age") else: print(name + " is " + str(age) + " years old") name_and_age("Eoin", 20)
28754e483584b8086d4ab6661f9a40b885af61b7
kowshik448/python-practice
/python codes/pairsum.py
1,292
3.8125
4
class Node: def __init__(self,data): self.data=data self.left=None self.right=None class BST: def __init__(self,data): self.root=Node(data) def insert(self,root,data): if root is None: return Node(data) elif root.data==data: return root elif root.data<data: root.right=self.insert(root.right,data) elif root.data>data: root.left=self.insert(root.left,data) return root def inorder(self,root,arr): if root: self.inorder(root.left,arr) arr.append(root.data) self.inorder(root.right,arr) def find_pair(self,arr,summ): i=0 j=len(arr)-1 while i<j: if arr[i]+arr[j]==summ: return (arr[i],arr[j]) elif arr[i]+arr[j]>summ: j-=1 else: i+=1 return "NO PAIRS" bst=BST(15) # bst.insert(bst.root,15) bst.insert(bst.root,10) bst.insert(bst.root,20) bst.insert(bst.root,8) bst.insert(bst.root,12) bst.insert(bst.root,16) bst.insert(bst.root,25) print(bst.root.left.data) arr=[] bst.inorder(bst.root,arr) print(arr) print(bst.find_pair(arr,46))
c3c436157ce035b2fb860db0d719cbbe46e40e80
jkoser/euler
/solved/p44.py
851
3.90625
4
#!/usr/bin/env python3 # Pentagonal numbers are generated by the formula Pn = (3n - 1) / 2. The # first ten pentagonal numbers are: # # 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... # # It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their # difference, 70 - 22 = 48, is not pentagonal. # # Find the pair of pentagonal numbers, Pj and Pk, for which their sum and # difference is pentagonal and D = |Pk - Pj| is minimized; what is D? def pentagonals_below(n): i = 1 p = 1 while p < n: yield p i += 1 p = i * (3 * i - 1) // 2 pents = list(pentagonals_below(100000000)) pents_set = set(pents) d_min = -1 for n in pents: for m in pents: if m > n and m + n in pents_set and m - n in pents_set: d = m - n if d_min < 0 or d > d_min: d_min = d print(d_min)
a398b13e6f88a70bec40b007228369cfe0556a88
superpigBB/Happy-Coding
/Algorithm/Sum of Two Integers.py
963
4.15625
4
# Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. # # Example: # Given a = 1 and b = 2, return 3. # # Credits: # Special thanks to @fujiaozhu for adding this problem and creating all test cases. ### Original Method: ### This should be basic knowledge of how to transform from decimalism to binary ### test more like computer knowledge ### decimalism can be binary=> two methods ### 1. binary = lambda n: '' if n==0 else binary(n/2) + str(n % 2) ### 2. binary = '{0:b}', format(i) ### 2 is faster ### I will directly check anwsers since no meaning for finding the rules ### int('binary', 2) => binary to decimal ### Directly copy from other solution class Solution(object): def getSum(self, a, b): mask = 0xFFFFFFFF _min = 0x80000000 while b: a, b = (a ^ b) & mask, ((a & b) << 1) & mask return a if a <= _min else ~(a ^ mask) obj = Solution() print obj.getSum(1,2)
2d8cf44446c0690136fef92d532032fc1247a4ad
dubonzi/estudos
/python/Lista2CT/exe4.py
326
4.09375
4
valor = input("Digite o 1º número:") num1 = float(valor) valor = input("Digite o 2º número:") num2 = float(valor) soma = num1 + num2 multiplicacao = num1 * num2 divisao = num1 / num2 resto = num1 % num2 print(f"Soma:{soma}") print(f"Multiplicação:{multiplicacao}") print(f"Divisão:{divisao}") print(f"Resto:{resto}")
60a978f6a833207d35bbc0ad92f130e239f1c302
iisojunn/advent-of-code-2020
/day4-passport-protection/main.py
1,960
3.625
4
"""Day 4 advent of code 2020""" import re REQUIRED_FIELDS = {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"} def passport_dict(chunk): fields = chunk.replace("\n", " ").rstrip().split(" ") return {k: v for k, v in [field.split(":") for field in fields]} def read_input(): with open("input", "r") as input_file: data = input_file.read() return [passport_dict(chunk) for chunk in re.split("\n\n", data)] def is_valid(passport): return REQUIRED_FIELDS.issubset(set(passport.keys())) def count_valid(passports): return [is_valid(passport) for passport in passports].count(True) def validate_field(key, value): if key == "byr": return 1920 <= int(value) <= 2002 if key == "iyr": return 2010 <= int(value) <= 2020 if key == "eyr": return 2020 <= int(value) <= 2030 if key == "hgt": if value.endswith("cm"): return 150 <= int(value[:-2]) <= 193 elif value.endswith("in"): return 59 <= int(value[:-2]) <= 76 else: raise Exception("Not good height") if key == "hcl": return bool(re.match("#[0-9a-f]{6}$", value)) if key == "ecl": return value in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"] if key == "pid": return bool(re.match("[0-9]{9}$", value)) if key == "cid": return True def is_strictly_valid(passport): try: fields_valid = [validate_field(k, v) for k, v in passport.items()] return is_valid(passport) and all(fields_valid) except Exception: return False def count_strictly_valid(passports): return [is_strictly_valid(passport) for passport in passports].count(True) if __name__ == '__main__': passport_info = read_input() print(f"All passport info dicts: {passport_info}") print(f"Valid passports {count_valid(passport_info)}") print(f"Strictly valid passports {count_strictly_valid(passport_info)}")
4badacf85290ab2a74cd0897cefd3f4b647cf84d
nicolasmancera/Insertion_sort
/insertion_sort.py
195
3.84375
4
def insertion_sort(lista): for p in range (1,len(lista)): valor=lista[p] i=p-1 while i>=0: if valor < lista[i]: lista[i+1] = lista[i] lista[i]=valor i=i-1 else: break
03cbc768200366cfc81b0a489a3d98c1dfff9b02
jazhten/python
/similar_list.py
447
3.9375
4
import random #this could also be used to show/test Pigeon hole principle len1 = int(input('Enter length of the first list: ')) len2 = int(input('Enter length of the second list: ')) list1 = random.sample(range(100),len1) list2 = random.sample(range(100),len2) print('list one :' + str(list1)) print('list two :' + str(list2)) listcommon = [i for i in list1 if i in list2] listcommon.sort() print('Common numbers are : ' + str(listcommon))
f3d14dc0ed2d6ad7a5fffcf7b3ee3aee3bd13c98
HuipengXu/leetcode
/reverse.py
267
3.8125
4
def reverse(x): """ :type x: int :rtype: int """ if x >= 0: reverse_x = int(str(x)[::-1]) else: reverse_x = - int(str(abs(x))[::-1]) if reverse_x > 2 ** 31 - 1 or reverse_x < -2 ** 31: return 0 return reverse_x
177a5afbe29feff781f99a892f9d71b7b51d9970
RafaelBispoCunha/Curso_em_Video
/Curso_Python3_Mundo1/exercicio_016.py
278
3.90625
4
''' Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela sua porção inteira. 13/01/2020 ''' from math import trunc numero = float(input('Digite um valor qualquer: ')) print('A porção inteira do numero {} é de {}'.format(numero, trunc(numero)))
fb43f3fdaf39cf2f85e1b9397c6641d8f53b8b14
geniousisme/CodingInterview
/Company Interview/SC/meetingRoomII.py
1,169
3.578125
4
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution1(object): def minMeetingRooms(self, intervals): """ :type intervals: List[Interval] :rtype: int TC: O(nlogn) SC: O(n) """ start_times = [] end_times = [] for interval in intervals: start_times.append(interval.start) end_times.append(interval.end) start_times.sort() end_times.sort() si = ei = 0 room_count = 0 min_room_num = 0 while si < len(intervals): # Means need one more room in this period, since there is a meeting on-going. if start_times[si] < end_times[ei]: room_count += 1 # Need one more room min_room_num = max(min_room_num, room_count) # Check if current room number is avaible or not si += 1 # Means we don't need room in this period, since one meeting is over else: room_count -= 1 ei += 1 return min_room_num
b62c78a58ec2d1ca63b5147d9ab03bbba5a2a847
MayraMRossi/Codo_A_Codo_4.0--Python
/Clases/PYTHON - Ejemplos/ejemplos-python-3/diccionarios.py
593
4.3125
4
# DICCIONARIOS # Ejemplos de diccionarios {} # diccionario vacío {'Juan': 56} # diccionario de un elemento {'Juan': 56, 'Ana': 15} # diccionario de dos elementos # Creación: Por extensión diccionario = {'Juan': 56, 'Ana': 15} print(diccionario) # Creación: Por compresión diccionario = {x: x ** 2 for x in (2, 4, 6)} print(diccionario) # Acceso diccionario = {1: 'uno', 2:'dos', 3:'tres'} print(diccionario.keys()) for i in diccionario.keys(): print(diccionario[i]) for clave, valor in diccionario.items(): print(clave, ':', valor, end= '; ')
cbe12849f009cf790e12a6a94800b90bab6ae8a5
50417/phd
/learn/ctci/0104-escape-string.py
2,060
4.4375
4
from absl import app # Exercise 1.4: # # Write a method to replace all spaces in a string with '%20'. You # may assume that the string has sufficient space at the end of # the string to hold the additional characters, and that you given # the "true" length of the string. # # First off, let's get the obvious way over and done with: def escape_spaces_regexp(string, strlen): return string.replace(' ', '%20') # Of course, this misses the purpose of the question by operating on a # string, not a character array. Implementing a proper character array # solution requires two passes, and operates in O(n) time, with O(1) # space complexity (it operates in place): def escape_spaces(string, strlen): # The first pass is to ascertain the number of ' ' characters # which need escaping, which can then be used to calculate the new # length of the escaped string. spaces_count = 0 for c in list(string[:strlen]): if c == ' ': spaces_count += 1 new_strlen = strlen + 2 * spaces_count # Now that we know the new string length, we work from front to # back, copying original string characters into their new # positions. If we come across a ' ' character, it is replaced # with the padded equivalent. # # We can make a cheeky optimisation because we know that if the # escaped string length and the original string length are equal, # then there are no characters which need escaping, so we don't # need to do anything. if new_strlen != strlen: for i in range(strlen - 1, -1, -1): new_strlen -= 1 if string[i] == ' ': string[new_strlen - 2] = '%' string[new_strlen - 1] = '2' string[new_strlen] = '0' new_strlen -= 2 else: string[new_strlen] = string[i] return string def main(argv): del argv assert escape_spaces_regexp("Hello, the World!", 17) == "Hello,%20the%20World!" assert (''.join(escape_spaces(list("Hello, the World! "), 17)) == "Hello,%20the%20World! ") if __name__ == "__main__": app.run(main)
1f38806edac48cfa9422c668dccb56034029dc7f
David-Carrasco-Vidaurre/trabajo04.CarrascoVidaurreDavid
/Calculadora03.py
306
3.609375
4
#calculadora nro3 #esta calculadora realiza el calculade de la potencia #declaracion de variables trabajo,tiempo,potencia=0.0,0.0,0.0 #calculadora trabajo=18 tiempo=9 potencia=(trabajo//tiempo) #motrar datos print("trabajo =",trabajo) print("tiempo =",tiempo) print("potencia=",potencia)
c07f2d2aee46063041bbdfd704730496c98484bc
gaurav638012/SURP_IPL
/Week2/stats.py
2,672
3.578125
4
import pandas as pd #This function will take player name as input and output is dict in the form - #{match_id: [innings, batting position, runs scored, balls faced, strikerate, out/notout, 50, 100, runs in powerplay, runs in middle overs, runs in death overs, result of match, str in first 20, str in next 10, str after 30, number of 4s, number of 6s]} #strikerates are -1 where not applicable def stats(name): data = open("clean.csv", 'r') matches = pd.read_csv("IPL Matches 2008-2020.csv") content = {} prev_id = 0 prev_inn = 0 for line in data: l = line.split(",") id = l[0] if id == "id": continue id = int(id) if prev_id != id or prev_inn != l[1]: count = 0 #count is for batting position if l[4] == name: if id not in content.keys(): content[id] = [int(l[1]), count, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] if list(matches.loc[matches['id'] == id]['winner'])[0] == l[16]: content[id][11] = 1 #0 -> loss, 1 -> win content[id][2] += int(l[7]) #runs scored if int(l[2]) < 6: content[id][8] += int(l[7]) #runs scored in powerplay elif int(l[2]) > 15: content[id][10] += int(l[7]) #runs scored in death overs else: content[id][9] += int(l[7]) #runs scored in middle overs if l[15] != "wides": content[id][3] += 1 #balls faced if content[id][3] <= 20: content[id][12] += int(l[7]) elif content[id][3] <= 30: content[id][13] += int(l[7]) else: content[id][14] += int(l[7]) if int(l[7]) == 4 and l[10] == "0": content[id][15] += 1 if int(l[7]) == 6 and l[10] == "0": content[id][16] += 1 if l[13] == name: if id not in content.keys(): content[id] = [int(l[1]), count, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] if list(matches.loc[matches['id'] == id]['winner'])[0] == l[16]: content[id][11] = 1 content[id][5] = 1 #0 -> not out, 1 -> out if l[11] == "1": count += 1 #number of players out before batsman came to bat prev_id = id prev_inn = l[1] data.close() for id in content.keys(): if content[id][3] > 0: content[id][4] = float("{:.2f}".format(100*content[id][2]/content[id][3])) else: content[id][4] = -1 if content[id][2] >= 100: content[id][7] = 1 elif content[id][2] >= 50: content[id][6] = 1 if content[id][3] > 0: content[id][12] = float("{:.2f}".format(100*content[id][12]/max(content[id][3], 20))) else: content[id][12] = -1 if content[id][3] > 20: content[id][13] = float("{:.2f}".format(100*content[id][13]/max(content[id][3]-20, 10))) else: content[id][13] = -1 if content[id][3] > 30: content[id][14] = float("{:.2f}".format(100*content[id][14]/(content[id][3]-30))) else: content[id][14] = -1 return content
ba4bdecaba6569f57bcf30754491acfdc30ca103
rajat-jain9/python
/excel.py
2,075
3.53125
4
import pandas as pd df = pd.read_excel(r"./test data_Malkajgiri.xlsx") #print(df) df2 = df.set_index("#") print(df2) ### 1) INDEXING###### print(df2.loc[1:5,"From":"To"]) print(df2.loc[: ,"To"]) print(df2.head(2)) OR print(df2.loc[1:2,"ID":"Booking History"]) (For first two rows) print(df2.tail(2)) (For Last two rows) print(df2.loc[1, :]) print(df2.loc[1,"To"]) print(df2.loc[: ,"Start Time Hour"].mean()) print(df2.iloc[0:2,0:1]) print(df2.ix[0:2,"From":"To"]) df2["Start Time"] = df2["Start Time Hour"].map(str) + df2["Start Time Minutes"].map(str) df2['Start Time'] = df[['Start Time Hour','Start Time Minutes']].apply(lambda x: ''.join(x), axis=1) df['ColumnA'] = df[df.columns[3:5]].apply(lambda x: ','.join(x.dropna().astype(int).astype(str)),axis=1) sd = df.reindex(column=['column name',[column name],..]) #To show only specific columns ### 2) MErging Two DaaFrames Having all common columns #Let df1 and df2 are two DataFrames merge = pd.merge(df1,df2) (This will print all common columns) merge = pd.merge(df1,df2,on = "Any Common Column NAme") (Will print only specific common column) ### 3) JOIN Two DataFrames joined = df1.join(df2) ### 4) TO change INdex df2 = df.set_index("column name") ### 5) Rename Column Header df = df.remname(column={"Start Time Hour","Start Time"}) ### 6) Draw Graph using matplotlib import matplotlib as plt from matplotlib import style style.use("fivethirtyeight") df.plot() plt.show() ### 7) Concatenation in DataFrames concat = pd.concat([df1,df2]) ### 8) Converting a csv file into html file(Data Munging) csv = pd.read_csv('File Path',index_col=0) csv.to_html('new.html') #(file will be downloaded in your current working directory) ### 9) Statistics using python(Mean,Median,Mode,Variance) from statistics import mean from statistocs import median from statistics import mode from statistics import variance print(mean([1,2,2,3,4,4,5])) print(median([1,2,2,3,4,4,5])) print(mode([1,2,2,3,4,4,5])) print(variance([1,2,2,3,4,4,5]))
1743307e92942f4324451c3ebdf31315cf8ccdf6
sumitsethtest/Python-67
/Alien_invasion/ship.py
2,923
3.53125
4
# coding=utf-8 import pygame from pygame.sprite import Sprite class Ship(Sprite): def __init__(self, ai_settings, screen): """初始化飞船并设置其初始位置""" super(Ship, self).__init__() self.screen = screen self.ai_settings = ai_settings # 加载飞船图像并获取其外接矩形 self.image = pygame.image.load('ship.bmp') # 返回一个表示飞船的surface self.rect = self.image.get_rect() # 获取一个飞船surface属性的外接矩形 self.screen_rect = self.screen.get_rect() # 获取屏幕的外接矩形 # 将每艘新飞船放在屏幕中央底部 self.rect.centerx = self.screen_rect.centerx # 飞船中心的x坐标居中 值为600 self.rect.bottom = self.screen_rect.bottom # 飞船下边缘的y坐标 值为800 # 在飞船的属性center中存储小数值 self.center = float(self.rect.centerx) # 水平坐标 self.bottom = float(self.rect.bottom) # 纵向坐标 # 移动标志,飞船默认不移动为False self.moving_right = False self.moving_left = False self.moving_up = False self.moving_down = False self.moving_speed_low = False self.shot_continue = False def update(self): """根据移动标志调整飞船的位置""" if self.moving_right and self.rect.right < self.screen_rect.right: if self.moving_speed_low: self.center += self.ai_settings.ship_speed_low else: self.center += self.ai_settings.ship_speed_factor if self.moving_left and self.rect.left > self.screen_rect.left: if self.moving_speed_low: self.center -= self.ai_settings.ship_speed_low else: self.center -= self.ai_settings.ship_speed_factor if self.moving_up and self.rect.top > self.screen_rect.top: if self.moving_speed_low: self.bottom -= self.ai_settings.ship_speed_low else: self.bottom -= self.ai_settings.ship_speed_factor if self.moving_down and self.rect.bottom < self.screen_rect.bottom: if self.moving_speed_low: self.bottom += self.ai_settings.ship_speed_low else: self.bottom += self.ai_settings.ship_speed_factor # 更新rect属性 self.rect.centerx = self.center # rect属性只能获取整数部分 self.rect.bottom = self.bottom def blitme(self): """在指定位置绘制飞船""" self.screen.blit(self.image, self.rect) def center_ship(self): """让飞船在屏幕上居中""" self.center = self.screen_rect.centerx self.bottom = self.screen_rect.bottom
fabb46f73fd5920a7db1a5a4c330c1f7d47d6bb2
brackengracie/CS-1400
/Class_average.py
779
4.03125
4
# Class Average by Gracie Bracken def main() : # print instructions print("This program inputs test scores") print("and calculates the average.") print("") # get the # of students number_students=input("please enter the number of students -> ") number_students=int(number_students) # get the scores score_list=[] for i in range(number_students) : score=input("score -> ") score=int(score) score_list.append(score) # calc the average total=0 for i in range(len(score_list)): total= total + score_list[i] average_score=total/len(score_list) # print results print("I have thought long and hard . . . .") print("The average score is",average_score,"!") main()
8a95aa4ba4b867852e03aab0bcb879b837790b06
supernifty/dovex
/util.py
248
3.546875
4
def choose_delimiter(fh): start = (fh.readline(), fh.readline()) if start[0].count('\t') >= 1 and start[0].count('\t') == start[1].count('\t'): delimiter = '\t' else: delimiter = ',' fh.seek(0) return delimiter
ca3a018ba6b17a539aee8ed4539e32db117af83f
MychalCampos/Udacity_CS101_Lesson3
/measure_udacity.py
608
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 26 13:35:29 2015 # Define a procedure, measure_udacity, # that takes as its input a list of strings, # and returns a number that is a count # of the number of elements in the input # list that start with the uppercase # letter 'U'. @author: Mychal """ def measure_udacity(p): count = 0 for e in p: if e.find('U') != -1: count = count + 1 return count def test(): assert measure_udacity(['Dave', 'Sebastian', 'Katy']) == 0 assert measure_udacity(['Umika', 'Umberto']) == 2 print "All Test Cases Passed!" test()
d707ba68840748f3e9736999ceb64c589c635bfe
thiagosousadasilva/Curso-em-Video
/CURSO DE PYTHON 3/Mundo 3 - Estruturas Compostas/1 - Tuplas em Python/Exerc077.py
519
4.15625
4
''' Exercício Python #077 - Contando vogais em Tupla: Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais. ''' print("== Exercício Python #077 - Contando vogais em Tupla ==") palavras = ('thiago', 'sousa', 'sofia', 'karolina') for palavra in palavras: print(f'\nVogais de {palavra.upper()}: ', end='') for letra in palavra: if letra.lower() in 'aeiou': print(letra, end=' ')
f1b8b884adb7c7601a16d8360aa5012c65decc31
Baalajisk/pythonPrograms
/week2_2p.py
497
3.78125
4
def depth(string): total=0 inc=0 dec=0 count=0 for i in string: if i=='(': inc=inc+1 count=count+1 elif i==')': dec=dec+1 if inc==dec: if count>total: total=count count=0 inc=0 dec=0 print(total) s=input("enter the string") depth(s)
be22bce00e4a152a337f08e3b727180422836ed7
ygorfds/1_Exercicios_Python3
/7_LISTA1.py
424
4.1875
4
""" 7. Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário. """ # LISTA 1 - EXERCÍCIO 7 print('Cálculos geométricos: quadrado') b = float(input('Entre com o valor da base em milímetros:')) h = float(input('Entre com o valor da altura em milímetros:')) area = b*h print(f'Área do quadrado é {area} mm2.') print(f'O dobro da área do quadrado é {2*area} mm2.')
790eea7941c1ec85dea3a33d220e82d8089036c1
nmoore32/coursera-fundamentals-of-computing-work
/1 An Introduction to Interactive Programming in Python/Week 7 and 8/Mini project for week 7 and 8/asteroids_clone.py
14,243
3.78125
4
# program template for Spaceship # Provided via An Introduction to Interactive Programming in Python (Part 2) (Coursera, Rice University) import SimpleGUICS2Pygame.simpleguics2pygame as simplegui from math import cos, pi, sin, sqrt from random import random, randrange # Hide the simplegui control panel area simplegui.Frame._hide_controlpanel = True # globals for user interface (provided as part of starting template) WIDTH = 800 HEIGHT = 600 score = 0 lives = 3 time = 0 started = False # New constants I defined FONT_SIZE = 30 MARGIN = 20 GAP = 300 # Space between ship and any spawning rocks # New global variables I defined rock_group = set() missile_group = set() explosion_group = set() class ImageInfo: # Class provided as part of starting template) def __init__(self, center, size, radius=0, lifespan=None, animated=False): self.center = center self.size = size self.radius = radius if lifespan: self.lifespan = lifespan else: self.lifespan = float('inf') self.animated = animated def get_center(self): return self.center def get_size(self): return self.size def get_radius(self): return self.radius def get_lifespan(self): return self.lifespan def get_animated(self): return self.animated # art assets created by Kim Lathrop (provided) debris_info = ImageInfo([320, 240], [640, 480]) debris_image = simplegui._LocalImage('images/debris2_blue.png') nebula_info = ImageInfo([400, 300], [800, 600]) nebula_image = simplegui._LocalImage('images/nebula_blue.f2014.png') splash_info = ImageInfo([200, 150], [400, 300]) splash_image = simplegui._LocalImage('images/splash.png') ship_info = ImageInfo([45, 45], [90, 90], 35) ship_image = simplegui._LocalImage('images/double_ship.png') missile_info = ImageInfo([5, 5], [10, 10], 3, 50) missile_image = simplegui._LocalImage('images/shot2.png') asteroid_info = ImageInfo([45, 45], [90, 90], 40) asteroid_image = simplegui._LocalImage('images/asteroid_blue.png') explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True) explosion_image = simplegui._LocalImage('images/explosion_alpha.png') # These lines provided but I replaced the sound files # Soundtrack created by Speedenza and obtained from freesound.org # Creation Commons Attribution noncommercial license http://creativecommons.org/licenses/by-nc/3.0/ soundtrack = simplegui._LocalSound('sounds/soundtrack.ogg') missile_sound = simplegui._LocalSound('sounds/missile.ogg') missile_sound.set_volume(.5) # Thrust sound created by primeval_polypod and obtained from freesound.org # Creative Commons Attribution license https://creativecommons.org/licenses/by/3.0/ ship_thrust_sound = simplegui._LocalSound('sounds/thrust.ogg') # Explosion sound created by LiamG_SFX and obtained from freesound.org # Creation Commons Attribution noncommercial license http://creativecommons.org/licenses/by-nc/3.0/ explosion_sound = simplegui._LocalSound('sounds/explosion.ogg') def angle_to_vector(ang): # Provided as part of starting template return [cos(ang), sin(ang)] def dist(p, q): # Provided as part of starting template return sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2) # Ship class class Ship: def __init__(self, pos, vel, angle, image, info): # init provided as part of starting template self.pos = [pos[0], pos[1]] self.vel = [vel[0], vel[1]] self.thrust = False self.angle = angle # In radians, not degrees self.angle_vel = 0 self.image = image self.image_center = info.get_center() self.image_size = info.get_size() self.radius = info.get_radius() def draw(self, canvas): # If thrust is on use thrust image if self.thrust: # Need to specify the center of the thrust image on the ship_image tilesheet center = (self.image_center[0] + self.image_size[0], self.image_center[1]) # draw_image(image, center_source, width_height_source, center_dest, width_height_dest, rotation=0) canvas.draw_image(self.image, center, self.image_size, self.pos, self.image_size, self.angle) else: # Center of non-thrust image and self.image_center are the same canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle) def update(self): # Update ship position, ensuring ship wraps screen self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT # Update angular position self.angle += self.angle_vel # Have the ship automatically slow down over time (numbers should be less than, but close to, 1) # This also puts an upper limit on ship speed once this decrease is equal to the ship thrust velocity self.vel[0] *= 0.98 self.vel[1] *= 0.98 # Get unit vector pointing indicating direction the ship is facing forward = angle_to_vector(self.angle) # Accelerate forward if self.thrust if self.thrust: # Multipler is arbitrary, larger multipler means more acceleration self.vel[0] += forward[0] * 0.25 self.vel[1] += forward[1] * 0.25 def set_angle_vel(self, key, key_state): # Set angular velocity to -0.1 if left is down and set back to zero if right is released if (key == 'left' and key_state == 'down') or (key == 'right' and key_state == 'up') and self.angle_vel != -0.1: self.angle_vel -= 0.1 # Set angular velocity to 0.1 if right is down and set back to zero if left is released elif (key == 'right' and key_state == 'down') or (key == 'left' and key_state == 'up') and self.angle_vel != 0.1: self.angle_vel += 0.1 def set_thrust(self, thrust): self.thrust = thrust if self.thrust: ship_thrust_sound.rewind() ship_thrust_sound.play() else: ship_thrust_sound.rewind() def shoot(self): # Set the starting position of the missile to the tip of the ship forward = angle_to_vector(self.angle) pos = [self.pos[0] + (self.image_size[0] / 2) * forward[0], self.pos[1] + (self.image_size[1] / 2) * forward[1]] # Set the velocity of the missile as the velocity of the ship plus some forward missile velocity vel = [self.vel[0] + 5 * forward[0], self.vel[1] + 5 * forward[1]] ang = 0 ang_vel = 0 missile_group.add(Sprite(pos, vel, ang, ang_vel, missile_image, missile_info, missile_sound)) def get_position(self): return self.pos def get_radius(self): return self.radius # Sprite class class Sprite: def __init__(self, pos, vel, ang, ang_vel, image, info, sound=None): # init provided as part of starting template self.pos = [pos[0], pos[1]] self.vel = [vel[0], vel[1]] self.angle = ang self.angle_vel = ang_vel self.image = image self.image_center = info.get_center() self.image_size = info.get_size() self.radius = info.get_radius() # Measure of how long sprite 'lives' before automatic removal self.lifespan = info.get_lifespan() self.animated = info.get_animated() self.age = 0 if sound: sound.rewind() sound.play() def draw(self, canvas): if self.animated == False: canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle) else: pos_x = self.image_center[0] + self.age * self.image_size[0] pos_y = self.image_center[1] canvas.draw_image(self.image, [pos_x, pos_y], self.image_size, self.pos, self.image_size, self.angle) def update(self): self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT self.angle += self.angle_vel self.age += 1 return self.age >= self.lifespan def collide(self, other_object): return dist(self.pos, other_object.get_position()) <= self.radius + other_object.get_radius() def get_position(self): return self.pos def get_radius(self): return self.radius def draw(canvas): global time, lives, score, started # animate background (this part of the code was provided as part of starting template) time += 1 wtime = (time / 4) % WIDTH center = debris_info.get_center() size = debris_info.get_size() canvas.draw_image(nebula_image, nebula_info.get_center( ), nebula_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT]) canvas.draw_image(debris_image, center, size, (wtime - WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT)) canvas.draw_image(debris_image, center, size, (wtime + WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT)) # Draw and update ship ship.draw(canvas) ship.update() # Draw lives and score pos_lives = [MARGIN, MARGIN + FONT_SIZE] canvas.draw_text(f"Lives: {lives}", pos_lives, FONT_SIZE, 'White') # Length of each character approx 2/3 of font size, 'score' has 5 characters pos_score = [WIDTH - MARGIN - 2/3 * FONT_SIZE * 5, MARGIN + FONT_SIZE] canvas.draw_text(f"Score: {score}", pos_score, FONT_SIZE, 'White') if started: # Draw and update sprites process_sprite_group(rock_group, canvas) process_sprite_group(missile_group, canvas) process_sprite_group(explosion_group, canvas) # Check for collisions if group_collide(rock_group, ship): lives -= 1 if lives == 0: started = False reset_game() score += group_group_collide(missile_group, rock_group) else: canvas.draw_image(splash_image, splash_info.get_center(), splash_info.get_size(), (WIDTH / 2, HEIGHT / 2), splash_info.get_size()) def rock_spawner(): # Timer handler that spawns a rock if started: if len(rock_group) == 12: # Maximum number of rocks on screen at a time return else: pos = [randrange(WIDTH), randrange(HEIGHT)] # Make sure new rocks spawn a reasonable distance from the ship while dist(pos, ship.get_position()) <= GAP: pos = [randrange(WIDTH), randrange(HEIGHT)] # Numbers here are fairly arbitrary, they give velocities that seem reasonable to me # Velocities components can range from -6 to 6 vel = [6 * (random() - 1), 6 * (random() - 1)] ang = random() * 2 * pi # Number between 0 and 2pi for initial angle ang_vel = random() / 5 - 0.1 # Angular velocity can range from -0.1 to 0.1 rock_group.add(Sprite(pos, vel, ang, ang_vel, asteroid_image, asteroid_info)) def process_sprite_group(group, canvas): new_set = set(group) for obj in new_set: # Delete sprite if it's reached its lifespan if obj.update(): group.discard(obj) obj.draw(canvas) def group_collide(group, other_object): new_set = set(group) for obj in group: if obj.collide(other_object): group.discard(obj) explosion_group.add(Sprite(obj.get_position(), [ 0, 0], 0, 0, explosion_image, explosion_info, explosion_sound)) return True def group_group_collide(group1, group2): # Track number of missile-rock collision to add to score num_collisions = 0 for obj in set(group1): if group_collide(group2, obj): num_collisions += 1 return num_collisions def reset_game(): global rock_group, missile_group, explosion_group, lives, score, ship rock_group = set() missile_group = set() explosion_group = set() lives = 3 score = 0 ship = Ship(ship.get_position(), [0, 0], 0, ship_image, ship_info) soundtrack.rewind() ship_thrust_sound.rewind() def key_down(key): if started: if key == simplegui.KEY_MAP['left']: ship.set_angle_vel('left', 'down') elif key == simplegui.KEY_MAP['right']: ship.set_angle_vel('right', 'down') elif key == simplegui.KEY_MAP['up']: ship.set_thrust(True) elif key == simplegui.KEY_MAP['space']: ship.shoot() def key_up(key): if started: if key == simplegui.KEY_MAP['left']: ship.set_angle_vel('left', 'up') elif key == simplegui.KEY_MAP['right']: ship.set_angle_vel('right', 'up') elif key == simplegui.KEY_MAP['up']: ship.set_thrust(False) def mouse_click(pos): global started # Start the game if user clicks in play area if pos[0] < WIDTH and pos[1] < HEIGHT and not started: started = True soundtrack.rewind() soundtrack.play() # initialize frame (provided as part of starting template) frame = simplegui.create_frame("Asteroids", WIDTH, HEIGHT) # initialize ship (provided as part of starting template) ship = Ship([WIDTH / 2, HEIGHT / 2], [0, 0], 0, ship_image, ship_info) # register handlers (provided as part of starting template except for mouseclick_handler) frame.set_draw_handler(draw) frame.set_keydown_handler(key_down) frame.set_keyup_handler(key_up) frame.set_mouseclick_handler(mouse_click) # Set timers to automatically stop when frame is closed simplegui.Frame._keep_timers = False # Provided as part of starting template timer = simplegui.create_timer(1000.0, rock_spawner) # get things rolling (provided as part of starting template) timer.start() frame.start() # To do # 1. Find sounds I can use # 260 lines of code (exlcuding comments and blank lines) # 95 lines of code provided (most of it the art/sound assets, ImageInfo class, and Ship/Sprite init) # 164 lines of code my own
3094f53640d45deb4eb3a0bcda0496f36326f5bf
omar1slam/Code-Wars
/Multiples of 3 & 5.py
435
3.875
4
# Find multiples of 3 and 5 below the number given # https://www.codewars.com/kata/514b92a657cdc65150000006/train/python # 6 kyu def solution(number): found = [] for i in range(number-1,0,-1): if (i % 3) == 0 or (i % 5) == 0: if i not in found: found.append(i) return sum(int(digit) for digit in found) #############################DONE#####################
2d36f3a77acbddea594a50263af67e41971b583d
bitterengsci/algorithm
/九章算法/强化班LintCode/Word Search II.py
4,092
3.875
4
DIRECTIONS = [(0, -1), (0, 1), (-1, 0), (1, 0)] class TrieNode: # define node in a trie def __init__(self): self.children = {} self.is_word = False self.word = None class Trie: def __init__(self): self.root = TrieNode() def add(self, word): # insert the word into trie node = self.root for c in word: if c not in node.children: node.children[c] = TrieNode() #在此节点申请节点 node = node.children[c] # continue traversing node.is_word = True node.word = word #存入单词 def find(self, word): node = self.root for c in word: node = node.children.get(c) if node is None: return None return node class Solution: """ @param board: A list of lists of character @param words: A list of string @return: A list of string """ # Approach: 不用Trie,直接使用hashset的方法 def wordSearchII(self, board, words): if board is None or len(board) == 0: return [] # pre-process word_set = set(words) prefix_set = set() for word in words: for i in range(len(word)): prefix_set.add(word[:i + 1]) result = set() for i in range(len(board)): for j in range(len(board[0])): c = board[i][j] self.search(board, i, j, board[i][j], word_set, prefix_set, set([(i, j)]), result) return list(result) def search(self, board, x, y, word, word_set, prefix_set, visited, result): if word not in prefix_set: return if word in word_set: result.add(word) for delta_x, delta_y in DIRECTIONS: x_ = x + delta_x y_ = y + delta_y if not self.inside(board, x_, y_) or (x_, y_) in visited: continue visited.add((x_, y_)) self.search(board, x_, y_, word + board[x_][y_], word_set, prefix_set, visited, result) visited.remove((x_, y_)) # Approach: 使用Trie进行剪枝 ''' 考点: - dfs - Trie树, 一种树形结构, 哈希树的变种 典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串), 所以经常被搜索引擎系统用于文本词频统计 题解: 首先建立字典树,字典树从root开始。利用字母的公共前缀建树。 遍历字母矩阵,将字母矩阵的每个字母,从root开始dfs搜索,搜索到底部时,将字符串存入答案返回即。 ''' def wordSearchII_trie(self, board, words): if board is None or len(board) == 0: return [] trie = Trie() for w in words: trie.add(w) result = set() # traverse the board/matrix, start dfs with each entry for i in range(len(board)): for j in range(len(board[0])): self.dfs(board, i, j, trie.root.children.get(board[i][j]), set([(i, j)]), result) return list(result) def dfs(self, board, x, y, node, visited, result): # search.. if node is None: return if node.is_word: result.add(node.word) for delta_x, delta_y in DIRECTIONS: # search for 4 directions x_ = x + delta_x y_ = y + delta_y if not self.inside(board, x_, y_) or (x_, y_) in visited: continue # valid direction, do explore.. visited.add((x_, y_)) self.dfs(board, x_, y_, node.children.get(board[x_][y_]), visited,result) visited.remove((x_, y_)) def inside(self, board, x, y): return 0 <= x < len(board) and 0 <= y < len(board[0])
f5cc79eca4426aefcc3220491a3d953d0e6f8b65
DevGusta/AplicacaoPython
/ListaTarefas/main.py
863
3.796875
4
from opcaoTarefas import addTarefas, listarTarefas, desfazer, refazer tarefas = [] excluidos = [] while True: print("#" * 50) print("1. Adicione uma tarefa.") print("2. Liste suas tarefas.") print("3. Desfaça sua última alteração.") print("4. Refaça sua última alteração") opcao = input("Escolha uma opção: ") if opcao == '1': novaTarefa = input("Digite sua nova tarefa: ") addTarefas(tarefas, novaTarefa) continue elif opcao == '2': print("Tarefas:") listarTarefas(tarefas) print() continue elif opcao == '3': desfazer(tarefas, excluidos) continue elif opcao == '4': refazer(tarefas, excluidos) continue else: print("Opção inválida. Tente novamente.") continue
bfd227edc6b79aed92e3a4357e1091aa0690ee25
phibzy/InterviewQPractice
/Solutions/CourseSchedule/courseSchedule.py
4,004
4.125
4
#!/usr/bin/python3 """ Takes in numCourses(int) and prerequisites (list of list of int) aka graph edges Returns if possible to finish all courses Questions to Interviewer: - Will there be redundant prereqs? E.g. [[1,0], [2,1], [2,0]] - Multiple prereqs? - Max numCourses? - Range of prereqs size? Algo: If prereqs >= numCourses then impossible to finish all courses Make directed graph (adj matrix) of prereqs Hash of coords to check if we've visited coord before Do DFS/BFS on graph, if you end up at node you already visited, then it's impossible to finish all courses Logic: if that happens, then you need to finish course further down the line to do course you've already completed, which makes no nense """ import pdb import copy class Solution: def canFinish(self, numCourses, prerequisites): if prerequisites == []: return True # if len(prerequisites) >= numCourses: return False # # Step 1 - make da graph # graph = [[] for _ in range(numCourses)] # for i in range(numCourses): # graph[i] = [0 for _ in range(numCourses)] # # Step 2 - Add edges # for x, y in prerequisites: # if not (0 <= x < numCourses and 0 <= y < numCourses): return False # graph[y][x] = 1 # # print(graph) # # Step 3 - do search # doneDFS = dict() # for x in range(numCourses): # if x in doneDFS: continue # visited = dict() # # If returns false, then we break/return false # if not self.dfs(x, numCourses, graph, visited, doneDFS): # return False # Algo: Make array of indegrees, graph as adj matrix (using hash of ints -> List) # Do topological sort, using queue graph = dict() inDegrees = [ 0 for _ in range(numCourses) ] for i in range(numCourses): graph[i] = list() # Add +1 to indegree for node with something pointing to it # Add to adjacency lists to represent edges (assuming directed graph) for x, y in prerequisites: if not (0 <= x < numCourses and 0 <= y < numCourses): return False inDegrees[x] += 1 graph[y].append(x) # Make queue, add all 0 indegree nodes to queue q = list() for i, val in enumerate(inDegrees): if val == 0: q.append(i) count = 0 while q: # Take node out of queue, subtract from indegree of neighbours, then add neighbours if indegree = 0 # Keep track of count too - if we don't service all nodes in queue then there is a cycle nextNode = q.pop(0) count += 1 #For each neighbour for n in graph[nextNode]: inDegrees[n] -= 1 if inDegrees[n] == 0: q.append(n) return count == numCourses def dfs(self, x, numCourses, graph, visited, doneDFS): # Problem with algo - check if it visits origin? But that's wrong since you could get cycle elsewhere if x in visited: return False if x in doneDFS: return True # For future reference, in a problem like this with unique integers in a given range - use an array for visited visited[x] = True doneDFS[x] = True # pdb.set_trace() for i in range(numCourses): if graph[x][i] == 1: if not self.dfs(i, numCourses, graph, copy.deepcopy(visited), doneDFS): return False return True """ Graph implementation tradeoffs: - Adj Matrix: O(V^2) space complexity, but constant access time - Adj List: O(V+E) space complexity, but worst case access time of O(E) Some cases e.g. if E is way bigger than V, then matrix might be good idea """ # a = Solution() # print(a.canFinish(5, [[1,0],[2,1],[3,1],[4,2],[4,3]]))
f9a38cd6067ee20c8e7604db2e2c2c23b9b6f507
mccornet/leetcode_challenges
/Python/0167.py
1,659
3.84375
4
class Solution: def twoSum(self, nums: list[int], target: int) -> list[int]: """ ## Challenge: Given an array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length. The tests are generated such that there is exactly one solution. You may not use the same element twice. You can return the answer in any order. Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. ## Solution - Two pointer approach: Set a pointer at the start and at the end If the sum of those is bigger than the target Decrease the last pointer with one step If the sum is bigger than the target increase the First pointer with one step. """ pointer_start = 0 pointer_end = len(nums) - 1 while nums[pointer_start] + nums[pointer_end] != target: if nums[pointer_start] + nums[pointer_end] > target: pointer_end -= 1 else: pointer_start += 1 return [pointer_start + 1, pointer_end + 1] if __name__ == "__main__": s = Solution() res_1 = s.twoSum([2,7,11,15], 9) print(res_1) res_2 = s.twoSum([2,3,4], 6) print(res_2)
24d3541ed5122c20cd1d7c10955025689b3f3541
michnik3/Python
/Lesson6/ask4.py
199
3.71875
4
primes_list = [] for N in range(2,100+1): for i in range(2,N): if N % i == 0: break else: print("It's prime") primes = tuple(primes_list) print(primes)
7ede1bbe6fac1040529944e8637f819db14ffc43
justinbourb/coding_challenges
/code_challenges_python/google_round_f_2021_festival_2.py
2,668
3.59375
4
""" Problem Festival You have just heard about a wonderful festival that will last for D days, numbered from 1 to D. There will be N attractions at the festival. The i-th attraction has a happiness rating of hi and will be available from day si until day ei , inclusive. You plan to choose one of the days to attend the festival. On that day, you will choose up to K attractions to ride. Your total happiness will be the sum of happiness ratings of the attractions you chose to ride. What is the maximum total happiness you could achieve? Input The first line of the input gives the number of test cases, T . T test cases follow. The first line of each test case contains the three integers, D , N and K. The next N lines describe the attractions. The i-th line contains hi, si and ei . Output For each test case, output one line containing Case #x : y, where x is the test case number (starting from 1) and y is the maximum total happiness you could achieve. Limits Memory limit: 1 GB. 1≤T≤100 . 1≤K≤N. 1≤si≤ei≤D, for all i. 1≤hi≤3×105, for all i . Test Set 1 Time limit: 20 seconds. 1≤N≤1000 . 1≤D≤1000 . Test Set 2 Time limit: 90 seconds. For at most 10 test cases: 1≤N≤3×105 . 1≤D≤3×105 . For the remaining cases, 1≤N,D≤1000. Sample Sample Input save_alt content_copy 2 10 4 2 800 2 8 1500 6 9 200 4 7 400 3 5 5 3 3 400 1 3 500 5 5 300 2 3 Sample Output save_alt content_copy Case #1: 2300 Case #2: 700 In sample test case 1, the festival lasts D=10 days, there are N=4 attractions, and you can ride up to K=2 attractions. If you choose to attend the festival on the 6th day, you could ride the first and second attractions for a total happiness of 800+1500=2300 . Note that you cannot also ride the third attraction, since you may only ride up to K=2 attractions. This is the maximum total happiness you could achieve, so the answer is 2300 . In sample test case 2, the festival lasts D=5 days, there are N=3 attractions, and you can ride up to K=3 attractions. If you choose to attend the festival on the 3rd day, you could ride the first and third attractions for a total happiness of 400+300=700 . This is the maximum total happiness you could achieve, so the answer is 700. """ # D days # N attractions # hi happiness, Si start date, ei end date # K which attractions to ride # output # sum of happiness rating for attactions in K # input # T # of test cases class Solution: def main(self): for j in range(int(input())): n, p = map(int, input().strip().split()) l = list(map(int, input().split())) print(l) if __name__ == "__main__": Solution.main(input())
47e09c4881150ee24fd0992596e6a1257c702161
GregFriedlander/Python-Stack
/OOP/hospitalsolution.py
2,201
3.59375
4
class Patient(object): PATIENT_COUNT = 0 def __init__(self, name, allergies): self.name = name self.allergies = allergies self.id = Patient.PATIENT_COUNT self.bed_num = None Patient.PATIENT_COUNT += 1 class Hospital(object): def __init__(self, name, cap): self.name = name self.cap = cap self.patients = [] self.beds = self.initialize_beds() # don't understand how this function works def initialize_beds(self): beds = [] for i in range(0, self.cap): beds.append({ "bed_id": i, "Available": True }) return beds def admit(self, patient): if len(self.patients) < self.cap: self.patients.append(patient) for i in range(0, len(self.beds)): if self.beds[i]["Available"]: patient.bed_num = self.beds[i]["bed_id"] self.beds[i]["Available"] = False break print "Patient #{}, {}, admitted to bed #{}".format(patient.id, patient.name, patient.bed_num) return self else: print "Hospital is at full capacity" return self def discharge(self, patient_id): for patient in self.patients: if patient.id == patient_id: # free up bed for bed in self.beds: if bed["bed_id"] == patient.bed_num: bed["Available"] = True break self.patients.remove(patient) print "Patient #{}, {}, sucessfully discharged. Bed #{} now available".format(patient.id, patient.name, patient.bed_num) return self return "Patient not found" Greg=Patient("Greg", "Seafood") Andrea=Patient("Andrea", "Flour") Eddie=Patient("Eddie", "Bread") Michael=Patient("Michael", "Grain") Marissa=Patient("Marissa", "Fruit") # hosp = Hospital("LA CITY HOSPITAL", 4) # hosp.initialize_beds().admit(Greg) Hospital("LA CITY HOSPITAL", 4).admit(Greg).admit(Andrea).admit(Michael).admit(Marissa).admit(Eddie).discharge(1)
ba61a1f46c8cd9fcff0e6ff65ab0ff3940f506eb
korysas/MIT-6.00.1x
/problem-set-1/vowels.py
664
4.0625
4
"""program that counts the number of vowels in a string""" def main(): res1 = vowels_in_string('azcbobobegghakl') print_result(res1) res2 = vowels_in_string('hello') print_result(res2) res3 = vowels_in_string('HELLO') print_result(res3) def vowels_in_string(string): """accepts a string and returns the number of vowels in the string""" count = 0 string = string.lower() for c in string: if c is 'a' or c is 'e' or c is 'i' or c is 'o' or c is 'u': count += 1 return count def print_result(no_vowels): print("Number of vowels: {0}".format(no_vowels)) if __name__ == '__main__': main()
d57d9aa8e99b69d71646cabaf17534300a000758
Julianhm9612/seti-python-course
/stage-1/conditionals.py
728
4
4
x = 10 y = 1 color = 'blue' first_name = 'Julian' last_name = 'Henao' # < > <= <= == if x < 30: print('X is less than 30') else: print('X is greater than 30') if color == 'red': print('The color is red') else: print('Any color') if color == 'yellow': print('The color is yellow') elif color == 'blue': print('The color is blue') else: print('Any color') if first_name == 'Julian': if last_name == 'Henao': print('Tu eres Julian Henao') else: print('Tu no eres Julian Henao') # and, or, not if x > 2 and x < 100: print('x is greater than 2 and less than 100') if x < 2 or x > 100: print('x is less than 2 or greater than 100') if not(x == y): print('x is not equal y')
4fdf333f8af81e44903a957485d954bc6784e43f
joetechem/python_tricks
/pascal/pascals_calc.py
490
3.953125
4
def pascal(previous_row): next_row = [1] # working formatting def numberFormat(number): if number > 10: return " " + str(number) + " " else: return " " + str(number) + " " for i in range(len(previous_row)-1): next_row.append(previous_row[i] + previous_row[i+1]) next_row.append(1) return next_row def test_pascal(start, rows): for i in range(rows): start = pascal(start) print(start) howMany = int(raw_input("How many rows?")) test_pascal([1,1], howMany)
2b1b59c65341bd3d1ac896952c5a80d5d18c1a43
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_118/1139.py
757
3.8125
4
#! /usr/bin/python from sys import argv,exit from math import sqrt def palindrome(n): s = str(n) return s == s[-1::-1] def not_is_square(n): return sqrt(n) != int(sqrt(n)) def square_palindrome(n): if not_is_square(n): return False sq = int(sqrt(n)) return palindrome(sq) def analizar_linea(s): a = int(s.split(" ")[0]) b = int(s.split(" ")[1]) l = [a for a in range(a,b+1) if square_palindrome(a) and palindrome(a)] return str(len(l)) if len(argv) != 3: print "Usage: prog <filein> <fileout>" exit(0) filein = open(argv[1],"r") fileout = open(argv[2],"w") lines = filein.read().split("\n") nlines = int(lines[0]) for i in range(1,nlines+1): fileout.write("Case #" + str(i) + ": ") fileout.write(analizar_linea(lines[i]) + "\n")
1bdb6aa475f96e2cf27ff4aa3d4bc5237476c26e
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/mthsfi005/question1.py
292
4.0625
4
def backward(s): if s=='': return '' else: return backward(s[1:]) + s[0] def main(): c = input('Enter a string:\n') if c == backward(c): print('Palindrome!') else: print('Not a palindrome!') main()
c2ee4fe42af7a23a233367a4d8db77d339437c1f
zeeking786/BSCIT_PYTHON_PRACTICAL
/PRACTICAL-7/Pract_3.py
1,569
4.15625
4
""" Create a class called Numbers, which has a single class attribute called MULTIPLIER, and a constructor which takes the parameters x and y (these should all be numbers). i. Write a method called add which returns the sum of the attributes x and y. ii. Write a class method called multiply, which takes a single number parameter a and returns the product of a and MULTIPLIER. iii. Write a static method called subtract, which takes two number parameters, b and c, and returns b - c. iv. Write a method called value which returns a tuple containing the values of x and y. Make this method into a property, and write a setter and a deleter for manipulating the values of x and y. """ class cal(): def __init__(self,a,b): self.a=a self.b=b def add(self): return self.a+self.b def mul(self): return self.a*self.b def div(self): return self.a/self.b def sub(self): return self.a-self.b a=int(input("Enter first number: ")) b=int(input("Enter second number: ")) obj=cal(a,b) choice=1 while choice!=0: print("0. Exit") print("1. Add") print("2. Subtraction") print("3. Multiplication") print("4. Division") choice=int(input("Enter choice: ")) if choice==1: print("Result: ",obj.add()) elif choice==2: print("Result: ",obj.sub()) elif choice==3: print("Result: ",obj.mul()) elif choice==4: print("Result: ",round(obj.div(),2)) elif choice==0: print("Exiting!") else: print("Invalid choice!!") print()
48b15e5372d144965e1ace9a3bf5e1c1003e4daf
Palash51/Python-Programs
/program/dictionary_sort.py
424
4.125
4
def sortByValue(dictionary): tmp = [] for key,value in dictionary.items(): tmp.append((value,key)) tmp.sort() return tmp def sortByKey(dictionary): tmp = [] for key,value in dictionary.items(): tmp.append((key,value)) tmp.sort() return tmp #test the sorts. dictionary = {"c":1, "b":2, "a":3} print (sortByValue(dictionary)) print (sortByKey(dictionary))
037782e55e9b1f3a522c3afe0f98d35f281d4c54
phylp/NerdTalk
/algorithmic_toolbox/sort/swap_sort.py
332
4.03125
4
#Uses python3 #runtime is quadratic #swap based on index values def swap(a, x, y): temp = a[x] a[x] = a[y] a[y] = temp def swap_sort(a): for i in range(0, len(a)): min_index = i for j in range(i+1, len(a)): if a[j] < a[min_index]: min_index = j swap(a, min_index, i) return a print(swap_sort([5,3,8,7,1,9]))
643f6968a3431ea006d80b4b8f5227b9129ab37d
Jasmine-syed2197/PYTHON_LAB
/count/11.py
111
3.71875
4
s=input("Enter the sentence :") li=s.split() s=set(li) d={} for i in s: d[i]=li.count(i) print(d)
3aec1078c0288f9c079c475952b2aa0e31626e86
Coders222/Shared
/CCC/CCC 12 J3 Icon Scaling.py
416
3.5625
4
top = list("*x*") middle = [" ", "x", "x"] bottom = ["*", " ", "*"] bruh = [top, middle, bottom] num = int(input()) matrix = [] for i in bruh: new = [] for e in i: new.append(e * num) matrix.append(new) final = [] counter = 0 for i in matrix: for m in range(num): final.append(matrix[counter]) counter += 1 for i in final: print(''.join(i))
839632c5a9269a562162450739812509fb5cd460
Aasthaengg/IBMdataset
/Python_codes/p02405/s318015421.py
232
3.53125
4
while True: h,w = map(int,input().split()) if h==0 and w==0: break for i in range(h): s = '' for j in range(w): if (i+j)%2==0: s += '#' else: s+='.' print(s) print()
d21efe105cecb5f88a49dd7998cb8533786ec301
dillonp23/CSPT19_Sprint_1
/1.2/lecture_notes.py
6,191
4.125
4
""" # Sprint 1 Module 2 - Problem Solving The U.P.E.R. Framework: (U)nderstand - know what youre being asked to do - create 3-5 test-cases, you can actually discover the optimal algorithm in doing so - tests should not be too easy or too hard (P)lan - takes the most time for this step - you know the problem, whats the game plan? - address each of the cases you developed in the Understand step - what patterns have you seen before that you can apply? - what techniques/data structures can I use? - start with brute force if no immediate optimal solution - rough layout of code - what functions do I need? - DO NOT PROCEED TO NEXT STEP if you don't know what you'll be coding (E)xecute - convert your pseudocode into actual code - code your algorithm - if you plan properly this should be the fastest step yet - pay attention to any bugs (R)eflect - correct any bugs - make a note of the bug but don't immediately address - make sure to take time to and plan how to fix - DO NOT do anything rash and regress your code - go through line by line and explain the solution - test your code with your test cases from step 1 - state your runtime and space complexity if you havent addressed in plan step """ """ Exercise 1: "1512. Number of Good Pairs" (https://leetcode.com/problems/number-of-good-pairs/) Given an array of integers nums. A pair (i,j) is called good if nums[i] == nums[j] and i < j. Return the number of good pairs. ** Example ** Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. """ def numIdenticalPairs(nums): dict = {} for i in nums: if i in dict: dict[i] += 1 else: dict[i] = 1 max_pairs = 0 # Lets say we have a value repeated 4 times. # Since we're looking at pairs, its like having 2 sets for each count, i.e. count^2 # But the value cannot be paired with itself, so only count-1 max # Finally divide by 2 to get the number of pairs # Since the value can only be a pair with everything but itself, it would look like: # ((count^2 - count) / 2) for count in dict.values(): max_pairs += ((count**2) - count) / 2 return int(max_pairs) print(numIdenticalPairs([1,2,3,1,1,3])) # expected: 4 print(numIdenticalPairs([1,1,1,1])) # expected: 6 print(numIdenticalPairs([1,2,3])) # expected: 0 """ Exercise 2: "1672. Richest Customer Wealth" (https://leetcode.com/problems/richest-customer-wealth/) You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. ** Example ** Input: accounts = [[1,2,3],[3,2,1]] Output: 6 Explanation: 1st customer has wealth = 1 + 2 + 3 = 6 2nd customer has wealth = 3 + 2 + 1 = 6 Both customers are considered the richest with a wealth of 6 each, so return 6. Constraints: m == accounts.length n == accounts[i].length 1 <= m, n <= 50 1 <= accounts[i][j] <= 100 * Understand: - input is an array of customers, where each customer is represented by an array of bank accounts - for each customer get the sum of their bank accounts - return an int represting the amount of money that is in the wealthiest account * Plan: def max_wealth_function(input_list): # store a max_wealth variable w/ init = 0 # loop through the outer accounts array # cust_accounts = accounts[index] # loop through accounts and get sum # if sum is > max, update max # return max """ # Brute Force Solution: # def maximumWealth(accounts): # max_wealth = 0 # for index in range(len(accounts)): # customer_accounts = accounts[index] # wealth = 0 # for item in customer_accounts: # wealth += item # if wealth > max_wealth: # max_wealth = wealth # return max_wealth # Optimized Solution: # def maximumWealth(accounts): # max_wealth = 0 # for index in range(len(accounts)): # customer_wealth = sum(accounts[index]) # max_wealth = max(customer_wealth, max_wealth) # return max_wealth # Fully Reduced Solution: def maximumWealth(accounts): return max(map(sum, accounts)) print(maximumWealth([[1,2,3],[3,2,1]])) # => expected: 6 print(maximumWealth([[1,2,3],[4,5,6]])) # => expected: 15 print(maximumWealth([[1,2],[0,0],[5,6]])) # => expected: 11 print(maximumWealth([[1,2,3]])) # => expected: 6 """ Exercise 3: "961. N-Repeated Element in Size 2N Array" (https://leetcode.com/problems/n-repeated-element-in-size-2n-array/) In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. Return the element repeated N times. ** Example ** Input: [1,2,3,3] Output: 3 """ def repeatedNTimes(nums): # Given a list of nums, length of list is 2N, w/ N+1 unique elements, and one element (x) repeats N times # length of list / 2 == the number of times (N) that the element (x) is repeated n = len(nums) / 2 # we want to return the value (x) that is repeated N times # use a dictionary with "x" as key and "count" as the value dict = {} for x in nums: # if "x" in dict, increment, otherwise set dict[x] = 1 if x in dict: dict[x] += 1 else: dict[x] = 1 # if the "count" == "n" then we'll return the key "x" count = dict[x] if count == n: return x print(repeatedNTimes([1,2,3,3])) # expected: 3 print(repeatedNTimes([2,1,2,5,3,2])) # expected: 2 print(repeatedNTimes([5,1,5,2,5,3,5,4])) # expected: 5
ddaf97d5d4f6f84ac8635b4a911911428033cf75
pavaniailuri/euler
/the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.py
155
3.53125
4
odd,even=0,1 pavani=0 while True: odd,even=even,odd+even if even>=4000000: break if even%2==0: pavani+=even print(pavani)
2dc8d8c29929deead505b0220a1401099f3478ba
nikita-chudnovskiy/ProjectPyton
/00 Базовый курс/043 Рекурсивный обход файлов в Python/01 Обход папок Windows.py
747
3.640625
4
import os #os.isdir #os.isfile #path =input('Ведите путь где искать ') path = 'C:\\Movies' # Путь где искать print(os.listdir(path)) # os.listdir показывает содержимое по указанному пути в виде списка name = '123' for i in os.listdir(path): # функция возвр все в виде списка print(path+'\\'+i,os.path.isdir(path+'\\'+i)) # папки файлами не являются # print('Нажмите 1 для выхода') # # # while True: # a = int(input()) # if a ==1: # print('Exit') # break # else: # print('Нажмите 1 для выхода') # else: # print('Завершено')
b57f3962db2ae6c67fbb02145296a713115487f1
sergiogbrox/guppe
/Seção 4/exercicio08.py
602
4.21875
4
""" 8- Leia uma temperatura em graus Kelvin e apresente-a convertida em graus Celsius. A fórmula de conversão é: K = C + 273.15, sendo C a temperatura em Ceusius e K a temperatura em Kelvin. """ print("\nDigite uma tenmperatura em graus Kelvin para ser convertida para graus Celsius:\n") kelvin = input() try: kelvin = float(kelvin) print(f'\n "{kelvin}" graus Kelvin é equivalente a:\n {kelvin - 273.15} graus Celsius.') except ValueError: print(f''' "{kelvin}" não é um numero. Somente numeros são aceitos, inteiros ou reais. Feche o programa e tente novamente.''')
7a2ceec21a313d567a9cda250dcb6798e0d11551
larissacsf/Exercises-1
/PYTHON/Questao22.py
1,257
4.1875
4
'''Uma empresa concederá um aumento de salário aos seus funcionários, variável de acordo com o cargo, conforme a tabela abaixo. Faça um algoritmo que leia o salário e o cargo de um funcionário e calcule o novo salário. Se o cargo do funcionário não estiver na tabela, ele deverá, então, receber 40% de aumento. Mostre o salário antigo, o novo salário e a diferença. Código Cargo Percentual 101 Gerente 10% 102 Engenheiro 20% 103 Técnico 30%''' tabela_salario = {'Gerente': 10, 'Engenheiro': 20, 'Técnico': 30, 'Outros': 40 } def codigoPreco(cargo): car = tabela_salario[cargo] return car def calcSalarioDiferenca(cargo, salario): salarioDiferenca = (salario * tabela_salario[cargo]) / 100 return salarioDiferenca def calcSalarioAumento(cargo, salario): salarioAumento = salario + (salario * tabela_salario[cargo]) / 100 return salarioAumento def main(): print("Gerente | Engenheiro | Técnico| Outros ") cargo = input("Digite seu cargo: ") salario = float(input("Digite o valor do salário: ")) print("Salário Antigo: R$", salario) print("Novo Salário: R$", calcSalarioAumento(cargo,salario)) print("Diferença: ", calcSalarioDiferenca(cargo,salario)) main()
7362631ac591a1882c451473f906d99dcdfe1da5
nataway/Python-PTIT
/sapdatlaixaukytu.py
384
3.75
4
""" Author: Tris1702 Github: https://github.com/Tris1702 Gmail: phuonghoand2001@gmail.com Thank you so much! """ T = int(input()) for t in range(1, T+1): s1 = input() s2 = input() print('Test '+str(t)+': ', end = '') if (len(s1) != len(s2)): print('NO') continue s1 = sorted(s1) s2 = sorted(s2) if s1 == s2: print('YES') else: print('NO')
ae4377b2ca41344f4d2197f6120a79812bfb882a
dmdang/ECE-40862-Python-for-Embedded-Systems
/dangd_lab0/program2.py
276
3.96875
4
def main(): a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] newList = [] print("a =", a) number = int(input("Enter number: ")) for i in a: if i >= number: break newList.append(i) print("The new list is", newList) main()
73dd81ce1b8a2e4832a8c52095fa2d31622d6b6d
caesarhoo/Algorithm
/Move Zeros.py
227
3.6875
4
# nums = [0,1,2,0,3] # a=[] # for i in nums: # if i!=0: # a.append(i) # while len(a)<len(nums): # a.append(0) # nums=a # print nums nums = [0,1,3,4,0,7,0,9,0] nums.sort(cmp=lambda a,b:0 if b else -1) print nums
7f07c69e51245ba9c9463fb696ab22e95bc0869a
krombout/heuristics_2017
/src/Example.py
2,154
3.5625
4
from src.Groundplan import Groundplan from src.GroundplanFrame import GroundplanFrame from districtobjects.Mansion import Mansion from districtobjects.Bungalow import Bungalow from districtobjects.FamilyHome import FamilyHome from districtobjects.Playground import Playground from districtobjects.Waterbody import Waterbody from random import random class Example(object): NUMBER_OF_HOUSES = 40 PLAYGROUND = True def __init__(self): self.plan = self.developGroundplan() self.frame = GroundplanFrame(self.plan) self.frame.setPlan() self.frame.root.mainloop() def developGroundplan(self): plan = Groundplan(self.NUMBER_OF_HOUSES, self.PLAYGROUND) x = 10 + random() * (plan.WIDTH - 50) y = 10 + random() * (plan.HEIGHT - 50) plan.addResidence(Mansion(x, y)) print "Placing a mansion at location:", x, ",", y x = 10 + random() * (plan.WIDTH - 50) y = 10 + random() * (plan.HEIGHT - 50) plan.addResidence(Bungalow(x, y).flip()) print "Placing a bungalow at location:", x, ",", y x = 10 + random() * (plan.WIDTH - 50) y = 10 + random() * (plan.HEIGHT - 50) plan.addResidence(FamilyHome(x, y)) print "Placing a family home at location:", x, ",", y x = 50 + random() * (plan.WIDTH - 100) y = 50 + random() * (plan.HEIGHT - 100) plan.addPlayground(Playground(x, y)) print "Placing a playground at location: ", x, ",", y width = random() * 20 + 20 height = random() * 30 + 30 x = 10 + random() * (plan.WIDTH - width - 10) y = 10 + random() * (plan.HEIGHT - height - 10) plan.addWaterbody(Waterbody(x, y, width, height)) print "Placing a waterbody at location: ", x, ",", y, "of size", width, "x", height if(plan.isValid()): print "Plan is valid" else: print "Plan is invalid" print "Value of plan is:", plan.getPlanValue() return plan Example()
38911d7a848623a0a756e3e0f24ad7a0ef9ed7f5
cerulean2014/COMP2041
/Test13/palindrome.py
327
3.59375
4
#!/usr/bin/python3 import sys, re l = list(sys.argv[1]) result = [] for char in l: match = re.match(r'\w', char) if match: result.append(char.lower()) maxlen = (len(result)+1) // 2 i = 0 p = 1 while i < maxlen: if result[i] != result[len(result)-1-i]: p = 0 break i += 1 if p == 0: print("False") else: print("True")
9cd3b6d106e85ba7eb2f81daa57bc125393dcfa7
Amal-Alharbi/systematicreviews
/log-likelihood.py
2,280
3.59375
4
def find_log_likelihood(topics,frq_word_rel_doc,frq_word_non_rel_doc,threshold): """ This method finds the log likelihood (LL) for terms in the training dataset For each topic in the training dataset, it uses the text of relevant and non-relevant documents. then calculate the average ll for each term by divide the value by the total number of topics in the training dataset topics --> list of the training dataset topics frq_word_rel_doc --> frequency of the term in the relevant documents frq_word_non_rel_doc --> frequency of the term in the non-relevant documents threshold --> to exclude terms appears less than the threshold """ log_likelihood = list() for topic in topics: for i, word in enumerate(frq_word_rel_doc): a = frq_word_rel_doc[i][1] b = frq_word_non_rel_doc[i][1] c = frq_word_rel_doc[i][2] # c = C-a d = frq_word_non_rel_doc[i][2] # d = D-b C = total_rel D = total_non_rel #E1, E2 E1 = C * (a + b)/(C + D) E2 = D * (a + b)/(C + D) log_value1 = (math.log(a/E1)) log_value2 = (math.log(b/E2)) LL = 2 * ( (a * log_value1) + (b * log_value2 )) log_likelihood.append((frq_word_rel_doc[i][0],LL)) #sort the list LL_sorted = sorted(log_likelihood,key=lambda l:l[1], reverse=True) #for each topic append the list of terms and LL LL_all.append((topic[1],LL_sorted)) combained_list = list() for i,record in enumerate(LL_all): for j,t in enumerate(LL_all[i][1]): combained_list.append((t[0],t[1])) # for ecah term find all the LL, example (blood,[20,11,17]) term_lls = {} for tuple in combained_list: key,val = tuple term_lls.setdefault(key, []).append(val) temp = list() terms_LL = [] #calculate the average LL (divide the LL by total number of topics) for term , value in term_lls.items(): temp.append((term, (sum(value)/len(topics)))) #sort the list of LL temp = sorted(temp,key=lambda l:l[1], reverse=True) for term, value in temp: terms_LL.append((term,str(value))) return terms_LL
75e8589621e725384a2afc92b79f87ab7b859c3a
praveenbommali/DS_Python
/Stack/linkedllImpl/LinkedListImpl.py
890
4.03125
4
# Stack implementation using Linked list class Node: def __init__(self, data): self.data = data self.next = None class StackImpl(object): def __init__(self): self.root = None self.size = 0 def push(self, data): newNode = Node(data) if self.root is None: self.root = newNode else: newNode.next = self.root self.root = newNode def pop(self): print("deleted node :", self.root.data) self.root = self.root.next def printStack(self): temp = self.root while temp is not None: print(temp.data, end=" ->") temp = temp.next if __name__ == '__main__': stackImpl = StackImpl() stackImpl.push(10) stackImpl.push(20) stackImpl.push(30) stackImpl.printStack() stackImpl.pop() stackImpl.printStack()
3b3f6bd18eb590309927109ea56e614688486bb3
Mietunteol/playground
/codewars.com/python/kyu_8/stringy_strings.py
132
3.59375
4
# https://www.codewars.com/kata/stringy-strings def stringy(size): return ''.join(str(int(not (x % 2))) for x in range(size))
e00edfb653fd75c198d5c46d1d007e7c536517ed
handeyildirim/Access-And-Change-A-Python-Nested-Dictionary-Variables
/access_key_value_pairs.py
1,740
4.65625
5
def key_value_accessing(): # car is a dict and we need to access to each key and the value of this dictionary car = { "brand": "Ford", "model": "Mustang", "year": 1964, "color": { "blue": "Dark", "green": ['Dark','Leight'], "pink": ['Dark','Leight', 'Bright'] } } # First, get the dict_values class which includes keys of the dictionary to understand what values() method will return # dict_value class will be as: dict_values(['Ford', 'Mustang', 1964]) x = car.values() print(x) # you can see the type of x --> "class" print(type(x)) # Then, get the dict_keys class to see what are values of the dict and to understand what values() method will return # dict_value class will be as: dict_keys(['brand', 'model', 'year']) y = car.keys() print(y) # you can see the type of x --> "class" print(type(y)) # Now we can find each key-value pairs as elements of a tuple # For the first key-value pair: print(list(car.items())[0]) # this print returns ('brand', 'Ford') print((list(car.items())[0])[1]) # this print returns 'Ford' # For the second key-value pair: print(list(car.items())[1]) # this print returns ('model', 'Mustang') print((list(car.items())[1])[1]) # this print returns 'Mustang' # For the last key-value pair: print(list(car.items())[2]) # this print returns ('year', '1964') print((list(car.items())[2])[1]) # this print returns '1964' # Sometimes there will be nested dictionaries which include a dictionary inside of the another dictionary nested_dict = list(car.items())[3] # this print returns the dictionary called "color" if __name__ == '__main__': call_func = key_value_accessing() call_func.run()
76d75b98919b4557d123bf93046463a70f8d1e71
Edigiraldo/holbertonschool-higher_level_programming
/0x0B-python-input_output/6-from_json_string.py
237
3.78125
4
#!/usr/bin/python3 """"Module for from_json_string function.""" import json def from_json_string(my_str): """function that returns an object (Python data structure) represented by a JSON string""" return json.loads(my_str)
3788dfe4369c6f11deefbd95ab05fb018da996d5
camilaffonseca/Learning_Python
/Prática/ex002.py
209
4.375
4
# coding: utf-8 # Programa que lê um número é mostra o antecessor e o sucessor numero = int(input('Digite um número: ')) print(f'O antecessor de {numero} é {numero - 1} e o sucessor é {numero + 1}')
cd0ff4fd0dca84da49def6f172d0504885d33e67
mbirostris/technologiainformacyjna
/zajecia02.py
1,902
3.703125
4
# -*- coding: utf-8 -*- import os import numpy ''' #rzutowanie na typy zmiennych: strin(), int(), float(), long() a=3; b=4; print(a+b) #a, b to liczby typu integer c='3'; d ="4"; print(c+d) #a,b to ciagi znakow print(str(a)+str(b)) print(int(c)+int(d)) ''' ############################################################## #funkcje wbudowane: https://docs.python.org/3.3/library/functions.html ############################################################## ''' #funkcja input() liczba = input('Wpisz liczbe: ') print(liczba) ''' ############################################################## ''' #if...elif...else right_number = 7 liczba = input('Zgadnij liczbe od 0 do 10: ') liczba = int(liczba) if liczba == right_number: print('Zgadłes!'); elif (liczba < right_number): print('Za malo') else: print('Za duzo') ''' ############################################################## ''' print(__name__) if __name__ == '__main__': #if...elif...else right_number = 7 liczba = input('Zgadnij liczbe od 0 do 10: ') liczba = int(liczba) if liczba == right_number: print('Zgadłes!'); elif (liczba < right_number): print('Za malo') else: print('Za duzo') ''' ##############################################################a #petla while ''' i = 10; while i>0: print(i); i=i-1; ''' ##############################################################a #poprawiona wersja zgadywanki z petla while ''' right_number = 7 while True: liczba = input('Zgadnij liczbe od 0 do 10: ') liczba = int(liczba) if liczba == right_number: print('OK!'); break; elif (liczba < right_number): print('Za malo') else: print('Za duzo') ''' ##############################################################a #rozwiazanie równania kwadratowego a = input('Podaj a') b = input('Podaj b') c = input('Podaj c')
98a3277365ae62dbdf9c012b37d32dbbc0b1a6fa
Suryamadhan/9thGradeProgramming
/CPLAB_08/CPLab_08/Dinner.py
1,657
4.375
4
""" Ex_01 In this exercise, you will be putting together a dinner plate. You will create inputs for the meat, vegetable, starch, appetizer, and drink, and print out your dinner at the end. """ class Dinner: def __init__(self, m, v, s, a, d): self.meat = m self.vegetable = v self.starch = s self.appetizer = a self.drink = d def getMeat(self): return self.meat def getVegetable(self): return self.vegetable def getStarch(self): return self.starch def getAppetizer(self): return self.appetizer def getDrink(self): return self.drink def main(): m = input("What meat are you consuming today? ") v = input("What vegetable are you going to eat today? ") s = input("What source of starch are you consuming today? ") a = input("What appetizer are you going to eat today? ") d = input("What drink are you going to drink today? ") print ("Meat: ", m) print ("Vegetable:", v) print ("Starch: ", s) print ("Appetizer:", a) print ("Drink: ", d) main() """Constructor: inputs for meat, veg, starch, appetizer, and drink""" """Modifier: reset your food items on each object""" """Accessors: one for each of the food items""" """ Main function take user inputs, instantiate a new Dinner object, and print out your dinner. You should get results similar to the following.... Your dinner tonight.... Meat: Ribeye Vegetable: Peppers Starch: Baked Potatoes Appetizer: Mozzarella Sticks Drink: Coke """
2e045daf4cef41aaf733c3d489bacbd9cf8f8817
vinnav/Python-Crash-Course
/10Files/10-8.CatsAndDogs.py
320
3.625
4
try: with open("cats.txt") as f: contents = f.read() except FileNotFoundError: print("cats.txt not found!") else: print(contents) try: with open("dogs.txt") as f: contents = f.read() except FileNotFoundError: print("dogs.txt not found!") else: print(contents)
377908bbf9d8fd4685895dc5ad110e04423f707c
jacobaek/whoisjacobaek
/hw1_1.py
245
3.828125
4
def if_function(a,b,c): if(a==True): return b else: return c print(if_function(True, 2, 3)) print(if_function(False, 2, 3)) print(if_function(3==2, 3+2, 3-2)) print(if_function(3>2, 3+2, 3-2) )
3692c0a3b4b38ce62aa89eeb2053fd987c0376ad
jmsalmeida/tdd
/exercicios-python/primeira-lista/4-holerite.py
1,008
3.984375
4
valor_plano_saude = 347.00 salario = float(input("Entre com o salário do colaorador: ")) total_descontado = 0 desconto_INSS = salario * 0.09 total_descontado += desconto_INSS desconto_vale_transporte = salario * 0.03 total_descontado += desconto_vale_transporte desconto_plano_saude = valor_plano_saude * 0.15 total_descontado += desconto_plano_saude salario_liquido = salario - total_descontado print("##################### HOLERITE #####################") print("") print("#### SALARIO INTEGRAL: ", salario) print("----------------------------------------------------") print("#### DESCONTOS") print("#### INSS: ", desconto_INSS) print("#### PLANO DE SAÚDE: ", desconto_plano_saude) print("#### VALE TRANSPORTE: ", desconto_vale_transporte) print("#### TOTAL DESCONTADO: ", total_descontado) print("----------------------------------------------------") print("") print("#### SALARIO LIQUIDO: ", salario_liquido) print("####################################################")
ee5bbff91138916c2fdff2a409ad3cc7f0d0d622
Parkavi-C/DataScience
/Python Exercise 2.py
3,600
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: ###1. Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700(both included) # In[20]: List = [] for x in range(1500,2700,1): if(x%5 == 0 and x%7==0): List.append(x) print(*List, sep=", ") # In[ ]: ###Write a Python program to construct the following pattern, using a nested for loop. # In[12]: a = int (input()) for x in range (1,a+1): for y in range (1,x+1): print("*",end=" ") print("\r") for x in range (a,0,-1): for y in range(0,x-1): print("*",end=" ") print("\r") # In[ ]: ###Write a Python program to count the number of even and odd numbers from a series of numbers. # In[ ]: x = int (input()) y = int (input()) even = 0 odd = 0 for i in range(x,y+1): if(i%2 == 0): even += 1 else: odd += 1 print("Number of even numbers : ",even) print("Number of odd numbers : ",odd) # In[ ]: ###Write a Python program to find numbers between 100 and 400 (both included) where each digit of a number is an even number. The numbers obtained should be printed in a comma-separated sequence. # In[9]: a=[] for x in range(100,401): s = str(x) if(int(s[0])%2 == 0 and int(s[1])%2 == 0 and int(s[2])%2 == 0): a.append(x) print(*a,sep=", ") # In[ ]: ### Write a Python program to calculate a dog's age in dog's years. Go to the editor ### Note: For the first two years, a dog year is equal to 10.5 human years. After that, each dog year equals 4 human years. # In[4]: age = int(input("Input a dog's age in human years: ")) cal_age = 0 if(age > 2): cal_age = ((age-2)*4) + (2*10.5) elif(age<=2): cal_age = age*10.5 print("The dog's age in dog's years is ",cal_age) # In[ ]: ###Write a Python function to find the Max of three numbers. # In[7]: a = [] for x in range(0,3): a.append(input()) def max_function(a): print("The Three numbers are: ",tuple(a)) print(max(a)) max_function(a) # In[ ]: ###Write a Python function that takes a number as a parameter and check the number is prime or not. # In[16]: num = int(input("The number is: ")) def prime_function(a): if(a > 1): for x in range(2,a): if(a%x == 0): print("False") break; else: print("True") prime_function(num) # In[ ]: ###Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. Go to the editor # In[21]: input_str = input("Original String : ") def case_calculator(s): upper = 0 lower = 0 for x in s: if(x.isupper()): upper += 1 elif(x.islower()): lower += 1 print("No. of Upper case characters : ",upper) print("No. of Lower case Characters : ",lower) case_calculator(input_str) # In[ ]: ###Write a Python program to reverse a string. # In[29]: def reverse(s): return "".join(reversed(s)) input_str = input("The original string is: ") print("The reversed string: ",reverse(input_str)) # In[ ]: ###Write a Python program to find the greatest common divisor (gcd) of two integers. # In[36]: def gcd(x,y): List = [] small = 0 if(x>y): small = y else: small = x for i in range(1,small+1): if(x%i == 0 and y%i == 0): List.append(i) return max(List) a = int (input()) b = int (input()) print("The two numbers are:",a,",",b) print("The GCD of the numbers are:",gcd(a,b))
ded2a86d33f73256e03d4ff48297e2d6481fed75
YoshiBrightside/Ode-to-my-Failures
/Codeforces/19_07_05/Accepted/A.py
226
3.65625
4
# 1189A # Keanu Reeves stringlen = int(input()) string = str(input()) if len(string)%2==1 or len(string.split('0'))!= len(string.split('1')): print('1') print(string) else: print('2') print(string[0]+' '+string[1:])
91dbe3ad2beac8759bea9305df8ccb2837c3fb04
osfp-Pakistan/python
/GIS_Python/Calculations/bmi.py
800
4.25
4
# Jon Nordling # GEOG656 Python Programing # December 9, 2012 # bmi.py # This is the main function that will call function and # print the bim of the user imputs def main(): bmi = calc_bmi() result = bmi_means(bmi) print 'You are: ',result # This function will determine the users Weight and hight # and calculate there bmi def calc_bmi(): w = input('Enter your Weight: ') h = input('Enter Height: ') bmi = (w*703)/(h*h) return bmi # This function passed the bim and then # Determines the output def bmi_means(bmi): if bmi < 18.5: r = 'Under Weight' elif bmi >= 18.5 and bmi <25: r = 'Healthy Weight' elif bmi >=25 and bmi <30: r = 'Over Weight' else: r = 'obesity' return r # This function insures that the main function will exicute first if __name__ == '__main__': main()
b36fc6a00dff862c046506e140e2c3fd1061ae65
nauman-sakharkar/Python-3.x
/Data Structure & Artificial Intelligence/Evaluate - Postfix, Infix Expression.py
1,081
3.8125
4
print("---------------------------------\nName : Nauman\nRoll No. : 648\n---------------------------------") class Stack: def __init__(self): self.l=[] def push(self,e): self.l.append(e) def Pop(self): if not(self.isEmpty()): return(self.l.pop()) def isEmpty(self): return(self.l==[]) def peek(self): if not(self.isEmpty()): return(self.l[-1]) s=Stack() a=input("Enter the Postfix for Evaluation : ") l=a.split(' ') for i in l: if i in '+-*/': b=s.Pop() a=s.Pop() c=eval(a+i+b) s.push(str(c)) else: s.push(i) print(s.Pop()) a=input("Enter the Infix Expression : ") l=a.split(' ') p='' b={'+':1,'-':1,'*':3,'/':4,'(':0} for i in l: if i in '+-*/': while (not s.isEmpty()) and b[i]<=b[s.peek()]: p=p+s.Pop() s.push(i) elif i=='(': s.push(i) elif i==')': while s.peek()!='(': p=p+s.Pop() s.Pop() else: p=p+i while not s.isEmpty(): p=p+s.Pop() print(p)
4eb0c3f4191f1f749605d29d371e4064cef96850
anvesh001/testgit
/New folder/file.py
114
4.03125
4
hungry=str(input('enter value:')) if hungry=='Yes': print('he is hungry') else: print("he doesn't hungry")
8a96854a97aa391385cebfac1ae63319f944f182
areaofeffect/hello-world
/week3/examples/python3/dice-game.py
1,336
4.375
4
#!/usr/bin/env python3 # a classic dice rolling app # start by configuring your dice below. # python roll-dice.py to run # import required modules import random # to generate random numbers # configure options numberOfSides = 6 # how many sides on your dice weightedDiceOption = True # True or False prediction = 0 # global variable # function to roll the dice def rollDice(inNumberOfSides, weightedDice=weightedDiceOption): global prediction # we need to access the global variable # if weighted dice is true, we will cheat if (weightedDice == True): result = prediction else: # generate a random number between 1 and the number of sides result = random.randint(1, numberOfSides) print ("You roll a: " + str(result) + " out of " + str(numberOfSides)) return result def main(): global prediction # we need to access the global variable # user input prediction = input("Enter a prediction up to " + str(numberOfSides) + " : ") # roll the dice and assign the result to a variable diceRoll = rollDice(numberOfSides, True) # if the prediction is correct, we will print a message if (diceRoll == prediction): print("Winner winner!") else: print("You lose!") if __name__ == "__main__": print("Running app...") main()
c85b681564d48c731f24e18227b71426d28cc6e3
linusqzdeng/python-snippets
/exercises/list_remove_duplicates.py
644
4.125
4
# This program takes a list and returns a new list that contains all the elements of # the first list minus all the duplicates. a = [1, 1, 3, 5, 7, 4, 3, 6, 5, 8, 8, 13, 24, 33, 12, 13, 17, 14] def remove_duplicates(list): new_list = [] for x in a: if x not in new_list: new_list.append(x) else: pass return new_list print(remove_duplicates(a)) print('-' * 45) # another way using sets a = [1, 1, 3, 5, 7, 4, 3, 6, 5, 8, 8, 13, 24, 33, 12, 13, 17, 14] def remove_duplicates_bysets(alist): return list(set(alist)) print(remove_duplicates_bysets(a))
c56ade9061a43536fecd51e9509a04956920e265
NorCalVictoria/week-2-assess-quiz-answers
/def print_melon_at_price(price):.py
1,367
4.46875
4
def print_melon_at_price(price): """Given a price, print all melons available at that price, in alphabetical order. Here are a list of melon names and prices: Honeydew 2.50 Cantaloupe 2.50 Watermelon 2.95 Musk 3.25 Crenshaw 3.25 Christmas 14.25 (it was a bad year for Christmas melons -- supply is low!) If there are no melons at that price print "None found" >>> print_melon_at_price(2.50) Cantaloupe Honeydew >>> print_melon_at_price(2.95) Watermelon >>> print_melon_at_price(5.50) None found """ #create a dictionary of melon prices melon_prices = { 'Honeydew': 2.50, 'Cantaloupe': 2.50, 'Watermelon': 2.95, 'Musk': 3.25, 'Crenshaw': 3.25, 'Christmas': 14.25 } #if inputted price is in the values list of melon_prices if price in melon_prices.values(): #Iterate through iteritems for melon, cost in sorted(melon_prices.iteritems()): #if price is equal to the cost of the melon # if price == cost: #print melon print melon #If you don't find the cost in the values, print 'None found' else: print 'None found' print_melon_at_price(3.25)
3ad093e73ba0a1f0e212618f3e3e7c7c819b7b7d
UrvashiBhavnani08/Python
/binary_search.py
809
3.859375
4
import array as arr a = arr.array('i',[0,1,2,3,4,5,6,7,8,9,10,11,12]) for i in range(0,10): print(a[i],end=" ") print("\n") num = int(input("Enter which number you want to search through LINEAR SEARCH : ")) def linear_search(a,l1,num): for i in range(0,length): beg = a[0] end = a[12] mid = (a[0] + a[12])/2 if (num <= mid): beg = a[0] end = mid mid = (beg + end)/2 if (num <= mid): beg = a[0] end = mid mid = (beg+end)/2 return -1 #print(a.index(6)) #print(len(a)) length = len(a) result = linear_search(a,length,num) if (result == -1): print("Sorry not found.") else: print("Number is at index: ",result) #print(a[0])
bb1f5b16ac0316037317d072b03776a6d1ecaeeb
Leoleopardboy12/Tasks-for-Programming
/No.25.py
295
3.609375
4
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> A= int(input()) 1 >>> if A<=2: F= (A*2)+(4*A)+5 print(F) else: F=1/((A*2)+(4*A)+5) print(F) 11 >>>
2b95f26c3be5bca0d6658a78512d398c40f9b744
iHeroGH/Assignment6
/MajorLeagueSoccerAnim/artist.py
26,085
4.0625
4
import pygame import random import math # File Imports from colors import Color class Artist: """ Handles all the draw operations and visual aspects of the project. Attributes ---------- clouds : list[list[int, int]] A list of [x, y] coordinates for all the clouds that should be drawn stars : list[list[int, int, int, int]] A list of [x, y, r, r] coordinates for all the stars that should be drawn """ def __init__(self): """Initializes the cloud and star list for visualization later""" self.init_clouds() self.init_stars() def init_clouds(self, cloud_count: int = 20) -> None: """ Creates a list of 20 random [x,y] coordinates for cloud positions Parameters ---------- cloud_count : int The number of clouds to create (default 20) """ # List comprehension to create a list of [rand number x, rand number y] # x is from -100 to 1600 # y is from 0 to 150 # We do this 20 times self.clouds = [ [random.randrange(-100, 1600), random.randrange(0, 150)] for _ in range(cloud_count) ] def init_stars(self, star_count:int = 200, max_star_size:int = 2) -> None: """ Creates a list of 200 random [x,y,size] coordinates for stars Parameters ---------- star_count : int The number of stars to create (default 200) max_star_size : int The maximum size for stars """ # List comprehension to create a list of [rand x, rand y, rand r, r] # These values will be used to create an elipse, so it needs an extra 'rect' variable # x is from 0 to 800 # y is from 0 to 200 # r is either 1 or 2 # The last item of the list is a repeat of r # We do this 200 times self.stars = [ [ random.randrange(0, 800), random.randrange(0, 200), r:=random.randrange(1, max_star_size), r ] for _ in range(star_count) ] def config_darkness(self, darkness: pygame.Surface) -> None: """Initializes the darkness surface""" darkness.set_alpha(200) darkness.fill(Color.BLACK) def config_see_through(self, see_through: pygame.Surface) -> None: """Initializes the see_through surface""" see_through.set_alpha(150) see_through.fill(Color.COLOR_KEY) see_through.set_colorkey(Color.COLOR_KEY) def move_clouds(self, cloud_speed: float = 0.5) -> None: """ Moves each cloud to the left 0.5 units. Parameters ---------- cloud_speed : float How many units to move clouds each tick """ # Loop through each cloud in self.clouds and move it to the left 0.5 units for cloud in self.clouds: cloud[0] -= cloud_speed # If we reach the edge of the screen, re-randomize its position if cloud[0] < -100: cloud[0] = random.randrange(800, 1600) cloud[1] = random.randrange(0, 150) def draw_clouds( self, surface: pygame.Surface, see_through: pygame.Surface, cloud_color: tuple) -> None: """ Draws every cloud in the cloud list Simply uses the draw_single_cloud method to draw each cloud, then places the see_through surface on the main screen Parameters ---------- surface : pygame.Surface The main screen to draw the see_through surface onto see_through : pygame.Surface The see_through surface to draw clouds onto cloud_color : tuple A tuple representing the (R,G,B) values of the cloud's color """ # Loop through each cloud in self.clouds and draw it # using self.draw_single_cloud(...) # We draw the clouds onto the see_through surface for cloud in self.clouds: self.draw_single_cloud( see_through, cloud[0], cloud[1], cloud_color ) # Place the see_through surface on top of the screen surface.blit(see_through, (0, 0)) def draw_single_cloud( self, surface: pygame.Surface, x: int, y: int, cloud_color: tuple) -> None: """ Draws a single cloud given its (x, y) coordinates and its color Parameters ---------- surface : pygame.Surface The surface to draw the clouds onto x : int The x poisiton of the cloud y : int The y position of the cloud cloud_color : tuple A tuple representing the (R, G, B) values of the cloud's color """ # Draw the cloud shape by drawing some ellipse pygame.draw.ellipse( # Bottom Left surface, cloud_color, [x, y + 8, 10, 10] ) pygame.draw.ellipse( # Top Left surface, cloud_color, [x + 6, y + 4, 8, 8] ) pygame.draw.ellipse( # Top Right surface, cloud_color, [x + 10, y, 16, 16] ) pygame.draw.ellipse( # Bottom Right surface, cloud_color, [x + 20, y + 8, 10, 10] ) pygame.draw.rect( # Bottom surface, cloud_color, [x + 6, y + 8, 18, 10] ) def draw_stars(self, surface: pygame.Surface) -> None: """ Draws every star in the stars list Parameters ---------- surface : pygame.Surface The surface to draw the stars onto """ # Loop through each star in self.stars and draw an ellipse at the location for star in self.stars: pygame.draw.ellipse( surface, Color.WHITE, star ) def draw_fence(self, surface: pygame.Surface) -> None: """ Draws the fences of the field Parameters ---------- surface : pygame.Surface The surface to draw the fences onto """ # Draw the vertical fence separators y = 170 for x in range(5, 800, 30): pygame.draw.polygon( surface, Color.NIGHT_GRAY, [ [x + 2, y], [x + 2, y + 15], [x, y + 15], [x, y] ] ) # Draw the vertical fence parts (not the separators) y = 170 for x in range(5, 800, 3): pygame.draw.line( surface, Color.NIGHT_GRAY, [x, y], [x, y + 15], 1 ) # Draw the horizontal fence parts x = 0 for y in range(170, 185, 4): pygame.draw.line( surface, Color.NIGHT_GRAY, [x, y], [x + 800, y], 1 ) def draw_sun_or_moon( self, surface: pygame.Surface, is_day: bool, sky_color: tuple) -> None: """ Chooses to draw the sun or the moon depending on if it's day or not Parameters ---------- surface : pygame.Surface The surface to draw the sun/moon onto is_day : bool A bool denoting whether or not it's day sky_color : tuple A tuple representing the (R, G, B) values of the sky's color """ # If it's day, draw the sun if is_day: pygame.draw.ellipse( surface, Color.BRIGHT_YELLOW, [520, 50, 40, 40] ) # If it's night, draw the moon else: pygame.draw.ellipse( surface, Color.WHITE, [520, 50, 40, 40] ) # The moon ellipse pygame.draw.ellipse( surface, sky_color, [530, 45, 40, 40] ) # The moon cutout, for the crescendo shape def check_darkness( self, is_day: bool, light_on: bool, surface: pygame.Surface, darkness: pygame.Surface) -> None: """ Determines the darkness of the field based on is_day and light_on The method simply checks whether or not it's day and the lights are on and blits the darkness surface onto the original surface Parameters ---------- is_day : bool A bool denoting whether or not it's day light_on : bool A bool denoting whether or not the lights are on surface : pygame.Surface The surface to draw the darkness onto darkness : pygame.Surface The surface that visually darkens the original surface """ # Check if it should be dark and place the darkness surface onto the screen if not (is_day or light_on): surface.blit(darkness, (0, 0)) def draw_grass( self, surface: pygame.Surface, field_color: tuple, stripe_color: tuple) -> None: """ Draws the grassy area on the field Parameters ---------- surface : pygame.Surface The surface to draw the grass onto field_color : tuple A tuple representing the (R, G, B) values of the field's color stripe_color : tuple A tuple representing the (R, G, B) values of the stripe's color """ # Draw the base field y = 180 pygame.draw.rect( surface, field_color, [0, y, 800 , 420] ) # Draw each stripe on the field for height in [42, 52, 62, 82]: pygame.draw.rect( surface, stripe_color, [0, y, 800, height] ) y += 2 * height def draw_out_of_bounds(self, surface: pygame.Surface) -> None: """ Draws the out-of-bounds lines along the edges of the field Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ # Set constants that will determine the size of the field top_y = 220 top_left = 140 top_right = 660 bottom_y = 580 bottom_left = 0 bottom_right = 800 mid_y = bottom_y - top_y # Top pygame.draw.line( surface, Color.WHITE, [top_left, top_y], [top_right, top_y], 3 ) # Bottom pygame.draw.line( surface, Color.WHITE, [bottom_left, bottom_y], [bottom_right, bottom_y], 5 ) # Left pygame.draw.line( surface, Color.WHITE, [bottom_left, mid_y], [top_left, top_y], 5 ) # Right pygame.draw.line( surface, Color.WHITE, [top_right, top_y], [bottom_right, mid_y], 5 ) def draw_safety_circle(self, surface: pygame.Surface) -> None: """ Draws the safety circle near the center of the field Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ pygame.draw.ellipse( surface, Color.WHITE, [240, 500, 320, 160], 5 ) def draw_outer_goal_box(self, surface: pygame.Surface) -> None: """ Draws the goal box onto the field Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ # Left pygame.draw.line( surface, Color.WHITE, [260, 220], [180, 300], 5 ) # Bottom pygame.draw.line( surface, Color.WHITE, [180, 300], [620, 300], 3 ) # Right pygame.draw.line( surface, Color.WHITE, [620, 300], [540, 220], 5 ) def draw_arc(self, surface: pygame.Surface) -> None: """ Draws the arc near the goal box on the field Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ pygame.draw.arc( surface, Color.WHITE, [330, 280, 140, 40], math.pi, 2 * math.pi, 5 ) def draw_scoreboard(self, surface: pygame.Surface) -> None: """ Draws the scoreboard behind the goal Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ # Scoreboard Stand pygame.draw.rect( surface, Color.GRAY, [390, 120, 20, 70] ) # Scoreboard Screen pygame.draw.rect( surface, Color.BLACK, [300, 40, 200, 90] ) # Scoreboard Border pygame.draw.rect( surface, Color.WHITE, [302, 42, 198, 88], 2 ) def draw_goal(self, surface: pygame.Surface) -> None: """ Draws the goal-post itself Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ # Goal Border pygame.draw.rect( surface, Color.WHITE, [320, 140, 160, 80], 5 ) # Goal Bottom Center pygame.draw.line( surface, Color.WHITE, [340, 200], [460, 200], 3 ) # Goal Bottom Left pygame.draw.line( surface, Color.WHITE, [320, 220], [340, 200], 3 ) # Goal Bottom Right pygame.draw.line( surface, Color.WHITE, [480, 220], [460, 200], 3 ) # Goal Stand Left pygame.draw.line( surface, Color.WHITE, [320, 140], [340, 200], 3 ) # Goal Stand Right pygame.draw.line( surface, Color.WHITE, [480, 140], [460, 200], 3 ) def draw_inner_goal_box(self, surface: pygame.Surface) -> None: """ Draws the inner goal box in front of the goal Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ # Left pygame.draw.line( surface, Color.WHITE, [310, 220], [270, 270], 3 ) # Bottom pygame.draw.line( surface, Color.WHITE, [270, 270], [530, 270], 2 ) # Right pygame.draw.line( surface, Color.WHITE, [530, 270], [490, 220], 3 ) def draw_light_poles(self, surface: pygame.Surface) -> None: """ Draws the two light poles on either side of the field Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ # Left Pole # Pole pygame.draw.rect( surface, Color.GRAY, [150, 60, 20, 140] ) # Bottom pygame.draw.ellipse( surface, Color.GRAY, [150, 195, 20, 10] ) # Right Pole # Pole pygame.draw.rect( surface, Color.GRAY, [630, 60, 20, 140] ) # Bottom pygame.draw.ellipse( surface, Color.GRAY, [630, 195, 20, 10] ) def draw_lights( self, surface: pygame.Surface, light_color: tuple) -> None: """ Draws the lights onto both light poles Parameters ---------- surface : pygame.Surface The surface to draw the grass onto light_color : tuple A tuple representing the (R, G, B) values of the color of the light """ # Left Pole light_pos1 = 0 # Draw the two separator lines on the pole for i in range(1,3): pygame.draw.line( surface, Color.GRAY, [110, 80 - 20*i], [210, 80 - 20*i], 2 ) # For each separator, draw 6 light bulbs for i in range(1,6): pygame.draw.ellipse( surface, light_color, [90 + 20*i, 40 - light_pos1, 20, 20] ) light_pos1 += 20 # Draw the left pole's top border pygame.draw.line( surface, Color.GRAY, [110, 20], [210, 20], 2 ) # Right Pole light_pos2 = 0 # Draw the two separator lines on the pole for i in range(1,3): pygame.draw.line( surface, Color.GRAY, [590, 80 - 20*i], [690, 80 - 20*i], 2 ) # For each separator, draw 6 light bulbs for i in range(1,6): pygame.draw.ellipse( surface, light_color, [570 + 20*i, 40 - light_pos2, 20, 20] ) light_pos2 += 20 # Draw the right pole's top border pygame.draw.line( surface, Color.GRAY, [590, 20], [690, 20], 2 ) def draw_net(self, surface: pygame.Surface) -> None: """ Draws the net inside the goal Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ # DOWN # CENTER # Left for i in range(1, 9): pygame.draw.line( surface, Color.WHITE, [320 + 5*i, 140], [338 + 3*i, 200], 1 ) # MidLeft for i in range(1, 5): pygame.draw.line( surface, Color.WHITE, [360 + 4*i, 140], [361 + 4*i, 200], 1 ) # Mid pygame.draw.line( surface, Color.WHITE, [380, 140], [380, 200], 1 ) for i in range(1, 11): pygame.draw.line( surface, Color.WHITE, [380 + 4*i, 140], [380 + 4*i, 200], 1 ) pygame.draw.line( surface, Color.WHITE, [424, 140], [423, 200], 1 ) # MidRight for i in range(1, 4): pygame.draw.line( surface, Color.WHITE, [424 + 4*i, 140], [423 + 4*i, 200], 1 ) pygame.draw.line( surface, Color.WHITE, [440, 140], [438, 200], 1 ) # Right for i in range(1, 8): pygame.draw.line( surface, Color.WHITE, [440 + 5*i, 140], [438 + 3*i, 200], 1 ) # LEFT for i in range(1, 9): pygame.draw.line( surface, Color.WHITE, [320, 140], [322 + i*2, 218 - i*2], 1 ) # RIGHT for i in range(1, 9): pygame.draw.line( surface, Color.WHITE, [480, 140], [478 - i*2, 218 - i*2], 1 ) # ACROSS # TOP for i in range(1, 10): pygame.draw.line( surface, Color.WHITE, [324, 140 + i*4], [476, 140 + i*4], 1 ) # MIDDLE pygame.draw.line( surface, Color.WHITE, [335, 180], [470, 180], 1 ) # BOTTOM for i in range(1, 5): pygame.draw.line( surface, Color.WHITE, [335, 180 + i*4], [465, 180 + i*4] ) def draw_stands(self, surface: pygame.Surface) -> None: """ Draws the stands on either side of the field Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ # RIGHT # Bottom pygame.draw.polygon( surface, Color.RED, [ [680, 220], [800, 340], [800, 290], [680, 180] ] ) # Top pygame.draw.polygon( surface, Color.WHITE, [ [680, 180], [800, 100], [800, 290] ] ) # LEFT # Bottom pygame.draw.polygon( surface, Color.RED, [ [120, 220], [0, 340], [0, 290], [120, 180] ] ) # Top pygame.draw.polygon( surface, Color.WHITE, [ [120, 180], [0, 100], [0, 290] ] ) def draw_corner_flags(self, surface: pygame.Surface) -> None: """ Draws the flags on either corner of the field Parameters ---------- surface : pygame.Surface The surface to draw the grass onto """ # RIGHT # Stand pygame.draw.line( surface, Color.BRIGHT_YELLOW, [140, 220], [135, 190], 3 ) # Flag pygame.draw.polygon( surface, Color.RED, [ [132, 190], [125, 196], [135, 205] ] ) # LEFT # Stand pygame.draw.line( surface, Color.BRIGHT_YELLOW, [660, 220], [665, 190], 3 ) # Flag pygame.draw.polygon( surface, Color.RED, [ [668, 190], [675, 196], [665, 205] ] ) def draw_field( self, surface: pygame.Surface, field_color: tuple, stripe_color: tuple, light_color: tuple, ) -> None: """ Draws each aspect of the field by calling each draw_x function This function takes all the necessary configurations to pass to the respective functions Parameters ---------- surface : pygame.Surface The surface to draw the grass onto field_color : tuple A tuple representing the (R, G, B) values of the field's color stripe_color : tuple A tuple representing the (R, G, B) values of the stripe's color light_color : tuple A tuple representing the (R, G, B) values of the light's color """ # Draw the grass self.draw_grass(surface, field_color, stripe_color) # Draw the back fence self.draw_fence(surface) # Draw field markings self.draw_out_of_bounds(surface) self.draw_safety_circle(surface) self.draw_outer_goal_box(surface) self.draw_inner_goal_box(surface) self.draw_arc(surface) # Draw the scoreboard self.draw_scoreboard(surface) # Draw the goal frame self.draw_goal(surface) # Draw the nets self.draw_net(surface) # Draw the light poles and lights self.draw_light_poles(surface) self.draw_lights(surface, light_color) # Draw the audience stands self.draw_stands(surface) # Draw the corner flags self.draw_corner_flags(surface) def update_screen(self) -> None: """Updates the pygame screen by simply calling display.flip()""" pygame.display.flip()
ec8c72e8733decf551e5d54354b2db2498168df3
CodeYueXiong/Python_basics
/5_elif_statements.py
955
4.15625
4
my_num = 5.0 if my_num % 2 == 0: print("Your number is even") elif my_num % 2 != 0: print("Your number is odd") else: print('Are you sure your number is an integer') dice_value = 32 if dice_value == 1: print('You rolled a {}. Great job!'.format(dice_value)) elif dice_value == 2: print('You rolled a {}. Great job!'.format(dice_value)) elif dice_value == 3: print('You rolled a {}. Great job!'.format(dice_value)) elif dice_value == 4: print('You rolled a {}. Great job!'.format(dice_value)) elif dice_value == 5: print('You rolled a {}. Great job!'.format(dice_value)) elif dice_value == 6: print('You rolled a {}. Great job!'.format(dice_value)) else: print("None of the conditions above (if elif) were valid inputs in a dice!") ## assigned tasks num = 10 if num % 3 == 0 and num % 5 == 0: print("FizzBuzz") elif num % 3 == 0: print('Fizz') elif num % 5 == 0: print('Buzz') else: print(str(num))
835f3b4868cc97a3a2c7a93ae56281d1080f5d74
CalebChacko/Grocery-List
/recipe.py
551
3.640625
4
from ingredient import Ingredient class Recipe: name = 'None' ingredients = {} # Determines if we add/remove ingredient on update addIngredients = bool(0) def __init__(self, name): self.name = name def addIngredient(self, newIngred): self.ingredients[newIngred] = Ingredient(newIngred) def removeIngredients(self): print("I'm removing ingredients") def updateIngredients(self, addIngredients): print ("I'm", addIngredients) def print(self): print(self.ingredients)
18774214ec41e300a76f414c3423f0b09b06095b
eduardogomezvidela/Summer-Intro
/6 Functions/excersises/10B.py
251
3.578125
4
import turtle screen=turtle.Screen() screen.bgcolor("black") alex=turtle.Turtle() alex.color("orange") alex.pensize(2) alex.speed(0) x=0 y=90 for i in range (103): alex.right(y) alex.forward(x+4) x=x+4 y=y-0.02 screen.exitonclick()
de4955ac1acc612285c1f2a08fba703f4426a996
heatherstafford/unit3
/favorites.py
165
3.890625
4
#Heather Stafford #2/14/18 #favorites.py word = input('Enter your favorite word: ') num = int(input('Enter your favorite number: ')) for i in range(0, num): print(word)
abb92b4c0b846d4f99126ff31a43d4cc7b594e2a
wushengbin-debug/Python_Course
/student_grades2.py
937
4.125
4
print("Practicing conditionals by using student grades with 'and' operator") grade1 = float ( input("Type in the grade of 1st test: ")) grade2 = float ( input("Type in the grade of 2nd test: ")) absences = int ( input("Type in the number of absences: ")) total_classes = int ( input("Type in the total number of classes: ")) avg_grade = (grade1 + grade2)/2 attendance = (total_classes - absences)/total_classes print("Average grade: ",round(avg_grade,2)) print("Attendance: ",str(round((attendance * 100),2))+'%') if(avg_grade >= 6 and attendance >= 0.8): print("Student was approved.") elif(avg_grade < 6 and attendance < 0.8): print("Student has failed due to a grade lower than 6.0 and an attendance rate lower than 80%.") elif(attendance >= 0.8): print("Student has failed due to a grade lower than 6.0.") else: print("Student has failed due to an attendance rate lower than 80%.")
ddf829203156704312f588d4a4121d762b67ed89
vanissawanick/flask_project
/exercises/weather.py
2,581
3.515625
4
# script to access weather information # complex... unfinished import datetime import json import urllib.request # our variables city_id = "London" appi_id = " " # function to convert the time stamp def time_converter(time): converted_time = datetime.datetime.fromtimestamp( int(time) ).strftime('%I:%M %p') return converted_time # create the url def url_builder(city_id): user_api = '' # Obtain yours form: http://openweathermap.org/ unit = 'metric' # For Fahrenheit use imperial, for Celsius use metric, and the default is Kelvin. api = 'http://api.openweathermap.org/data/2.5/weather?id=' # Search for your city ID here: http://bulk.openweathermap.org/sample/city.list.json.gz full_api_url = api + str(city_id) + '&mode=json&units=' + unit + '&APPID=' + user_api return full_api_url # query def data_fetch(full_api_url): with urllib.request.urlopen(full_api_url) as url: return json.loads(url.read().decode('utf-8')) def data_organizer(raw_data): main = raw_data.get('main') sys = raw_data.get('sys') data = dict( city=raw_data.get('name'), country=sys.get('country'), temp=main.get('temp'), temp_max=main.get('temp_max'), temp_min=main.get('temp_min'), humidity=main.get('humidity'), pressure=main.get('pressure'), sky=raw_data['weather'][0]['main'], sunrise=time_converter(sys.get('sunrise')), sunset=time_converter(sys.get('sunset')), wind=raw_data.get('wind').get('speed'), wind_deg=raw_data.get('deg'), dt=time_converter(raw_data.get('dt')), cloudiness=raw_data.get('clouds').get('all') ) return data def data_output(data): data['m_symbol'] = '\xb0' + 'C' s = '''--------------------------------------- Current weather in: {city}, {country}: {temp}{m_symbol} {sky} Max: {temp_max}, Min: {temp_min} Wind Speed: {wind}, Degree: {wind_deg} Humidity: {humidity} Cloud: {cloudiness} Pressure: {pressure} Sunrise at: {sunrise} Sunset at: {sunset} Last update from the server: {dt} ---------------------------------------''' print(s.format(**data)) # python2 def getWeatherCondition(city) : try : url = "http://api.openweathermap.org/data/2.5/forecast/city?q=" url += city req = urllib.request.Request(url) response = urllib.request.urlopen(req) return response.read() except Exception as e : #print("Sth went wrong") print(e) if __name__ == "__main__": print (getWeatherCondition("London"))
2b3b31dfc0baa77f79b18e5d7f63959f049d563d
tanzim721/Python
/13-Queue.py
2,761
4.0625
4
""" Name : Tanzimul Islam Roll : 180636 Session : 2017-18 E-mail : tanzimulislam799@gmail.com Blog : https://tanzim36.blogspot.com/ Dept.of ICE, Pabna University of Science and Technology """ #Problem-13: Write a program to implement a queue data structure along with its typical operation. class Queue: # Initialize queue def __init__(self, size): self.q = [None] * size # list to store queue elements self.capacity = size # maximum capacity of the queue self.front = 0 # front points to front element in the queue if present self.rear = -1 # rear points to last element in the queue self.count = 0 # current size of the queue # Function to remove front element from the queue def pop(self): # check for queue underflow if self.isEmpty(): print("Queue UnderFlow!! Terminating Program.") exit(1) print("Removing element : ", self.q[self.front]) self.front = (self.front + 1) % self.capacity self.count = self.count - 1 # Function to add a value to the queue def append(self, value): # check for queue overflow if self.isFull(): print("OverFlow!! Terminating Program.") exit(1) print("Inserting element : ", value) self.rear = (self.rear + 1) % self.capacity self.q[self.rear] = value self.count = self.count + 1 # Function to return front element in the queue def peek(self): if self.isEmpty(): print("Queue UnderFlow!! Terminating Program.") exit(1) return self.q[self.front] # Function to return the size of the queue def size(self): return self.count # Function to check if the queue is empty or not def isEmpty(self): return self.size() == 0 # Function to check if the queue is full or not def isFull(self): return self.size() == self.capacity if __name__ == '__main__': # create a queue of capacity 100 q = Queue(100) while True: print("Press 0 then exit.") print("Press 1 then go to append.") print("Press 2 then go to pop.") print("Press 3 then go to check isEmpty?") n = int(input()) if n==0: print("EXIT.") break; elif n==1: x = int(input("Enter the element : ")) q.append(x) elif n==2: print("Queue size is", q.size()) print("Front element is", q.peek()) q.pop() elif n==3: if q.isEmpty(): print("Queue is empty") else: print("Queue is not empty")
d9ad0959c78d9d8bfcf83dae2281dde3ce0aa83d
wyrdvans/TDD-Katas
/fizzbuzz/fizzbuzz.py
478
3.84375
4
def fizzbuzz(values = range(1, 101)): output_list = [] for value in values: if (not value % 3) and (not value % 5): output_list.append("fizzbuzz") elif (not value % 3): output_list.append("fizz") elif (not value % 5): output_list.append("buzz") else: output_list.append(str(value)) return output_list def main(): print '\n'.join(fizzbuzz()) if __name__ == '__main__': main()
cf683a20fbabf4a469b090af58394f92415d08c9
ministep/PythonSpider
/多线程/productConsumer.py
1,545
3.828125
4
# 生产者消费者 import threading import time import random gTimes = 0 gTotalTimes = 10 gMoney = 1000 gCondition = threading.Condition() class Producer(threading.Thread): def run(self): global gMoney global gTimes while True: money = random.randint(100, 1000) gCondition.acquire() if gTimes > gTotalTimes: gCondition.release() break gMoney += money gCondition.notify_all() gTimes += 1 print('%s生产了%d的钱,还剩%d的钱' % (threading.current_thread(), money, gMoney)) gCondition.release() time.sleep(0.5) class Consumer(threading.Thread): def run(self): global gMoney while True: money = random.randint(100, 1000) gCondition.acquire() while gMoney < money: if gTimes >= gTotalTimes: gCondition.release() return print('%s准备消费%d,还剩%d的钱,钱不足' % (threading.current_thread(), money, gMoney)) gCondition.wait() gMoney -= money print('%s消费了%d的钱,还剩%d的钱' % (threading.current_thread(), money, gMoney)) gCondition.release() time.sleep(0.5) def main(): for x in range(5): Consumer(name='消费者%d' % x).start() for x in range(5): Producer(name='生产者%d' % x).start() if __name__ == '__main__': main()
cd5442a58e4193d62791b2400e2875a5d9bea719
jinurajan/Datastructures
/LeetCode/medium/add_two_numbers.py
2,352
3.84375
4
""" You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. """ class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def pad_len(self, head, pad_len): node = head while node.next is not None: node = node.next i = 0 while i < pad_len: i += 1 node.next = ListNode(0) node = node.next return head def length(self, head): count = 0 node = head while node is not None: count += 1 node = node.next return count def addTwoNumbers(self, l1, l2): len1 = self.length(l1) len2 = self.length(l2) if len1 > len2: l2 = self.pad_len(l2, len1 - len2) else: l1 = self.pad_len(l1, len2 - len1) result_ll = self.add_list(l1, l2, 0) return result_ll def add_list(self, ll_1, ll_2, carry): if ll_1 is None and ll_1 is None and carry == 0: return None value = carry if ll_1 is not None: value += ll_1.val if ll_2 is not None: value += ll_2.val remainder = value % 10 result = ListNode(remainder) if ll_1 is not None or ll_2 is not None: more = self.add_list( None if ll_1 is None else ll_1.next, None if ll_2 is None else ll_2.next, 1 if value >= 10 else 0) result.next = more return result def print_ll(head): node = head while node is not None: print node.val, # if node.next is not None: # print "->" node = node.next if __name__ == "__main__": l1 = ListNode(0) # l1.next = ListNode(9) # l1.next.next = ListNode(9) l2 = ListNode(7) l2.next = ListNode(3) # l2.next.next = ListNode(4) # print "\n" res = Solution().addTwoNumbers(l1, l2) print_ll(res)
7b7bc735edede502a081da862f5dfde575af6067
ayyjohn/pb950oOzYABB2j8
/spreadsheet_encoding.py
1,576
4.03125
4
# write a function that takes in a string such as A, Q, Z, AA, AX, ZZ # corresponding to a spreadsheet column header and outputs the # integer mapping, eg for A it outputs 1, for D it outputs # 4, for ZZ it outputs 702. # at first glance this seems like it's just base 26? # A => 1 # Z => 26 # AA => 27 # so at the top we have 1x26**1 + 1x26**0 # that would mean ZZ = 26x26**1 + 26x26**0 # which, yes, that equals 702! # so a brute force approach is to map # each value to its corresponding letter # and then keep a running sum through the number import string import functools def spreadsheet_column(s): total = 0 for i in reversed(range(len(s))): total += (string.ascii_uppercase.index(s[i]) + 1) * 26**i return total print(spreadsheet_column('ZZ')) print(spreadsheet_column('AA')) print(spreadsheet_column('A')) # there's a better algorithm, though, that I remember from before # where when building up the values we can do less multiplications # essentially you traverse the string in order, multiplying by the base # each time. so for base 10, and 314 we add 3, then multiply by 10. # then we add 1, getting 31, then we multiply by 10 again. # then we add 4. # the general algorithm is initialize a partial to 0, # then for partial value, multiply by 10 and add # so partial = 0 # 0x10 + 3 = 3 # 3x10 + 1 = 31 # 31x10 + 4 = 314 def spreadsheet_column(col): return functools.reduce(lambda result, c: result * 26 + ord(c) - ord('A') + 1, col, 0) print(spreadsheet_column('ZZ')) print(spreadsheet_column('AA')) print(spreadsheet_column('A'))
cc8e39e4dc8f5cd2bf9ebb16a7ee51610fc3106d
HEriks/doctool
/test.py
833
3.75
4
import sys f = open("faf.txt","w+") f.write("Hej") f.close print("Welcome, this tool will help you to quickly generate a short summary of your programs") userInput = input("Please enter the search path of your file (including file ending)") f = open(userInput, "r") line = 1 numFunc = 0 print("--- Functions ---") for x in f: x = x.strip() if len(x) > 1: # print(x[:2]) if (x[:2] == "//"): if ('f:' in x): print("Line " + str(line) + ":") print(x[2:]) numFunc = numFunc+1 elif ('p:' in x): print(x[2:]) elif ('c:' in x): print(x[2:]) line = line + 1 print("--- Summary ---") print("Number of lines: " + str(line)) print("Number of documented functions: " + str(numFunc))
4201b54888cb9e76b03492f41f957aa57868cffa
amisha1garg/Arrays_In_Python
/FindMinMax.py
744
4.09375
4
# Given # an # array # A # of # size # N # of # integers.Your # task is to # find # the # minimum and maximum # elements in the # array. # # Example # 1: # # Input: # N = 6 # A[] = {3, 2, 1, 56, 10000, 167} # Output: # min = 1, max = 10000 # User function Template for python3 def getMinMax(a, n): return min(a), max(a) # { # Driver Code Starts # Initial Template for Python 3 def main(): T = int(input()) while (T > 0): n = int(input()) a = [int(x) for x in input().strip().split()] product = getMinMax(a, n) print(product[0], end=" ") print(product[1]) T -= 1 if __name__ == "__main__": main() # } Driver Code Ends
81c7074f589b3d13c2af0458647575c40f0f5421
lukbut/extreme_computing2
/task 2/reducer.txt
248
3.65625
4
#!/usr/bin/python # Code adapted from labs import sys i = 0 for line in sys.stdin: # For ever line in the input from stdin line = line.strip() # Remove trailing characters if i < 10: print(line) i += 1
1e0bbcb8ae0fd9e9a3712d4e2500ae204b8ad080
hatan4ik/python-3-keys-study
/solutions/test_person.py
342
3.5625
4
import unittest from person import Person class TestPerson(unittest.TestCase): def test_main(self): guy = Person("John", "Doe") self.assertEqual("John", guy.first) self.assertEqual("Doe", guy.last) self.assertEqual("John Doe", guy.full_name()) self.assertEqual("Mr. John Doe", guy.formal_name("Mr."))
ab276acc7fe33d6d3e2dd77d84876cec23bdfda3
yinshengLi/exercise
/arithmatic/basic_01.py
1,784
3.921875
4
#__author:iruyi #date:2018/10/11 # bubble sort 气泡排序 def bubble_sort(nums): for i in range(len(nums) -1): for j in range(len(nums) -i -1): if nums[j] < nums[j + 1]: temp = nums[j] nums[j] = nums[j+1] nums[j+1] = temp return nums ''' 数组中的数字本是无规律的排放,先找到最小的数字,把他放到第一位,然后找到最大的数字放到最后一位。 然后再找到第二小的数字放到第二位,再找到第二大的数字放到倒数第二位。以此类推,直到完成排序。 ''' def cocktailSort(nums): size = len(nums) for i in range(size//2): for j in range(i, size-i-1): if nums[j] < nums[j+1]: nums[j],nums[j+1] = nums[j+1],nums[j] #将最大值排到队头 (size-i-2 因为上面执行就会排好一个最小的,所以就要少排一个) for j in range(size-i-2, i, -1): if nums[j] > nums[j-1]: nums[j], nums[j-1] = nums[j-1], nums[j] return nums # direct insert sort def directInsertSort(nums,n): for i in range(1, n): temp = nums[i] j = i -1 while j > -1 and temp < nums[j]: nums[j+1] = nums[j] j = j-1 nums[j+1] = temp def insertSort(nums): size = len(nums) for i in range(1, size): for j in range(i, 0, -1): if nums[j] < nums[j-1]: nums[j-1], nums[j] = nums[j], nums[j-1] lista = [10, 40, 3, 5, 9, 80, 100] print('origin:', lista) # print('bubble_sort:',bubble_sort(lista)) # print('cocktail_sort:', cocktailSort(lista)) # directInsertSort(lista,len(lista)) # print('directInsertSort',lista) # insertSort(lista) # print('insertSort', lista)
a66261c56139f09054c607f219ff02fd47d8e3aa
FilipVidovic763/vjezba
/kisa.py
248
3.78125
4
kisa=input('unesi vjerovatnost kiše:') kisa=float(kisa) if kisa >= 0.0 and kisa <=0.5: print('nema potrebe ponijet kišobran') elif kisa >=0.5 and kisa <=1: print('ponesi kišobran') else: print('neispravna vrijednost')
6b4cbf2bd84205ea7c06a31a59d4893fb4b4c434
shadanan/python-challenge
/pc30.py
1,717
3.734375
4
#!/usr/bin/env python3 # encoding: utf-8 # Start at: http://www.pythonchallenge.com/pc/ring/yankeedoodle.html # User: repeat, Pass: switch # Photograph of a beach with lounge chairs and umbrellas # Page title: "relax you are on 30" # Image named: "yankeedoodle.jpg" # Caption: "The picture is only meant to help you relax" # Comment in HTML: "<!-- while you look at the csv file -->" import math import pandas as pd import requests from PIL import Image # Grab the CSV file. response = requests.get( "http://www.pythonchallenge.com/pc/ring/yankeedoodle.csv", auth=("repeat", "switch") ) # Read the data into a pandas Series. str_data = [v.strip() for v in response.text.split(",")] values = pd.Series([float(v) for v in str_data]) # There are 7637 values whose factors are 53 and 139. # Let's interpret the data as grayscale image data. width = 139 height = math.ceil(len(values) / width) img = Image.new(mode="L", size=(width, height)) for i, v in enumerate(values): img.putpixel((i // height, i % height), int(v * 255)) img.show() # The result is an image with the following text: # n=str(x[i])[5] # +str(x[i+1])[5] # +str(x[i+2])[6] # Let's extract bytes according to this from the values: data = [] for i in range(0, len(str_data) - 2, 3): n = int(str_data[i][5] + str_data[i + 1][5] + str_data[i + 2][6]) data.append(n) print(bytes(data).decode("utf-8")) # The result contains a long bit of text starting with: # So, you found the hidden message. # There is lots of room here for a long message, but we only need very little space to # say "look at grandpa", so the rest is just garbage. # Go to: http://www.pythonchallenge.com/pc/ring/grandpa.html # User: repeat, Pass: switch
da1a05a1d415603c66b705f02400c0e8894d6ca9
southpawgeek/perlweeklychallenge-club
/challenge-121/cristian-heredia/python/ch-1.py
900
3.8125
4
''' TASK #1 › Invert Bit Submitted by: Mohammad S Anwar You are given integers 0 <= $m <= 255 and 1 <= $n <= 8. Write a script to invert $n bit from the end of the binary representation of $m and print the decimal representation of the new binary number. Example Input: $m = 12, $n = 3 Output: 8 Binary representation of $m = 00001100 Invert 3rd bit from the end = 00001000 Decimal equivalent of 00001000 = 8 Input $m = 18, $n = 4 Output: 26 Binary representation of $m = 00010010 Invert 4th bit from the end = 00011010 Decimal equivalent of 00011010 = 26 ''' m = 12 n = 3 # Convert to binary with leading 0 bits = list("{0:08b}".format(m)) # invert $n bit from the end of the binary if bits[-n] == '0': bits[-n] = '1' else: bits[-n] = '0' # Convert to decimal string result = int(''.join(bits), 2) print(f"Output: {result}")
84fca47c55c7ac43d34c5d4321755392356744c1
oaifaye/tensorflow_demo
/logistic_regression/test1.py
1,741
3.5
4
# -*- coding:utf-8 -*- #功能: 使用tensorflow实现一个简单的逻辑回归 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt #创建占位符 X=tf.placeholder(tf.float32) Y=tf.placeholder(tf.float32) #创建变量 #tf.random_normal([1])返回一个符合正太分布的随机数 w=tf.Variable(tf.random_normal([1],name='weight')) b=tf.Variable(tf.random_normal([1],name='bias')) y_predict=tf.sigmoid(tf.add(tf.matmul(X,w),b)) num_samples=400 cost=tf.reduce_sum(tf.pow(y_predict-Y,2.0))/num_samples #学习率 lr=0.01 optimizer=tf.train.AdamOptimizer().minimize(cost) #创建session 并初始化所有变量 num_epoch=500 cost_accum=[] cost_prev=0 #np.linspace()创建agiel等差数组,元素个素为num_samples xs=np.linspace(-5,5,num_samples) ys=np.sin(xs)+np.random.normal(0,0.01,num_samples) with tf.Session() as sess: #初始化所有变量 sess.run(tf.initialize_all_variables()) #开始训练 for epoch in range(num_epoch): for x,y in zip(xs,ys): sess.run(optimizer,feed_dict={X:x,Y:y}) train_cost=sess.run(cost,feed_dict={X:x,Y:y}) cost_accum.append(train_cost) print ("train_cost is:",str(train_cost)) #当误差小于10-6时 终止训练 if np.abs(cost_prev-train_cost)<1e-6: break #保存最终的误差 cost_prev=train_cost #画图 画出每一轮训练所有样本之后的误差 plt.plot(range(len(cost_accum)),cost_accum,'r') plt.title('Logic Regression Cost Curve') plt.xlabel('epoch') plt.ylabel('cost') plt.show()