blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
55df812750f5c96725cb9e823b0247d599ab67c1
DmitryVakhrushev/Python
/PythonProjects/MOOC_ProgForEverybody/Py4Inf_24_RegularExpressions.py
5,863
4.46875
4
#------------------------------------------- # Regular Expressions #------------------------------------------- # Really clever "wild card" expressions for matching and parsing strings. # ^ Matches the beginning of a line # $ Matches the end of the line # . Matches any character # \s Matches whitespace # \S Matches any non-whitespace character # * Repeats a character ZERO or more times # *? Repeats a character ZERO or more times (non-greedy) # + Repeats a character ONE or more times # +? Repeats a character ONE or more times (non-greedy) # [aeiou] Matches a single character IN the listed set # [^XYZ] Matches a single character NOT in the listed set # [a-z0-9] The set of characters can include a range # ( Indicates where string extraction is to START # ) Indicates where string extraction is to END import re import math # You can use re.search()to see if a string matches # a regular expression similar to using the find() method for strings # You can use re.findall() extract portions of a string that match your # regular expression similar to a combination of find() and slicing: var[5:10] hand = open('mbox-short.txt') for line in hand: line = line.rstrip() if line.find('From:')>= 0: print(line) print('-------------------------------------------') import re hand = open('mbox-short.txt') for line in hand: line = line.rstrip() if re.search('From:', line): print(line) ######################################################################## # Wild-Card Characters ######################################################################## # 1. The dot "." character matches any character # 2. If you add the asterisk "*" character, the character is "any number of times" print('---------- Pattern: "^X.*:" ----------') # Match the start of the line with "X" followed by any character any number of time and then ":" hand = open('mbox-short.txt') for line in hand: line = line.rstrip() if re.search('^X.*:', line): print(line) ######################################################################## # \S -- Matches any non-whitespace character # "+" -- any number of times print('---------- Pattern: "^X-\S+:" ----------') # This is a more specific pattern hand = open('mbox-short.txt') for line in hand: line = line.rstrip() if re.search('^X-\S+:', line): print(line) print("#----------------------------------------------") ######################################################################## # Matching and Extracting Data ######################################################################## # The re.search() returns a True/False depending on whether the string matches the regular expression # If we actually want the matching strings to be extracted, we use re.findall() # Look for a single character (number in our case) # [0-9]+ # "+" means one or more digits defined in [0-9] -- between 0 and 9 # "Smart" wat to extract numbers from the string import re x = 'My 2 favorite numbers are 19 and 42' y = re.findall('[0-9]+',x) print(y) z = re.findall('[faAEIOU]+',x) print(z) print("#----------------------------------------------") ######################################################################## # Greedy Matching #----------------------------------------------------------------------- # The repeat characters (*and +) push outward in both directions (greedy) to match the largest possible string x = 'From: Using the :character' y = re.findall('^F.+:', x) print(y) # ['From: Using the :'] --> it did not stop at the first ":" --> "GREEDY Match" print("#----------------------------------------------") ######################################################################## # Non-Greedy Matching #----------------------------------------------------------------------- x = 'From: Using the : character' y = re.findall('^F.+?:', x) print(y) # ['From:'] --> ^F.+?: print("#----------------------------------------------") ######################################################################## # Fine Tuning String Extraction #----------------------------------------------------------------------- # Pull an email address out of the string x = "From [email protected] Sat Jan 5 09:14:16 2008" y = re.findall('\S+@\S+',x) print(y) # Parenthesis are not part of the match - but they tell where to start and stop what string to extract y = re.findall('^From (\S+@\S+)',x) print(y) # Extracting the domain name -- The Regex Version # '@([^ ]+)' --> Look through the string until you find an at-sign # [^ ] --> Match non-blank character # + --> Match many of them at least ones # () extract only match in parenthesis line = 'From [email protected] Sat Jan 5 09:14:16 2008' y = re.findall('@([^ ]+)',line) print(y) # ['uct.ac.za'] y = re.findall('^From .*@([^ ]*)',line) # Starting at the beginning of the line, look for the string 'From ' # Skip a bunch of characters, looking for an at-sign # () --> Start 'extracting' print(y) # ['uct.ac.za'] ###################################### # Spam Confidence ###################################### hand = open('mbox-short.txt') numlist = list() for line in hand: line = line.rstrip() stuff= re.findall('^X-DSPAM-Confidence: ([0-9.]+)', line) if len(stuff) != 1: continue num = float(stuff[0]) numlist.append(num) print('Maximum:', max(numlist)) ###################################### # Escape Character ###################################### # If you want a special regular expression character to just # behave normally (most of the time) you prefix it with '\' x = 'We just received $10.00 for cookies.' y = re.findall('\$[0-9.]+',x) # Look for A real dollar sign; a digit or period print(y)
d6e110ba693489057038cd6433a60d4e150bd56f
dom-0/python
/oldstuff/remove.py
275
3.671875
4
#!/usr/bin/env python pets= [] while input != "quit": input = raw_input("Enter the name of the pet: ") pets.append(input) print ("\n\n" + str(pets)) remove = raw_input("Which pet would you like to remove? ") while remove in pets: pets.remove(remove) print (pets)
a84986a9e0c92907cabaa604d24394e976c46f10
fiscompunipamplona/taller-orbitas-fibonacci-DiegoPalacios11
/segkepler.py
527
3.96875
4
v1=float(input("ingrese la velocidad del perihelio")) r1=float(input("ingrese la posicion del perihelio")) g=6.67e-11 m=5.97e24 pi=3.1416 v2=(((2*g*m)/(v1*r1))+(((2*g*m)/(v1*r1))**2+4*((v1**2-2*g*m)/r1))**1/2)/r1 r2=(r1*v1)/v2 print("la velocidad del afelio es: ",v2) print("la posicion del felio es: ",r2) emy=(r1+r2)/2 eme=(r1*r2)**1/2 print("el eje mayor es: ",emy) print("el eje menor es: ",eme) t=(2*pi*(ema*eme))/r1*v1 e=(r2-r1)/(r1+r2) print("el periodo de orbita es: ",t) print("la excentricidad de la orbita es: ",e)
204a901abca752ca84ced55e31cd58dedca3afdc
SL-PROGRAM/Mooc
/UPYLAB-5-10.py
1,195
3.828125
4
"""Auteur: Simon LEYRAL Date : Octobre 2017 Enoncé Écrire une fonction prime_numbers qui reçoit comme paramètre un nombre entier nb et qui renvoie la liste des nb premiers nombres premiers. Si le paramètre n’est pas du type attendu, ou ne correspond pas à un nombre entier positif ou nul, la fonction renvoie None. Consignes Dans cet exercice, il vous est demandé d’écrire seulement la fonction prime_numbers. Le code que vous soumettez à UpyLaB doit donc comporter uniquement la définition de cette fonction, et ne fait en particulier aucun appel à input ou à print. On rappelle qu’un nombre premier est un entier naturel qui possède exactement deux diviseurs distincts et positifs, 1 et lui-même. """ def prime_numbers(nb): if type(nb) != int or nb<0: list = None else: k = 2 list = [] while len(list) < nb: test = True for j in range(2,k-1): print(j) if k % j == 0: test = False break if test == True: list.append(k) k+=1 return list print(prime_numbers(15))
4c24a67a3e67906faa5daa162b8bd68fa8d6d3ed
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/f17d7688682e4fff90e437e759f4d5df.py
512
4
4
# -*- coding: utf-8 -*- # Skeleton file for the Python "Bob" exercise. import re def hey(what): #Remove white spaces in the string what = what.strip() if re.search('äÜ', what): return "Whatever." #Yeling at bob elif re.search('!$', what) or re.search("[A-Z][A-Z][A-Z][A-Z]", what): return "Whoa, chill out!" #Making questions elif re.search('\?$', what): return "Sure." #Long silence elif len(what) == 0: return "Fine. Be that way!" else: return "Whatever." print hey('ÜMLäÜTS!')
be7e3d4518f4ceb83cc2b921e63c99bd7f5833ae
arvindbis/PythonPract
/PDemo/src/com/demo/Learning.py
174
3.734375
4
''' Created on 02-Mar-2019 @author: arvindkumar ''' thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x,y in thisdict.items(): print(x , y)
1cfec37ab1c6cefdc2ddf4e16a502b178db37c49
RahulBantode/Python_Automation
/Duplicate_File_Detector/duplicate_file_detector.py
3,774
3.5625
4
#File Contains the Code of Duplicate files detector and then sending the email to specified recipient from sys import * import os import hashlib import time total_scanned_file = 0 file_path = " " def CalculateCheckSum(path, blocksize = 512): global total_scanned_file total_scanned_file = total_scanned_file + 1 file_descriptor = open(path,"rb") hash_obj = hashlib.md5() #here we select the algorithm from the hashlib module. Buffer = file_descriptor.read(blocksize) while len(Buffer) > 0: hash_obj.update(Buffer) Buffer = file_descriptor.read(blocksize) file_descriptor.close() return hash_obj.hexdigest() # hexdigest will create hexadecimal string of our checksum. def DirectoryTraversal(path): directory = " " duplicate_files = {} #dictonary. if not os.path.exists(path): print("Failure : please enter valid path") exit() #if not os.path.isabs(path): #here we check the path is absolute or not. directory = os.path.abspath(path) #this function creates the path as absolute and returns the op # as string for Folder, Subfolder, Filename in os.walk(directory): for file in Filename: actual_path = os.path.join(Folder,file) hash = CalculateCheckSum(actual_path) if hash in duplicate_files: #checksum is already present duplicate_files[hash].append(actual_path) else: #checksum not present then add it into the dictonary duplicate_files[hash] = [actual_path] return duplicate_files def Generate_list_duplicate_files(dict_duplicates): list_duplicates_files = list(filter(lambda x : len(x) > 1, dict_duplicates.values())) #nested list counter = 0 files_duplicates = [] #this file for write in the file which files are going to deleted. if(len(list_duplicates_files) > 0): #print("There are duplicate files") for lists in list_duplicates_files: counter = 0 for file_path in lists: counter = counter + 1 if counter >= 2: files_duplicates.append(file_path) else: print("There is no duplicate files") exit() return files_duplicates def Generate_Log_file(dup_files,Folder="Duplicate_Files"): global file_path if not os.path.exists(Folder): os.mkdir(Folder) file_path = os.path.join(Folder,"_filelog-{}.txt".format(time.ctime())) file_path = (file_path.replace(" ","_").replace(":","-")) file_descriptor = open(file_path,"w") for element in dup_files: file_descriptor.write("{}\n".format(element)) file_descriptor.close() def Display_Statistics(dup_files): print() print("----Statistics Of Operations----") print("Total Number of file scanned : ",total_scanned_file) print("Total Number of duplicate files : ",len(dup_files)) print("Folder\\file name of file log created : ",file_path) input_text = input("Are you want to delete duplicate files [y/n] ? ") if (input_text == "y") or (input_text == "Y"): for file in dup_files: os.remove(file) elif (input_text == "n") or (input_text == "N"): exit() def main(): print("----Duplicate file Detector----") if(len(argv) != 2): print("Error : Invalid number of arguments") exit() if(argv[1]=="-h") or (argv[1]=="-H"): print("Help : It's a Directory cleaner script") if(argv[1]=="-u") or (argv[1]=="-U"): print("Usage : Provide the absolute path of the target directory") dict_duplicates = {} dup_files = [] dict_duplicates = DirectoryTraversal(argv[1]) if dict_duplicates != 0: dup_files = Generate_list_duplicate_files(dict_duplicates) Generate_Log_file(dup_files) Display_Statistics(dup_files) if __name__ == '__main__': main()
d7a3829ee80b6eb449cdb006bf26d4add0cc4c82
ErvinCs/FP
/Lab05-09-Library/src/domain/Book.py
1,845
3.609375
4
class Book: bookIterator = 0 #bookId generator def __init__(self, title, description, author): ''' Sets bookId using the bookIterator :param title, description, author: strings ''' self.__bookId = Book.bookIterator Book.bookIterator += 1 self.__title = title.strip() self.__description = description.strip() self.__author = author.strip() def getId(self): return self.__bookId def getTitle(self): return self.__title def getDescription(self): return self.__description def getAuthor(self): return self.__author def setTitle(self, title): self.__title = title.strip() def setDescription(self, description): self.__description = description.strip() def setAuthor(self, author): self.__author = author.strip() def __str__(self): ''' :return: a String: 'Book[ID]: Title - Author - Descrpition' ''' aString = 'Book ' + str(self.__bookId) + ': ' aString += str(self.__title) + ' - ' aString += str(self.__author) + ' - ' aString += str(self.__description) return aString # Not used def strToStore(self): ''' :return: a String: 'Title - Author - Description' ''' #aString = 'Book ' + str(self.__bookId) + ': ' aString = str(self.__title) + ' - ' aString += str(self.__author) + ' - ' aString += str(self.__description) return aString def __eq__(self, book): ''' :param book: to compare to :return: True if the 2 books are identical (except for the bookId); False otherwise ''' return self.__title == book.__title and self.__author == book.__author and self.__description == book.__description
07fd697bf0578792184f59edadb02ae361d0955e
fujunguo/learning_python
/The_3rd_week_in_Dec_2017/function_map.py
93
3.515625
4
def f(x): return x * x a = [1, 2, 3, 4, 5, 6, 7, 8, 9] r = map(f, a) print(list(r))
e9126adc80eb97150ca4cf18d8471978c4772305
bridgetlane/Python-Puzzles
/src/palindrome.py
895
4.3125
4
# tells you if a given string is a palindrome def palindrome(string): for i in string: # remove non-alphabetical characters if (i.isalpha() == False): string = string.replace(i, "") if (i.isupper() == True): string = string.replace(i, i.lower()) reverse = "" # create the reverse string i = len(string) - 1 while (i >= 0): reverse += string[i] i -= 1 is_pal = False if ((len(string) > 1) and (string == reverse)): is_pal = True return is_pal # some examples def main(): print(palindrome("Taco cat")) print(palindrome("not a palindrome :(")) print(palindrome("Amor, Roma")) print(palindrome("A man, a plan, a canal: Panama")) print(palindrome("")) # is not fooled by empty strings/one letter main()
983edcb27edd0e01b465c88f6df18b57cd79995d
benoxoft/mti880handcopter
/HandcopterGame/gamelib/movement.py
7,555
3.546875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2010 Benoit <benoxoft> Paquet # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from pygame.sprite import Group from pygame.rect import Rect import math class Movement(Group): def __init__(self, moving_sprite, speedx = 0, maxspeedx = -1, speedy = 0, maxspeedy = -1, posx = 0, posy = 0, thrust_strength = 0, accelx = 0, accely = 0, gravity = 1000): Group.__init__(self) self.moving_sprite = moving_sprite self.speedx = speedx self.speedy = speedy self.maxspeedx = maxspeedx self.maxspeedy = maxspeedy self.posx = posx self.posy = posy self.thrust_strength = thrust_strength self.accelx = accelx self.accely = accely self.gravity = gravity self.bumping_walls = [] def get_speed(self): return math.sqrt(self.speedx**2 + self.speedy**2) def thrust(self, tick): self.speedy -= self.thrust_strength * tick / 1000.0 if self.maxspeedy != -1 and abs(self.speedy) > self.maxspeedy: self.speedy = -self.maxspeedy def moveleft(self, tick): self.speedx -= self.accelx * tick / 1000.0 if self.maxspeedx != -1 and abs(self.speedx) > self.maxspeedx: self.speedx = -self.maxspeedx def moveright(self, tick): self.speedx += self.accelx * tick / 1000.0 if self.maxspeedx != -1 and self.speedx > self.maxspeedx: self.speedx = self.maxspeedx def movedown(self, tick): self.speedy += self.accely * tick / 1000.0 if self.maxspeedy != -1 and abs(self.speedy) > self.maxspeedy: self.speedy = self.maxspeedy def calculate_movement(self, tick): self.speedy += self.gravity * tick / 1000.0 if self.maxspeedy != -1 and self.speedy > self.maxspeedy: self.speedy = self.maxspeedy self.check_collision(tick) self.posy = self.get_new_posy(tick) self.posx = self.get_new_posx(tick) def get_new_posx(self, tick): return self.posx + self.speedx * tick / 1000.0 def get_new_posy(self, tick): return self.posy + self.speedy * tick / 1000.0 def check_collision(self, tick): oldrect = self.moving_sprite.rect newrect = Rect(self.get_new_posx(tick), self.get_new_posy(tick), oldrect.width, oldrect.height) collisions = [col for col in self.sprites() if col.rect.colliderect(newrect)] if len(collisions) > 0: for coll in collisions: col = coll.rect if newrect.right >= col.x and oldrect.right <= col.x: self.posx = col.x - oldrect.width self.speedx = 0 if newrect.x <= col.right and oldrect.x >= col.right: self.posx = col.right self.speedx = 0 if newrect.bottom >= col.y and oldrect.bottom <= col.y: self.posy = col.y - oldrect.height self.speedy = 0 self.speedx /= 1.2 if self.speedx < 1 and self.speedx > -1: self.speedx = 0 if newrect.y <= col.bottom and oldrect.y >= col.bottom: self.posy = col.bottom self.speedy = 0 self.speedx /= 1.1 if self.speedx < 1 and self.speedx > -1: self.speedx = 0 self.bumping_walls = collisions def check_collision_x(self, tick): collisions = [] newposx = self.get_new_posx(tick) if self.speedx > 0: currentposx = self.moving_sprite.rect.right newposx += + self.moving_sprite.rect.width possible_cols = [col for col in self.sprites() if col.rect.x >= currentposx and col.rect.x <= newposx] for spr in possible_cols: dist = abs(spr.rect.right - currentposx) t = float(dist/abs(self.speedx)) ypos = self.get_new_posy(t) if ypos <= spr.rect.bottom and ypos >= spr.rect.top: collisions.append((t, spr.rect.x - self.moving_sprite.rect.width)) elif self.speedx < 0: possible_cols = [col for col in self.sprites() if col.rect.right <= self.posx and col.rect.right >= newposx] for spr in possible_cols: dist = abs(spr.rect.right - self.posx) t = float(dist/abs(self.speedx)) ypos = self.get_new_posy(t) if ypos <= spr.rect.bottom and ypos >= spr.rect.top: collisions.append((t, spr.rect.right)) if len(collisions) == 0: return tick else: self.speedx = 0 first_col = tick for t,x in collisions: if t < first_col: first_col = t self.posx = x return tick - first_col def check_collision_y(self, tick): collisions = [] newposy = self.get_new_posy(tick) if self.speedy > 0: currentposy = self.posy + self.moving_sprite.rect.height newposy += self.moving_sprite.rect.height possible_cols = [col for col in self.sprites() if col.rect.top >= currentposy and col.rect.top <= newposy] for spr in possible_cols: dist = abs(spr.rect.top - currentposy) t = float(dist/abs(self.speedy)) xpos = self.get_new_posx(t) if xpos <= spr.rect.right and xpos >= spr.rect.x: collisions.append((t, spr.rect.top - self.moving_sprite.rect.height)) elif self.speedy < 0: possible_cols = [col for col in self.sprites() if col.rect.bottom <= self.posy and col.rect.bottom >= newposy] for spr in possible_cols: dist = abs(spr.rect.bottom - self.posy) t = float(dist/abs(self.speedy)) xpos = self.get_new_posx(t) if xpos <= spr.rect.right and xpos >= spr.rect.x: collisions.append((t, spr.rect.bottom)) if len(collisions) == 0: return tick else: self.speedy = 0 self.speedx /= 1.2 if self.speedx < 1 and self.speedx > -1: self.speedx = 0 first_col = tick for t,y in collisions: if t < first_col: first_col = t self.posy = y return tick - first_col
640c6cc07b6b63a4c3741ddd04f6bab38e352d9e
humachine/AlgoLearning
/leetcode/Done/60_PermutationSequence.py
1,343
3.703125
4
#https://leetcode.com/problems/permutation-sequence/ '''The number 123..n has n! different permutations of its digits. Given n and a number k, return the kth permutation (when permutations are in ascending order). Inp: 3, 5 Out: 312 [123, 132, 213, 231, 312] ''' class Solution(object): def getPermutation(self, n, k): if n==1: return '1' if k==1: return ''.join([str(x) for x in range(1, n+1)]) factorials = [1, 1, 2, 6, 24, 120, 720, 5040, 40320] # With the first digit of the number fixed, we can get (n-1)! possibilities # Keeping this in mind, we try changing the first digit of the number, # until we find we need to find less than (n-1)! permutation. count, digit = 0, 1 while count + factorials[n-1]<k: digit+=1 count+=factorials[n-1] # We now look for the k-count permutation from (n-1) digits perm = list(self.getPermutation(n-1, k-count)) for i in xrange(n-1): # All digits that are greater than $digit are incremented by 1, to # match with the actual permutation if int(perm[i]) >= digit: perm[i] = chr(ord(perm[i])+1) return str(digit)+''.join(perm) s = Solution() print s.getPermutation(3, 5) print s.getPermutation(3, 2)
ada60480c5ffb10ae900dbfcf4833fe1b5e886f0
moileehyeji/Study
/keras/keras15_ensemble2.py
2,598
3.578125
4
#실습: 다:1 앙상블 구현 #1. 데이터 import numpy as np x1 = np.array([range(100), range(301,401), range(1,101)]) x2 = np.array([range(101,201), range(411,511), range(100,200)]) y1 = np.array([range(711,811), range(1,101), range(201,301)]) x1=np.transpose(x1) x2=np.transpose(x2) y1=np.transpose(y1) from sklearn.model_selection import train_test_split # train_test_split 3가지 데이터 x1_train, x1_test, x2_train, x2_test, y1_train, y1_test = train_test_split(x1, x2, y1, train_size=0.8, shuffle=True) #2. 모델구성 from tensorflow.keras.models import Model from tensorflow.keras.layers import Input,Dense #모델1 input1 = Input(shape=(3,)) dense1 = Dense(10, activation='relu')(input1) dense1 = Dense(30, activation='relu')(dense1) dense1 = Dense(140, activation='relu')(dense1) dense1 = Dense(50, activation='relu')(dense1) #모델2 input2 = Input(shape=(3,)) dense2 = Dense(10, activation='relu')(input2) dense2 = Dense(130, activation='relu')(dense2) dense2 = Dense(70, activation='relu')(dense2) dense2 = Dense(90, activation='relu')(dense2) #모델병합 / concatenate:연쇄시키다, 연관시키다 from tensorflow.keras.layers import concatenate, Concatenate #병합모델의 layer구성 merge1 = concatenate([dense1, dense2]) middle1 = Dense(35) (merge1) middle1 = Dense(50) (middle1) middle1 = Dense(50) (middle1) middle1 = Dense(60) (middle1) middle1 = Dense(80) (middle1) #모델분기 output1 = Dense(30)(middle1) output1 = Dense(60)(output1) output1 = Dense(100)(output1) output1 = Dense(20)(output1) output1 = Dense(3)(output1) #최종 아웃풋 #모델선언 model = Model(inputs=[input1, input2], outputs=output1) model.summary() #3.컴파일, 훈련 model.compile(loss='mse', optimizer='adam', metrics=['mse']) model.fit([x1_train,x2_train], y1_train, epochs=100, batch_size=1, validation_split=0.2, verbose=1) #4. 평가, 예측 loss = model.evaluate([x1_test,x2_test], y1_test, batch_size=1) print('model.metrics_names : ', model.metrics_names) print('loss: ', loss) y_predict = model.predict([x1_test,x2_test]) print('========================================================') print('y1_predict : \n', y_predict) print('========================================================') # RMSE, R2 from sklearn.metrics import mean_squared_error def RMSE(y_test, y_predict): return np.sqrt(mean_squared_error(y_test, y_predict)) print('RMSE: ',RMSE(y1_test, y_predict)) from sklearn.metrics import r2_score print('R2: ',r2_score(y1_test, y_predict))
e4315e9470089f476393a55914b9cd1a9300e4e3
Hyunsooooo/jump2python
/2장/Q9.py
110
3.59375
4
a= dict() a['name'] = 'python' print(a) a[('a',)] = 'python' print(a) a[250] = 'python' print(a)
d88fb3d27aa8e6a02642bf7b720e725867a60928
solaaa/alg_exercise
/rebuild_btree.py
779
3.578125
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def build_bt(pre, mid): # 1. build root root = TreeNode(pre[0]) # 2. find the root.val in mid idx = 0 for i in range(len(mid)): if root.val == mid[i]: idx = i break L_len = idx R_len = len(mid) - idx - 1 # 3. recursion if L_len: root.left = build_bt(pre[1:L_len+1], mid[:L_len]) if R_len: root.right = build_bt(pre[L_len+1:], mid[L_len+1:]) return root def pre(r): if r: print(r.val) else: return pre(r.left) pre(r.right) tree = build_bt([1,2,3,4,5,6,7,8,9],[4,3,2,5,6,1,8,7,9]) pre(tree)
87acfc1f5ba4a84cdd85209a1ebc9f3d7b789357
ebenz99/Math
/algos/spiralList.py
1,927
3.6875
4
def printSpiral(lists): checklist = [] numItems = 0 for row in lists: a = [] for item in row: a.append(1) numItems+=1 checklist.append(a) print(checklist) print(lists) dic = {"R":"D","D":"L","L":"U","U":"R"} direction = "R" currX, currY = 0,0 buffstr = "" i = 0 while i < numItems: if direction == "R": if currX >= len(lists[0]): currX -= 1 currY+=1 direction = dic[direction] elif checklist[currY][currX] == 0: currX -= 1 currY+=1 direction = dic[direction] else: checklist[currY][currX] = 0 i+=1 buffstr += str(lists[currY][currX]) buffstr += "," currX += 1 elif direction == "D": print(currX,currY) if currY >= len(lists): currY -= 1 currX-=1 direction = dic[direction] elif checklist[currY][currX] == 0: currY -= 1 currX-=1 direction = dic[direction] else: i+=1 checklist[currY][currX] = 0 buffstr += str(lists[currY][currX]) buffstr += "," currY += 1 elif direction == "L": if currX < 0: currX += 1 currY -=1 direction = dic[direction] elif checklist[currY][currX] == 0: currX += 1 currY -=1 direction = dic[direction] else: i+=1 checklist[currY][currX] = 0 buffstr += str(lists[currY][currX]) buffstr += "," currX -= 1 else: #if direction == "U" if currY < 0: currY += 1 currX += 1 direction = dic[direction] elif checklist[currY][currX] == 0: currX += 1 currY +=1 direction = dic[direction] else: i+=1 checklist[currY][currX] = 0 buffstr += str(lists[currY][currX]) buffstr += "," currY -= 1 print(buffstr) l = [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]] printSpiral(l) l = [[1,2,3],[12,13,14],[11,16,15],[10,9,8]] printSpiral(l) l = [[1,2],[12,13],[11,16],[10,9]] printSpiral(l) l = [[1],[12],[11],[10]] printSpiral(l) l = [[1,2,3,4,5,6,7,8,9,10]] printSpiral(l)
886cdf037ad3d72ea44f6bc4e437cf76d7a96c6a
FangyangJz/Black_Horse_Python_Code
/第二章 python核心/HX01_python高级编程/生成器_迭代器/hx11_生成器02.py
844
3.609375
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: Fangyang time:2018/1/5 def test(): i = 0 while i < 5: temp = yield i print(temp) i += 1 t = test() t.__next__() # 第一次执行到yield,在等号右侧停下, 返回一个值 t.__next__() # 第二次执行,从yield开始,需要向temp赋值,但是上一次的值已经返回了, # 此时没有值, # 没有返回值, # 出一个None, 同时循环一次返回yield下一次的值 # send 和 next 都可以让生成器往下执行一次 # 不同在于, send(value) 相当于把value整体给yield整体 t.send('haha') # 这里就有值了,不会返回None # 不能一上来就用 send, 要等一次next后用 # 上面的替代方法是 第一次send(None)先,然后send()
51b90f51c4c071765cc627c75f7fb98b60b76807
richardkefa/python-pre-work
/import_demo.py
422
3.8125
4
# print("enter a string") # input_string = input() # characters = {} # for character in input_string: # characters.setdefault(character,0) # characters[character] = characters[character] + 1 # print(characters) print("Enter a string") input_string = input() characters = {} for character in input_string: characters.setdefault(character,0) characters[character] = characters[character] + 1 print(characters)
4de9fa815d740248391767312a291e597c3b973d
welitonsousa/UFPI
/programacao_orientada_objetos/estudo/lista03/data/cont.py
1,446
3.609375
4
import datetime class Cont: __balance = 0.0 __date = 0 __limit = 500.0 __credit = __limit def __init__(self, client): if client.age() > 17: self.client = client self.__date = datetime.datetime.now() else: print('Cont not created') def data(self): return { 'client_data': self.client.data(), 'initial_date': self.__date, 'balance': self.__balance, 'credit': self.__credit, 'limit': self.__limit } def add_balance(self, value_add): self.__balance += value_add def add_limit(self, value_add): self.__limit += value_add self.__credit += value_add def buy_credit(self, value_of_buy): if value_of_buy <= self.__credit: self.__credit -= value_of_buy else: print('insufficient credit') def buy_balance(self, value_of_buy): if value_of_buy <= self.__balance: self.__balance -= value_of_buy else: print('insufficient balance') def pay_credit(self): self.__credit = self.__limit def to_string(self): return 'Client data:\n' + self.client.to_string() + '\n\nCont data:' + \ '\nInitial date: ' + str(self.__date) + '\nLimit: ' + str(self.__limit) + \ '\nBalance: ' + str(self.__balance) + '\nCredit: ' + str(self.__credit)
f61cc1a0afc9ea59306df4832a3721ce74149e71
KeremBozgann/Efficient-Blackbox-Optimization-for-Gaussian-Process-Objectives-with-Resource-Intensive-Samples
/bo_cost_budget_cont_domain/cats_opt_cy/scipy_minimze_class_test.py
611
3.546875
4
import numpy as np from scipy.optimize import minimize, Bounds class Optimize(): def __init__(self): pass def function(self, x): print('function') self.z= x**2 return -(self.z+ x**3) def gradient(self, x): print('gradient') return -(2*np.sqrt(self.z)+ 3*x**2) def minimize(self): fun= self.function grad= self.gradient x0= [1.0] domain= [[0.0, 2.0]] lower= [0.0]; upper= [2.0] b = Bounds(lb=lower, ub=upper) print(minimize(fun, x0, bounds= b, jac= grad))
779ffbb518603cefb987b6acd42d0fda16bf8a34
w3cp/coding
/python/python-3.5.1/7-input-output/4-format.py
393
3.53125
4
# print('We are the {} who say "{}!"'.format('knights', 'Ni')) print('{0} and {1}'.format('spam', 'eggs')) print('{1} and {0}'.format('spam', 'eggs')) print('This {food} is {adjective}.'.format( food='spam', adjective='absolutely horrible')) print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))
2d05bad405242c0e6e3bf54cb9d3d8a696ccf8c8
victsomie/pythonbasics
/random_number_game.py
304
4
4
#A game to gues three numbers and compete with computer from random import randint x = randint(0, 5) y = int(raw_input("Enter a number (0 - 5)")) #Note that you have to convert the string input print x print y print print if y==x: print "Won" else: print "try again" #x = int(randint(0,5))
901e4dcd9cc466be60d69681312bc67159210f27
terz99/course-advanced-programming-in-python
/p2-5/main.py
233
3.53125
4
# JTSK-350111 # a2 p5.py # Dushan Terzikj # [email protected] mins = int(input("Enter minutes: ")) if mins < 0: print("Invalid output") else: hours = mins//60 mins -= hours*60 print("{:d} hours and {:d} minutes.".format(hours, mins))
9a20102271fdfee461398ddc77a2446646b87d42
Shandmo/Struggle_Bus
/Chapter 9/9-14_Lottery.py
1,614
3.703125
4
# 9-14 Lottery # Make a list or tuple containing a series of 10 numbers and five letters. Randomly select 4 numbers or letters from the list # And print a message saying that any ticket matching these four numbers or letters wins a prize. from random import choice # Creating Tickets and empty list of prize winners. Tickets = ['1', '2', '3', '4', 'b','c','a','d','e','f'] Winners = [] # Select your 4 winners from the list of tickets. while len(Winners) != 4: winner = choice(Tickets) # Adding selection to list of Winners Winners.append(winner) # Removing previous selection Tickets.remove(winner) else: w1 = Winners[0] w2 = Winners[1] w3 = Winners[2] w4 = Winners[3] print(f"If your ticket matches {w1}, {w2}, {w3} or {w4} then you have earned a prize!") # Just for fun lets do it as a class from random import choice class Lottery(): def __init__(self, tickets=[]): self.tickets = tickets self.Winners = [] def pick_winners(self): while len(self.Winners) != 4: winner = choice(Tickets) self.Winners.append(winner) self.tickets.remove(winner) def display_winners(self): w1 = self.Winners[0] w2 = self.Winners[1] w3 = self.Winners[2] w4 = self.Winners[3] print(f"If your ticket matches {w1}, {w2}, {w3} or {w4} then you have earned a prize!") # Now to Test it Tickets = ['1', '2', '3', '4', 'b','c','a','d','e','f'] lot_1 = Lottery(Tickets) lot_1.pick_winners() lot_1.display_winners()
211dfc07a85c2017462419e22de6df01bbb54d56
laurengordonfahn/starting_algorithms
/19-caesar-cipher.py
1,771
4.4375
4
# Write a method that takes in an integer `offset` and a string. # Produce a new string, where each letter is shifted by `offset`. You # may assume that the string contains only lowercase letters and # spaces. # # When shifting "z" by three letters, wrap around to the front of the # alphabet to produce the letter "c". # # You'll want to use String's `ord` method and Integer's `chr` method. # `ord` converts a letter to an ASCII number code. `chr` converts an # ASCII number code to a letter. # # You may look at the ASCII printable characters chart: # # http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters # # Notice that the letter 'a' has code 97, 'b' has code 98, etc., up to # 'z' having code 122. # # You may also want to use the `%` modulo operation to handle wrapping # of "z" to the front of the alphabet. # # Difficulty: hard. Because this problem relies on outside # information, we would not give it to you on the timed challenge. :-) def caesar_cipher(x, string): new_string = "" alph = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] ind = 0 swap = 0 for letter in string: if letter not in alph: new_string = new_string + letter else: ind = alph.index(letter) if (ind + x) <= 25: new_string = new_string + alph[ind + x] else: swap = (ind + x) - 26 new_string = new_string + alph[swap] print new_string return new_string print( 'caesar_cipher(3, "abc") == "def": ' + str(caesar_cipher(3, 'abc') == 'def') ) print( 'caesar_cipher(3, "abc xyz") == "def abc": ' + str(caesar_cipher(3, 'abc xyz') == 'def abc') )
d169fa23f347a168f7bd7e003ec3ce0a90bdae69
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/mdlyud002/question3.py
1,006
4.3125
4
#Yudhi Moodley #Assignment 8 - Recursive function to encrypt a message # 09/05/2014 #store the alphabet in a list alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] encryptedString = [] def encryptMessage (rope): # proved base case if rope == '': return 0 # 'z' changes to 'a' not just end elif rope[0] == 'z': encryptedString.append('a') return encryptMessage (rope[1:]) elif rope[0] in alphabet: position = alphabet.index(rope[0]) + 1 encryptedString.append(alphabet[position]) return encryptMessage (rope[1:]) else: # not in lower case add string and recur. encryptedString.append(rope[0]) return encryptMessage (rope[1:]) message = input("Enter a message:\n") encryptMessage (message) print("Encrypted message:") print(''.join(encryptedString))
519e08aea509c0580d61bcfa69f4ef77d6ae7be6
Lev2307/Lev2007.github.io
/lesson8_1.py
571
3.953125
4
sentence ='Fair is foul, and foul is fair: Hover through the fog and filthy air.' alfabet = 'qwertyuiopasdfghjklzxcvbnm' def lower(w): count = 0 for i in w: for a in alfabet.lower(): if i == a: count += 1 return count def upper(w): count = 0 for i in w: for a in alfabet.upper(): if i == a: count += 1 return count print(f'Total uppercase letters in sentence is: {upper(sentence)}') print(f'Total lowercase letters in sentence is: {lower(sentence)}')
5eef8dcbd58c7d81faf52ca1e289981f9bdae92e
JasdeepSidhu13/Python_201
/rename.py
502
3.6875
4
import os def rename_files(): # get file names from a folder file_list = os.listdir(r"C:\Users\Jasdeep\Downloads\alphabet") print(file_list) current_path = os.getcwd() os.chdir(r"C:\Users\Jasdeep\Downloads\alphabet") print("The current path is " + current_path) # for each file, rename file for file_name in file_list: os.rename(file_name,file_name.translate(None,"0123456789")) os.chdir(r"C:\Users\Jasdeep\Downloads\alphabet") rename_files()
b40123aeda1929ac02fb2e522e66eb77f173dc03
ralucas/alg_prac
/graph/dfs.py
1,141
3.609375
4
""" Depth First Search Current implementation expects a Graph as a dictionary with adjacent list, e.g. G = {'A': ['B', 'D'], 'B': ['C'], 'C': ['D', 'A']} """ class DFS: def __init__(self, G): self.clock = 0 self.PP = {} self.visited = [] self.G = G def previsit(self, v): if v not in self.PP: self.PP[v] = {} self.clock += 1 self.PP[v]['pre'] = self.clock def postvisit(self, v): if v not in self.PP: self.PP[v] = {} self.clock += 1 self.PP[v]['post'] = self.clock def explore(self, v): self.visited.append(v) self.previsit(v) for E in self.G[v]: if E not in self.visited: self.explore(E) self.postvisit(v) def run(self): for V, E in self.G.items(): if V not in self.visited: self.explore(V) self.printPP() def printPP(self): for k, v in self.PP.items(): print "--- %s ---" % k print "pre : %d" % v['pre'] print "post : %d" % v['post']
e3e8b91c592f059de141faad062edae8ebd84946
kazaia/AlgoExpert_Solutions
/Recursion/product_sum.py
369
3.890625
4
# Product sum # Time complexity: O(n) where n is the number of elements in the array # Space complexity: O(n). due to recursion def productSum(array, depth = 1): outputSum = 0 for element in array: if type(element) is list: outputSum += productSum(element, depth + 1) else: outputSum += element return outputSum * depth
d56486b565276012ee34629b067af8c806d08e06
okazy/coding
/atcoder/abc097_b.py
173
3.5
4
x=int(input()) a=1 for b in range(2,x): for p in range(2,x): t=b**p if t<=a: continue if x<t: break a=t print(a)
87d5760ca4e92dc65e6665ac760b0ffdf1207552
AnneNamuli/python-code-snippets
/data_structure.py
1,089
4
4
#phone book # (1) Use a list class PhoneBookList(object): ''' This class employs 'list' datastructure in managing phone contacts ''' def __init__(self): self.book = [] def add_contact(self, username, phone_number): record = [username, phone_number] self.book.append(record) def search(self, username): ''' Returna a 'dict' with phone number and number of loop count e.g {"username": "Annie", "phone_number": "93973597302"} ''' count = 0 for u, p in self.book: count += 1 if u == username: result = { "count" : count, "phone_number" : p } return result result = { "count" : count, "phone_number" : None } book1 = PhoneBookList() book1.add_contact("Annie", "09981791384") book1.add_contact("Sammy", "8908247345") book1.add_contact("Rachel", "90374973874") book1.add_contact("Dannie", "798340074320") book1.add_contact("Dennis", "79340290348") book1.add_contact("Anthony", "87209384134") print book1.book #lets search print book1.search("Sammy") print book1.search("Annie") print book1.search("Margreth")
eddd0f9a8ad8407e9c90a48eaee524982ce91701
blei7/Software_Testing_Python
/mlist/flatten_list_prime.py
2,017
4.34375
4
# flatten_list_prime.py def flatten_list_prime(l): """ Flattens a list so that all prime numbers in embedded lists are returned in a flat list Parameters: - l: a list of numbers; largest prime cannot be greater than 1000 Returns: - flat_l: a flat list that has all the prime numbers in l Examples: a = [[2, 3, 4, 5], 19, [131, 127]] flatten_list_prime(a) # returns [2, 3, 5, 19, 131, 127] """ # Raise error if input not a list if type(l) != list: raise TypeError("Input must be a list") #set list of predefined list of prime numbers less than 1000 prime = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83, 89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179, 181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271, 277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379, 383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479, 487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599, 601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701, 709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823, 827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941, 947,953,967,971,977,983,991,997] l_copy = l[:] # flatten list in the loop flat_l = [] while len(l_copy) >= 1: elem = l_copy.pop() if not isinstance(elem, int) and not isinstance(elem, list): raise TypeError("Input must be list of intergers") if isinstance(elem, list): l_copy.extend(elem) else: if elem >= 1000: raise ValueError("Input values exceed 1000. Please limit range of input values to less than 1000.") if elem in prime: flat_l.append(elem) flat_l.sort() return flat_l
d6bdf29b4c3a8296f563a9e661c725e8e5e309cb
MystX65/P.2-Projects
/Choose Your Own Adventure 2.py
38,559
4.09375
4
def intro(): print("You wake up on the side of the beach covered in wet sand with cuts and bruises all over your body." "\nYou slowly stand up withstanding the pain from the wounds on your body." "\nYou can't recall anything" "\nThe light hits your face making you squint." "\nFinally, you see a woman dressed in a beautiful white flowy dress standing behind a palm tree staring at you") woman() def introBroken(): print("You wake up on the side of the beach covered in wet sand with cuts and bruises all over your body." "\nYou slowly stand up withstanding the pain from the wounds on your body." "\nYou suddenly felt a sharp pain in your right arm" "\nYou have no memory of anything that happened" "\nThe light hits your face making you squint." "\nFinally, you see...") print("\n1. a woman dressed in a beautiful white flowy dress standing behind a palm tree staring at you" "\n2. a man in a soldier's uniform staring right at you with a gun held in his hand") n=1 while n == 1: choice = int(input()) if choice == 1: woman() n=0 if choice == 2: man() n=0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def introBasic(): print("\nAt the tree, you see a man in a soldier's uniform staring right at you with a gun held in his hand.") man() def introWithWoman(): print("At the tree, you see a man in a soldier's uniform staring right at you with a gun held in his hand.") manwithGirl() def manwithGirl(): print("Seeing the woman that you are carrying, the man immediately aims his" " gun at your head ordering you to drop the woman." "You..." "\n1. lower the woman down to the ground gently" "\n2. drop her on the ground like the man ordered" "\n3. hold her as a shield and run away" "\n4. use her as hostage and force the man to drop his guns and walk away") n= 1 while n==1: choice = int(input()) if choice == 1: manwithGirl1() n = 0 if choice == 2: manwithGirl2() n = 0 if choice == 3: manwithGirl3() n = 0 if choice == 4: manwithGirl4() n = 0 if choice != 1 or choice != 2 or choice != 3 or choice != 4: print("Invalid. Enter Again.") def manwithGirl4(): print("The man doesn't budge and begins to shoot multiple shots into the woman making her scream in pain." "Instinctively, you drop the woman onto the ground.") manwithGirl2() def manwithGirl3(): print("The man begin to shoot multiple shots into the woman making her scream in pain." "Instinctively, you drop the woman onto the ground.") manwithGirl2() def manwithGirl2(): print("The moment that you drop the woman on the ground she begins to cry and shout." "\nThe man immediately shoots the woman in the face." "\nSurprised, you try to run, but failed miserably and ended up falling on your butt." "\nman: Thomas, what's wrong?" "\nYou:" "\n1. who?" "\n2. Who are you?" "\n3. do I know you?") n = 1 while n ==1: choice = int(input()) if choice == 1: manwithGirl21() n = 0 if choice == 2: manwithGirl22() n = 0 if choice == 3: manwithGirl23() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def manwithGirl23(): print("\nman: Yes, you do. I'm your ally, your friend. Trust me on this. We don't have time for chitchat.") manwithGirl211() def manwithGirl22(): manwithGirl213() def manwithGirl21(): print("\nman(looking concerned): You. Thomas, have you forgotten who you are?" "\n I guess that gas must've messed up your brain" "\nYou: " "\n1. I... I... I don't know" "\n2. What gas?" "\n3. There's no way that I would ever know someone that kills an innocent woman. Who are you?") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl211() n = 0 if choice == 2: manwithGirl212() n = 0 if choice == 3: manwithGirl213() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def manwithGirl213(): print("\nman: Trust me on this, I'm an ally. A friend. There's no point trying to get you to understand now. " "\n You just have to trust me.") manwithGirl211() def manwithGirl212(): print("\nman: Don't worry about it. If I tell you now, you still won't get it. Not in the state you're in at least...") manwithGirl211() def manwithGirl211(): print("\nman(looking around): Either way, we have to get out of here now." "\nThe man reaches his hand down hinting to help you get up." "\nYou:" "\n1. slaps his hand away and try to escape" "\n2. take his hand and follow him") n =1 while n ==1: choice = int(input()) if choice == 1: manwithGirl2111() n = 0 if choice == 2: manwithGirl2112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl2112(): manwithGirl21111() def manwithGirl2111(): print("\nThe man immediately pins you down before you can escape." "\nman(very serious tone): What are you trying to do, Thomas? You remember our orders." "\n If we don't get the cure, we're both dead. You hear me! Dead!" "\n I can't have you go running around attracting those monsters!" "\n Now you better get up and don't even think about running away!" "\nThe man slowly releases his grip allowing you to get up." "\nYou..." "\n1. get up slowly and follow him" "\n2. get up and punch him in the face") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl21111() n = 0 if choice == 2: manwithGirl21112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl21112(): print("\nThe man falls backwards onto his butt." "\nYou..." "\n1. continue to attack him" "\n2. run away") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl211121() n = 0 if choice == 2: manwithGirl211122() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl211122(): manwithGirl211111() def manwithGirl211121(): print("\nUnfortunately, he has anticipated your move and grabs your arm and forces you to the ground." "\nMaking sure that you won't run, he handcuffed you forcing you to follow him.") manwithGirl21111() def manwithGirl21111(): print("\nThe two of you comes to a stop in front of a laboratory further in to the woods." "\nYou open the door and go in slowly." "\nThe man holds out his hand clearly telling you to stay." "\nYou:" "\n1. run away into the laboratory" "\n2. run away into the woods" "\n3. stay") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl211111() n = 0 if choice == 2: manwithGirl211112() n = 0 if choice == 3: manwithGirl211113() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def manwithGirl211113(): manwithGirl2111112() def manwithGirl211112(): manwithGirl211111() def manwithGirl211111(): print("\nThe moment that you begin to run the man takes up his gun and tells you to freeze." "\nYou..." "\n1, continue running" "\n2. stay ") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl2111111() n = 0 if choice == 2: manwithGirl2111112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl2111112(): print("\nYou and the man reach the door with a sign that says 'Research Department'." "\nYou can see a glass encased bottle of liquid inside guarded by many laser beams through the window." "\nYou.." "\n1. go in through the door" "\n2. break the window and go through it.") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl21111121() n = 0 elif choice == 2: manwithGirl21111122() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl21111121(): manwithGirl2111111111() def manwithGirl21111122(): manwithGirl2111111112() def manwithGirl2111111(): print("\nYou keep running anticipating a shot to your head. The bullet never came." "\nYou thought that you would have been dead by now. You continue to run." "\nOut of nowhere, you get tackled. You roll on the ground with the attacker pinning you down." "\nUpon a closer look, you see that it was the same woman that you saw moments ago. " "\nYou..." "\n1. scream for help" "\n2. try to kick her off with your feet") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl21111111() n = 0 if choice == 2: manwithGirl21111112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl21111112(): print("\nYou successfully kick her off you. The next second, the woman went limp with another bullet to the face that came" " from behind you." "\nFrom the entrance you hear the man shout." "\nman: Thomas! come back here!" "\nYou..." "\n1. run to the man" "\n2. continue to run the other way.") choice = int(input()) if choice == 1: manwithGirl211111121() if choice == 2: manwithGirl211111122() def manwithGirl211111121(): manwithGirl211111111() def manwithGirl211111122(): manwithGirl211111112() def manwithGirl21111111(): print("\nBullets come flying over you hitting the woman straight in the face. " "\nThe woman flys backwards allowing you to get up." "\nFrom the entrance you hear the man shout." "\nman: Thomas! come back here!" "\nYou..." "\n1. run to the man" "\n2. continue to run the other way.") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl211111111() n = 0 if choice == 2: manwithGirl211111112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl211111112(): print("\nWithin seconds, another wave of bullets come flying towards you." "\nBefore you can react, three of the bullets hit you in the back and you fall to the ground." "\nBefore dying you hear the man saying something." "\nman: I'm sorry Thomas, it has to be done." "\nFriendly Fire End") def manwithGirl211111111(): print("\nYou meet up with the man. You prepare for him to lecture you or punish you in some ways for" " not listening to him." """\nSurprisingly, the man says nothing except "let's move " """) print("\nYou and the man reach the door with a sign that says 'Research Department'." "\nYou can see a glass encased bottle of liquid inside guarded by many laser beams through the window." "\nYou.." "\n1. go in through the door" "\n2. break the window and go through it.") n=1 while n == 1: choice = int(input()) if choice == 1: manwithGirl2111111111() n = 0 if choice == 2: manwithGirl2111111112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl2111111112(): manwithGirl2111111111111() def manwithGirl2111111111(): print("\nDoor: Locked" "\nImmediately after it says locked, the door requires a password to disable the alarm system." "\nYou..." "\n1. bust the door down" "\n2. smash the machine" "\n3. shoot the lock.") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl21111111111() n = 0 if choice == 2: manwithGirl21111111112() n = 0 if choice == 3: manwithGirl21111111113() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def manwithGirl21111111113(): manwithGirl2111111111111() def manwithGirl21111111112(): manwithGirl211111111111() def manwithGirl21111111111(): print("\nYou tackle the door with all you've got but the door is sealed shut. " "\nThe door does not budge" "\nYou..." "\n1. smash the machine" "\n2. shoot the lock" "\n3. break in through the window") n = 1 while n ==1: choice = int(input()) if choice == 1: manwithGirl211111111111() n = 0 if choice == 2: manwithGirl211111111112() n = 0 if choice == 3: manwithGirl211111111113() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def manwithGirl211111111113(): manwithGirl2111111111111() def manwithGirl211111111112(): manwithGirl2111111111113() def manwithGirl211111111111(): print("\nThe machine screen cracks." "\nYou hear the speaker announcing." "\nSpeaker: Intruder alert! Intruder alert! Self-destruct in t - 5 minutes" "\nYou... " "\n1. break in through the window." "\n2. run out the building." "\n3. shoot the lock.") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl2111111111111() n = 0 if choice == 2: manwithGirl2111111111112() n = 0 if choice == 3: manwithGirl2111111111113() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def manwithGirl2111111111113(): print("\nUnfortunately, the lock is bullet proof, and the bullets ricochet back into you." "\nYou fall upon receiving the bullets in your body." "\nThe man also falls with you." "\nBoth people die of over bleeding." "\nFool's End") def manwithGirl2111111111112(): print("\nYou and the man run out the building with a minute to spare. The building blows up behind you along with the " "\ncure inside it. Knowing that he has failed his mission the man became depressed." "\nYou..." "\n1. comfort him" "\n2. go back to the laboratory to see if the cure has somehow survived") n = 1 while n ==1: choice = int(input()) if choice == 1: manwithGirl21111111111121() n = 0 if choice == 2: manwithGirl21111111111122() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl21111111111121(): print("\nman: GET AWAY FROM ME!" "\n You slowly walk backwards" "\n The man gets up with tears in his face" "\n man: Look at what you've done" "\n He holds up his gun pointing directly at you and he shoots." "\n You feel the pain and collapsed on the floor." "\n Before passing out, you hear another gunshot and see that the man in front of you has also fallen." "\n You die." "\n Coward's End") def manwithGirl21111111111122(): print("\nYou walk back to the laboratory without the man. You can see debris flung everywhere." "\nThere are many unexplained body parts which you don't even dare think about where they come from." "\nIn the center of the explosion lies a shiny bottle of liquid. The cure." "\nYou go in to retrieve the cure. Almost immediately after retrieving the cure, a helicopter appears." "\nYou hear the man screaming something about failing the mission." "\nThe next second, you hear a gunshot. When you arrive at where the man is, the man has suicided." "\nThe helicopter lowers its ladder and you climbed on." "\nYou flew away from the mysterious island." "\nLone Hero Ending") def manwithGirl2111111111111(): print("\nYou go into the lab and you see the cure." "\nThe man tells you to wait." "\nYou..." "\n1. wait" "\n2. reach for the cure.") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl21111111111111() n = 0 if choice == 2: manwithGirl21111111111112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl21111111111112(): print("\nBefore reaching the cure, the gatling gun appears from the side of the wall and begins to shoot" " around the room. " "\nYour head gets lodged with many bullets and you die." "\nFool's End") def manwithGirl21111111111111(): print("\nThe man reaches into his pocket and throws a modified EMP that shuts down the security inside the room." "\nHe grabs the cure and signals you to follow him out." "\nSpeaker: Self-destruct in t - 3 minutes" "\nAs you get closer to the entrance, you see a pack of creatures that looks familiar to you." "\nYou recognize the pale face and the flowy white dress. " "\nYou see a pack of identical woman standing in front of the entrance blocking your only way out." "\nThe man turns around and sees another hoard of women getting closer." "\nYou..." "\n1. take the cure and push the man into the hoard blocking the entrance." "\n2. volunteer to distract the hoard while the man gets outside") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl211111111111111() n = 0 if choice == 2: manwithGirl211111111111112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl211111111111112(): print("\nBefore the man can stop you, you walk into the crowd of women where they begin to grab you." "\nYou feel the pain of your body ripping into shreds." "\nYou die a horrendous death." "\nHero End") def manwithGirl211111111111111(): print("\nSurprised the man falls forward into the crowd creating a space for you to escape." "\nYou run for it out into the forest." "\nYou continue running without looking behind and you hear an explosion behind you as " " debris bloody body parts from the explosion come shooting toward you." "\nYou reach your original waking place where you see a helicopter lowering its ladder to you." "\nInstinctively, you climbed on to the ladder and you fly away from this horrifying island." "\nSurvivalist's End") def manwithGirl1(): print("\nAs you lower the woman down, the woman eyes spring open and she bites your neck" "\nBefore long, you hear a gun shot, and you see the woman drop dead." "\nHowever, when you try to get up, you can't." "\nYou realize you are turning extremely pale like the girl before you." "\nYou feel the man's gun beginning to raise again." "\nYou..." "\n1. run away" "\n2. stay there and await your imminent death") n = 1 while n == 1: choice = int(input()) if choice == 1: manwithGirl11() n = 0 if choice == 2: manwithGirl12() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def manwithGirl11(): print("\nBefore the man can get his gun up to your head, you sprint away." "\nYou hear shots fired behind you." "\nAs you run, you realize how fast you have become and that you crave brains.") print("\nYou live out the rest of your undead life as a zombie." "\nZombie Ending") def manwithGirl12(): print("\nYou remain motionless." "\nYou can hear the man saying something." "\nman: Goodbye friend" "\nYou died" "\nHuman Ending") def woman(): print("\nYou wipe the sand that was on your face and rub your eyes in disbelief." "\nHappy to finally see another living soul around the area, you..." "\n1. run toward her" "\n2. wave at her telling her to get close" "\n3. slowly back away and go back to the tree") n = 1 while n ==1: choice = int(input()) if choice == 1: woman1() n = 0 if choice == 2: woman2() n = 0 if choice == 3: woman3() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def woman3(): introBasic() def woman2(): print("\nShe seems to not hear you." "\nYou..." "\n1. continue to wave at her telling her to get close." "\n2. run towards her." "\n3. slowly back away and go back to the tree.") n = 1 while n == 1: choice = int(input()) if choice == 1: woman21() n = 0 if choice == 2: woman22() n = 0 if choice == 3: woman23() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def woman23(): introBasic() def woman22(): woman1() def woman21(): print("\nShe still doesn't budge." "\nYou... " "\n1. continue doing the same thing" "\n2. run towards her." "\n3. slowly back away and go back to the tree.") n = 1 while n ==1: choice = int(input()) if choice == 1: woman211() n = 0 if choice == 2: woman212() n = 0 if choice == 3: woman213() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def woman213(): introBasic() def woman212(): woman1() def woman211(): print("\n Instead of walking towards you, she flew towards you as you" " see the beast that had just tackled her from behind." "\nLanding right next to you, your feet get soaked in the fresh blood oozing out of the woman's head" "\nYou..." "\n1. check the woman." "\n2. run away.") n = 1 while n == 1: choice = int(input()) if choice == 1: woman2111() n = 0 if choice == 2: woman2112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def woman2111(): print("\nUpon checking the woman, the woman, obviously dead, has a knife under her sleeves." "\nYou..." "\n1. take the knife and run." "\n2. take the knife and fight.") n = 1 while n == 1: choice =int(input()) if choice == 1: woman21111() n = 0 if choice == 2: woman21112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def woman21112(): print("\nYou turn around and you see the beast ready to jump at you." "\nYou..." "\n1. throw the knife at it." "\n2. wait for the tiger to jump forward before you stab it in mid-air.") n = 1 while n ==1: choice = int(input()) if choice == 1: woman211121() n = 0 if choice == 2: woman211122() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def woman211122(): print("\nThe beast jumps forward, and your knife goes through its belly." "\nThe beast cowards in fear as it runs off dripping a yellow liquid with the knife still attached " " to its bleeding stomach." "\nYou..." "\n1. investigate the liquid" "\n2. go back to the tree") n = 1 while n == 1: choice = int(input()) if choice == 1: woman2111221() n = 0 if choice == 2: woman2111222() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def woman2111222(): introBasic() def woman2111221(): print("\nYou bend down on your knees and scoop up the liquid with your right hand." "\nThe moment that the liquid touches your right hand, your hand begins to melt." "\nOut of shock, you faint.") introBroken() def woman211121(): print("\nThe handle of the knife hits the beast directly in the head" " and angers the beast." "\nThe beast jumps forward and bites your right arm off." "\nYou black out immediately.") introBroken() def woman21111(): print("\nUnfortunately, the time that you take checking the woman allowed the beast to move in on you. " "\nBefore you are able to run, the beast bite off your right arm" "\nThe extreme pain causes you to faint immediately.") introBroken() def woman2112(): woman111131() def woman1(): print("\nAbout twenty feet behind the mysterious woman, you see a beast with sharp fangs preparing to leap forward." "\nYou..." "\n1. yell at her to get away" "\n2. sprint the rest of the way and tackle her out of the beast's path" "\n3. turn the other way and run") n = 1 while n == 1: choice = int(input()) if choice == 1: woman11() n = 0 if choice == 2: woman12() n = 0 if choice == 3: woman13() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def woman13(): woman111131() def woman12(): print("\nYou succesfully saved the woman's life." "\nGetting up from the ground, you feel her holding on to your right wrist." "\nYou know that the beast will come back for another attack fast, so" " you turned around trying to hurry the woman to get up as well." "\nThe woman got up; however, she won't run with you." "\nYou..." "\n1. carry her on your back and start running." "\n2. let go of her and run." "\n3. stay there and fight.") n = 1 while n == 1: choice = int(input()) if choice == 1: woman121() n = 0 if choice == 2: woman122() n = 0 if choice == 3: woman123() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def woman122(): woman111131() def woman123(): print("\nAs you are about to make your attack against the beast, the woman, with a knife that must have been hidden in her dress, cuts off your right arm." "\nOut of shock, you black out immediately.") introBroken() def woman121(): print("\nAs you are about to scoop her up with your other arm, the woman begins to scream and shout." "\nYou..." "\n1. knock her out with your fists." "\n2. abandon her and run away.") n = 1 while n == 1: choice =int(input()) if choice == 1: woman1211() n = 0 if choice == 2: woman1212() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def woman1212(): woman111131() def woman1211(): print("\nShe instantly falls silent, and you ran back to the tree before the beast notices that you had " "escaped with the girl.") introWithWoman() def woman11(): print("\nShe seems to not hear you." "\nYou..." "\n1. continue to yell at her" "\n2. turn the other way and run") n = 1 while n == 1: choice = int(input()) if choice == 1: woman111() n = 0 if choice == 2: woman112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def woman112(): woman111131() def woman111(): print("\nShe still doesn't budge." "\nYou watch her get torn into pieces." "\n1. Fight the monster" "\n2. turn the other way and run") n = 1 while n == 1: choice = int(input()) if choice == 1: woman1111() n = 0 if choice == 2: woman1112() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def woman1112(): woman111131() def woman1111(): print("\nThe beast is about to attack." "\nYou..." "\n1. get ready to dodge and then attack full on" "\n2. attack it before it can attack you" "\n3. use the dead woman as a shield and hit the beast with your fist" "\n4. turn the other way and run") n = 1 while n == 1: choice = int(input()) if choice == 1: woman11111() n = 0 if choice == 2: woman11112() n = 0 if choice == 3: woman11113() n = 0 if choice == 4: woman11114() n = 0 if choice != 1 or choice != 2 or choice != 3 or choice != 4: print("Invalid. Enter Again.") def woman11114(): woman111131() def woman11112(): print("\nYou run straight towards the beast preparing to punch its face with all you've got." "\nUnfortunately, the beast is faster." "\nIt pins you down with ease, and it bites off your right arm" "\nImmediately, you blackout") introBroken() def woman11113(): print("\nAs you reach down to grab the dead woman, the beast lunges at you." "\nFortunately, you are able to get to the woman in time" "\nYou hold the woman up, and the beast bites on the woman once more," " and it gets its teeth stuck inside the woman" "\nYou..." "\n1. run away" "\n2. attack it with all you've got") n = 1 while n == 1: choice = int(input()) if choice == 1: woman111131() n = 0 if choice == 2: woman111132() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def woman111131(): print("\nThe moment that you started running away, the beast stops chasing you." "\nRelieved, you go back to where you started.") introBasic() def woman11111(): print("\nThe beast lunges at you but you were prepared." "\nYou..." "\n1. roll under" "\n2. dodge to the right" "\n3. dodge to the left" "\n4. jump back") n = 1 while n == 1: choice = int(input()) if choice == 1: woman111111() n = 0 if choice == 2: woman111112() n = 0 if choice == 3: woman111113() n = 0 if choice == 4: woman111114() n = 0 if choice != 1 or choice != 2 or choice != 3 or choice != 4: print("Invalid. Enter Again.") def woman111111(): print("\nYou sucessfully dodge the attack; however, the tail, covered in sharp razor blades, grazes your face" " and you begin to feel sleepy" "\nYou..." "\n1. continue to fight" "\n2. run away" "\n3. give up on fighting") n = 1 while n ==1: choice = int(input()) if choice == 1: woman1111111() n = 0 if choice == 2: woman1111112() n = 0 if choice == 3: woman1111113() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def woman1111112(): print("\nYou run away as fast as you can, but you continue to get dizzier." "\nBefore you know it, the lights are out") intro() def woman1111111(): print("\nYou jump onto the beast's back and you started pounding him with your bare fist" "; however, the longer that you are in physical contact with the beast, the sleepier you get," "\nBefore you know it, the lights are out") intro() def woman1111113(): print("\nThe beast suddenly stops in front of you when it tries to attack once more." "\nIt sniffs you, and then it turns and walks away." "\nYou..." "\n1. follow it" "\n2. stay where you are and rest") n = 1 while n == 1: choice = int(input()) if choice == 1: woman11111131() n = 0 if choice == 2: woman11111132() n = 0 if choice != 1 or choice != 2: print("Invalid. Enter Again.") def woman11111131(): print("\nSensing animosity towards it, the beast turns around and jumps at you." "\nUnable to react fast enough, your right hand gets bitten off" "\nAlmost instantaneously, you fainted.") introBroken() def woman11111132(): print("\nBefore you know it, you fell asleep") intro() def woman111112(): print("\nYou successfully dodge the attack; however, moving too fast, you hit the palm tree head first " "causing you to faint.") intro() def woman111113(): print("\nYou successfully dodge the attack and you jumped onto its back " "and you started pounding him with your bare fist" "; however, the longer that you are in physical contact with the beast, the sleepier you get," "\nBefore you know it, the lights are out") intro() def woman111114(): print("\nYou jump backwards. Unfortunately, the jump is too short and your right arm gets bitten off." "\nInstantaneously, you faint") introBroken() def woman111132(): woman1111111() def main(): print("FORGOTTEN") gender = raw_input("\nMale or Female:") if gender.lower() in ['male']: print("") else: print("Too bad, you're a male now.") intro() def man(): print("You walk up to the man quietly" "The man follows you with his eyes continuing to stare at you." "As you get closer, the man begins to lift up his gun" "You..." "\n1. stop and raise your hand showing that you have no concealed weapon." "\n2. run away as fast as possible." "\n3. stop in your track." "\n4. jump forward trying to grab hold of the gun before he aims it at you.") n = 1 while n == 1: choice = int(input()) if choice == 1: man1() n = 0 elif choice == 2: man2() n = 0 elif choice == 3: man3() n = 0 elif choice == 4: man4() n = 0 if choice != 1 or choice != 2 or choice != 3 or choice != 4: print("Invalid. Enter Again.") def man4(): manwithGirl21112() def man3(): man1() def man2(): manwithGirl2111() def man1(): print("The man lowers his gun and walks toward you." "The man speaks." "\nman: Thomas. Are you okay?" "\nConfused, you reply" "\n1. who?" "\n2. Who are you?" "\n3. do I know you?") n = 1 while n ==1: choice = int(input()) if choice == 1: manwithGirl21() n = 0 if choice == 2: manwithGirl22() n = 0 if choice == 3: manwithGirl23() n = 0 if choice != 1 or choice != 2 or choice != 3: print("Invalid. Enter Again.") def mn(): print("Staring at two different views on your window ledge" "\ncoffee is going cold, it's like time froze" "\nthere you go wishing floating down our wishing well" "\nIt's like I'm always causing trouble, causing hell" "\nI didn't mean to put you throuhg it I can tell" "\nWe can not sweep this under the carpet" "\n" "\nI hope that I can turn back the time" "\nto make it all alright, all alright for us" "\nI promise to make a new world, for us two" "\nwith you in the middle" "\n" "\nLying down beside you what's going through your head" "\nthe silence in the air, felt like my soul froze" "\nam i just overthinking feelings I conceal" "\nThis gut feeling I'm trying to get off me as well" "\nI hope we find our missing pieces and just chill" "\nWe can not sweep it under the carpet" "\n" "\nI hope that I can turn back the time" "\nto make it all alright, all alright for us" "\nI promise to make a new world, for us two" "\nwith you in the middle") main()
62d8394afac9d7629e3eb056a0238b4dfa6538c1
Jaimeen235/CS100-Python
/Homework8/HW8_JaimeenSharma.py
2,295
4
4
''' Jaimeen Sharma CS 100 2020F 033 HW 8, Octomber 26, 2020. ''' # Question 1: def twoWords(length, firstLetter): while True: oneWord = input('Enter a '+ str(length)+'-letter word please: ') if length == len(oneWord): break while True: twoWord = input('Enter A word beginning with ' + firstLetter+ ' please: ') if twoWord[0] == firstLetter.upper() or twoWord[0] == firstLetter.lower(): break return [oneWord,twoWord] print(twoWords(4,'B')) # Question 2: def twoWordsV2(length, firstLetter): oneWord = '' while int(length) != len(oneWord): oneWord = input('Enter a '+ str(length)+'-letter word please: ') twoWord = '' while twoWord[0] != firstLetter: twoWord = input('Enter A word beginning with ' + firstLetter + ' please: ') return [oneWord,twoWord] print(twoWordsV2(4,'B')) # Question 3 def enterNewPassword(): while True: inputStr = input("Enter password: ") if 15 < len(inputStr) < 8 or sum(str.isdigit(c) for c in inputStr) < 1: print("Password required minimum 8 characters ") continue else: print("The password is valid.") break enterNewPassword() # Question 4 import random def GuessNumber(): print("I'm thinking of a number in the range 0-50. You have five tries to guess it.") number = random.randint(1, 50) countValue = 1 print("Guess", countValue,end="") userToguess = int(input("? ")) while number != userToguess: if (countValue == 5 or userToguess == number): print("Sorry you have used all tries..the correct number is ", number) break; if userToguess < number: print(userToguess,"is too low") countValue = countValue + 1 print("Guess", countValue,end="") userToguess = int(input("? ")) elif userToguess > number: print(userToguess,"is too high") countValue = countValue + 1 print("Guess", countValue,end ="") userToguess = int(input("? ")) else: print ("you are right! I was thinking of ", userToguess,"!") break GuessNumber()
7b651a859123a0f2f7a704f28436e9f6868aaa52
mushfiqulIslam/tkinterbasic
/input.py
712
3.96875
4
import tkinter from tkinter import * def show(): label.config(text="Name is " +input.get() +"\n Email is "+input2.get()) print(input.get()) if __name__ == "__main__": root = tkinter.Tk() root.title("Window") root.geometry("200x200") label = Label(root, text="Name") label.grid(row=0, column=0, pady=2) #Input input = Entry(root) input.grid(row=0, column=1, pady=2)#pack(side=RIGHT) label2 = Label(root, text="Email") label2.grid(row=1, column=0, pady=2) #Input input2 = Entry(root) input2.grid(row=1, column=1, pady=2) btn = Button(root, text="show", background='blue', command=show) btn.grid(row=2, column=1, pady=2) root.mainloop()
e56045fb184f429205930f9e80056e7a82b00977
jeffwen/Interesting_Problems
/primefactorization.py
945
4.0625
4
# Given a number, return the prime factors of the number. The question required the use of a class class PrimeFactorizer: def __init__(self, n): self.n = n self.factors = [] d = 2 while self.n > 1: while self.n%d == 0: # if d is a factor of the number, then keep appending it to the factor list self.n /= d self.factors.append(d) # increment by 1 when the remainder is no longer zero d += 1 # not strictly needed as incrementing will eventually find the prime factors; however, this speeds up the calculations # the remaining n is appended as it is a prime number if d*d > self.n: if self.n > 1: self.factors.append(self.n) break # the break is necessary to stop the appending or else it will go until d == n and n !> 1
1edb6d292fbb55f3d55713e8616c6a682d27febd
luohuizhang/gilbert
/gilbert3d.py
4,667
3.5
4
#!/usr/bin/env python import sys def sgn(x): return (x > 0) - (x < 0) def gilbert3d(x, y, z, ax, ay, az, bx, by, bz, cx, cy, cz): """ Generalized Hilbert ('Gilbert') space-filling curve for arbitrary-sized 3D rectangular grids. """ w = abs(ax + ay + az) h = abs(bx + by + bz) d = abs(cx + cy + cz) (dax, day, daz) = (sgn(ax), sgn(ay), sgn(az)) # unit major direction ("right") (dbx, dby, dbz) = (sgn(bx), sgn(by), sgn(bz)) # unit ortho direction ("forward") (dcx, dcy, dcz) = (sgn(cx), sgn(cy), sgn(cz)) # unit ortho direction ("up") # trivial row/column fills if h == 1 and d == 1: for i in range(0, w): print x, y, z (x, y, z) = (x + dax, y + day, z + daz) return if w == 1 and d == 1: for i in range(0, h): print x, y, z (x, y, z) = (x + dbx, y + dby, z + dbz) return if w == 1 and h == 1: for i in range(0, d): print x, y, z (x, y, z) = (x + dcx, y + dcy, z + dcz) return (ax2, ay2, az2) = (ax/2, ay/2, az/2) (bx2, by2, bz2) = (bx/2, by/2, bz/2) (cx2, cy2, cz2) = (cx/2, cy/2, cz/2) w2 = abs(ax2 + ay2 + az2) h2 = abs(bx2 + by2 + bz2) d2 = abs(cx2 + cy2 + cz2) # prefer even steps if (w2 % 2) and (w > 2): (ax2, ay2, az2) = (ax2 + dax, ay2 + day, az2 + daz) if (h2 % 2) and (h > 2): (bx2, by2, bz2) = (bx2 + dbx, by2 + dby, bz2 + dbz) if (d2 % 2) and (d > 2): (cx2, cy2, cz2) = (cx2 + dcx, cy2 + dcy, cz2 + dcz) # wide case, split in w only if (2*w > 3*h) and (2*w > 3*d): gilbert3d(x, y, z, ax2, ay2, az2, bx, by, bz, cx, cy, cz) gilbert3d(x+ax2, y+ay2, z+az2, ax-ax2, ay-ay2, az-az2, bx, by, bz, cx, cy, cz) # do not split in d elif 3*h > 4*d: gilbert3d(x, y, z, bx2, by2, bz2, cx, cy, cz, ax2, ay2, az2) gilbert3d(x+bx2, y+by2, z+bz2, ax, ay, az, bx-bx2, by-by2, bz-bz2, cx, cy, cz) gilbert3d(x+(ax-dax)+(bx2-dbx), y+(ay-day)+(by2-dby), z+(az-daz)+(bz2-dbz), -bx2, -by2, -bz2, cx, cy, cz, -(ax-ax2), -(ay-ay2), -(az-az2)) # do not split in h elif 3*d > 4*h: gilbert3d(x, y, z, cx2, cy2, cz2, ax2, ay2, az2, bx, by, bz) gilbert3d(x+cx2, y+cy2, z+cz2, ax, ay, az, bx, by, bz, cx-cx2, cy-cy2, cz-cz2) gilbert3d(x+(ax-dax)+(cx2-dcx), y+(ay-day)+(cy2-dcy), z+(az-daz)+(cz2-dcz), -cx2, -cy2, -cz2, -(ax-ax2), -(ay-ay2), -(az-az2), bx, by, bz) # regular case, split in all w/h/d else: gilbert3d(x, y, z, bx2, by2, bz2, cx2, cy2, cz2, ax2, ay2, az2) gilbert3d(x+bx2, y+by2, z+bz2, cx, cy, cz, ax2, ay2, az2, bx-bx2, by-by2, bz-bz2) gilbert3d(x+(bx2-dbx)+(cx-dcx), y+(by2-dby)+(cy-dcy), z+(bz2-dbz)+(cz-dcz), ax, ay, az, -bx2, -by2, -bz2, -(cx-cx2), -(cy-cy2), -(cz-cz2)) gilbert3d(x+(ax-dax)+bx2+(cx-dcx), y+(ay-day)+by2+(cy-dcy), z+(az-daz)+bz2+(cz-dcz), -cx, -cy, -cz, -(ax-ax2), -(ay-ay2), -(az-az2), bx-bx2, by-by2, bz-bz2) gilbert3d(x+(ax-dax)+(bx2-dbx), y+(ay-day)+(by2-dby), z+(az-daz)+(bz2-dbz), -bx2, -by2, -bz2, cx2, cy2, cz2, -(ax-ax2), -(ay-ay2), -(az-az2)) def main(): width = int(sys.argv[1]) height = int(sys.argv[2]) depth = int(sys.argv[3]) if width >= height and width >= depth: gilbert3d(0, 0, 0, width, 0, 0, 0, height, 0, 0, 0, depth) elif height >= width and height >= depth: gilbert3d(0, 0, 0, 0, height, 0, width, 0, 0, 0, 0, depth) else: # depth >= width and depth >= height gilbert3d(0, 0, 0, 0, 0, depth, width, 0, 0, 0, height, 0) if __name__ == "__main__": main()
af4d4c2724c24b72fa4ba1b5cba89e66547ca6c7
nixawk/hello-python3
/PEP/pep-484-04-Type Definition Syntax.py
729
3.890625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # Type Definition Syntax # The syntax leverages PEP 3107-style annotations with a number of # extensions described in sections below. In its basic form, # type hinting is used bt filling function annotation slots with # classes: def greeting(name: str) -> str: return "Hello " + name # This states that the expected type of the name argument is str. # Analogically, the expected return type str is str. # Expressions whose type is a subtype of a specfic argument type # are also accepted for that argument. if __name__ == '__main__': print(greeting('Python')) # https://www.python.org/dev/peps/pep-3107 # https://www.python.org/dev/peps/pep-0484/#type-definition-syntax
ebb952aeab71fabeff076a4675af32443a66447e
mayur12891/Demo2020
/filereadwrite.py
675
3.875
4
# File read write # w - write # r - read # r+ - read and write # a - append # Below code will create/write a new file and read a file # By default it will save the file in same directory location # This will added to test Git. # This line is again added to test Git. # This is added to reflect in deep branch. my_file = open("firstfile.txt", "w") my_file.write("this is first line" + "\n") my_file.write("this is second line") my_file.close() file = open("firstfile.txt", "r") print(file.read()) #this will read full file #print(file.readline()) #this will read code line by line #print(file.readlines()) #this will store the content in a list file.close()
e302ead5bf5c715224e0033dd07280bad8c818df
inderbhushanjha/Machine_Learning
/data_program.py
1,343
3.625
4
import numpy as np import pandas as pd import sklearn from sklearn import linear_model import matplotlib.pyplot as pyplot import pickle from matplotlib import style data=pd.read_csv("student-mat.csv", sep=";") #print(data.head()) data=data[["G1","G2","G3","absences","failures"]] #print(data.head()) predict="G3" x=np.array(data.drop([predict],1)) y=np.array(data[predict]) x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x,y,test_size=0.1) best=0 '''for best_score in range (50): x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x,y,test_size=0.1) linear = linear_model.LinearRegression() linear.fit(x_train,y_train) acc = linear.score(x_test,y_test) print(acc) if acc > best : with open("saved_model.pickle","wb") as f: pickle.dump(linear,f)''' pickle_input=open("saved_model.pickle", "rb") linear = pickle.load(pickle_input) print("coefficient : ", linear.coef_) print("intercept : ",linear.intercept_) prediction = linear.predict(x_test) for x in range (len(prediction)): print(prediction[x], x_test[x], y_test[x]) #Ploting things x_axis_plot="G1" y_axis_plot=predict style.use("ggplot") pyplot.scatter(data[x_axis_plot],data[y_axis_plot]) pyplot.xlabel="First Term Grade" pyplot.ylabel="Final Term Grade" pyplot.show()
3cd45d4bed04ef6478d408f966d4623a364d8fc4
WuAlin0327/python3-notes
/面向对象编程/day3/绑定方法与非绑定方法.py
320
3.640625
4
class Foo: def __init__(self,name): self.name = name def tell(self):# 绑定到对象的函数 print('name:%s'%self.name) @classmethod def func(cls): #cls=Foo 绑定到类的方法 print(cls) @staticmethod def func1(x,y):#类中的普通函数 print(x+y) f = Foo('wualin') Foo.func1(1,2) f.func1(1,3)
23e4f96eb10524a3d27a449e2116354b882b43f8
gracejpw/play
/markdown-musings/test1.py
430
3.609375
4
import markdown text = """# Heading 1 Some words. ## Heading two More words, followed by a list. 1. Plan A 2. Plan B The list *pros:* * Plans are **good** This list has _cons:_ * It lacks a Plan C """ xhtml = markdown.markdown(text) print(xhtml) print("----------") html5 = markdown.markdown(text, output_format='html5') if xhtml == html5: print("html5 output is the same as xhtml output") else: print(html5)
596eab16cd05da96284b65dd7bb85cf051929ce9
aleranaudo/SizeItUp
/ran.py
211
3.734375
4
import random print(random.random()*100) import random myList=["red","green","blue","yellow","purple",1,2,3,] print(random.choice(myList)) import random for i in range(3): print(random.randrange(0,100))
34aa6e4ebff9a4306f30ca9a5f681a94292f30f5
chumbalayaa/6.935Final
/libs/yql-finance-0.1.0/build/lib/yql/request.py
1,062
3.578125
4
import requests class Request(object): """Class is responsible for prepare request query and sends it to YQL Yahoo API.""" parameters = { 'q': '', 'format': 'json', 'diagnostics': 'false', 'env': 'store://datatables.org/alltableswithkeys', 'callback': '' } api = 'https://query.yahooapis.com/v1/public/yql' def prepare_query(self, symbol, start_date, end_date): """Method returns prepared request query for Yahoo YQL API.""" query = \ 'select * from yahoo.finance.historicaldata where symbol = "%s" and startDate = "%s" and endDate = "%s"' \ % (symbol, start_date, end_date) return query def send(self, symbol, start_date, end_date): """Method sends request to Yahoo YQL API.""" query = self.prepare_query(symbol, start_date, end_date) self.parameters['q'] = query response = requests.get(self.api, params=self.parameters).json() results = response['query']['results']['quote'] return results
b296b6f04b924a99b4111d5376ed1dd543fff568
jxie0755/Learning_Python
/LeetCode/LC142_linked_list_cycle_ii.py
1,525
3.75
4
""" https://leetcode.com/problems/linked-list-cycle-ii/ LC142 Linked List Cycle II Medium Given a linked list, return the node where the cycle begins. If there is no cycle, return null. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. Note: Do not modify the linked list. """ from typing import * from A01_ListNode import * class Solution_A: def detectCycle(self, head: ListNode) -> ListNode: """ Time O(N), Space O(N), use set to search existing node ListNode instance is hashable, this method search at O(1), and will not break down the original linked list """ ss = set() while head: if head.next in ss: return head.next else: ss.add(head) head = head.next return None if __name__ == "__main__": # Use is instead of == to avoid max recursion when comparing cycling linked list testCase = Solution_A() L1 = genNode([3, 2, 0, 4]) L1.next.next.next.next = L1.next # 3 2 0 4 # a b c d # d->b assert testCase.detectCycle(L1) is L1.next, "Example 1" L2 = genNode([1, 2]) L2.next.next = L2 # 1 2 # a b # b->a assert testCase.detectCycle(L2) is L2, "Example 2" L3 = genNode([1]) assert not testCase.detectCycle(L3), "Edge 1, no cycle" print("All passed")
01b719174bd5b1bc7d189fc2e29988ea7cd2c3e6
jacchkiki/kiki-python
/before/0601.py
312
3.6875
4
print "kiki" y=10 print "kiki is %d years old."% y x=range(0,3) name=["xuan","kiki","will"] for number in range(0,3): print name[number] for number in range(0,3): if name[number]=="kiki": print name[number] for number1 in range(0,3): if name [number1]!="kiki": print name[number1]
0604b688b99ad5edb5f094e1b6bfb5dd3bcb835e
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/edabit/_Edabit-Solutions-master/First and Last Index/solution.py
373
3.828125
4
def char_index(word, char): output = [] for i in range(len(word)): if word[i] == char: output.append(i) elif char not in word: return None output.sort() if len(output) == 1: output.append(output[0]) if len(output) > 2: for i in range(1,len(output)- 1): output.pop(i) return output
ec34abe668c3982db9ff2b43aa6a5e0e8a485c5e
Taoge123/OptimizedLeetcode
/LeetcodeNew/LinkedList/LC_203_Remove_Linked_List_Elements.py
1,147
3.84375
4
""" Remove all elements from a linked list of integers that have value val. Example: Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5 """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements(self, head, val): dummy = ListNode(-1) dummy.next = head pointer = dummy while (pointer.next): if pointer.next.val == val: pointer.next = pointer.next.next else: pointer = pointer.next return dummy.next class Solution2: def removeElements(self, head, val): dummy = ListNode(-1) dummy.next = head next = dummy while next != None and next.next != None: if next.next.val == val: next.next = next.next.next else: next = next.next return dummy.next class Solution3: def removeElements(self, head, val): if not head: return head head.next = self.removeElements(head.next, val) return head.next if head.val == val else head
f52571826a5c390887d29faa43e8202b7eebeca1
diditaditya/geocalc
/shallow_fdn/src/model/earth_pressure_coeff.py
3,203
4.1875
4
"""Import trigonometry functionality from math module.""" from math import sin, cos, radians, sqrt def at_rest(eff_friction): "This function returns at rest pressure based on Jacky, 1944." return 1 - sin(radians(eff_friction)) def at_rest_2(eff_friction): "This function returns at rest pressure based on Brooker and Ireland, 1965." return 0.95 - sin(radians(eff_friction)) def rankine_active(eff_friction, backfill_inclination=0): """This function returns active earth pressure based on Rankine for granular soil, where the wall is assumed to be vertical. The backfill inclination is taken with respect to horizontal.""" phi = radians(eff_friction) #trigonometry in math module uses radians alpha = radians(backfill_inclination) reducer = sqrt((cos(alpha))**2 - (cos(phi))**2) upper_right = cos(alpha) - reducer lower_right = cos(alpha) + reducer return cos(alpha) * (upper_right/lower_right) def rankine_passive(eff_friction, backfill_inclination=0): """This function returns passive earth pressure based on Rankine for granular soil, where the wall is assumed to be vertical. The backfill inclination is taken with respect to horizontal.""" phi = radians(eff_friction) #trigonometry in math module uses radians alpha = radians(backfill_inclination) reducer = sqrt((cos(alpha))**2 - (cos(phi))**2) upper_right = cos(alpha) + reducer lower_right = cos(alpha) - reducer return cos(alpha) * (upper_right / lower_right) def coulomb_active(eff_friction, wall_angle, backfill_inclination=0, wall_friction_coeff=2/3): """This function returns active earth pressure based on Coulomb for granular soil. The wall angle is 90 for vertical wall, while the backfill is taken with respect to horizontal hence 0 is for horizontal backfill.""" phi = radians(eff_friction) beta = radians(wall_angle) alpha = radians(backfill_inclination) delta = radians(wall_friction_coeff*eff_friction) top_eq = (sin(beta + phi))**2 bottom_right = (1 + sqrt((sin(phi+delta)*sin(phi-alpha))/(sin(beta-delta)*sin(alpha+beta))))**2 bottom_eq = (sin(beta))**2 * sin(beta-delta) * bottom_right return top_eq/bottom_eq def coulomb_passive(eff_friction, wall_angle, backfill_inclination=0, wall_friction_coeff=2/3): """This function returns passive earth pressure based on Coulomb for granular soil. The wall angle is 90 for vertical wall, while the backfill is taken with respect to horizontal hence 0 is for horizontal backfill.""" phi = radians(eff_friction) beta = radians(wall_angle) alpha = radians(backfill_inclination) delta = radians(wall_friction_coeff*eff_friction) top_eq = (sin(beta - phi))**2 bottom_right = (1 - sqrt((sin(phi+delta)*sin(phi+alpha))/(sin(beta+delta)*sin(alpha+beta))))**2 bottom_eq = (sin(beta))**2 * sin(beta+delta) * bottom_right return top_eq/bottom_eq # friction_angle = float(input("Effective angle of internal friction: ")) # print("Coulomb active coefficient: {}".format(coulomb_active(friction_angle, 90))) # print("Coulomb passive coefficient: {}".format(coulomb_passive(friction_angle, 90)))
a96c376d2eca98dab4979f1f60251bdd5f697bc8
tddontje/wordsearch
/WordSearch.py
16,805
4.09375
4
""" WordSearch - This program searches a given grid of letters for words contained in a given dictionary file. * The grid of letters will be randomly generated. * The search for words have the following constraints: * Words will be search forwards, backwards, up, down and diaganol * Words will not be tested for wrapping of the edge of grid * Dictionary will be given as a file (defaulting to words.txt) """ import unittest import os.path import argparse import string import random class WordSearch(): """ WordSearch: __init__ : setup object with defined grid find_words : find words in grid that matches dictionary """ def __init__(self, dict_file: str, xsize: int = 15, ysize: int = 15): """ Setup WordSearch object * initialize random grid using xsize and ysize values * load dictionary file to be used in word search :param dict_file: Filename of dictionary to load :param xsize: X-axis size of word grid :param ysize: Y-axis size of word grid """ print("initializing WordSearch") self.xsize = xsize self.ysize = ysize self.words_dictionary = self._load_dictionary(dict_file) self.letter_grid = self._generate_grid() self.found_words = set() def _load_dictionary(self, dict_file: str) -> list: """ Load dictionary from file and order by length :param dict_file: Filename of dictionary to load :return: list of dictionary words in size order :exceptions: if dictionary contains no words """ words_dictionary = list() # load dictionary from file with open(dict_file, 'rt') as dictionary: words_dictionary = [word.split('\n')[0] for word in dictionary] # check for no entries in dictionary if len(words_dictionary) == 0: message = "No words in dictionary, need to specify a dictionary with at least 1 word." raise ValueError(message) else: print("loaded {} words in dictionary".format(len(words_dictionary))) # return sorted dictionary from shortest words to longest return sorted(words_dictionary, key=len) def _generate_grid(self): """ Generate a random grid of letters to be searched based on object's xsize and ysize :return: 2d list of lists containing the grid of letters """ letter_grid = [[random.choice(string.ascii_lowercase) for i in range(self.xsize)] for j in range(self.ysize)] return letter_grid def find_words(self) -> set: """ Find words in grid. Using the grid of letter we will search the grid horizontally and diagonally forwards and backwards. Since we are not worried about finding the exact location we can search for words based on a full slice instead of trying to searching through each position. :return: """ # generate comparison string lists from grid print('generating grid comparision string list') comp_strings = list() comp_strings.extend(self._get_horizontal_str()) comp_strings.extend(self._get_vertical_str()) comp_strings.extend(self._get_diagonal_str()) # find all dictionary words that occur in the comp_strings print('searching for words in comparison string list') for word_to_cmp in self.words_dictionary: if any(word_to_cmp in curr_string for curr_string in comp_strings): self.found_words.add(word_to_cmp) return self.found_words # Search methods. def _get_horizontal_str(self)->list: """ get strings for horizontal comparisons :return: string_list of all horizontal strings forward and backward """ string_list = list() for char_list in self.letter_grid: curr_string = ''.join(char_list) string_list.append(curr_string) bwd_string = ''.join(reversed(curr_string)) string_list.append(bwd_string) return string_list def _get_vertical_str(self)->list: """ get strings for vertical comparisons Currently :return: string_list of all vertical strings forward and backward """ string_list = list() for curr_x in range(self.xsize): char_list = [self.letter_grid[y][curr_x] for y in range(self.ysize)] curr_string = ''.join(char_list) string_list.append(curr_string) bwd_string = ''.join(reversed(curr_string)) string_list.append(bwd_string) return string_list def _get_diagonal_str(self)->list: """ get strings for diagonal comparisons - Currently only getting diagonals that start at the top row :return: string_list of all diagonal strings to the right and left, forward and backward """ string_list = list() # get diagonal from top row going to the right and then left for curr_x in range(self.xsize): d_upper_right = [self.letter_grid[inc][curr_x + inc] for inc in range(self.xsize - curr_x)] curr_string = ''.join(d_upper_right) string_list.append(curr_string) bwd_string = ''.join(reversed(curr_string)) string_list.append(bwd_string) d_upper_left = [self.letter_grid[inc][(self.xsize - 1 - curr_x) - inc] for inc in range(self.xsize - curr_x)] curr_string = ''.join(d_upper_left) string_list.append(curr_string) bwd_string = ''.join(reversed(curr_string)) string_list.append(bwd_string) return string_list def check_axis(arg): try: value = int(arg) except ValueError as err: raise argparse.ArgumentTypeError(str(err)) if value <= 0: message = "Expected value > 0, got value = {}".format(value) raise argparse.ArgumentTypeError(message) return value def check_file(arg): try: value = str(arg) except ValueError as err: raise argparse.ArgumentTypeError(str(err)) if not os.path.isfile(value): message = "Could not find dictionary file {}".format(value) raise argparse.ArgumentTypeError(message) return value def main(): parser = argparse.ArgumentParser('WordSearch a randomly generated grid') parser.add_argument('--xsize', dest='xsize', default=15, type=check_axis, help='X-Axis size') parser.add_argument('--ysize', dest='ysize', default=15, type=check_axis, help='Y-Axis size') parser.add_argument('--dictionary', dest='dict_file', default='words.txt', type=check_file, help='dictionary filename') args = parser.parse_args() print("Xsize={}, Ysize={}, Dictionary={}".format(args.xsize, args.ysize, args.dict_file)) grid = WordSearch(args.dict_file, args.xsize, args.ysize) found = grid.find_words() print("found following {} words:".format(len(found))) print(found) if __name__ == '__main__': main() class TestWordSearch(unittest.TestCase): def test_create_with_no_words(self): """ Test for object creation with dictionary of no words. """ # verify the right exception is done self.assertRaises(ValueError, WordSearch, "nowords.txt") def test_create_default_grid(self): """ Test for object creation using defaults """ grid = WordSearch("words.txt") # verify dictionary is set self.assertTrue(len(grid.words_dictionary) > 0) # verify x-axis length self.assertTrue(len(grid.letter_grid) == 15) # verify y-axis length self.assertTrue(len(grid.letter_grid[0]) == 15) def test_create_1x100_grid(self): """ Test for object creation of a grid that is 1 row and 100 chars """ grid = WordSearch("words.txt", 1, 100) # verify dictionary is set self.assertTrue(len(grid.words_dictionary) > 0) # verify x-axis length self.assertTrue(len(grid.letter_grid) == 100) # verify y-axis length self.assertTrue(len(grid.letter_grid[0]) == 1) def test_create_100x1_grid(self): """ Test for object creation of a grid that is 100 rows and 1 char """ grid = WordSearch("words.txt", 100, 1) # verify dictionary is set self.assertTrue(len(grid.words_dictionary) > 0) # verify x-axis length self.assertTrue(len(grid.letter_grid) == 1) # verify y-axis length self.assertTrue(len(grid.letter_grid[0]) == 100) def test_create_100x100_grid(self): """ Test for object creation of a grid that is 100 rows and 100 chars """ grid = WordSearch("words.txt", 100, 100) # verify dictionary is set self.assertTrue(len(grid.words_dictionary) > 0) # verify x-axis length self.assertTrue(len(grid.letter_grid) == 100) # verify y-axis length self.assertTrue(len(grid.letter_grid[0]) == 100) def test__get_horizontal_str(self): """ Test that the string_list returned is of the right value. We force the grid to be a numeral string and then validate that the returned list looks correct. """ input_grid = [[string.ascii_lowercase[x] for x in range(9)] for y in range(9)] expect_strings = ['abcdefghi', 'ihgfedcba', 'abcdefghi', 'ihgfedcba' ] grid = WordSearch("words.txt", 9, 9) grid.letter_grid = input_grid actual_strings = grid._get_horizontal_str() print(actual_strings) print("---") print(expect_strings) self.assertTrue(actual_strings[0] == expect_strings[0]) self.assertTrue(actual_strings[1] == expect_strings[1]) self.assertTrue(actual_strings[16] == expect_strings[2]) self.assertTrue(actual_strings[17] == expect_strings[3]) def test__get_vertical_str(self): """ Test that the string_list returned is of the right value. We force the grid to be a numeral string and then validate that the returned list looks correct. """ input_grid = [[string.ascii_lowercase[x] for x in range(9)] for y in range(9)] expect_strings = ['aaaaaaaaa', 'aaaaaaaaa', 'iiiiiiiii', 'iiiiiiiii' ] grid = WordSearch("words.txt", 9, 9) grid.letter_grid = input_grid actual_strings = grid._get_vertical_str() print(actual_strings) print("---") print(expect_strings) self.assertTrue(actual_strings[0] == expect_strings[0]) self.assertTrue(actual_strings[1] == expect_strings[1]) self.assertTrue(actual_strings[16] == expect_strings[2]) self.assertTrue(actual_strings[17] == expect_strings[3]) def test__get_diagonal_str(self): """ Test that the string_list returned is of the right value. We force the grid to be a numeral string and then validate that the returned list looks correct. """ input_grid = [[string.ascii_lowercase[x] for x in range(9)] for y in range(9)] expect_strings = ['abcdefghi', # upper left to lower right 'ihgfedcba', # ul2lr backwards 'ihgfedcba', # upper right to lower left 'abcdefghi', # ul2lr backwards 'bcdefghi', # upper left to lower right (shift by one) 'ihgfedcb', # ul2lr backwards 'hgfedcba', # upper right to lower left (shift by one) 'abcdefgh', # ul2lr backwards 'i', # upper left last character 'i', # upper left last character backwards 'a', # upper right last character 'a' # upper right last character backwards ] grid = WordSearch("words.txt", 9, 9) grid.letter_grid = input_grid actual_strings = grid._get_diagonal_str() print(actual_strings) print("---") print(expect_strings) self.assertTrue(actual_strings[0] == expect_strings[0]) self.assertTrue(actual_strings[1] == expect_strings[1]) self.assertTrue(actual_strings[2] == expect_strings[2]) self.assertTrue(actual_strings[3] == expect_strings[3]) self.assertTrue(actual_strings[4] == expect_strings[4]) self.assertTrue(actual_strings[5] == expect_strings[5]) self.assertTrue(actual_strings[6] == expect_strings[6]) self.assertTrue(actual_strings[7] == expect_strings[7]) self.assertTrue(actual_strings[32] == expect_strings[8]) self.assertTrue(actual_strings[33] == expect_strings[9]) self.assertTrue(actual_strings[34] == expect_strings[10]) self.assertTrue(actual_strings[35] == expect_strings[11]) def test_search_horizontal_fwd(self): """ Test searching grid horizontal forward Checking the following conditions: 1. word at start 2. word in middle 3. word at end 4. word non-existant """ input_grid = [['a','b','a','t','e','f','g','h','i'], ['a', 'b', 'c', 'c', 'a', 'n', 'g', 'h', 'i'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], ['a', 'b', 'c', 'd', 'i', 'r', 'e', 'c', 't'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']] expected_words = {'can', 'abate', 'direct'} grid = WordSearch("testwords.txt", 9, 9) grid.letter_grid = input_grid actual_words = grid.find_words() self.assertTrue(len(expected_words) == len(actual_words)) def test_search_vertical_fwd(self): """ Test searching grid vertical forward Checking the following conditions: 1. word at top 2. word in middle 3. word at end 4. word non-existant """ input_grid = [['c','b','a','t','e','f','g','h','i'], ['o', 'b', 'c', 'c', 'a', 'n', 'g', 'h', 'i'], ['m', 'b', 'c', 'p', 'e', 'f', 'g', 'h', 'i'], ['p', 'b', 'c', 'y', 'e', 'f', 'g', 'a', 'i'], ['u', 'b', 'c', 't', 'e', 'f', 'g', 'b', 'i'], ['t', 'b', 'c', 'h', 'e', 'f', 'g', 'a', 'i'], ['e', 'b', 'c', 'o', 'c', 'f', 'g', 't', 'i'], ['r', 'b', 'c', 'n', 'a', 'r', 'e', 'e', 't'], ['a', 'b', 'c', 'd', 'n', 'f', 'g', 'h', 'i']] expected_words = {'can', 'abate', 'computer', 'python'} grid = WordSearch("testwords.txt", 9, 9) grid.letter_grid = input_grid actual_words = grid.find_words() self.assertTrue(len(expected_words) == len(actual_words)) def test_search_diagonal_fwd(self): """ Test searching grid diagonal forward Checking the following conditions: 1. word at start 2. word in middle 3. word at end 4. word non-existant """ input_grid = [['d','b','a','t','e','f','g','h','n'], ['a', 'i', 'c', 'c', 'a', 'n', 'g', 'a', 'i'], ['a', 'b', 'r', 'd', 'e', 'f', 'c', 'h', 'i'], ['a', 'b', 'c', 'e', 'e', 'f', 'g', 'h', 'i'], ['a', 'b', 'c', 'd', 'c', 'f', 'g', 'h', 'i'], ['a', 'b', 'c', 'd', 'e', 't', 'g', 'h', 'i'], ['a', 'b', 'c', 'd', 'a', 'f', 'g', 'h', 'i'], ['a', 'b', 'c', 'b', 'i', 'r', 'e', 'c', 't'], ['a', 'b', 'a', 'd', 'e', 'f', 'g', 'h', 'i']] expected_words = {'can', 'direct'} grid = WordSearch("testwords.txt", 9, 9) grid.letter_grid = input_grid actual_words = grid.find_words() self.assertTrue(len(expected_words) == len(actual_words))
f51bfec0753fbbff8a429a504600b8751a4d0297
wy2530/Record_python
/CBOW/01 logger/2、property.py
1,875
4.5
4
""" 用类实现的装饰器:property property:是一个装饰器,是将功能属性转换为数据属性 """ # 应用案例1(体质): # class People: # def __init__(self, name, weight, height): # self.name = name # self.weight = weight # self.height = height # # ''' # 因为BMI是计算出来的,所以需要单独写一格函数,不然会写死 # 但是在用户看来BMI又属于数据属性,需要之间查看,因此需要用到property属性 # ''' # # @property # def bmi(self): # return self.weight / (self.height ** 2) # # # obj1 = People("WY", 45, 1.57) # # print(obj1.bmi()) # ''' # 加property与不加的区别: # 没有加装饰器时,BMI是一个函数,你需要调用函数,因此需要加括号 # 加装饰器后,BMI是一个数据属性,访问属性,不需要加括号的 # ''' # print(obj1.bmi) # 应用案例二: class People: def __init__(self, name): self.__name = name @property # get_name=property(get_name) def get_name(self): return self.__name @get_name.setter def set_name(self, val): if type(val) is not str: print("输入必须为字符串") return self.__name = val @get_name.deleter def del_name(self): print("不可删除") # name=property(get_name,set_name,del_name) obj1 = People("hello") # obj1.set_name("aaa") # print(obj1.get_name) del obj1.del_name ''' 对于使用者来说: 调用删、改、查 更像是一个功能 那么如何使它更像一个数据呢? 两种办法: 1、name=property(get_name,set_name,del_name) 2、将功能函数的名字都改成name 定义@property @name.setter 设置 @name.deleter 删除 ''' ''' 问题:到底什么时候用print '''
4671f6f884610554b7793fd02bff024c444784d1
AndreaCrotti/my-project-euler
/prob_5/prob_5.py
165
3.765625
4
#!/usr/bin/env/python # smallest divisible by 1..20, doing another reverse loop res = 1 for i in range(20,0,-1): if (res % i) != 0: res *= i print res
e97b031674490b87fd4704fb43305c8dfc5bcf44
RaMaaT-MunTu/learn-python
/list_comprehension.py
892
4.28125
4
########################## # List comprehension 101 # ########################## numbers = [1, 4, 10, 3, 30, 2, 66, 20, 30] words = ['jacqueline', 'Robert', 'tulipes en fleurs', 'rue des chemins', 'palmiers de Dubai', 'Paris la nuit', 'bracelet', 'jantes', 'bois foncé'] # multiply per 2 all numbers # convert all numbers into string # keep words that does not contain blank spaces. # create a new list with even numbers only (nombres pairs). # Use a conditional structure! double_numbers = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] #create a new list from double_numbers with odd numbers only # should look like : [1, 3, 5, 7, 9] # create a new list with numbers and words as tuples. # should look like: [('jacqueline', 1), ('robert', 4)] # A good resource: https://hackernoon.com/list-comprehension-in-python-8895a785550b
b53d3032257e236aa5088f31d491d296c9a07aca
xiaoqi2019/python14
/week_7/class_0301/class_unittest_learn.py
4,068
3.640625
4
#测试用例===准备好 类TestCase #执行用例 套件TestSuite # 测试报告类TextTestRunner 一致pass 不一致Failed 测试结果 #开始对加法进行单元测试 import unittest #引入单元测试模块 from week_7.class_0228.my_log import MyLog class TestAdd(unittest.TestCase): #继承编写测试用例的类 def setUp(self): print('------开始执行测试用例了------') #测试用例执行前的准备工作,比如环境部署,数据库连接,每执行一条测试用例就执行一次 def tearDown(self): print('------测试用例执行完毕------') #用例执行完毕的清场工作,如断开数据库连接,每执行一条测试用例就执行一次 def test_001(self): #两个正数相加 a=1 b=2 expected=3 c=a+b try: self.assertEqual(expected,c) #调用父类的断言函数 except AssertionError as e: print('001测试用例执行失败,错误信息是:{}'.format(e)) # raise e MyLog().error(e) print('两个正数相加的结果是:{}'.format(c)) def test_002(self): #两个负数相加 a=-1 b=-2 expected = -3 c=a+b try: self.assertEqual(expected,c) #调用父类的断言函数 except AssertionError as e: print('002测试用例执行失败,错误信息是:{}'.format(e)) raise e print('两个负数相加的结果是:{}'.format(c)) def test_003(self): #一正一负相加 a=1 b=-2 c=a+b expected =-1 try: self.assertEqual(expected,c) #调用父类的断言函数 except AssertionError as e: print('003测试用例执行失败,错误信息是:{}'.format(e)) raise e print('一正一负相加的结果是:{}'.format(c)) def test_004(self): #两个0相加 a=0 b=0 c=a+b expected =0 try: self.assertEqual(expected,c) #调用父类的断言函数 except AssertionError as e: print('004测试用例执行失败,错误信息是:{}'.format(e)) raise e print('两个0相加的结果是:{}'.format(c)) class TestSub(unittest.TestCase): def setUp(self): print('------开始执行测试用例了------') def tearDown(self): print('------测试用例执行完毕------') def test_two_positive(self): #两个正数相减 a=1 b=2 c=a-b expected =-1 try: self.assertEqual(expected,c) #调用父类的断言函数 except AssertionError as e: print('两个正数相减用例执行失败,错误信息是:{}'.format(e)) raise e print('两个正数相减的结果是:{}'.format(c)) def test_two_negative(self): #两个负数相减 a=1 b=2 c=a-b expected =-1 try: self.assertEqual(expected,c) #调用父类的断言函数 except AssertionError as e: print('两个负数相减用例执行失败,错误信息是:{}'.format(e)) raise e print('两个负数相减的结果是:{}'.format(c)) def test_positive_negative(self): #一正一负相减 a=3 b=-2 c=a-b expected =5 try: self.assertEqual(expected,c) #调用父类的断言函数 except AssertionError as e: print('一正一负相减用例执行失败,错误信息是:{}'.format(e)) raise e print('一正一负相减的结果是:{}'.format(c)) def test_two_zero(self): #两个0相减 a=0 b=0 c=a-b expected =0 try: self.assertEqual(expected,c) #调用父类的断言函数 except AssertionError as e: print('两个0相减用例执行失败,错误信息是:{}'.format(e)) raise e print('两个0相减的结果是:{}'.format(c))
b963110b2e12dc1a052e978d63418a82e4d821d4
stdiorion/competitive-programming
/contests_atcoder/abc179/abc179_c_tle.py
719
3.5
4
from itertools import accumulate,chain,combinations,groupby,permutations,product from collections import deque,Counter from bisect import bisect_left,bisect_right from math import gcd,sqrt,sin,cos,tan,degrees,radians from fractions import Fraction from decimal import Decimal import sys input = lambda: sys.stdin.readline().rstrip() #from sys import setrecursionlimit #setrecursionlimit(10**7) MOD=10**9+7 INF=float('inf') n = int(input()) def count_divisors(n): i = 1 cnt = 0 while i * i <= n: if n % i == 0: cnt += 1 if i != n // i: cnt += 1 i += 1 return cnt ans = 0 for c in range(n-1, 0, -1): ans += count_divisors(n - c) print(ans)
3f7bfbadf9329b5930c000e11628cb365ad9c346
JoeJiang7/python-crash-course
/chapter 15/15-3.py
573
3.5625
4
import matplotlib.pyplot as plt from random_walk import RandomWalk while True: rw = RandomWalk() rw.fill_walk() point_numbers = list(range(rw.num_points)) plt.plot(rw.x_values, rw.y_values, linewidth=1) plt.scatter(0, 0, c='green', edgecolors='none', s=100) plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100) plt.show() while True: keep_running = input("Make another walk? (y/n): ") if keep_running == 'y' or keep_running == 'n': break if keep_running == 'n': break
705fba5ed021c0a28ed235258509c87b3cc00bec
mtariquekhan11/PycharmProjects
/welcome Projects/LCM_HCF.py
1,257
4.0625
4
# Author: Mohd Tarique Khan # Date: 14/10/2019 # Purpose: To calculate the LCM and HCF/GCD condition = "True" def hcf(x, y): if x < y: smaller = x elif x > y: smaller = y for i in range(1, smaller + 1): if x % i == 0 and y % i == 0: hcf = i return hcf def lcm(x, y): if x > y: greater = x elif x < y: greater = y while True: if greater % x == 0 and greater % y == 0: lcm = greater break greater = greater + 1 return lcm while condition is "True": choice = int(input("Enter the your choice \n '1' for HCF '2' for LCM: ")) if choice == 1: num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) print("HCF of ", num1, num2, "are: ", hcf(num1, num2)) elif choice == 2: num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) print("LCM of ", num1, num2, "are: ", lcm(num1, num2)) else: print("Invalid Input") break condition1 = input("Do you want to check more, Press Y or y: ") if condition1 == "y" or condition1 == "Y": condition = "True" else: break
627123d01077a372465ebba1d3e850ee45c00124
nileshnmahajan/helth
/temp/select.py
402
3.640625
4
import sqlite3 conn = sqlite3.connect('hospital.db') #con.isolation_level = None c = conn.cursor() #create table for store hospitals data for row in c.execute(' select * from Hospital'): print (row) for row in c.execute(' select * from Users'): print (row) for row in c.execute(' select * from Disease'): print (row) #conn.commit() no require while selecting no changes occure conn.close()
c6f8e67f6c2cd1fad9db4674a6b05f281a50e684
vorjat/PythonBootCamp
/zjazd_2/funkcje/zadanie_dod9.py
783
3.625
4
def rysuj(liczba=0): liczba = int(input("Podaj liczbe: ")) if liczba == 0: print(f""" *** * * * * * * ***""") elif liczba == 1: print(f""" * * * * * * """) elif liczba == 2: print(f""" *** * * * * *****""") elif liczba == 3: print(f"""***** * *** * *****""") elif liczba == 4: print(f"""* * * * ***** * *""") elif liczba == 5: print(f"""***** * ***** * *****""") elif liczba == 6: print(f"""***** * ***** * * *****""") elif liczba == 7: print(f"""***** * * * * """) elif liczba == 8: print(f"""***** * * ***** * * ***** """) elif liczba == 9: print(f"""***** * * ***** * ***** """) rysuj()
cda784e37c249e2baefb6b7b32bfa47ed90867d6
AbhijitEZ/PythonProgramming
/Beginner/DataTypes/i_o_operation.py
997
3.875
4
import os print(os.getcwd()) # get the working dirctory of the python executable. current_path = os.path.dirname(__file__) # current working file directory print(current_path) my_file = open(os.getcwd() + '/Resource/myFile.txt') print(my_file.read()) # second time it empty string because cursor has moved to the end of positon on first read. print(my_file.read()) my_file.seek(0) # bring back the cursor to the inital character. print(my_file.read()) my_file.close() # should close the file after operation on it is done """ with statement is used for exception handling also removes the resource after some time. There is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources """ with open(os.getcwd() + '/Resource/myFile.txt') as new_file: contents = new_file.read() print(contents, 'Contents') with open(os.getcwd() + '/Resource/myAppendFile.txt', 'a') as file: file.write('\nAppend Line')
69dc6ec22f6ee5b6d971aa5f0a59a7ce71d1a6c2
Mbaoma/workedExamples
/examples/small-primes/soln.py
2,728
4.3125
4
import time UPPER_BOUND = 10000000 # Warning! Values > 100,000,000 will take a LONG time. PRIMES_TO_SHOW = 10 def main(): print("This program will test whether a specified integer is prime.") print("It will also print out the " + str(PRIMES_TO_SHOW) + " primes <= the provided value.") print("For the sake of time, only numbers up to " + str(UPPER_BOUND) + " are allowed.") print("Calculating primes up to " + str(UPPER_BOUND) + ". Please wait...") primes = calculate_primes() while True: n = int(input("Please enter an integer in [0, " + str(UPPER_BOUND) + "]: ")) # Check the primality of the provided value. prime = primes[n] if prime: print(str(n) + " is prime!") else: print(str(n) + " is not prime!") # Find the largest PRIMES_TO_SHOW <= n. to_show = last_n_primes(primes, n) print("The " + str(len(to_show)) + " primes <= " + str(n) + " are: ") print(to_show) print("") def calculate_primes(): """Calculates primes <= UPPER_BOUND. pre: UPPER_BOUND >= 0 post: returns a list of booleans [0, UPPER_BOUND] indicating if the number at index i is prime. """ # Initialize a list of size UPPER_BOUND + 1 to represent the integers in the # range [0, UPPER_BOUND]. primes = [True] * (UPPER_BOUND + 1) # We know 0 and 1 are not prime so treat them as special cases. primes[0] = primes[1] = False # Keep track of time to display to the user later. start_time = time.time() # We only need to iterate up to the square root of n because the inner # loop starts at n^2. upper_bound = int(UPPER_BOUND**0.5) for i in range(2, upper_bound + 1): if primes[i]: # Cross out all numbers that are multiples of i starting at i^2 for j in range(i * i, UPPER_BOUND + 1, i): primes[j] = False end_time = time.time() print("Calculated all primes up to " + str(UPPER_BOUND) + " in " + str(end_time - start_time) + " seconds.") return primes def last_n_primes(primes, n): """Finds the PRIMES_TO_SHOW largest primes <= n. pre: PRIMES_TO_SHOW >= 0 primes: a list of primes n: an integer specifying the maximum prime to display post: returns a list of up to PRIMES_TO_SHOW largest primes <= n """ show = [] i = n # Start at n and work downward keeping track of primes. # Loop should also ensure we don't drop below zero. while len(show) < PRIMES_TO_SHOW and i >= 0: if primes[i]: show.append(i) i -= 1 return show if __name__ == "__main__": main()
10de8ee6d7fe7b8511c05fb768a27b9bf4379338
luismedinaeng/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
384
3.671875
4
#!/usr/bin/python3 def read_lines(filename="", nb_lines=0): n_line = 0 with open(filename, mode='r', encoding='utf-8') as a_file: if nb_lines <= 0: print(a_file.read(), end="") else: for a_line in a_file: print(a_line, end="") n_line += 1 if n_line >= nb_lines: break
da0baf0430309450bd274c7fa40bb310385a9213
EwertonBar/CursoemVideo_Python
/mundo03/desafios/desafio103.py
302
3.796875
4
def ficha(nome='<desconhecido>', gols=0): print(f'{nome} fez {gols} gols.') nome = str(input('Nome do jogador: ')) gols = str(input('Quantos gols: ')) if gols.isnumeric(): gols = int(gols) else: gols = 0 if nome.strip() == '': ficha(gols=gols) else: ficha(nome, gols)
c93a996d951ed561e748344f4458bc128448847a
2020cbustos/Coding
/ceasar.py
1,988
4.3125
4
#encrypt a message with a shift in letters. Takes into accounts letters 1 to 26. #LOGIC of INCRIPTION #main idea: loop through a string and shift #create hash with each letter and their numeric value (of the alphabet) #create function that takes in string and returns the same string with shift #create empty array (for output) #get value from key in hash #implement shifting #use .join to turn array into string #add to array #return encrypted message with shift #LOGIC of DECRIPTION #take in word with shift #reverse shift #return initial value (output) #call a function with string (message) and shift (input of how many letters to shift) def encrypt(string,shift): #create hash of letters and their numeric value letters_hash = { 'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8', 'i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15', 'p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22', 'w':'23','x':'24','y':'25','z':'26' } #empty array where output will go answer = [] nums = [] #take string into list string = list(string) for x in string: #loop through the hash for key, value in letters_hash.items(): num = letters_hash[x] num = int(num) shift = int(shift) #define variable shifting shifting = num + shift #add the shifting nums.append(shifting) #starting the second array number_one = [ str(item) for item in nums] letters_hash_1 = {y:x for x,y in letters_hash.items()} #loop over the second hash for n in number_one: for key, value in letters_hash_1.items(): alpha = letters_hash_1[n] #add with .append answer.append(alpha) #join output = " ".join(answer) return output #these are the user inputs string = input() string = str(string) shift = input() shift = str(shift) #call the function and print print(encrypt(string, shift))
5cf314668cf0144daceb2e1314b72adae30df001
Y1ran/python
/工资函数.py
677
4.1875
4
#用户的薪资输入水平>=0 #超出40小时的工时按1.5倍工资计算 def computepay(): try: pay1 = raw_input("Please Enter your Hours:") work_hours = float(pay1) pay2= raw_input("Please Enter your Rate:") work_salary = float(pay2) except: print "Error, please enter a numeric input" quit() #This is only for workers < 40hs if work_hours >= 40: overtime_pay = (work_hours - 40) * work_salary * 1.5 total_pay = overtime_pay + work_salary * 40 return total_pay else: only_pay = work_hours * work_salary return only_pay print computepay()
5507ec2388c2a546a285efe064d5f35c26b8cf4b
DoctorSad/_Course
/Lesson_05/_6_recursion_1.py
997
4.375
4
""" Рекурсию можно применить например к алгоритму вычисления факториала. """ def main(): n = int(input("n: ")) result = fact(n) print(result) def fact(n): if n == 0: return 1 # если n == 0 - возвращаем 1, так как факториал числа !0 = 1 return n * fact(n - 1) # умножаем число n на вызов функции с числом n - 1 if __name__ == "__main__": main() # пример вычисления !5 # сначала идет рекурсивный вызов функции, # затем начиная с последнего вызова идет возвращение значения - return # факториал числа 5 -> !5 = 1 * 2 * 3 * 4 * 5 = 120 # 5 * fact(4) # 4 * fact(3) # 3 * fact(2) # 2 * fact(1) # 1 * fact(0) # 1 # 2 # 6 # 24 # 120
cba823b9cdbd1b9ff37ab53b5f1e2316368e7cc5
pavarotti305/python-training
/use_module_sys.py
871
3.796875
4
import sys introduction = "Module Sys allow interaction with user with special object stdin (standard input) and readline" print(introduction) introduction = sys.stdin.readline(18) print(introduction) print('') def old_joke(): sys.stdout.write('What this your name ?\n') print('Please enter you name below:') name = input() print('How old are you ?') print('Please enter you old below:') old = int(sys.stdin.readline()) # old between 10 and 13 if 10 <= old <= 13: print('%s That give 13 + 49 ? The migraine !' % name) elif 0 <= old <= 9: print("%s you are too young for this experience." % name) elif 14 <= old <= 17: print("%s You are not major you'll have to wait your 18 years." % name) else: print('%s Sorry your old is outside our preferences !' % name) old_joke() print(sys.version)
a242336c34ce52034739ed524bfb92612c51e17b
samarla/LearningPython
/backup/guessing_game_two.py
881
4
4
import random compare = None recent_guess = random.randint(0, 100) count = 0 print('Please keep some Random number (0-100) in your mind, and let me guess it. \n Here we go') def print_random(x, y, z): """this function will display the guess and gets the feedback from the user""" x = +1 #y = random.randint(0, 100) print('My guess is : \t', y) z = int(input('let me know how accurate i guess: ' '1. matched \t 2. higher \t 3. lower')) return x, z print_random(count, recent_guess, compare) while compare: if compare == 1: print('i won in ', count, 'moves') break elif compare == 2: recent_guess = random.randint(0, recent_guess) print_random(count, recent_guess, compare) elif compare == 3: recent_guess = random.randint(recent_guess, 100) print_random(count, recent_guess, compare)
e398ba34cb1c6f8b47685c378081f5c17f66e12c
rahulmahajann/pep_sht
/random questions/fourdivisor.py
560
3.796875
4
import math ans=[] def primeFactors(n): # ans.append() while n % 2 == 0: ans.append(2) n = n//2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: ans.append(i) n = n // i # if n > 2: # ans.append(n) # ans.append return ans nu=[21,4,7] fans=[] for _ in nu: primeFactors(_).append(_) if(len(set(primeFactors(_)))==3): for _ in set(primeFactors(_)): fans.append(_) fans.append(1) primeFactors(_).clear() else: primeFactors(_).clear() print(fans) # print(primeFactors(21))
644c1c618dd32fdd8ffb9cbcdfbdef00d416a021
quangdbui9999/CS-171
/week4Python/Week4/HighwayNumber.py
833
4.40625
4
highway_number = int(input()) ''' Type your code here. ''' if(highway_number == 0): print(f'{highway_number} is not a valid interstate highway number.') if(1 <= highway_number <= 999): if(1 <= highway_number <= 99): if(highway_number % 2 == 0): print(f'The {highway_number} is primary, going east/west.') else: print(f'The {highway_number} is primary, going north/south.') if(100 <= highway_number <= 999): if(highway_number % 2 == 0): print(f'The {highway_number} is auxiliary, serving the {highway_number % 100}, going east/west.') else: print(f'The {highway_number} is auxiliary, serving the {highway_number % 100}, going north/south.') if(highway_number >= 1000): print(f'{highway_number} is not a valid interstate highway number.')
e37479be93febc2e689ef0cbaa9835a2c03eba4f
brunacarenzi/thunder-code
/par.impar.py
312
3.859375
4
from random import randint numero = int(input('Digite um número para saber se é par ou impar:')) resto = numero % 2 if resto == 0: print('Número {} é par'.format(numero)) else: print(f'Número {numero} é impar') pc = randint(0, 10) resto = numero % 2 print(' escolhi {}'.format(pc))
076c6d4eee28a516dabd8e70ddc78c4b45ac9b3c
Mikicodes/pinterestkingz
/Pin.py
1,199
3.53125
4
class Pin: #Construct a pin def __init__(self): #self.name = name #self.picture = picture # self.description # self.posting_date self.comments = [] #Reassign Name of Pin def set_name(self,name): self.name =name #Get Name of the Pin def get_name(self): return self.name #Reassign Description of the pin def set_description(self, description): self.description =description #Get the description of the pin def get_description(self): return self.description #Set the picture of the pin def set_picture(self, picture): self.picture = picture #Get the picture of the pin def get_picture(self): return picture #Set date and time of posting of the the pin def set_posting_date(self, posting_date): self.posting_date = posting_date #Return date and time of posting of the pin def get_posting_date(selfs): return posting_date #Add a comment to a pin def set_comments(self, comment): self.comments.append(comment) #Return comments of the pin def get_comments(self): return self.comments
44cc9cdf998c20eebda2075fe0152cb7b637e4f7
yl4669458/spyderfile
/test_29_itertools.py
1,499
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 1 09:39:37 2020 @author: yl """ import itertools print('accumulate') x = itertools.accumulate(range(2, 10), lambda x, y: x * 10 + y) l = list(x) print(l) class Test(object): def test_2(self): return map(lambda x, y : x == y, range(10), range(5)) t = Test() #for i in t.test(10): # print(i) print(list(t.test_2())) #chain print('chain') a = itertools.chain(range(4),range(18,27),['a'],('b')) print(list(a)) #combinations_with_replacement print('combinations_with_replacement') y = itertools.combinations_with_replacement('123', 2) for i in y: print(i) #product print('product') z = itertools.product('abc', 'xyz','123') for i in z: print(i, ) #permutations print('permutations') p = itertools.permutations('123') for i in p: print(i) #combinations print('combinations') b = itertools.combinations('123', 2) print(list(b)) #repeat print('repeat') j = itertools.repeat({1:'2'}, 5) for i in j: print(i) #tee print('tee') f = itertools.tee(range(10), 5) for i in f: print(list(i)) #count c = itertools.count(15, -1) print('count') for i in itertools.islice(c, 10): print(i, ) print() #cycle print('cycle') x = itertools.cycle('ABC') for i in itertools.islice(x, 10): print(i) #groupby print('groupby') x = itertools.groupby(range(10), lambda x: x < 5 or x > 8) for condition, numbers in x: print(condition, list(numbers))
f2a5ff360bbfa37449526b39f82d861b7b899f39
Yehia-Fahmy/pathfinding
/pathfind_test.py
2,307
3.8125
4
import queue def createSmallMaze(): maze = [] maze.append([" ", " ", "O"]) maze.append([" ", " ", " "]) maze.append(["X", " ", " "]) return maze def createMaze(): maze = [] maze.append(["#", "#", "#", "#", "#", "O", "#"]) maze.append(["#", " ", " ", " ", "#", " ", "#"]) maze.append(["#", " ", "#", " ", "#", " ", "#"]) maze.append(["#", " ", "#", " ", " ", " ", "#"]) maze.append(["#", " ", "#", "#", "#", " ", "#"]) maze.append(["#", " ", " ", " ", "#", " ", "#"]) maze.append(["#", "#", "#", "X", "#", "#", "#"]) return maze def queue_test(): queue1 = [" ", " "] x = queue1.pop(0) while len(x) < 5: x = queue1.pop(0) queue1.append(x + "R") queue1.append(x + "L") queue1.append(x + "D") queue1.append(x + "U") print(len(x)) print(queue1) def print_maze(maze): # function to print the maze as it is for i in range(len(maze)): for j in range(len(maze[0])): print(maze[i][j], end="") print(" ", end="") print() def find_starting_pos(maze): # function to find the starting postion of the maze for i in range(len(maze)): for j in range(len(maze[0])): if maze[i][j] == "O": return i, j # returns the pos coordinates as col, row (y,x) def add_valid( starting_pos, queue ): # this function will add any valid paths to the queue current_pos = ( starting_pos ) # using the starting position as a start we follow the path at the top of the queue to find the current position path = queue.pop(0) temp = ( path ) # we dont want to modify the path we are dealing with so we use a temp for the next step while len(temp) > 0: next_move = temp.pop(0) if next_move == "R": current_pos[1] += 1 elif next_move == "L": current_pos[1] -= 1 elif next_move == "U": current_pos[0] -= 1 elif next_move == "D": current_pos[0] += 1 # we now want to make sure that we add only valid entries to the path if current_pos[0] > 0: queue.append(path + "U") our_queue = "" our_maze = createSmallMaze() print_maze(our_maze) print(find_starting_pos(our_maze))
67c6fcf33372630df6ea562df32580e84ebdfff8
KWolf484/PythonProject
/CMD_Test_Text_file_compiler/CMD_Test_Text_file_compiler/CMD_Test_Text_file_compiler.py
920
3.59375
4
import os, re def txt_file(): tfile = os.system(r'dir \\TheRig\Movies\ /b > C:/Users/Wolf/Documents/text_files/Movie_list.txt') return tfile txt_file() def movie_find(): movie = input('What Movie are you looking for?' ) tfile = (r'C:/Users/Wolf/Documents/text_files/Movie_list.txt') tfile = open(tfile, 'r') tfile = tfile.readlines() for m in tfile: if re.findall(movie, m): print (('%s is available') % movie, ) print (('Full name: %s') % m, ) #movie_find() def movie_find1(): movie = input('What Movie are you looking for?' ) tfile = (r'C:/Users/Wolf/Documents/text_files/Movie_list.txt') tfile = open(tfile, 'r') tfile = tfile.readlines() for m in tfile: if re.finditer(movie, m): print (('%s is available') % movie, ) print (('Full name: %s') % m, ) movie_find1()
cdfca8146193d1ea6898ee3cd4ed1df8992e8235
Keyxllai/PythonCook
/Basic/variableDemo.py
327
3.875
4
if __name__ == "__main__": ''' referencing ''' v = 110 print(v) ''' assign multiple values at once ''' tu=('a',1,3) (x,y,z) = tu print("X:{x},Y:{y},Z:{z}".format(x=x,y=y,z=z)) ''' assign consecutive values ''' (MON,TUE,WED,THU,FRI,SAT,SUN)=range(1,8) print MON
b1931b9b7bc509fb729d601f35cfc148784b3638
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shodges/lesson08/circle.py
3,080
3.90625
4
#!/usr/bin/env python3 import math class Circle(object): def __init__(self, radius): try: self._radius = float(radius) self._diameter = float(radius) * 2 except ValueError: raise TypeError("radius expects a float") def __str__(self): return 'Circle with radius {:.5f}'.format(self._radius) def __repr__(self): return '{}({})'.format(self.__class__.__name__, self._radius) def __add__(self, other): try: return self.__class__(self._radius + other._radius) except AttributeError: return self.__class__(self._radius + other) def __radd__(self, other): return self.__add__(other) def __sub__(self, other): try: return self.__class__(self._radius - other._radius) except AttributeError: return self.__class__(self._radius - other) def __rsub__(self, other): return self.__class__(other - self._radius) def __mul__(self, other): try: return self.__class__(self._radius * other._radius) except AttributeError: return self.__class__(self._radius * other) def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): try: return self.__class__(self._radius / other._radius) except AttributeError: return self.__class__(self._radius / other) def __rtruediv__(self, other): return self.__class__(other / self._radius) def __lt__(self, other): return self._radius < other._radius def __gt__(self, other): return self._radius > other._radius def __le__(self, other): return self._radius <= other._radius def __ge__(self, other): return self._radius >= other._radius def __eq__(self, other): return self._radius == other._radius def __ne__(self, other): return self._radius != other._radius @property def radius(self): return self._radius @property def diameter(self): return self._diameter @property def area(self): return math.pow(self._radius, 2) * math.pi @classmethod def from_diameter(cls, value): return cls(value / 2) @radius.setter def radius(self, value): try: self._radius = float(value) self._diameter = float(value) * 2 except ValueError: raise TypeError("radius expects a float") @diameter.setter def diameter(self, value): try: self._radius = float(value) / 2 self._diameter = float(value) except ValueError: raise TypeError("radius expects a float") class Sphere(Circle): def __str__(self): return 'Sphere with radius {:.5f}'.format(self._radius) @property def area(self): return 4 * math.pow(self._radius, 2) * math.pi @property def volume(self): return (4/3) * math.pow(self._radius, 3) * math.pi
c32567a01fdb538daf47de7d05447658bca74e28
fengbaoheng/leetcode
/python/79.word-search.py
2,024
3.578125
4
# # @lc app=leetcode.cn id=79 lang=python3 # # [79] 单词搜索 # from typing import List, Set, Tuple class Solution: # 深度搜索 # 记录走过的路径 def exist(self, board: List[List[str]], word: str) -> bool: try: rows = len(board) cols = len(board[0]) for r in range(rows): for c in range(cols): # 对每个网格点都尝试搜索, 此时无禁忌位置 if self.search(board, word, r, c, set([])): return True return False except Exception as e: raise e def search(self, board: List[List[str]], word: str, r: int, c: int, tabu: Set[Tuple[int]]) -> bool: # 排除禁忌位置 if (r, c) in tabu: return False # 空字符串匹配,永远为True length = len(word) if length == 0: return True # 首字母就匹配失败即返回False if word[0] != board[r][c]: return False elif length == 1: return True # 首字母匹配成功 # 生成新的禁忌位置和新的子串 tabu = tabu.copy() tabu.add((r, c)) word = word[1:] # 搜索四周的单元格 if c > 0 and self.search(board, word, r, c-1, tabu): return True if r > 0 and self.search(board, word, r-1, c, tabu): return True if c < len(board[0]) - 1 and self.search(board, word, r, c+1, tabu): return True if r < len(board) - 1 and self.search(board, word, r+1, c, tabu): return True return False if __name__ == "__main__": board = [ ['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E'] ] s = Solution() print("{}:{}".format("ABCCED", s.exist(board, "ABCCED"))) print("{}:{}".format("SEE", s.exist(board, "SEE"))) print("{}:{}".format("ABCB", s.exist(board, "ABCB")))
a45f290e5f36b4213bb2f5393065d6bf4f741dd6
thezhu007/P5_interfaces
/samples/re_page/demo5.py
255
3.578125
4
#re.finditer 查找所有,并返回迭代器,迭代器中都是match对象 import re str = 'hello 123 hello' pattern = re.compile('\w+') result_03 = pattern.finditer(str,pos=5,endpos=12) print(type(result_03)) for i in result_03: print(i.group())
6cd2158e215cd4e65ca15a3a2a654e8c5949503a
Wendy-Omondi/alx-higher_level_programming
/0x04-python-more_data_structures/100-weight_average.py
222
3.5
4
#!/usr/bin/python3 def weight_average(my_list=[]): if my_list: total = 0 div = 0 for x in my_list: total += x[0] * x[1] div += x[1] return total/div return 0
58d463c2652c94f51ab64703aa0413a2a02e3e5a
MinecraftDawn/LeetCode
/Hard/124. Binary Tree Maximum Path Sum.py
686
3.6875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxPathSum(self, root: TreeNode) -> int: self.maxPath = -2e30 self.dfs(root) return self.maxPath def dfs(self, node:TreeNode) -> int: if not node: return 0 left = self.dfs(node.left) right = self.dfs(node.right) curMaxPath = max(node.val, left+node.val, right+node.val) includeNodePath = max(curMaxPath, node.val+left+right) self.maxPath = max(self.maxPath, includeNodePath) return curMaxPath
9128bb60eeb1c0b8a84ac392adc92379016e7f58
faantoniadou/Computer-Simulation
/CP1Test.py
380
3.640625
4
from CP1 import Polynomial def main(): pol1 = Polynomial([2,0,4,-1,0,6]) pol2 = Polynomial([-1,-3,0,4.5]) pol2.polyadd(pol2) print(str(pol2)) pol1.antiderivative() print(" The antiderivative of the polynomial is " + str(pol1.antiderivative)) pol1.derivative() print(" The derivative of the polynomial is " + str(pol1.derivative)) main()
8c8c0d3962ca0f419e130775c33ed72af5af8c31
anwarali12255/tip-caalculator
/main.py
349
4.1875
4
print('welcome to the tip calculaor.') total_bill=int(input('what is the total bill? ')) tip_percentage=int(input('what percentage tip would you like to give? 10,12 or 15? ')) per=(tip_percentage)/100*(total_bill) no_of_people=int(input('how many people to split the bill? ')) final=(per)/(no_of_people) print(f'each person should pay {final} ')
369422ced0ab09537779747498a1f4a48379ac08
yehonadav/python_course
/lessons/regEx/regex_examples.py
1,759
4.25
4
import re text = "today i got to work early" # Search the string to see if it starts with "today" and ends with "early" x = re.search(r"^today.*early$", text) print(x) # Print a list of all matches x = re.findall(r"to", text) print(x) # Return an empty list if no match was found x = re.findall(r"zombie", text) print(x) # Search for the first white-space character in the string x = re.search(r"\s", text) print("The first white-space character is located in position:", x.start()) # Make a search that returns no match x = re.search(r"boni", text) print(x) # Split at each white-space character x = re.split(r"\s", text) print(x) # Split the string only at the first occurrence x = re.split(r"\s", text, 1) print(x) # Replace every white-space character with the number 9 x = re.sub(r"\s", "9", text) print(x) # Replace the first 2 occurrences x = re.sub(r"\s", "9", text, 2) print(x) # Do a search that will return a Match Object x = re.search(r"go", text) # The Match object has properties and methods # used to retrieve information about the search, and the result: # # .span() returns a tuple containing the start-, and end positions of the match. # .string returns the string passed into the function # .group() returns the part of the string where there was a match print(x) # Print the position (start- and end-position) of the first match occurrence. # The regular expression looks for any words that starts with a "w" x = re.search(r"\bw\w+", text) print(x.span()) # Print the string passed into the function x = re.search(r"\bS\w+", text) print(x.string) # Print the part of the string where there was a match. # The regular expression looks for any words that starts with a "w" x = re.search(r"\bS\w+", str) print(x.group())
eb8ab4242c89b74d52ef192f8f1667afe6b8ae1e
Pbharathwajan/all-code
/Problems/problrm.py
210
3.984375
4
num = 7 if num>1: for i in range (2,num): if num%i == 0: print(f'{num} is not prime') break elif num%i !=0: print(f'{num} is prime') break
2029515ea026dadb5118faa61b981c659eb7731d
tarunbhatiaind/Pyhtonbasicprogs
/args.py
981
4.09375
4
#args and kwargs #Actual way : # def func1 (a,b,c,d): # print(a,b,c,d) # # func1("A","b","c","d") #args: def func2(*args): #can use any name not only args print(args[1]) for item in args: print(item,end="") itm=["A","B","C","D"] func2(*itm) #works fine with one argument at first place and list in second def func3(normal,*args): print(normal) for item in args: print(item, end="") itm1=["d","e"] func3('abc',*itm1) #Below wont work because the list or combined arguments shoiuld not come in first place # def func4(*args,normal): # # print(normal) # # for item in args: # # print(item, end="") # # itm2=["d","e"] # # func4(*itm2,'abc') def func4(normal,*args, **kwargs): #kwargs take dictionary as input print(normal) for item in args: print(item) for key,value in kwargs.items(): print(f"The {key} is {value}") itm1=["d","e"] itm2={"Tarun":"name","bhatia":"surname"} func4('abc',*itm1,**itm2)
06e66ef4355902f462b8e90609f916a705bf6fba
Yema94/Python-Projects
/ioproject/mysandwich.py
1,143
4.15625
4
#yourway sandWITCH availableToppings = ["Onion", "Paprika", "Tomato", "Chicken", "Alpinos", "Teriyaki Sauce"] print("Available Toppings List : ") for i in range(len(availableToppings)) : print(i+1, availableToppings[i], sep=' : ') selectedToppings = [availableToppings[int(x)-1] for x in input("Select any 3 Toppings using comma separator: ") .split(',')] print("Toppings selected are :") for i in selectedToppings: print(i) #pizzaCost = 5 #menge = int(input("How many Pizzas ? ")) print("Your total is {} euros!".format(5*int(input("How many Pizzas? ")))) """ greeting = print("Hello,this is MyWay Sandwiches.\nWe offer sandwiches with the following toppings:\n - onions, lettuce, tomoto, olives, peppers, tomotoes.") print(type(greeting) = print("Please choose three of the above. \nEnter your choice in one row, separated by comma:") choice_1 = input() """choice = (x for x in input().split(",")) print(choice)""" thx = print("Thank you") num_sand_gues = print("How many sandwiches would you like?") num_quest_answ = int(input()) total = 5 * num_quest_answ print(f"You bill is {total}.\nThanks for visiting\nHave a nice day!") """
c50e122e5cb0cd39df9778c7dc8ba74b6e5fe85d
Shao-Ting/ST-s-Python-work
/'w401.py'35.py
726
3.734375
4
# coding: utf-8 words=''' 人生長至一世、短如一瞬 寰宇浩瀚無際,此生飄渺無歸 旅途上,我們將會遇到許多 或許喜悅、或許傷悲、或許歡喧、或許靜寧 請記得哭過、笑過,要繼續活下去 真正重要的到底是什麼 我們似乎都在追求著什麼 最後才發現 握緊手心,裡面什麼都沒有 一呼一吸 花開花落 追日、探月、索星、尋夢、逐塵 無論他人怎麼說,我們都是獨一無二的我們 紛紛擾擾的一生中 或許只有自己明白 或許自己也不明白''' words.split('\n') phrase=words.split('\n') p=randint(2,7) for i in range(p): pp=randint(1,3) egg=(choice(phrase,pp)) ham=','.join(egg) print(ham)
7b979b62e0828aae93811ff6b9c39fd5bca83ec5
sushmithasuresh/Python-basic-codes
/p9.py
228
4.28125
4
n1=input("enter num1") n2=input("enter num2") n3=input("enter num3") if(n1>=n2 and n1>=n3): print str(n1)+" is greater" elif(n2>=n1 and n2>=n3): print str(n2)+" is greater" else: print str(n3)+" is greater"
67ffa7346ed08a55081219fa505b1dade540f30a
SCOTPAUL/tangowithdjango
/tangowithdjango/rango/bing_search.py
1,882
3.5625
4
import json import urllib2 import keys BING_API_KEY = keys.BING_API_KEY def run_query(search_terms): # Base URL root_url = 'https://api.datamarket.azure.com/Bing/Search/' source = 'Web' results_per_page = 10 offset = 0 # Wrap search terms in quotation marks and make URL safe query = urllib2.quote("'{0}'".format(search_terms)) # The full URL, giving results in JSON with parameters above search_url = "{0}{1}?$format=json&$top={2}&$skip={3}&Query={4}".format( root_url, source, results_per_page, offset, query) # Used for authenticating with Bing servers username = '' # Authentication handler password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, search_url, username, BING_API_KEY) # List of search results results = [] try: # Prepare for connection to Bing's servers handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(handler) urllib2.install_opener(opener) # Connect to Bing server and read the response given response = urllib2.urlopen(search_url).read() # Convert JSON response to python dictionary json_response = json.loads(response) # Populate results list for result in json_response['d']['results']: results.append({ 'title': result['Title'], 'link': result['Url'], 'summary': result['Description']}) except urllib2.URLError as e: print "Error when querying the Bing API: " + str(e) return results def main(): results = run_query('hello world') for result in results: print result['title'] print result['link'] print result['summary'] print if __name__ == '__main__': main()
e7f3c1ea41c84714f907bea459b7fc743ee6f19d
gyang274/leetcode
/src/0900-0999/0977.squares.of.a.sorted.array.py
598
3.578125
4
from typing import List class Solution: def sortedSquares(self, A: List[int]) -> List[int]: stack, ans = [], [] for x in A: if x < 0: stack.append(x * x) else: s = x * x while stack and stack[-1] < s: ans.append(stack.pop()) ans.append(s) while stack: ans.append(stack.pop()) return ans if __name__ == '__main__': solver = Solution() cases = [ [-4,-1,0,3,5], [-8,-5,2,3,5], ] rslts = [solver.sortedSquares(A) for A in cases] for cs, rs in zip(cases, rslts): print(f"case: {cs} | solution: {rs}")
ab245ca8a5f29a0bf569aa2dfbdac15c472b15ac
Krzysztof-Lewandowski89/Python
/kurs-python/roz6/t6_5.py
239
3.640625
4
#przykłady krotek, operacje values = (1,2,3,4,5,6,7,8) new_values = values[:3] #wyciecie wartosci od 0 do 3 print(2 in new_values) new_values2 = new_values + (12, 24) #doklejenie/dodanie kolejnych dwoch wartości print(new_values2)
3f011626dfe2f23cd9240fb020ec56043280c907
lakshaysharma12/programs-in-python
/mile_to_km.py
1,025
3.84375
4
from tkinter import * windows = Tk() windows.minsize(width=300,height=500) windows.title("Miles to Kilometer") windows.config(padx = 20, pady = 20) input = Entry(width = 20) input.grid(column = 1,row =0) # input.config(padx = 10, pady =10) miles = Label(text = "MILES" ,font =("Arial",24)) miles.grid(column = 2, row =0) miles.config(padx = 10,pady = 10) def converter(): change = int(round(float(input.get()) *1.60934)) blank_text.config(text = change) guide = Label(text = "is equal to", font = ("Arial",24)) guide.grid(row = 1, column =0) # guide.config(padx = 10, pady = 10) blank_text = Label(text = "", font = ("Arial",24)) blank_text.grid(row = 1,column =1) # blank_text.config(padx = 10,pady =10) mile = Label(text = "KM",font =("Arial",24)) mile.grid(row = 1 ,column = 2) # mile.config(padx = 10,pady =10) button = Button(text= "CONVERT",command =converter) button.grid(row = 3 ,column =1) button.config(padx = 10, pady = 10) windows.mainloop()
8b86a6d0703659d631af14cfaaf4637df5a4d4ca
rishky1997/Python-Practice
/Day 9/Q2.py
227
4.5
4
#2.Write python program to check that given number is valid mobile number or not? import re s=input('Enter mobile no.') o=re.findall('[7-9][0-9]{9}',s) if o==[s]: print('No. is valid') else: print('No. is not valid')
041366d1c7e1ceac451623ce72e205c9a6efaf91
codingyen/CodeAlone
/Python/0108_convert_sorted_array_to_binary_search_tree.py
607
3.734375
4
# DFS # Find the logic and how to recursive. class TreeNode: def __init__(self, val = 0, left = None, right = None): self.val = val self.left = left self.right = right class Solution: def sortedArrayToBST(self, nums): if not nums: return None mid = len(nums) // 2 root = TreeNode(nums[mid]) root.left = self.sortedArrayToBST(nums[:mid]) root.right = self.sortedArrayToBST(nums[mid + 1 :]) return root if __name__ == "__main__": a = [-10, -3, 0, 5, 9] s = Solution() s.sortedArrayToBST(a)
a66da356646ef9b94841ebeb9638bb61c1ff0ada
idontknoooo/leetcode
/python-interview-project/question3.py
2,582
3.671875
4
# This is a program find minimum spanning tree(mst) from a graph # Import sys for sys.maxint import sys # Question3 def question3(G): # Return the edge size of G size = len(G) # Handle the one node case if size==1: single = {} for i in G: single[i] = [] print single return single # A vertex list for all vertex vertex = [key for key in G] # Convert input dict to matrix for further calculation matrix = [[sys.maxint for i in range(size)] for j in range(size)] visited_row = [0] # Initialize the matrix for node, row in zip(G, range(size)): for i in G[node]: column = vertex.index(i[0]) matrix[row][column] = i[1] # Initialize MST mst = {} for times in range(size): tmp_min = sys.maxint tmp_row = -1 tmp_col = -1 # Create MST using Prim's algorithm for i in visited_row: for j in range(size): if j not in visited_row and tmp_min > matrix[i][j]: tmp_min = matrix[i][j] tmp_row = i tmp_col = j visited_row.append(tmp_col) # add into visited list # Append intu MST if vertex[tmp_row] not in mst and vertex[tmp_row] != vertex[tmp_col]: mst[vertex[tmp_row]] = [] mst[vertex[tmp_row]].append((tmp_min, vertex[tmp_col])) elif vertex[tmp_row] != vertex[tmp_col]: mst[vertex[tmp_row]].append((tmp_min, vertex[tmp_col])) print mst return mst # Main function with test case def main(): # Test Cases # Udacity case G = {'A': [('B', 2), ('D', 4)], 'B': [('A', 2), ('C', 5), ('D', 3)], 'C': [('B', 5), ('D', 2)], 'D': [('A', 4), ('B', 3), ('C', 2)]} question3(G) # A simple case G1 = {'A': [('B', 2)], 'B': [('A', 2), ('C', 5)], 'C': [('B', 5)]} question3(G1) # A complicated case G2 = {'A': [('B', 2), ('C', 3), ('D', 3)], 'B': [('A', 2), ('C', 4), ('E', 3)], 'C': [('A', 3), ('B', 4), ('E', 1), ('F', 6)], 'D': [('A', 3), ('F', 7)], 'E': [('B', 3), ('C', 1), ('F', 8)], 'F': [('C', 6), ('D', 7), ('E', 8), ('G', 9)], 'G': [('F', 9)]} question3(G2) # Empty case G3 = {} question3(G3) # One node case G4 = {'A': []} question3(G4) # Two node case G5 = {'S': [('OS', 4)], 'OS': [('S', 4)]} question3(G5) return 0 # Call main function if __name__ == "__main__": main()
497eebcb804b1b56a816b81c665292a289e1a8c4
doug3230/Portfolio
/Simplex/src/rational.py
14,702
3.8125
4
""" ------------------------------------------------------- rational.py contains code for the Rational class. ------------------------------------------------------- Author: Richard Douglas Email: [email protected] Version: 2014-01-21 ------------------------------------------------------- """ import rational_functions from math import pow class Rational: """ ------------------------------------------------------- The Rational class models fractions used in math. ------------------------------------------------------- Attributes: num (the top of the fraction) den (the bottom of the fraction) Both of these are integers with the denominator not equal to 0. ------------------------------------------------------- Operations: Rational(num, den = 1) - Initializes Rational. str - Converts Rational to string form. num - Rational's numerator. den - Rational's denominator. + - Sum operation. - - Subtraction operation. * - Multiplication operation. / - Division operation. == - Test for equality. < - Less than comparator. <= - Less than or equal to comparator. (and other comparators by extension.) is_negative - Checks if Rational is less than 0. is_zero - Checks if Rational is equal to 0. is_positive - Checks if Rational is greater than 0. is_int - Checks if Rational is an integer. to_float - Rational as a floating point number. ------------------------------------------------------- Static Operations: parse_number - Converts a number to a Rational. parse_string - Converts a string to a Rational. ------------------------------------------------------- """ def __init__(self, num, den=1): """ ------------------------------------------------------- Initializes self. ------------------------------------------------------- Preconditions: num - the passed in numerator (int) den - the passed in denominator (int != 0) (den is optional and defaults to 1) Postconditions: Constructs an instance of the Rational class. Note: to make working with Rationals easier, the stored numerator and denominator have no factors in common. Thus Rational(2,4) has the same numerator and denominator as Rational(1,2). Also, negative Rationals have their numerators as negative and the 0 Rational has a denominator of 1. ------------------------------------------------------- """ assert num == int(num), "numerator must be an integer" assert den == int(den), "denominator must be an integer" assert den != 0, "denominator cannot be 0" num, den = rational_functions.normalize(num, den) # by default has them as floats for some reason self._num = int(num) self._den = int(den) return def __str__(self): """ ------------------------------------------------------- Converts self to string form. ------------------------------------------------------- Postconditions: returns - If self is an integer, the string form of that integer. Otherwise returns a string of form "'num' / 'den'" (string) ------------------------------------------------------- """ if self.is_int(): return str(self._num) else: return "{0:d} / {1:d}".format(self._num, self._den) def num(self): """ ------------------------------------------------------- self's numerator. ------------------------------------------------------- Postconditions: returns - the top number of the fraction (int) ------------------------------------------------------- """ return self._num def den(self): """ ------------------------------------------------------- self's denominator. ------------------------------------------------------- Postconditions: returns - the bottom number of the fraction (int) ------------------------------------------------------- """ return self._den def __add__(self, other): """ ------------------------------------------------------- The sum of self and other. ------------------------------------------------------- Preconditions: other - the right operand of the sum (Rational or float) Postconditions: returns - the value resulting from the sum (Rational) ------------------------------------------------------- """ try: new_num = (self._num * other._den) + (self._den * other._num) new_den = (self._den * other._den) return Rational(new_num, new_den) except AttributeError: return (self + Rational.parse_number(other)) def __sub__(self, other): """ ------------------------------------------------------- The subtraction from self of other. ------------------------------------------------------- Preconditions: other - the right operand of the subtraction (Rational or float) Postconditions: returns - the value resulting from the subtraction (Rational) ------------------------------------------------------- """ try: new_num = (self._num * other._den) - (self._den * other._num) new_den = (self._den * other._den) return Rational(new_num, new_den) except AttributeError: return (self - Rational.parse_number(other)) def __mul__(self, other): """ ------------------------------------------------------- The product of self and other. ------------------------------------------------------- Preconditions: other - the right operand of the multiplication (Rational or float) Postconditions: returns - the value resulting from the multiplication (Rational) ------------------------------------------------------- """ try: new_num = (self._num * other._num) new_den = (self._den * other._den) return Rational(new_num, new_den) except AttributeError: return (self * Rational.parse_number(other)) def __truediv__(self, other): """ ------------------------------------------------------- The division from self of other. ------------------------------------------------------- Preconditions: other - the right operand of the division (Rational != 0 or float != 0) Postconditions: returns - the value resulting from the division (Rational) ------------------------------------------------------- """ try: assert not other.is_zero(), "cannot divide by 0." new_num = (self._num * other._den) new_den = (self._den * other._num) return Rational(new_num, new_den) except AttributeError: return (self / Rational.parse_number(other)) def __eq__(self, other): """ ------------------------------------------------------- Is self equal to other? ------------------------------------------------------- Preconditions: other - the right operand of the '==' test for equality (Rational or float) Postconditions: returns - True if self and other have the same numerator and denominator, False otherwise. ------------------------------------------------------- """ try: same_num = (self._num == other._num) same_den = (self._den == other._den) return same_num and same_den except AttributeError: return (self == Rational.parse_number(other)) def __lt__(self, other): """ ------------------------------------------------------- Is self less than other? ------------------------------------------------------- Preconditions: other - the right operand of the '<'comparison (Rational or float) Postconditions: returns - True if the fraction corresponding to self is less than the fraction corresponding to other, False otherwise. ------------------------------------------------------- """ try: lhs = (self._num * other._den) rhs = (other._num * self._den) return (lhs < rhs) except AttributeError: return (self < Rational.parse_number(other)) def __le__(self, other): """ ------------------------------------------------------- Is self less than or equal to other? ------------------------------------------------------- Preconditions: other - the right operand of the '<=' comparison (Rational or float) Postconditions: returns - True if the fraction corresponding to self is less than or equal to the fraction corresponding to other, False otherwise. ------------------------------------------------------- """ try: lhs = (self._num * other._den) rhs = (other._num * self._den) return (lhs <= rhs) except AttributeError: return (self <= Rational.parse_number(other)) def is_negative(self): """ ------------------------------------------------------- Is self less than 0? ------------------------------------------------------- Postconditions: returns - True if the fraction corresponding to self is < 0, False otherwise. Note: This method is provided for convenience as it requires less overhead than using < 0. ------------------------------------------------------- """ return (self._num < 0) def is_zero(self): """ ------------------------------------------------------- Is self equal to 0? ------------------------------------------------------- Postconditions: returns - True if the fraction corresponding to self is 0, False otherwise. Note: This method is provided for convenience as it requires less overhead than using == 0. ------------------------------------------------------- """ return (self._num == 0) def is_positive(self): """ ------------------------------------------------------- Is self greater than 0? ------------------------------------------------------- Postconditions: returns - True if the fraction corresponding to self is > 0, False otherwise. Note: This method is provided for convenience as it requires less overhead than using > 0. ------------------------------------------------------- """ return (self._num > 0) def is_int(self): """ ------------------------------------------------------- Is self an integer? ------------------------------------------------------- Postconditions: returns - True if the fraction corresponding to self is an integer, False otherwise. ------------------------------------------------------- """ return (self._den == 1) def to_float(self): """ ------------------------------------------------------- self as a floating point number. ------------------------------------------------------- Postconditions: returns - self's numerator divided by its denominator (float) ------------------------------------------------------- """ return (self._num / self._den) @staticmethod def parse_number(value): """ ------------------------------------------------------- Converts a number to a Rational. ------------------------------------------------------- Preconditions: value - the number to convert (float) Postconditions: returns - a Rational object corresponding to the number's representation as a fraction (Rational) ------------------------------------------------------- """ string_form = str(value) comps = string_form.split(".") int_comp = int(comps[0]) if (len(comps) == 1): return Rational(int_comp) else: dec_string = (comps[1]) tens = len(dec_string) dec_comp = int(dec_string) den = (pow(10, tens)) num = (int_comp * den) + dec_comp return Rational(num, den) @staticmethod def parse_string(str_value): """ ------------------------------------------------------- Converts a string to a Rational. ------------------------------------------------------- Preconditions: str_value - the string to convert (string of form 'a/b' or 'a / b', the string could also just be of an integer like "2") Postconditions: returns - a Rational object corresponding to the number's representation as a fraction (Rational) ------------------------------------------------------- """ comps = str_value.split("/") assert len(comps) <= 2, "Cannot parse {0} as Rational".format(str_value) num_string = comps[0].strip() if (len(comps) == 1): return Rational(int(num_string)) else: den_string = comps[1].strip() return Rational(int(num_string), int(den_string))
52c3ddeb6b3a17f2183a9125eaafaa2f5c5ab6b7
thanhtuan18/anthanhtuan-fundametal-c4e15
/Session5/test.py
884
3.921875
4
#person = ["Tuan anh", 22, 2, "Hanoi", "Moc chau", 5, 4, "Maria", "Ping pong"] # person = {} # print(person) # # person = { # # key : value # "name": "Tuan anh" # } # print(person) person = { # key : value "name": "Tuan anh", "age": 22, "sex": "male" } # for k in person: # print(k, person[k]) # if "age" in person: # print(person["age"]) # for k in person: # print(person[k]) # for k in person.values(): # print(k) # for key, value in person.items(): # print(key, value) # person["age"] +=1 # cach 1 for key in person: print(key, end=" ") print() code = input("Your code? ") if code in person: print(code, person[code]) else: new = input("Not found, do you want to contribute this word? (Y/N)?" ) if new == "Y": new_key = input("Enter your translation: ") person[code] = new_key print("Updated")
4309a71d5fe0604a27141238c207f1f3b6d87866
paulo-caixeta/Curso_Python-CursoEmVideo-Guanabara
/ex016.py
90
3.734375
4
import math n = float(input('Digite um número real qualquer: ')) print(math.floor(n))