blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
ececf84cecb60878a30edeca512123ce6c5aa5d1
s16003/PythonTutorial
/janken/play.py
2,021
3.875
4
HANDS = ('ใ‚ฐใƒผ', 'ใƒใƒงใ‚ญ', 'ใƒ‘ใƒผ') def select_hand(): """ ใ‚ณใƒณใƒ”ใƒฅใƒผใ‚ฟใฎๆ‰‹ใ‚’ใƒฉใƒณใƒ€ใƒ ใซๆฑบใ‚ใ‚‹ :return: HANDSใฎไธญใฎใ„ใšใ‚Œใ‹ใ€‚ """ import random return random.choice(HANDS) def judgement(player, computer): """ ใ˜ใ‚ƒใ‚“ใ‘ใ‚“ใฎๅ‹ๆ•—ใ‚’ๅˆคๅฎšใ™ใ‚‹ใ€‚ :param player: HANDSใฎไธญใฎใฉใ‚Œใ‹ :param computer: HANDSใฎไธญใฎใฉใ‚Œใ‹ :return: ใƒ—ใƒฌใ‚คใƒคใƒผใŒๅ‹ใกใฎๅ ดๅˆใฏ1,ใ‚ใ„ใ“ใฏ0,่ฒ ใ‘ใฏ-1ใ‚’่ฟ”ใ™ """ if player == 1: if computer == 'ใƒใƒงใ‚ญ': return 1 elif computer == 'ใƒ‘ใƒผ': return -1 else: return 0 elif player == 2: if computer == 'ใƒ‘ใƒผ': return 1 elif computer == 'ใ‚ฐใƒผ': return -1 else: return 0 elif player == 3: if computer == 'ใ‚ฐใƒผ': return 1 elif computer == 'ใƒใƒงใ‚ญ': return -1 else: return 0 def save_score(result): """ 'score.txt'ใซๆˆฆ็ธพใ‚’ไฟๅญ˜ใ€‚ win:x lose:y draw:zใฎใƒ‡ใ‚ฃใ‚ฏใ‚ทใƒงใƒŠใƒชใƒ‡ใƒผใ‚ฟใ‚’ไฟๅญ˜ใ™ใ‚‹ใ€‚ :param result: :return: None """ import json dic = {"win": "x"} dic2 = {"lose": "y"} dic3 = {"draw": "z"} with open('score.txt', 'a') as f: if result == 1: json.dump(dic, f, sort_keys=True, indent=4) elif result == -1: json.dump(dic2, f, sort_keys=True, indent=4) elif result == 0: json.dump(dic3, f, sort_keys=True, indent=4) return None if __name__ == '__main__': player = int(input('ใ‚ฐใƒผ(1)/ใƒใƒงใ‚ญ(2)/ใƒ‘ใƒผ(3)ใ‚’้ธใ‚“ใงใใ ใ•ใ„(ๆ•ฐๅญ—): ')) computer = select_hand() result = judgement(player, computer) # ใ‚ณใƒณใƒ”ใƒฅใƒผใ‚ฟใฎๆ‰‹ใจๅ‹ๆ•—ใฎ็ตๆžœใ‚’่กจ็คบ print(computer) if result == 1: print("win") elif result == 0: print("draw") elif result == -1: print("lose") save_score(result)
92dc8e04eff81c4473800ea900bd8ade076cca4e
akshat12000/Python-Run-And-Learn-Series
/Codes/205) regex.py
5,086
4.4375
4
# A regular exepression is a special text string for describing a search pattern import re String='Akshat is 20 and Lekhansh is 16' # 1) findall() --> to find all the patters of similar types in the given string names=re.findall(r"[A-Z][a-z]*",String) # for alphabets ( here [A-Z][a-z]* means selecting pattern which has both lower and upper case letters) age=re.findall(r'\d',String) # by this it will create a list of of one digit numbers print(names) # this will print : ['Akshat', 'is', 'and', 'Lekhansh', 'is'] ; that is all the alphabets pattern! print(age) # this will print : ['2', '0', '1', '6'] ; that is all the digits pattern! age2=re.findall(r'\d{1,2}',String) # by this it will create a list of of two digit numbers print(age2) # this will print : ['20', '16'] names2=re.findall(r'[A-Z]',String) # for alphabets ( here [A-Z] means selecting only upper case letters) print(names2) # this will print : ['A','L'] names3=re.findall(r'[a-z]',String) # for alphabets ( here [a-z] means selecting only lower case letters) print(names3) # this will print : ['k', 's', 'h', 'a', 't', 'i', 's', 'a', 'n', 'd', 'e', 'k', 'h', 'a', 'n', 's', 'h', 'i', 's'] # Note: if we write names2=re.findall(r'[A-Z]',String) then it would have included the spaces also and same case for names3 names4=re.findall(r'[A-Z]*',String) print(names4) # this will print : ['A', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'L', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] names5=re.findall(r'[a-z]*',String) print(names5) # this will print : ['', 'kshat', '', 'is', '', '', '', '', 'and', '', '', 'ekhansh', '', 'is', '', '', '', ''] test="He is very cool. He is awsome!" matches=re.findall("is",test) # this will find all the "is" from the given text and make a list of them print(matches) for i in matches: print(i) pat="Sat, mat, pat, cat" res=re.findall("[Smpc]at",pat) # this will collect all the pattern from the string 'pat' which ends with 'at' and starts with 'S','m','p'and'c' (specified through [Smpc]) !! print(res) res2=re.findall("[mp]at",pat) # this will collect all the pattern from the string 'pat' which ends with 'at' and starts with 'm' and 'p' (specified through [mp]) !! print(res2) res3=re.findall("[c-p]at",pat) # this will collect all the pattern from the string 'pat' which ends with 'at' and starting ranging from 'c' to 'p' (specified through [c-p]) !! print(res3) res3=re.findall("[^m-p]at",pat) # this will collect all the pattern from the string 'pat' which ends with 'at' and exclude the starting ranging from 'm' to 'p' (specified through [^m-p]) !! print(res3) # Note: ^ is used to exclude specific pattern # 2) search() --> this helps us to search for any pattern in the given text String2="This is very nice tutorial for beginners!" print(type(re.search("very",String2))) # it will print <class 're.Match'> , it is an object of class re.Match if re.search("very",String2): print("It is present") else: print("Not Found!") if re.search("Hello",String2): print("It is present") else: print("Not Found!") ran="Here is \\akshat" print(ran) print(re.search(r"\\akshat",ran)) # it will print <re.Match object; span=(8, 15), match='\\akshat'> # 3) finditer() --> this will give the starting and ending index of matched pattern in the given text(or string) test2="He is very cool. He is awsome!" for i in re.finditer("is",test2): tup=i.span() # this will make tuple 'tup' and put the starting and ending index in it!! print(tup) print(type(tup)) # 4) compile() and sub() t1=re.compile("is") print(t1) a1=re.sub("is","was",test2) # by this it will replace all "is" with "was" print(a1) a2=t1.sub("was",test2) # by this also it will replace all "is" with "was" print(a2) a3= re.sub("is","was",test2,1) # by this it will replace only one "is" with "was" print(a3) String3='''Hi! How are You? ''' print(String3) t2=re.compile("\n") String3=t2.sub(" ",String3) # replacing "\n" with " " print(String3) # Difference between \d and \D num="12345" print("Matches",re.findall('\d',num)) # it give the list one digit numbers in the given string print("Matches",re.findall('\d{5}',num)) # it will print ['12345'] print("Matches",re.findall('\d{4}',num)) # it will print ['1234'] print("Matches",re.findall('\D',num)) # it will print [] since \D means anything except numbers or [^0-9] num1="123 1234 12345 123456 1234567" print("Matches",re.findall('\d{5,7}',num1)) # it will print ['12345', '123456', '1234567'] ; i.e. those patterns which contain 5 to 7 length of digits!! # Note: \w --> [a-zA-Z0-9] and \W --> [^a-zA-Z0-9] # Note: \s --> [\f\n\r\t\v] ans \S --> [^\f\n\r\t\v] # Example question --> Email verifier!! '''A valid Email should have : 1) 1 to 20 lowercase and uppercase letters, numbers 2) @ symbol 3) 2 to 20 lowercase and uppercase letters, numbers 4) A period(.) 5) 2 to 3 lowercase and uppercase letters ''' emails="akshat174@gmail.com lekhansh@.com" print("Matched Emails!",re.findall("[\w]{1,20}@[\w]{2,20}.[A-Za-z]{2,3}",emails)) # Note: only "akshat174@gmail.com" will get printed!
5761ee14b524939698d5a1751d6212148dcc509d
anubhab-code/HackerRank
/Python/Introduction/Python If-Else.py
147
3.625
4
N = int(input().strip()) n= N w = 'Weird' nw = 'Not Weird' if ((n % 2 == 1) or (n % 2 == 0 and (n>=6 and n<=20))): print(w) else: print(nw)
fc55c50207ef42b6b45f28bf6e426be88317baca
Eok99/python_workout
/20201127/8-1.py
939
3.515625
4
#ํ‘œ์ค€ ์ž…์ถœ๋ ฅ print("ํŒŒ์ด์ฌ" , "์ž๋ฐ”", sep="vs") #sep์‚ฌ์ด์— ๋“ค์–ด ๊ฐ€๋Š” ๊ฐ’์„ ๋„ฃ์„ ์ˆ˜ ์žˆ์Œ. print("ํŒŒ์ด์ฌ" , "์ž๋ฐ”", sep=" , ", end = "?") # end ๋งˆ์ง€๋ง‰์— # # import sys # print("python", "java", file=sys.stdout) # print("python", "java", file=sys.stderr) # # ํ‘œ์ค€ ์—๋Ÿฌ๋กœ ์ฒ˜๋ฆฌ๋˜๋Š”๊ฑฐ?? ๋จผ๋ง์ธ์ง€๋ชจ๋ฆ„. # scores = {"์ˆ˜ํ•™":0, "์˜์–ด":50, "์ฝ”๋”ฉ":100} # for subject, score in scores.itmes(): # # print(subject,score) # print(subject.ljust(8), str(score).rjust(4), sep=":") #์™ผ์ชฝ์œผ๋กœ ์ •๋ ฌ์„ ํ•˜๋Š”๋ฐ 8์นธ์„ ํ™•๋ณดํ•˜๊ณ  ์ •๋ ฌ. # ์€ํ–‰ ๋Œ€๊ธฐ ์ˆœ๋ฒˆํ‘œ #001,002,003,004,005, ... for num in range(1,21): print("๋Œ€๊ธฐ๋ฒˆํ˜ธ : " +str(num).zfill(3)) answer = input("์•„๋ฌด๊ฐ’์ด๋‚˜ ์ž…๋ ฅํ•˜์„ธ์š” : ") #input์œผ๋กœ ๋ฐ›๋Š”๊ฒƒ์€ str๋กœ ๋œ๋‹ค๋Š”๊ฒƒ. print(type(answer)) # print("์ž…๋ ฅํ•˜์‹  ๊ฐ’์€ : "+answer + "์ž…๋‹ˆ๋‹ค") #str์—†์ด๋„ ์ž˜ ์ถœ๋ ฅ๋˜๋Š”๊ฑธ ์•Œ ์ˆ˜์žˆ์Œ
b167cdd607b70ec421d902a503b43c6d7d6055bd
ongaaron96/kattis-solutions
/python3/1_9-akcija.py
259
3.71875
4
num_books = int(input()) prices = [] for _ in range(num_books): prices.append(int(input())) prices.sort(reverse=True) total_price = 0 for index, price in enumerate(prices): if (index + 1) % 3 == 0: continue total_price += price print(total_price)
fd54bd44c782fe23a0592467590c57a5c02d1651
phucduongBKDN/100exercies
/100 exercise/no10.py
433
3.84375
4
# Number Complement def split(word): return [char for char in word] num = int(input("Enter num: ")) def numberComplement(num): num= format(num,'b') # print(type(num)) list = split(num) list2 = [] print(list) for i in list: i = int(i) i ^= 1 i = str(i) list2.append(i) list2 = ''.join(list2) number = int(list2, 2) return number print(numberComplement(num))
7774ca31be3c26d986106687d4350479b772d9b8
pedrodiogo219/graduation
/sd/anel_threads/anel-simplificado.py
2,022
3.75
4
#!/usr/bin/python import threading import time class myThread (threading.Thread): def __init__ (self, id): threading.Thread.__init__(self) self.id = id self.awake = False self.finished = False self.text = '' self.next = None def setNext(self, next): self.next = next def run(self): print(f'Thread {self.id} - Running') #roda enquanto nao terminou while not self.finished: #se eu nao devo acordar, volto a dormir if not self.awake: time.sleep(0.100) #se for minha vez de acordar else: #flag pra checar se eu achei alguma letra minuscula find = False for i in range (0, len(self.text)): #quando achar a primera minuscula #faz a troca e quebra o laรงo if self.text[i].islower(): find = True self.text = self.text[:i] + self.text[i].upper() + self.text[i+1:] break #se eu fiz alguma troca, volto a dormir e acordo a proxima if find: print(f'im #{self.id} --- {self.text}') self.awake = False self.next.wakeUp(self.text) #se nao fiz troca, o trabalho esta terminado else: self.finished = True #agora que eu sei que ja terminei, aviso a proxima self.next.finished = True print(f'Thread {self.id} - Exiting') #acorda a proxima thread def wakeUp(self, text): self.text = text self.awake = True def main(): t0 = myThread(0) t1 = myThread(1) t2 = myThread(2) t0.setNext(t1) t1.setNext(t2) t2.setNext(t0) t0.start() t1.start() t2.start() text = input('Digite uma string:\n') print(text) t0.wakeUp(text) print('exiting main') main()
c5c7057fc9039dcb2b16d37d321b66557c75ad9c
tan-eddie/google-code-jam-2020
/round_1a/pattern_matching/pattern_matching.py
1,939
3.609375
4
def head_match(a, b): i = 0 j = 0 while i < len(a) and j < len(b): if a[i] != b[j]: return False else: i += 1 j += 1 return True def tail_match(a, b): i = len(a) - 1 j = len(b) - 1 while i >= 0 and j >= 0: if a[i] != b[j]: return False else: i -= 1 j -= 1 return True def get_subpatterns(pattern): """ Get subpattern such that there is always a head and tail. E.g. A*B*C gives ["A", "B", "C"], *ABC gives ["", "ABC"] ABC* gives ["ABC", ""] A*BC* gives ["A", "BC", ""] """ subpatterns = [] curr = "" for c in pattern: if c == "*": subpatterns.append(curr) curr = "" else: curr += c subpatterns.append(curr) return subpatterns def match_all(patterns): subpatterns = [] for p in patterns: subpatterns.append(get_subpatterns(p)) # Build head. head = subpatterns[0][0] for s in subpatterns: if len(s[0]) > len(head): head = s[0] for s in subpatterns: if not head_match(head, s[0]): return "*" # Build tail. tail = subpatterns[0][-1] for s in subpatterns: if len(s[-1]) > len(tail): tail = s[-1] for s in subpatterns: if not tail_match(tail, s[-1]): return "*" # Build middle (can be in any order). middle = [] for s in subpatterns: middle.extend(s[1:-1]) # Build the string. return head + "".join([x for x in middle]) + tail def main(): num_cases = int(input()) for i in range(num_cases): n = int(input()) patterns = [] for j in range(n): patterns.append(input()) answer = match_all(patterns) print("Case #{:d}: {:s}".format(i+1, answer)) if __name__ == "__main__": main()
5e4353718e8a538482c8bbd0f5e360fc81f71399
ekeilty17/Project_Euler
/P089.py
3,661
3.96875
4
# Basic Rules of Roman Numerals # 1) Numerals must be written in descending order # 2) M, C, and X must not be equalled or exceeded by smaller demoninations # 3) D, L, and V can only appear once # But then we want subtractive combinations, so we add these rules # 4) Only one I, X, C can be used as the leading numeral in a subtractive pair # 5) I can only be placed before V and X # 6) X can only be placed before L and C # 7) C can only be placed before D and M roman_to_arabic = { 'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000, 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900 } # It'd be fun to write this function, but it's not needed for this problem """ def isroman_to_arabicidRomanNumeral(R): # Numerals must be written in descending order if R != "".join( sorted(R, key = lambda x: -roman_to_arabic[x]) ): return False # M, C, and X must not be equalled or exceeded by smaller demoninations if roman_to_arabic['I'] * R.count('I') >= roman_to_arabic['X'] or roman_to_arabic['V'] * R.count('V') >= roman_to_arabic['X']: return False if roman_to_arabic['X'] * R.count('X') >= roman_to_arabic['C'] or roman_to_arabic['L'] * R.count('L') >= roman_to_arabic['C']: return False if roman_to_arabic['C'] * R.count('C') >= roman_to_arabic['M'] or roman_to_arabic['D'] * R.count('D') >= roman_to_arabic['M']: return False # D, L, and V can only appear onces if R.count('V') > 1 or R.count('L') > 1 or R.count('D') > 1: return False return True print isroman_to_arabicidRomanNumeral('MMMMDCLXVII') """ def RomanToArabic(R): #if not isroman_to_arabicidRomanNumeral(R): # return False total = 0 i = 0 while i < len(R): if i < len(R) - 1 and R[i:i+2] in ['IV', 'IX', 'XL', 'XC', 'CD', 'CM']: total += roman_to_arabic[R[i:i+2]] i += 2 else: total += roman_to_arabic[R[i]] i += 1 return total def minRomanNumeral(n): R = "" while n > 0: # recall # - C can only be placed before D and M # - X can only be placed before L and C # - I can only be placed before V and X # Therefore, we just add the largest possible roman digit we can add (i.e. greedy algorithm) for roman_digit, value in reversed(sorted(roman_to_arabic.items(), key=lambda t: t[1])): if n >= value: R += roman_digit n -= value break return R # counting the total number of characters in a list of strings def total_characters(L): return sum([len(x) for x in L]) def main(roman_numerals): roman_numerals_minimal = [] for R in roman_numerals: n = RomanToArabic(R) R_minimal = minRomanNumeral(n) roman_numerals_minimal.append( R_minimal ) #print(n, R, R_minimal) diff = total_characters(roman_numerals) - total_characters(roman_numerals_minimal) print(f"The number of characters saved by writing each of the roman numerals in their minimal form is:", diff) if __name__ == "__main__": # reading files with open("p089_roman.txt",'r') as f: lines = f.readlines() # cleaning inputs roman_numerals = [line.strip() for line in lines] # getting solution main(roman_numerals)
2d381445f2c99d0f766e6b89003035809f5d4a93
Parth731/Python-Tutorial
/pythontut/46_Self_and_Constructor.py
617
3.96875
4
class Employee: no_of_leaves = 8 def __init__(self,name,salary,role): self.name = name self.salary = salary self.role = role def printdetails(self): # print(self) return f"The Name is {self.name}. Salary is {self.salary} and role is " \ f"{self.role} " harry = Employee("harry", 455, "instructor") rohan = Employee("Rohan", 4554, "student") # harry.name = "harry" # harry.salary = 455 # harry.role = "instructor" # # rohan.name = "Rohan" # rohan.salary = 4554 # rohan.role = "student" print(rohan.printdetails()) print(harry.printdetails())
1ca1e31c9635559a29a96e11b0c680099ae9b88d
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/sieve/b45fd325255346eab82f5767f079a6bd.py
204
3.65625
4
#!/usr/bin/env python3 def sieve(limit): a = [i*j for i in range(2, limit + 1) for j in range(2, limit + 1) if i*j <= limit] b = set(range(2, limit + 1)) return list(b ^ set(a))
3bad3eb204fe6bcaf9d8beb8ec291c296486cbc4
angelvv/HackerRankSolution
/Algorithms/Warmup/06.PlusMinus.py
566
3.8125
4
#!/bin/python3 import math import os import random import re import sys # from decimal import * # Complete the plusMinus function below. def plusMinus(arr): # getcontext().prec = 6 length = len(arr) print("%.6f" % (sum(n>0 for n in arr)/length)) print("%.6f" % (sum(n<0 for n in arr)/length)) print("%.6f" % (sum(n==0 for n in arr)/length)) #print(round(sum(n==0 for n in arr)/length,6)) # not work for 0.5 though if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) plusMinus(arr)
1899af5f154956047fd5f2a59a58a02f8de04596
Hamza-ai-student/hamza
/Untitled27.py
7,529
4.03125
4
#!/usr/bin/env python # coding: utf-8 # # ..........................ASSIGMENT AI BATCH 3.....27/11/19................................... # In[137]: dir(name) # ## CAPITALIZE() # In[1]: name = "My NamE is HaMZa i AM a sTuDent of PiAic iSlaMAbaD,baTch 3 OF aRtiFiciAl inTtelligenCE" print(name.capitalize()) #the capitalize() method converts the first character of a string to capital (uppercase) #letter # ## CASEFOLD() # In[2]: print(name.casefold()) #The casefold() method is an aggressive lower() method which convert strings to casefolded #strings for caseless matching. The casefold() method is removes all case distinctions #present in a string. It is used for caseless matching, i.e. ignores cases when comparing. # ## CENTE() # In[3]: name1 = "my name is hamza" #center() method alligns string to the center by filling paddings print(name1.center(20," ")) #left and right of the string. print(name1.center(30,"7")) #30 is total number of ibdex in this sentence while 7 is the word that print(name1.center(17,"s")) #we wannt to add on both side of string print(name1.center(26,"h")) # ## COUNT() # In[4]: x = ('a','b','a','c','a','d') #it is used to count anyword,integer or alphabet in a tuple, sentence = ('my name is hamza and hamza is my cousin also') #list and index and etc. z = ('hamza','daud','pak','hamza','fruit') print(x.count('a')) print(sentence.count('my')) print(z.count('hamza')) # ## END # In[5]: print('my name is hamza',end=' ') print('my name is hamza forever') print('my name is hamza as a pakistani') # In[6]: print('my name is hamza and i am from Pakistan',end='.') #The end key of print function will set the string print('i like to play hockey',end=' national game .') #that needs to be appended when printing is done print('there are 12 players in hockey') print('my father name is Muhammmad') # ## ENDSWITH() # In[11]: print(name.endswith('E')) #it will match the latter with the latter present at the end of the string print(name.endswith('n')) print(name1.endswith('a')) print(name1.endswith('h')) # ## EXPANDTABS() # In[22]: name2 = "hamza\tis a PIAIC student" name3 = "My NamE is HaMZa\ti AM a sTuDent of PiAic iSlaMAbaD\t,baTch 3 OF aRtiFiciAl inTtelligenCE" print(name2.expandtabs(20)) print(name3.expandtabs(10)) # ## FORMAT # In[24]: name4 = 'my name is {fname} and {fname} is also my friend i have a lot of friends named as {fname}' print(name4.format(fname ='hamza')) # ## FIND() # In[27]: print(name.find('my')) #through this function you can get the position of a word in an index string tuple and list # ## FORMAT_MAP() # In[42]: address={'area':'model town','city':'Islamabad','country':'Pakistan'} print('{area} {city} {country}' .format_map(address)) # ## INDEX() # In[49]: print(name.index('m')) #it will give you the index of na specified chaacte in a sting # ## ISALNUM() # In[50]: print(name.isalnum()) #tell you if sting is alphanumeic or not # ## ISALPHA() # In[53]: name6 ='hamza' name7 ='hamza89' print(name6.isalpha()) print(name7.isalpha()) # ## ISDECIMAL() # In[59]: name8 ='hamza' #it can tell you that the string has any decimal value............decimal is the num name9 ='10' #which can be divided by 10 print(name.isdecimal()) print(name8.isdecimal()) print(name9.isdecimal()) # ## ISDIGIT() # In[62]: print(name.isdigit()) #it can tell you will the sting holds any digit print(name9.isdigit()) #name9 = 10 # ## ISIDENTIFIER() # In[65]: name10 = 'hamzashaif' name11 = 'hamza_shaif' print(name.isidentifier()) #it can be used to detect the identifie like _ that and can warn you about the print(name10.isidentifier()) print(name11.isidentifier()) #spaces between the two words # ## ISLOWER() # In[69]: print(name.islower()) #the all the wodrs of the string are small or not print(name10.islower()) # ## ISNUMERIC() # In[72]: name12 = '67897h' name13 = '800086' print(name.isnumeric()) #the all the words of the string ae numbers or not print(name12.isnumeric()) print(name13.isnumeric()) # ## ISPRINTABLE() # In[76]: print(name.isprintable()) #the all charactes of the string are printable or not print(name12.isprintable()) # ## ISSPACE() # In[79]: name14 = ' ' print(name.isspace()) #all the string is included on whitespaces o not if it is then it will be tue othewise false print(name14.isspace()) # ## ISTITTLE() # In[82]: name15 = 'My Name Is Hamza' print(name.istitle()) #each alphabet of the each letter is upper case or not print(name15.istitle()) # ## ISUPPER() # In[84]: name16 = 'MY NAME IS HAMZA' print(name.isupper()) #whole string has upper case letter or not print(name16.isupper()) # ## JOIN () # In[87]: name17 ={'hamza','is','my','friend'} print(' '.join(name17)) print('>>>>'.join(name17)) # ## IJUST() # In[91]: name18='i am livivng in ' name18=name18.ljust(20) print(name18,"islamabad") #return 20 character space from left justified # ## LOWER() # In[92]: print(name.lower()) #it will convet all the alphabets in samll letter # ## ISTRIP() # In[98]: name19 = " hamza" print(name19.lstrip()) #remove all spaces from the left side of the sting # ## PARTITION() # In[101]: name='my name is hamza' print(name.partition('hamza')) #it will resturn a tuple # ## REPLACE() # In[102]: name = 'my name is hamza and i am student of BA' print(name.replace('BA','PIaic islamabad of batch 3')) # ## RFIND() # In[105]: print(name.rfind('a')) #find the index of the specified word and if index not found then the return will be -1 # ## RJUST() # In[112]: name = 'islamabad' print(name.rjust(25)) # ## RPASRTITIOM() # In[116]: name = "My NamE is HaMZa i AM a sTuDent of PiAic iSlaMAbaD,baTch 3 OF aRtiFiciAl inTtelligenCE" print(name.rpartition('sTuDent')) #split the specified wod into an r index # ## RSPLIT() # In[118]: print(name.rsplit()) #convet string into list # ## RSTRIP() # In[120]: print(name.rstrip()) # ## SPLIT() # In[122]: print(name.split()) # ## SPLITLINES # In[124]: print(name.splitlines()) # ## STARTSWITH() # In[127]: print(name.startswith('start ')) #it will tell you the first letter of sting will be this or not\ print(name.startswith('My')) # ## Strip() # In[128]: print(name.strip()) # ## swapcase() # In[129]: print(name.swapcase()) #it will convet upper case letter into lower case letter and lower case letter into #upper case letter # ## tittle() # In[131]: print(name.title()) #convet first letter of each wod in the sting into upper case letter # ## upper() # In[133]: print(name.upper()) #convert all the letters of the sting into the upper case letter # ## zfill() # In[136]: name25 = 'hamza' print(name25.zfill(7)) #add zero into the sting afte the total the wods inthe string # # ____________________ERRORS_______________________ # In[ ]: #1)flush function...... #2)file function...... #3)sep function....... #4)translate function............ #if any one will guide me about these 3 functions then it will help me a lot #regads hamza
24dbc8f8a9b1f0ecfa7452369fbff2a91e65435e
ElHa07/Python
/Curso Python/Aula02/Exercicios/Exercicios03.py
339
4.1875
4
# Exercรญcio Python #003 - Mรฉdia Aritmรฉtica # Exercรญcio: Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua mรฉdia. n1 = float(input('Digite sua primeira Nota: ')) n2 = float(input('Digite sua segunda Nota: ')) media = (n1+n2)/2 print('A media entre {} e {} รฉ igual a {:.1f}! '.format(n1,n2,media))
761be92352f40de279b1672f33cd8ed69433deed
castertr0y357/RecipeBook
/RecipeBook/Testing/parsing_test.py
2,091
4.03125
4
from fractions import Fraction if Fraction(1/2) > 0: print(True) ingredient_1 = "1 1/2 cups flour" ingredient_2 = "1/4 cups of sugar" ingredient_3 = "3 tablespoons of salt" ingredients = [ingredient_1, ingredient_2, ingredient_3] for ingredient in ingredients: if "/" in ingredient: split_point = ingredient.find("/") values = ingredient[0:(split_point + 2)] ingredient_name = ingredient[(split_point + 3):] print("values:", values) if " " in values: whole_number = values.split(" ")[0] fraction = values.split(" ")[1] combined_fraction = int(whole_number) + Fraction(fraction) manipulated_fraction = Fraction(combined_fraction * 0.5) print("whole number:", whole_number) print("fraction:", fraction) print("combined fraction:", combined_fraction) print("manipulated fraction:", manipulated_fraction) print("Resized ingredient:", manipulated_fraction, ingredient_name) print() else: manipulated_fraction = Fraction(values) / 2 print("manipulated fraction:", manipulated_fraction) if manipulated_fraction < Fraction(1/4): manipulated_fraction = manipulated_fraction * 16 print("tablespoons:", manipulated_fraction) print("Resized ingredient:", manipulated_fraction, ingredient_name) print() else: whole_number = 0 value = ingredient[0] print("value:", value) fraction = Fraction(value) print("fraction:", fraction) manipulated_fraction = fraction / 2 print("manipulated fraction:", manipulated_fraction) while manipulated_fraction > 1: whole_number += 1 manipulated_fraction -= 1 if whole_number > 0: print("whole number:", whole_number) print("new manipulated fraction:", manipulated_fraction) print("new values:", str(whole_number) + " " + str(manipulated_fraction)) print()
731c5f3653e422859009daf4d4de94f297ef0069
idobleicher/pythonexamples
/examples/functional-programming/partial_example.py
534
4.4375
4
# You can create partial functions in python by using the partial function from the functools library. # # Partial functions allow one to derive a function with x parameters to a function with # fewer parameters and fixed values set for the more limited function. from functools import partial def multiply(x,y): return x * y # create a new function that multiplies by 2 dbl = partial(multiply,2) print(dbl(4)) #8 def func(u,v,w,x): return u*4 + v*3 + w*2 + x p = partial(func,5,6,7) print(p(8)) # 60 5*4 +6*3 +7*2 + 8
e0dfa26cebd90d0db0ed68c13817da89797342f9
matt6frey/python-math-attack
/ma.py
4,284
3.671875
4
# # Math Attack 1.0 # # A simple math game that helps people practice basic # addition, subtraction, multiplication and division. # # Developed on September 24th, 2017 by Matt Frey import random def compare(int1,int2,operator,ans_type): #Tests which int is larger and what type of information to return. if ans_type == "str": #Return Equation in String Form. if operator == " / ": if int1 < int2: return str(int2*int1) + operator + str(int1) else: return str(int1*int2) + operator + str(int2) else: if int1 < int2: return str(int2) + operator + str(int1) else: return str(int1) + operator + str(int2) else: #Return the Answer to the Equation if int1 < int2: if operator == " + ": ans = int2+int1 elif operator == " - ": ans = int2-int1 elif operator == " * ": ans = int2*int1 else: ans = int2 return ans else: if operator == " + ": ans = int1+int2 elif operator == " - ": ans = int1-int2 elif operator == " * ": ans = int1*int2 else: ans = int1 return ans def get_questions(amount, diff, range1, range2): i = 1 amount+= 1 questions = [] while i < amount: if diff == "easy" or diff == "ez": int1 = random.randint(1,10) int2 = random.randint(1,10) elif diff == "medium" or diff == "med": int1 = random.randint(1,10) int2 = random.randint(1,20) else: int1 = random.randint(1,10) int2 = random.randint(1,30) get_op = random.randint(range1,range2) #determine the type of arithmetic to be performed. if get_op == 0: #Determine Operator operator = " + " elif get_op == 1: operator = " - " elif get_op == 2: operator = " * " else: operator = " / " q = compare(int1, int2, operator,"str") ans = compare(int1, int2, operator,"int") questions.append(["Question "+str(i)+": "+q,str(ans)]) i+= 1 return questions def game_settings(typeQ, diff, amount): if typeQ == "a": questions = get_questions(amount, diff, 0, 1) # Addition/Subtraction elif typeQ == "m": questions = get_questions(amount, diff, 2, 3) # Multiplication/Division else: questions = get_questions(amount, diff, 0, 3) # All Operators Included return questions def ask(questions): stats = {"right":0,"wrong":0,"total":0} i = 0 while i < len(questions): answer = input("\n"+str(questions[i][0]+" ")) if answer == questions[i][1]: stats["right"] += 1 else: stats["wrong"] += 1 stats["total"] +=1 i+= 1 print("\nGood Job! You Finished up with "+ str(stats["right"]) +" correct, out of a total of "+ str(stats["total"]) +" problems.\n Giving you "+ str((stats["right"]/stats["total"])*100) +"%.") replay = input("\nWant to play again? Y/N ").upper() if replay.startswith("Y"): play() else: print("Thanks for playing!") def play(): print("Welcome to Math Attack 1.0 . The Game is simple, get as many correct as possible. \nTry to do every question only using mental arithmetic. Why?! Because it will help your brain! Good Luck!") while True: amount = input("\nHow many questions do want to complete? It can be any number. ") if amount.isnumeric(): #[num for num in range(0,10)] break while True: diff = input("\nChoose a difficulty: Easy ('e'), Medium ('m'), or Hard ('h'). ").lower() if diff.startswith("e") or diff.startswith("m") or diff.startswith("h"): break while True: typeQ = input("\nChoose between Addition/Subtraction (a), Multiplication/Division (b), or All (c): ").lower() if typeQ.startswith("a") or typeQ.startswith("b") or typeQ.startswith("c"): break questions = game_settings(typeQ, diff, int(amount)) ask(questions) print("\n\n\n") print("----------------------------------------------------------------------------------------") print("| MM MM AAA TTTTTT HH HH AAA TTTTTT TTTTTT AAA CCCC KK KK |") print("| MMMMMMMM AA AA TT HHHHHH AA AA TT TT AA AA CC KKK |") print("| MM M MM AA AA TT HH HH AA AA TT TT AA AA CCCC KK KK |") print("----------------------------------------------------------------------------------------") print("\n\n\n") play() #Start game
eaca002be0673b0e09c2359feada7b7cb0ce88d8
xtreia/pythonBrasilExercicios
/02_EstruturasDecisao/20_media_tres_notas.py
363
3.84375
4
nota1 = float(raw_input('Informe a primeira nota: ')) nota2 = float(raw_input('Informe a segunda nota: ')) nota3 = float(raw_input('Informe a terceira nota: ')) media = (nota1 + nota2 + nota3) / 3.0 print 'Media do aluno: {}'.format(media) if (media == 10): print 'Aprovado com Distincao' elif (media >= 7): print 'Aprovado' else: print 'Reprovado'
97175b3a50259474c273bbb8644c16658ae92cc4
pilosus/stepik-algorithms
/04_sorting/mergegen.py
682
3.546875
4
#!/usr/local/bin/python3 import sys from random import randint, choice def usage(): print("usage: inpgen N outfile") print("N - number of elements in the list") print("outfile - file name to write into") def generate(N, out): if (N >= int(10e5)): N = int(10e5) - 1 f = open(out, 'w+') f.write(str(N) + '\n') for e in range(N): line = str(randint(1, 1000)) + " " f.write(line) f.close() print("File {0} successfuly generated!".format(out)) if __name__ == "__main__": args = sys.argv[1:] if (len(args) == 0): usage() else: N = int(args[0]) out = args[1] generate(N, out)
de7a366e05873258fb3961a2fe034db6fa00fdd3
ag220502/Python
/Programs/ForLoops/PrintOddNo1ToN.py
106
4.09375
4
#Print Odd No from 1 to N n = int(input("Enter Value Of N : ")) for i in range(1,n+1,2): print(i," ")
c36a63f232c9092705529a5ebc4365197b63ead4
Louis-YuZhao/MAS_visceral_ANT
/EigenfaceKNN/Func_k_nearest_neighbor_sklearning.py
2,934
4.28125
4
import numpy as np from sklearn.neighbors import NearestNeighbors # version 3 # 2017-06-04 # author louis # (2) using sklearn #%% class KNearestNeighbor(object): """ a kNN classifier """ def __init__(self, algorithm='auto', metric='minkowski', p=2): self.algorithm = algorithm self.metric = metric self.p = p """Parameter for the Minkowski metric from sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.""" def train(self, X, y): """ Train the classifier. For k-nearest neighbors this is just memorizing the training data. Inputs: - X: A numpy array of shape (num_train, D) containing the training data consisting of num_train samples each of dimension D. - y: A numpy array of shape (N,M) containing the training labels, where y[i] is the label for X[i]. """ self.X_train = X self.y_train = y def predict(self, x_test, k=1): """ Predict labels for test data using this classifier. Inputs: - X: A numpy array of shape (num_test, D) containing test data consisting of num_test samples each of dimension D. - k: The number of nearest neighbors that vote for the predicted labels. - num_loops: Determines which implementation to use to compute distances between training points and testing points. Returns: - y: A numpy array of shape (num_test,) containing predicted labels for the test data, where y[i] is the predicted label for the test point X[i]. """ nbrs = NearestNeighbors(n_neighbors=k, algorithm=self.algorithm, metric=self.metric, p=self.p,).fit(self.X_train) distances, indices = nbrs.kneighbors(x_test) return self.predict_labels(indices, k=k) def predict_labels(self, indices, k=1): """ Given a matrix of distances between test points and training points, predict a label for each test point. Inputs: - dists: A numpy array of shape (num_test, num_train) where dists[i, j] gives the distance betwen the ith test point and the jth training point. Returns: - y: A numpy array of shape (num_test,) containing predicted labels for the test data, where y[i] is the predicted label for the test point X[i]. """ N, M = np.shape(self.y_train) num_test = indices.shape[0] y_pred = np.zeros((M,num_test)) dist_dice =indices[:,0:k] for i in xrange(num_test): # A list of length k storing the labels of the k nearest neighbors to # the ith test point. dice_i = dist_dice[i,:] dice_i = list(dice_i.reshape(-1)) closest_y = self.y_train[dice_i] y_pred_temp = np.mean(closest_y, axis=0) y_pred[:,i] = y_pred_temp return y_pred, indices
9c230476a54c42604a051e54fe1d6f8db96aa976
idaeung/programmers
/Lev1/ํ‰๊ท  ๊ตฌํ•˜๊ธฐ.py
390
3.6875
4
""" ๋ฌธ์ œ ์„ค๋ช… ์ •์ˆ˜๋ฅผ ๋‹ด๊ณ  ์žˆ๋Š” ๋ฐฐ์—ด arr์˜ ํ‰๊ท ๊ฐ’์„ returnํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•ด๋ณด์„ธ์š”. ์ œํ•œ์‚ฌํ•ญ arr์€ ๊ธธ์ด 1 ์ด์ƒ, 100 ์ดํ•˜์ธ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค. arr์˜ ์›์†Œ๋Š” -10,000 ์ด์ƒ 10,000 ์ดํ•˜์ธ ์ •์ˆ˜์ž…๋‹ˆ๋‹ค. ์ž…์ถœ๋ ฅ ์˜ˆ arr return [1,2,3,4] 2.5 [5,5] 5 """ def solution(arr): return sum(arr) / len(arr) print(solution([1, 2, 3, 4]))
2191eed012b9251bc1a37d86e4fdd7a4aa3df4f7
tomxelliott/PythonCode
/src/keras_NN/model.py
1,564
3.96875
4
from keras.models import Sequential from keras.layers import Dense, Activation import numpy # fix random seed for reproducibility numpy.random.seed(7) # load 2003data.csv dataset dataset = numpy.loadtxt("2005data.csv", delimiter=",") # split into input (X) and output (Y) variables # First 36 are input variables # 37th is output variable # 37 total variables X = dataset[:,0:36] Y = dataset[:,36] # create model # Rectifier (โ€˜reluโ€˜) activation function on the first two layers and the sigmoid ('sigmoid') function in the output layer model = Sequential() model.add(Dense(12, input_dim=36, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile model # Specify loss function - in this case: # use logarithmic loss, which for a binary classification problem is defined in Keras as โ€œbinary_crossentropyโ€œ. # โ€œadamโ€ is an efficient gradient descent algorithm. Look at other options as well. # metrics=['accuracy'] reports the classification accuracy of the model. model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model # we will run for a small number of iterations (150) and use a relatively small batch size of 10. # Again, these can be chosen experimentally by trial and error. # can add , verbose=0 , parameter to to the fit() method to stop the bars when running model. model.fit(X, Y, epochs=150, batch_size=10, initial_epoch=0) # evaluate the model scores = model.evaluate(X, Y) print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
e1444e6b474bc0599663b5e3e3cf7cb0131f6b24
ajitabhkalta/Python-Training
/logging/dosa.py
979
3.828125
4
import logging logging.basicConfig(level=logging.CRITICAL) class Dosa(): def __init__(self, name, price): self.name = name self.price = price logging.debug("Dosa object created: {} (INR-{})".format(self.name, self.price)) #print("Dosa object created: {} (INR-{})".format(self.name, self.price)) #By using print stmt we can't turn off printing def make(self, quantity): logging.info(f"Made {quantity} {self.name} Dosa(s)") #print(f"Made {quantity} {self.name} Dosa(s)") #By using print stmt we can't turn off printing def pack(self, quantity): logging.warning(f"Packed {quantity} {self.name} Dosa(s)\nBill:{quantity*self.price}") #print(f"Packed {quantity} {self.name} Dosa(s)\nBill:{quantity*self.price}") #By using print stmt we can't turn off printing Dosa1 = Dosa("Masala", 15) Dosa1.make(3) Dosa1.pack(3) Dosa2 = Dosa("Onion", 12) Dosa2.make(2) Dosa2.pack(2)
a67d58195b1bbf553421b55f084ab627eeeb4438
hsiangyi0614/X-Village-2018-Exercise
/Lesson03-Python-Basic-two/exercise2.py
344
3.90625
4
#Exercise2: swap #method1 def f(a,b): print("origin : ",a,b) c=a a=b b=c print("new :",a,b) a=int(input("input a number : ")) b=int(input("input a number : ")) f(a,b) #method2 def w(a,b): print("origin : ",a,b) a,b=b,a print("new :",a,b) a=int(input("input a number : ")) b=int(input("input a number : ")) w(a,b)
5f9ffc3aa3a58fe5b053dc77942b096a699cfe6d
refanr/2020
/6/4.py
154
3.921875
4
a_str = input("Input a float: ") a_str = round(float(a_str), 2) a_str = str(a_str) if a_str[-1] == '0': a_str = a_str + '0' print(a_str.rjust(12))
c5d576fedbc1679380da337d9306e7a0530bc8f6
18cyoung/SoftwareDev2
/Tasks/ListSum.py
453
3.96875
4
#MAIN BODY CODE list = [] UI = "\n" numberFlag = True while (UI != ""): UI = input("Enter a value for the list: ") if (UI != ""): try: UI = float(UI) except ValueError: numberFlag = False list.append(UI) print("The current values are: ") print(list) def SumList(list): total = 0 for i in list: total = total + i print(total) return SumList SumList(list)
49dfd07ad950d90c524c5162ec7b8ee91419f6be
xintiansong/tensorflow_test
/MLP.py
2,629
3.5625
4
#MLP:ๅ…ฑไธ‰ๅฑ‚๏ผŒ้š่—ๅฑ‚1000็ฅž็ปๅ…ƒ๏ผŒAccuracy: 0.9638 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import tensorflow.examples.tutorials.mnist.input_data as input_data mnist = input_data.read_data_sets('MNIST_data/', one_hot = True) #ๅปบ็ซ‹layerๅ‡ฝๆ•ฐ def layer(output_dim, input_dim, inputs, activation = None): W = tf.Variable(tf.random_normal([input_dim, output_dim])) b = tf.Variable(tf.random_normal([1, output_dim])) XWb = tf.matmul(inputs, W) + b if activation is None: outputs = XWb else: outputs = activation(XWb) return outputs #ๅปบ็ซ‹่พ“ๅ…ฅๅฑ‚x x = tf.placeholder('float', [None, 784]) #ๅปบ็ซ‹้š่—ๅฑ‚h1 h1 = layer(output_dim = 200, input_dim = 784, inputs = x, activation = tf.nn.relu ) #ๅปบ็ซ‹่พ“ๅ‡บๅฑ‚y y_predict = layer(output_dim = 10, input_dim = 200, inputs = h1, activation = None ) y_label = tf.placeholder('float', [None, 10]) #ๅฎšไน‰ๆŸๅคฑๅ‡ฝๆ•ฐ๏ผˆไบคๅ‰็†ตcross_entropy๏ผ‰ loss_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = y_predict, labels = y_label)) #ๅฎšไน‰ไผ˜ๅŒ–ๅ™จ optimizer = tf.train.AdamOptimizer(learning_rate = 0.001).minimize(loss_function) #่ฎก็ฎ—ๆฏไธ€้กนๆ•ฐๆฎๆ˜ฏๅฆ้ข„ๆต‹ๆˆๅŠŸ correct_prediction = tf.equal(tf.argmax(y_label, 1), tf.argmax(y_predict, 1)) #้ข„ๆต‹ๆญฃ็กฎ็ป“ๆžœ็š„ๅนณๅ‡ๅ€ผ accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float')) #ๅฎšไน‰่ฎญ็ปƒๅ‚ๆ•ฐ trainEpochs = 15 batchSize = 100 totalBatchs = 550 loss_list = [] epoch_list = [] accuracy_list = [] from time import time sess = tf.Session() sess.run(tf.global_variables_initializer()) #่ฟ›่กŒ่ฎญ็ปƒ for epoch in range(0, trainEpochs): for i in range(0, totalBatchs): batch_x, batch_y = mnist.train.next_batch(batchSize) sess.run(optimizer, feed_dict = {x: batch_x, y_label: batch_y}) loss, acc = sess.run([loss_function, accuracy], feed_dict = {x: mnist.validation.images, y_label: mnist.validation.labels} ) epoch_list.append(epoch) loss_list.append(loss) accuracy_list.append(acc) print('Train Epoch:', '%02d' % (epoch + 1), 'Loss=', '{:.9f}'.format(loss), 'Accuracy=', acc) print('่ฎญ็ปƒ็ป“ๆŸ') #ๆจกๅž‹ไฟๅญ˜ๅ’Œ่ฏปๅ– saver = tf.train.Saver() saver.save(sess, "MLP_Model/model.ckpt") saver.restore(sess, "./MLP_Model/model.ckpt") #่ฏ„ไผฐๆจกๅž‹ๅ‡†็กฎ็އ print('Accuracy:', sess.run(accuracy, feed_dict = {x: mnist.test.images, y_label: mnist.test.labels} ))
b362953b359377b86d28cdbb0fe8f55a3f6b705f
LordAzazzello/Work2020
/OOPLAB/2_semestr/Pyt1/Pyt1.13/Pyt1.13.py
711
3.78125
4
#13 #ะะฐะฟะธัˆะธั‚ะต ัะพะฑัั‚ะฒะตะฝะฝัƒัŽ ะฒะตั€ัะธัŽ ะณะตะฝะตั€ะฐั‚ะพั€ะฐ enumerate ะฟะพะด ะฝะฐะทะฒะฐะฝะธะตะผ extra_enumerate. ะ’ ะฟะตั€ะตะผะตะฝะฝะพะน cum ั…ั€ะฐะฝะธั‚ัั ะฝะฐะบะพะฟะปะตะฝะฝะฐั ััƒะผะผะฐ ะฝะฐ ะผะพะผะตะฝั‚ ั‚ะตะบัƒั‰ะตะน #ะธั‚ะตั€ะฐั†ะธะธ, ะฒ ะฟะตั€ะตะผะตะฝะฝะพะน frac โ€“ ะดะพะปั ะฝะฐะบะพะฟะปะตะฝะฝะพะน ััƒะผะผั‹ ะพั‚ ะพะฑั‰ะตะน ััƒะผะผั‹ ะฝะฐ ะผะพะผะตะฝั‚ ั‚ะตะบัƒั‰ะตะน ะธั‚ะตั€ะฐั†ะธะธ. def extra_enumerate(list): cum = 0 frac = 0 sum_elem = 0 for i in list: sum_elem += i for i in list: cum += i frac = cum / sum_elem yield i, cum, frac [print((elem, cum, frac), end=" ") for elem, cum, frac in extra_enumerate([1, 3, 4, 2])]
e4d0544924e6e67aa032382efd7348b12fe1a599
rtgfd157/docker-Stock-Analysis-Project
/App/stock_analysis_project/others/y2.py
550
3.625
4
import time import asyncio async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): print(f"started at {time.strftime('%X')}") await say_after(1, 'hello') await say_after(2, 'world') print(f"finished at {time.strftime('%X')}") A = [1,2,3,4,5,6,7] B = A[:len(A)//2] C = A[len(A)//2:] def split_list(a_list): half = len(a_list)//2 return a_list[:half], a_list[half:] if __name__ == "__main__": B, C = split_list(A) print("b ",B) print("C ",C) #asyncio.run(main())
975a77b7e20f09532b63ba915715b94afed01a40
RicardoMart922/estudo_Python
/Exercicios/Exercicio061.py
1,751
4.40625
4
# Crie um programa que leia dois valores e mostre um menu na tela: # [ 1 ] Somar # [ 2 ] Multiplicar # [ 3 ] Maior # [ 4 ] Novos Nรบmeros # [ 5 ] Sair do Programa # Seu programa deverรก realizar a operaรงรฃo solicitada em cada caso. from time import sleep numero1 = float(input('Informe um nรบmero: ')) numero2 = float(input('Informe outro nรบmero: ')) opcao = 0 soma = 0 produto = 0 while opcao != 5: print('-=-=-=-=-=-> MENU <-=-=-=-=-=-') print('[ 1 ] Somar') print('[ 2 ] Multiplicar') print('[ 3 ] Maior') print('[ 4 ] Novos Nรบmeros') print('[ 5 ] Sair do Programa') print('-=-' * 10) opcao = int(input('Opรงรฃo: ')) if opcao == 1: soma = (numero1 + numero2) print('Somando...') sleep(1.5) print('A soma de {} com {} รฉ {}'.format(numero1, numero2, soma)) elif opcao == 2: produto = (numero1 * numero2) print('Multiplicando...') sleep(1.5) print('O produto de {} por {} รฉ {}'.format(numero1, numero2, produto)) elif opcao == 3: if numero1 > numero2: print('Analisando...') sleep(1.5) print('O primeiro nรบmero รฉ maior que o segundo.') elif numero1 == numero2: print('Em analise...') sleep(1.5) print('Os dois nรบmeros sรฃo iguais.') else: print('Aguarde...') sleep(1.5) print('O segundo nรบmero รฉ maior que o primeiro.') elif opcao == 4: numero1 = float(input('Informe um nรบmero: ')) numero2 = float(input('Informe outro nรบmero: ')) print('Carregando...') sleep(1.5) else: print('PROCESSANDO...') sleep(1.5) print('ENCERRADO.')
0a836403af4260c00d73a744ac1855ea374c60a4
loganrouleau/blokus
/src/validator.py
2,128
3.5
4
is_starting_block_for_player = {0: True, 1: True} def placement_is_valid(state, proposed_coordinates, player): all_immediate_neighbours = [] for coord in proposed_coordinates: if not __square_is_within_gameboard(state, coord) or not __square_has_player(state, coord, None): return False for immediate_neighbour in __get_immediate_neighbours(coord): if __square_is_within_gameboard(state, immediate_neighbour) and not immediate_neighbour in proposed_coordinates: if __square_has_player(state, immediate_neighbour, player): return False all_immediate_neighbours.append(immediate_neighbour) global is_starting_block_for_player if not is_starting_block_for_player[player] and not __is_block_connected(state, proposed_coordinates, player, all_immediate_neighbours): return False is_starting_block_for_player[player] = False return True def __is_block_connected(state, proposed_coordinates, player, all_immediate_neighbours): for coord in proposed_coordinates: for diagonal_neighbour in __get_diagonal_neighbours(coord): if __square_is_within_gameboard(state, diagonal_neighbour) and not diagonal_neighbour in proposed_coordinates and not diagonal_neighbour in all_immediate_neighbours: if __square_has_player(state, diagonal_neighbour, player): return True return False def __get_immediate_neighbours(square): return [[square[0]-1, square[1]], [square[0]+1, square[1]], [square[0], square[1]-1], [square[0], square[1]+1]] def __get_diagonal_neighbours(square): return [[square[0]+1, square[1]+1], [square[0]+1, square[1]-1], [square[0]-1, square[1]+1], [square[0]-1, square[1]-1]] def __square_is_within_gameboard(state, square): return not (square[0] < 0 or square[1] < 0 or square[0] > len(state) - 1 or square[1] > len(state) - 1) def __square_has_player(state, square, expected_player): return state[square[0]][square[1]] == expected_player
32d3ccd2db16235420be7edd3a877891eefeedf2
therishimitra/GitHub-Crawler
/GitHub crawler improvements/GitHub v3.py
6,398
3.78125
4
""" HOW TO RUN: To run execute the function: main(). This is done by execiting the script of "GitHub v3.py" IMPORTANT: Before running ensure GitHub_numpy_database.csv and numpy2.csv do not already exist. """ import requests import csv from bs4 import BeautifulSoup from urllib import request # Desc: Appends a list as a new row to an existing CSV document. In case the filename passed does not already exist, a new file is created with the given filename # Input: A string containing the path of the CSV file being updated. # Output: No returns. CSV file is updated with new row # Exception: UnicodeEncodeError - accounts for characters requiring explicit encoding def updateCSV(file_name, row): # appends row passed to it to the csv file whose name is passed to it try: with open(file_name, 'a', newline='') as f: obj = csv.writer(f) obj.writerow(row) print(row) except UnicodeEncodeError: with open(file_name, 'a', newline='') as f: obj = csv.writer(f) obj.writerow(['UnicodeEncodeError was encountered here while crawling']) print('UnicodeEncodeError was encountered here while crawling') # Desc: Visits the numpy libraries at GitHub.com and searches for all .py files and returns a list of links to each of the .py files # Input: A list to which the .py files found are to be added. The url at which the numpy library is located in GitHub # Output: Returns a list updated with the URLs of all the .py files located # Exception: None def list_updater(pylist, url): # recurses till it acquires list of all .py files in directory # updateCSV('GitHub_numpy_database.csv',['NAME','DESCRIPTION','PARAMETERS','RETURNS']) page1_source_code = requests.get(url) plain = page1_source_code.text soup = BeautifulSoup(plain, "html.parser") for all_links in soup.findAll('a', {'class': 'js-navigation-open'}): links = all_links.get('href') title = all_links.get('title') if title != "Go to parent directory" and links.endswith('.py'): links = 'https://github.com/' + links pylist.append(links) print(links) elif title != "Go to parent directory" and "." not in links: print('Checking link:' + links) links = 'https://github.com/' + links pylist = list_updater(pylist, links) else: print('Not .py file or folder') return pylist # Desc: Main function that controls the flow of contorl of the data retrieval and database creation processes. # Input: None # Output: None # Exception: None def main(): pylist = [] # list of .py files pylist = list_updater(pylist, 'https://github.com/numpy/numpy/tree/master/numpy') # returns list of all .py files in directory # print(pylist) # print(len(pylist) , '.py files found') openWrite(pylist) # Desc: The code fo each .py file in the list of URLs is copied to a CSV file called "numpy2.csv" and "GitHub_numpy_database.csv" is populated with relevant fields # Input: A list of URLs leading to the .py files in GitHub that define various numpy functions # Output: None. CSV files "numpy2.csv" and "GitHub_numpy_database.csv" are created # Exception: IndexError - Accounts for empty rows or rows that are limited to one column def openWrite(url_list): updateCSV(r'C:\Users\rishi\PycharmProjects\numpy_crawler\venv\GitHub_numpy_database.csv', ['NAME', 'LOCATION', 'DESCRIPTION', 'PARAMETERS', 'RETURNS']) for url in url_list: source = requests.get(url) txt = source.text soup = BeautifulSoup(txt) table = soup.find('table') table_rows = table.findAll('tr') line = 1 updateCSV(r'C:\Users\rishi\PycharmProjects\numpy_crawler\venv\numpy2.csv', ['Function:', url]) dflag = 0 pflag = 0 rflag = 0 name_str = '' desc_str = '' param_str = '' ret_str = '' try: for tr in table_rows: td = tr.findAll('td') row = [i.text for i in td] row[0] = line updateCSV(r'C:\Users\rishi\PycharmProjects\numpy_crawler\venv\numpy2.csv', row) line += 1 loc_str = url if row[1].startswith('def '): newfunc = 1 dflag = 0 pflag = 0 rflag = 0 name_str = name_str.replace('def ', '') desc_str = desc_str.replace('"""', '') param_str = param_str.replace(' Parameters ---------- ', '') ret_str = ret_str.replace(' Returns ------- ', '') updateCSV(r'C:\Users\rishi\PycharmProjects\numpy_crawler\venv\GitHub_numpy_database.csv', [name_str, loc_str, desc_str, param_str, ret_str]) name_str = '' desc_str = '' param_str = '' ret_str = '' print(row[1]) name_str = name_str + row[1] if ' """' in row[1] or '"""' in row[1]: if dflag == 0 and newfunc == 1: dflag += 1 newfunc = 0 else: dflag = 0 if ' Parameters' == row[1]: pflag += 1 dflag = 0 if ' Returns' == row[1]: rflag += 1 dflag = 0 if dflag != 0: desc_str = desc_str + row[1] print(row[1]) if pflag != 0: param_str = param_str + row[1] print(row[1]) if rflag != 0: ret_str = ret_str + row[1] print(row[1]) if '' == row[1] and pflag == 1: pflag = 0 if '' == row[1] and rflag == 1: rflag = 0 except IndexError: pass main()
0aff32ac90d94365602addbbddc061bfc14c6411
rubetyy/Algo-study
/hyunsix/0910_๊ด„ํ˜ธ๋ณ€ํ™˜.py
1,085
3.640625
4
def check(p): is_open = 0 u = "" v = "" for i in range(len(p)): if p[i] == '(': is_open += 1 else: is_open -= 1 if i > 0 and is_open == 0: u = p[0:i + 1] v = p[i + 1:] break is_open = 0 for i in range(len(u)): if u[i] == '(': is_open += 1 else: if is_open > 0: is_open -= 1 if is_open == 0: return u, v, True return u, v, False def solution(p): if len(p) == 0: return "" is_open = 0 for i in range(len(p)): if p[i] == '(': is_open += 1 else: if is_open > 0: is_open -= 1 if is_open == 0: return p u, v, correct = check(p) answer = "" if correct: return u + solution(v) else: answer = '(' + solution(v) + ')' for i in range(1, len(u) - 1): if u[i] == '(': answer += ')' else: answer += '(' return answer
a76fb1035d3598c32e3c22315f833e20fe18f315
Dkpalea/midi-wfc
/wfc_2019f-master/wfc/wfc_tiles.py
2,545
3.5
4
"""Breaks an image into consituant tiles.""" import numpy as np from .wfc_utilities import hash_downto def image_to_tiles(img, tile_size): """ Takes an images, divides it into tiles, return an array of tiles. """ padding_argument = [(0,0),(0,0),(0,0)] for input_dim in [0, 1]: padding_argument[input_dim] = (0, (tile_size - img.shape[input_dim]) % tile_size) img = np.pad(img, padding_argument, mode='constant') tiles = img.reshape((img.shape[0]//tile_size, tile_size, img.shape[1]//tile_size, tile_size, img.shape[2] )).swapaxes(1, 2) return tiles def make_tile_catalog(image_data, tile_size): """ Takes an image and tile size and returns the following: tile_catalog is a dictionary tiles, with the hashed ID as the key tile_grid is the original image, expressed in terms of hashed tile IDs code_list is the original image, expressed in terms of hashed tile IDs and reduced to one dimension unique_tiles is the set of tiles, plus the frequency of occurance """ channels = image_data.shape[2] # Number of color channels in the image tiles = image_to_tiles(image_data, tile_size) tile_list = np.array(tiles, dtype=np.int64).reshape((tiles.shape[0] * tiles.shape[1], tile_size, tile_size, channels)) code_list = np.array(hash_downto(tiles, 2), dtype=np.int64).reshape((tiles.shape[0] * tiles.shape[1])) tile_grid = np.array(hash_downto(tiles, 2), dtype=np.int64) unique_tiles = np.unique(tile_grid, return_counts=True) tile_catalog = {} for i, j in enumerate(code_list): tile_catalog[j] = tile_list[i] return tile_catalog, tile_grid, code_list, unique_tiles def tiles_to_images(tile_grid, tile_catalog): return # tests import imageio def test_image_to_tiles(): filename = "../images/samples/Red Maze.png" img = imageio.imread(filename) tiles = image_to_tiles(img, 1) assert(tiles[2][2][0][0][0] == 255) assert(tiles[2][2][0][0][1] == 0) def test_make_tile_catalog(): filename = "../images/samples/Red Maze.png" img = imageio.imread(filename) print(img) tc, tg, cl, ut = make_tile_catalog(img, 1) print("tile catalog") print(tc) print("tile grid") print(tg) print("code list") print(cl) print("unique tiles") print(ut) assert(ut[1][0] == 7) if __name__ == "__main__": test_image_to_tiles() test_make_tile_catalog()
98cfe1d60dab4da99dfa6c4dc3893632dab2af6c
7ossam81/Scripts-for-CSV-results
/delete_rows_with_null.py
361
3.609375
4
# this script remove any row that has a "#NULL!" import csv with open('quiebras-spain-2005-clean.csv', 'r') as inp, open('first_edit6.csv', 'w',newline='\n') as out: writer = csv.writer(out) for row in csv.reader(inp): #if "#NULL!" not in row: if not any('#NULL!' in x for x in row): writer.writerow(row)
e37d310cc412685239ed740b6b85beaecf3f1f27
Gabriel-Tomaz/aprendendo-python
/desafios/desafio020.py
367
3.890625
4
# =========Desafio 20========== # Embaralhando nomes import random name1 = str(input("Infome o primeiro aluno: ")) name2 = str(input("Infome o segundo aluno: ")) name3 = str(input("Infome o terceiro aluno: ")) name4 = str(input("Infome o quarto aluno: ")) names = [name1,name2,name3,name4] sort = random.shuffle(names) print("A ordem de saida รฉ: ") print(names)
d72d29fd232e94c4e86db5ca498862d7390eb28f
CcWang/data_science
/Machine_Learning_in_Python/week1/example_one.py
823
3.640625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split fruits = pd.read_table('fruit_data_with_colors.txt') # print fruits.head() lookup_fruit_name = dict(zip(fruits.fruit_label.unique(), fruits.fruit_name.unique())) # print lookup_fruit_name # create train-test split # This function randomly shuffles the dataset and splits off a certain percentage of the input samples for use as a training set, and then puts the remaining samples into a different variable for use as a test set. x = fruits[['mass','width','height']] y = fruits['fruit_label'] # capital X means two dimensional array or data frame, y means one dimensional array X_train, X_test, y_train, y_test = train_test_split(X,y, random_state = 0) print X_train, X_test, y_train, y_test
ce0314dc7c07e3d1806ad97bb7ae3fa8567c42cb
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_116/821.py
2,899
3.546875
4
def x_win(elements): for i in range(4): win = True for j in range(4): if (elements[j][i] == 'X' or elements[j][i] == 'T') is False: win = False break if win is True: return True for i in range(4): win = True for j in range(4): if (elements[i][j] == 'X' or elements[i][j] == 'T') is False: win = False break if win is True: return True win = True for i in range(4): if (elements[i][i] == 'X' or elements[i][i] == 'T') is False: win = False break if win is True: return True win = True for i in range(4): if (elements[i][3-i] == 'X' or elements[i][3-i] == 'T') is False: win = False break if win is True: return True return False def o_win(elements): for i in range(4): win = True for j in range(4): if (elements[j][i] == 'O' or elements[j][i] == 'T') is False: win = False break if win is True: return True for i in range(4): win = True for j in range(4): if (elements[i][j] == 'O' or elements[i][j] == 'T') is False: win = False break if win is True: return True win = True for i in range(4): if (elements[i][i] == 'O' or elements[i][i] == 'T') is False: win = False break if win is True: return True win = True for i in range(4): if (elements[i][3-i] == 'O' or elements[i][3-i] == 'T') is False: win = False break if win is True: return True return False def is_completed(elements): for i in range(4): for j in range(4): if elements[i][j] == '.': return False return True f = open('A-large.in', 'r') set_count = int(f.readline()) results = [] for i in range(set_count): elements = [[0 for x in range(4)] for x in range(4)] for j in range(4): line = f.readline() for k in range(4): elements[k][j] = line[k] line = f.readline() if x_win(elements): results.append("Case #" + str(i+1) + ": X won") elif o_win(elements): results.append("Case #" + str(i+1) + ": O won") else: if is_completed(elements): results.append("Case #" + str(i+1) + ": Draw") else: results.append("Case #" + str(i+1) + ": Game has not completed") f = open('A-large.out', 'w') for line in results: f.write(line + '\n') print(set_count)
e7cf5641a3e65dbfc5e7cdafdc566c34e469f3ef
betty29/code-1
/recipes/Python/387776_Grouping_objects_indisjoint/recipe-387776.py
1,757
4.0625
4
class Grouper(object): """This class provides a lightweight way to group arbitrary objects together into disjoint sets when a full-blown graph data structure would be overkill. Objects can be joined using .join(), tested for connectedness using .joined(), and all disjoint sets can be retreived using .get(). The objects being joined must be hashable. For example: >>> g = grouper.Grouper() >>> g.join('a', 'b') >>> g.join('b', 'c') >>> g.join('d', 'e') >>> list(g.get()) [['a', 'b', 'c'], ['d', 'e']] >>> g.joined('a', 'b') True >>> g.joined('a', 'c') True >>> g.joined('a', 'd') False""" def __init__(self, init=[]): mapping = self._mapping = {} for x in init: mapping[x] = [x] def join(self, a, *args): """Join given arguments into the same set. Accepts one or more arguments.""" mapping = self._mapping set_a = mapping.setdefault(a, [a]) for arg in args: set_b = mapping.get(arg) if set_b is None: set_a.append(arg) mapping[arg] = set_a elif set_b is not set_a: if len(set_b) > len(set_a): set_a, set_b = set_b, set_a set_a.extend(set_b) for elem in set_b: mapping[elem] = set_a def joined(self, a, b): """Returns True if a and b are members of the same set.""" mapping = self._mapping try: return mapping[a] is mapping[b] except KeyError: return False def __iter__(self): """Returns an iterator returning each of the disjoint sets as a list.""" seen = set() for elem, group in self._mapping.iteritems(): if elem not in seen: yield group seen.update(group)
8ce5dffa72a57632da14eb80b06372fe7ccc199a
sandeepkapase/examples
/prep_question_sources/python/parameter_pass_by_ref.py
717
3.734375
4
#!/usr/bin/python # [[file:../../../prep/python/Questions.org::python parameter_pass_by_ref example.][python parameter_pass_by_ref example.]] from copy import deepcopy class testclass: def __init__(self): print("testclass initialized") self.var1 = 1 self.var2 = 2 def __repr__(self): return "var1:"+str(self.var1)+" var2:"+str(self.var2) def testfun1(obj=None): obj.var1 = obj.var1 + obj.var1 obj.var2 = obj.var2 + obj.var2 def testfun2(obj=None): obj[0] = 0 obj[1] = 1 x = testclass() print(x) testfun1(x) print(x) testfun1(deepcopy(x)) # pass new object print(x) y = [2,4] print(y) testfun2(y) print(y) # python parameter_pass_by_ref example. ends here
63379144f05e1d38063d7cfed59da0b677e6e5fb
Laksh8/competitive-programming
/Codechef/sumofdigits.py
184
3.8125
4
# Sum of Digits :== def su(a): temp = 0 while a>0: temp1 = a%10 temp = temp+temp1 a //=10 print(temp) for i in range(3): su(int(input()))
afd768a24326fdf1fd995da5c4896fd5fcfb0780
mikesuhan/ErrorCodeTallier
/tally_codes.py
6,792
3.890625
4
import os import re import docx2txt class Tallier: """Generates two csv files for the raw and normalized frequencies of substrings in a .docx file's text. Files should be named in a consistent pattern identifying the treatment and subject, because this will determine how the output is organized. For example: 1.Jimmy.docx 1.Sally.docx 2.Jimmy.docx 2.Sally.docx Arguments: folder: A folder of .docx files output_filename: The first part of the output file's filename. Keyword Arguments: key_text: A string after which point error codes are not counted anymore. For example, maybe there is an answer key at the end of a text that shows the subject the meaning of the codes, but the codes in it do not represent errors made by the subject. delimiter: The string used to separate the subject/case from the treatment. e.g. "." in 1.Jimmy.docx code_file: The filepath to the file in which a csv of the error codes are stored. If None is used, the codes class variable will be used in its place. code_file_encoding: Character encoding of code_file. treatment_ind: An integer representing the place of the treatment label in the docx filenames. case_ind: An integer representing the index of the case/subject in the docx filenames. Example: Creates MyCSV_frequencies.csv and MyCSV_normalized.csv from docx files in the example_texts directory. >>> from tally_codes import Tallier >>> t = Tallier('example_texts', 'MyCSV') >>> t.process() """ # default error codes used if no file is loaded codes = {'[AE]':'article_error', '[RO]':'run_on_sentence', '[WF]':'word_form_error', '[VT]':'verb_tense_error', '[PL]':'plural_error', '[SVA]':'3rd_person_error'} left_bound, right_bound = '[', ']' def __init__(self, folder, output_filename, key_text='Key for Error Types:', delimiter='.', code_file='codes.csv', code_file_encoding='UTF-8', treatment_ind=0, case_ind=1): self.folder = folder self.key_text = key_text self.delimiter = delimiter self.treatment_ind = treatment_ind self.case_ind = case_ind self.files = [f for f in os.listdir(folder) if not f.startswith('~')] self.output_filename = output_filename if code_file: self.codes = self.read_codes(code_file, code_file_encoding) def read_codes(self, code_file, code_file_encoding): """Defines error codes based on csv data. Arguments: code_file: the file the error codes are stored in code_file_encoding: the encoding of code_file CSV format example: [AE], article_error [RO], run_on_sentence [WF], word_form_error """ with open(code_file, encoding=code_file_encoding) as f: text = f.read().splitlines() # separates codes from labels codes = [line.split(',') for line in text if line.strip()] codes = [(item[0], ' '.join(item[1:]).strip()) for item in codes] codes = {code: label for code, label in codes} return codes def tally(self, rate=100): """Counts the error codes in each file, returning a string in csv format. Keyword arguments: rate: The rate at which error code counts will be normalized to using: n / word_count * rate """ docs = [] for file in self.files: print(file) text = self.docx_text(self.folder + '/' + file) fd = {e: text.count(e) for e in self.codes} word_count = self.docx_word_count(text) file = file.split(self.delimiter) treatment_label = file[self.treatment_ind] case_label = file[self.case_ind] # treatment label, case label, frequency distribution docs.append([file[0], file[1], fd, word_count]) if not self.files: raise Exception('No files have been loaded.') treatments = sorted(set(int(tr) for tr, _, __, ___ in docs)) cases = sorted(set(c for _,c,__, ___ in docs)) # table delimiter tdl = ', ' # makes column header for each treatment tr_header = '' for tr in treatments: for c in self.codes: tr_header += tdl + self.codes[c] + '_' + str(tr) tr_header += tdl + 'word_count_' + str(tr) header = 'subjects' + tr_header + '\n' table = header # makes row for each case for case in cases: row = case for treatment in treatments: item = [(tr,c,frd,wc) for tr, c, frd, wc in docs if int(tr) == treatment and c == case] if item: for code in self.codes: tr,c,frd,wc = item[0] # Adds error counts freq = frd.get(code, 0) if rate: row += tdl + str(round(freq/word_count*rate, 2)) else: row += tdl + str(freq) # Adds word count row += tdl + str(item[0][3]) else: # Adds blank spaces if there is no treatment for a case. + 1 because of word_count row += tdl * (len(self.codes) + 1) row += '\n' table += row return table def docx_text(self, filepath): '''Tokenizes the text in a .docx file (without punctuation)''' text = docx2txt.process(filepath) try: cut_off = text.index(self.key_text) return text[:cut_off] except ValueError: print('No answer key present in', filepath) return text def docx_word_count(self, text): """Returns the word count of a docx file.""" text = re.sub('[^A-Za-z\s0-9-\']', '', text) return len(text.split()) def process(self): """Runs everything and saves it as a csv.""" with open(self.output_filename + '_frequencies.csv', 'w', encoding='utf8') as f: f.write(self.tally(False)) with open(self.output_filename + '_normalized.csv', 'w', encoding='utf8') as f: f.write(self.tally())
299cdaea3d84a8bd6e32607d86446bfd7df2d3cc
PD12pd/Taschenrechner
/rechner.py
1,100
4.03125
4
# Taschenrechner while True: num1 = input("Gib die erste Zahl ein: ") num11 = input("gib deine erste Zahl nach dem Komma ein: ") oper = input("Welche Rechenoperation soll durchgefuehrt werden? (+,-,/.,*): ") num2 = input("Gib die zweite Zahl ein: ") num21 = input("Gib deine zweite Zahl nach dem Komma ein: ") numA = float(str(num1) + "." + str(num11)) numB = float(str(num2) + "." + str(num21)) if (oper == "+"): print("Deine Rechnung:", numA, " + ", numB) print("Ergebnis:", numA + numB) elif(oper == "-"): print("Deine Rechnung:", numA, " - ", numB) print("Ergebnis:", numA - numB) elif(oper == "/"): print("Deine Rechnung:", numA, " / ", numB) print("Ergebnis:", numA / numB) elif(oper == "*"): print("Deine Rechnung:", numA, " * ", numB) print("Ergebnis:", numA * numB) else: print("Deine Eingaben sind nicht gueltig") jein = input("Willst du weiter rechnen? (ja/nein)") if jein == "ja": print("Das isch ja mega he. Nรคchste rechnung bitte!") else: print("Ok tschรผss du kaspar") quit()
5debf0cc3c309005bc5f1be269d8100895b51d99
zhongyehong/docklet
/src/master/lockmgr.py
890
3.765625
4
#!/usr/bin/python3 ''' This module is the manager of threadings locks. A LockMgr manages multiple threadings locks. ''' import threading class LockMgr: def __init__(self): # self.locks will store multiple locks by their names. self.locks = {} # the lock of self.locks, is to ensure that only one thread can update it at the same time self.locks_lock = threading.Lock() # acquire a lock by its name def acquire(self, lock_name): self.locks_lock.acquire() if lock_name not in self.locks.keys(): self.locks[lock_name] = threading.Lock() self.locks_lock.release() self.locks[lock_name].acquire() return # release a lock by its name def release(self, lock_name): if lock_name not in self.locks.keys(): return self.locks[lock_name].release() return
9de37ce84dbfa7b82833bf7d89bfbc99402aab16
eroicaleo/LearningPython
/interview/leet/1283_Find_the_Smallest_Divisor_Given_a_Threshold.py
619
3.59375
4
#!/usr/bin/env python3 from math import ceil class Solution: def smallestDivisor(self, nums, threshold): lo, hi = ceil(sum(nums)/threshold), max(nums) while lo < hi: mi = (lo+hi)//2 t = sum([ceil(n/mi) for n in nums]) if t > threshold: lo = mi+1 elif t <= threshold: hi = mi return lo info_list = [ ([1,2,5,9], 6), ([2,3,5,7,11], 11), ([19], 5), ([962551,933661,905225,923035,990560], 10) ] sol = Solution() for nums, threshold in info_list: print(sol.smallestDivisor(nums, threshold))
095b62c14d55d663d683e6be16f9dad7970debb1
Maheboob1/Removing-duplicates-from-a-list
/chech_number_within_range.py
148
3.65625
4
def test_range(n): if n in range(1,9): print(n,"is within the range") else: print(n,"is not in range") test_range(10)
8ee4f4571f1880a092599794d5bafb6c228b426e
udhayprakash/PythonMaterial
/python3/09_Iterators_generators_coroutines/02_iterators/b_zip_map_filter.py
1,385
4.3125
4
#!/usr/bin/python3 """ Purpose: Iterating zip(), map(), filter() result objects - lazy loading object (or) on-demand loading object - Iterators are disposable objects - one time use only """ # iterables alpha = {"a", "e", "i", "o", "u"} nums = ("1", "2", "3", "4") pairs = zip(alpha, nums) # zip object at 0x00000165AE6CBEC0> print(f"pairs: {type(pairs)} {pairs}") # Method 1: Iterate over the object for ech_pair in pairs: print(ech_pair) # Method 2: Convert to other iterables pairs1 = list(pairs) print(f"pairs1: {type(pairs1)} {pairs1}") pairs2 = tuple(pairs) print(f"pairs2: {type(pairs2)} {pairs2}") pairs3 = set(pairs) print(f"pairs3: {type(pairs3)} {pairs3}") pairs4 = str(pairs) print(f"pairs4: {type(pairs4)} {pairs4}") # NOTE: Iterators are disposable objects. can give values only once # re-assign to retrieve values again print() pairs = zip(alpha, nums) pairs1 = list(pairs) print(f"pairs1: {type(pairs1)} {pairs1}") print() pairs = zip(alpha, nums) pairs2 = tuple(pairs) print(f"pairs2: {type(pairs2)} {pairs2}") print() pairs = zip(alpha, nums) pairs3 = set(pairs) print(f"pairs3: {type(pairs3)} {pairs3}") print() pairs = zip(alpha, nums) pairs4 = str(pairs) # <zip object at 0x0000000002606688> print(f"pairs4: {type(pairs4)} {pairs4}") print() pairs = zip(alpha, nums) pairs5 = dict(pairs) print(f"pairs5: {type(pairs5)} {pairs5}")
f7ef49e9cb84bce3ae2fcbd9a401902bffb89108
adamkoy/Learning_Python
/Python_Learning/Python_fundementals/14_OOP_Animal_Kingdom.py
3,002
4.5
4
# What is inside class is called members # one is a local variable - # function inside a class is called methods. functions are outside a class # # def speak2(self): # This however, is not inside the class . It is in the file hence is now called a function/ D # # functions are not used in OOP/classes #Changing animal in memory not in the class #Static # When you create a class - class is a description and like a template - not used directly - describe what you want. #Give me an example of this thing. # class Animal: # animal_kind = "cow" # Local variable in the class # # def speak(self): #This is inside a class hence it is a method # return "yum yum yum" # # def speak(eat): #This is inside a class hence it is a method # return "#I like bones" # # def speak2(): #This is inside a class hence it is a method # return "yum yum yum" # #print(Animal.animal_kind) #Why did this pass # # dog1 = Animal() # now I have an object of type animal # intiate line object # dog2 =Animal() #how object relate with class members # print(dog1.speak()) # Object dog know this because of having self # print(dog1.eat()) # object knows this so it works # # print(dog1.speak2()) #Object dog does not know this because of not having self - Does not have self so does not work # print(Animal.speak()) # Animal does not know this because it has self # print(Animal.speak2()) # Animal know this because it does not have self - Not working # # # # print(dog1.animal_kind) # dog1.animal_kind = "Im a dog you id" # print(dog1.animal_kind) # print(dog1.speak2()) # print(Animal.animal_kind) # Animal.animal_kind= "Mouse" # print(dog1.animal_kind) # # ferret = Animal() # cat = Animal() # # print(cat.speak2()) # print(ferret.speak2()) # How does dog relate to members # # dog3 =Animal() # #Using an object # print(dog3.animal_kind) # print(dog3.speak()) # # #Object calling the dog can speak - part of the object - isolate it - # print(dog3.speak()) # #can see animal kind but cannot speak - can hide - cant access it using the class - need an object to access it # # Using the class # print(Animal.speak()) class Animal: animal_kind = "cow" # Local variable in the class def speak(self): #This is inside a class hence it is a method return "yum yum yum" def speak(eat): #This is inside a class hence it is a method return "#I like bones" def speak2(): #This is inside a class hence it is a method return "yum yum yum" turtle = Animal() fish = Animal() print(Animal.animal_kind) print(turtle.animal_kind) print(fish.animal_kind) Animal.animal_kind ="spider" Animal.animal_kind = "Spider" print(Animal.animal_kind) print(turtle.animal_kind) print(fish.animal_kind) # print(dog.animal_kind) # print(dog2.animal_kind) # # dog2.animal_kind = "woff" # print(dog.animal_kind) # print(dog2.animal_kind) # # This dog is now an object - object in memory # # # Difference with self key word
8f39b70bdc5fb4642183661c44e47be601f3a7c7
gabriellaec/desoft-analise-exercicios
/backup/user_256/ch39_2020_04_23_14_16_27_780278.py
297
3.9375
4
numero = int(input("Digite um numero: ")) sequencia = numero lista = sequencia while numero < 1000: if sequencia %2 ==0: sequencia = sequencia/2 lista+= sequencia elif sequencia %2 !=0: sequencia = 3*sequencia +1 lista+= sequencia return lista
4dd49b67cba8d0943a7a9102f53e806de5e84b67
RedSunDave/recursivity-and-contingency
/recursive_functions.py
884
4.21875
4
import time import random def factorial_recursive(n): if n == 1: return 1 else: return n * factorial_recursive(n-1) def infinite_walk_recurse(n): print(n) time.sleep(2) return n + recurse(n + random.randint(-5,5)) def fibonacci_recursive(n): print("Calculating F", "(", n, ")", sep="", end=", ") # Base case if n == 0: return 0 elif n == 1: return 1 # Recursive case else: return fibonacci_recursive(n-1) + fibonacci_recursive(n-2) # Better fibonacci recursive from functools import lru_cache @lru_cache(maxsize=None) def fibonacci_recursive(n): print("Calculating F", "(", n, ")", sep="", end=", ") # Base case if n == 0: return 0 elif n == 1: return 1 # Recursive case else: return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
f4fc6fa9cd836ad87112917473037b25165b0bae
mkzia/eas503
/old/fall2021/week5/dict_syntax.py
1,815
4.46875
4
# Dictionaries # student # - name # - email # - id # - major # Most people use this my_dict = { 'name': 'john', 'email': 'john@email.com', 'id': 1234, 'major': 'Engineering' } # Can also do this my_dict = dict( name='john', email='john@email.com', id=1234, major='Engineering' ) ## accessing value key = 'name' my_dict['name'] my_dict[key] # ## iterating over dictionaries for value in my_dict.values(): print(value) for key in my_dict.keys(): print(key) ## access both for key, value in my_dict.items(): print(f'key is {key} and value is {value}') # ## test if dict contains a key if key in my_dict: print(True) else: print(False) ## test if dict contains a value # default is testing in key value = 'john' if value in my_dict.values(): print(True) else: print(False) # # dictionary methods my_dict.clear() ## empty dict my_dict.copy() ## copy dict -- unique objects in memory # # check == and is; == is for values and is for memory # # create default dictionary with initial value new_student = {}.fromkeys( ['name', 'email', 'id', 'major'], 'missing') my_dict = {}.fromkeys(range(5), 'iammissing') # ## get my_dict.get('name', None) # default my_dict.get('name', False) my_dict.get('name', 'defaultname') # ## pop remove value using key my_dict.pop('name') # ## update -- way to append to dictionary my_dict.update({'year':2010, 'ear': 2030}) # ## dictionary comprehension # {___:___ for ___ in ___} # my_dict = {}.fromkeys(range(5), 5) # {key: key*value for key, value in my_dict.items()} # {num: num*num for num in range(5)} list1 = ['john', 'jane', 'doe'] list2 = [95, 99, 98] {list1[i]: list2[i] for i in range(len(list1))} dict(zip(list1,list2)) {num: ("even" if num % 2 == 0 else "odd") for num in range(1, 20)}
bc36f62269be93c5d43ce1f93360b2c47bd50352
bobobyu/leecode-
/leecode/ๅ‰‘ๆŒ‡ Offer 16. ๆ•ฐๅ€ผ็š„ๆ•ดๆ•ฐๆฌกๆ–น.py
642
3.65625
4
class Solution: def myPow(self, x: float, n: int) -> float: def descending_power(x, n) -> float: if n == 0: return 1 if n == 1: return x if n == -1: return 1/x if n & 1: y = descending_power(x, (n - (1 if n > 0 else -1)) >> 1) return (y * y * x) if n > 0 else y * y * (1/x) else: y = descending_power(x, n >> 1) return (y * y) if n > 0 else y * y return descending_power(x=x, n=n) s = Solution() import time a = time.time() print(s.myPow(2, -3))
b22c2361d50a85e1daee62d3263e6a44afe492ea
DineshKumaranOfficial/Python_Reference
/Decorators/Power_of_Functions.py
353
3.828125
4
# This one is a higher order function since it accepts another function def hi(func): func() # This is a higher order function since it returns another function def hello(): def dummy(): print('this is hello dummy') return dummy def sample(): print("I'm just a sample") a = hi(hello()) a = hi(sample)
5fdf526131ad0456fe24d7ee5566c6d0eccd61cd
rosrez/python-lang
/06-iteration/for-enumerate.pl
262
4.15625
4
#!/usr/bin/env python list = [2, 4, 6, 8, 10]; print "Iteration using enumerate to get index" for i,n in enumerate(list): # enumerate(s), where s is a sequence, returns a tuple (index, item) print "squares[%d] = %d**2 = %d" % (i, n, 2**n)
61cd4b197f6ebce64dc7eabd8027727eddf8be23
sand8080/solar
/solar/solar/orchestration/traversal.py
990
3.578125
4
""" task should be visited only when predecessors are visited, visited node could be only in SUCCESS or ERROR task can be scheduled for execution if it is not yet visited, and state not in SKIPPED, INPROGRESS PENDING - task that is scheduled to be executed ERROR - visited node, but failed, can be failed by timeout SUCCESS - visited node, successfull INPROGRESS - task already scheduled, can be moved to ERROR or SUCCESS SKIPPED - not visited, and should be skipped from execution NOOP - task wont be executed, but should be treated as visited """ VISITED = ('SUCCESS', 'ERROR', 'NOOP') BLOCKED = ('INPROGRESS', 'SKIPPED') def traverse(dg): visited = set() for node in dg: data = dg.node[node] if data['status'] in VISITED: visited.add(node) for node in dg: data = dg.node[node] if node in visited or data['status'] in BLOCKED: continue if set(dg.predecessors(node)) <= visited: yield node
e29c8194afaab88b9dc0f253cdc9a1f35a2a8cef
wukunzan/algorithm004-05
/Week 1/id_040/LeetCode_70_040.py
1,187
3.84375
4
#ๅ‡่ฎพไฝ ๆญฃๅœจ็ˆฌๆฅผๆขฏใ€‚้œ€่ฆ n ้˜ถไฝ ๆ‰่ƒฝๅˆฐ่พพๆฅผ้กถใ€‚ # # ๆฏๆฌกไฝ ๅฏไปฅ็ˆฌ 1 ๆˆ– 2 ไธชๅฐ้˜ถใ€‚ไฝ ๆœ‰ๅคšๅฐ‘็งไธๅŒ็š„ๆ–นๆณ•ๅฏไปฅ็ˆฌๅˆฐๆฅผ้กถๅ‘ข๏ผŸ # # ๆณจๆ„๏ผš็ป™ๅฎš n ๆ˜ฏไธ€ไธชๆญฃๆ•ดๆ•ฐใ€‚ # # ็คบไพ‹ 1๏ผš # # ่พ“ๅ…ฅ๏ผš 2 #่พ“ๅ‡บ๏ผš 2 #่งฃ้‡Š๏ผš ๆœ‰ไธค็งๆ–นๆณ•ๅฏไปฅ็ˆฌๅˆฐๆฅผ้กถใ€‚ #1. 1 ้˜ถ + 1 ้˜ถ #2. 2 ้˜ถ # # ็คบไพ‹ 2๏ผš # # ่พ“ๅ…ฅ๏ผš 3 #่พ“ๅ‡บ๏ผš 3 #่งฃ้‡Š๏ผš ๆœ‰ไธ‰็งๆ–นๆณ•ๅฏไปฅ็ˆฌๅˆฐๆฅผ้กถใ€‚ #1. 1 ้˜ถ + 1 ้˜ถ + 1 ้˜ถ #2. 1 ้˜ถ + 2 ้˜ถ #3. 2 ้˜ถ + 1 ้˜ถ # # Related Topics ๅŠจๆ€่ง„ๅˆ’ #leetcode submit region begin(Prohibit modification and deletion) class Solution(object): # ็ฌฌไธ€้ 2019ๅนด10ๆœˆ14ๆ—ฅ def climbStairs(self, n: int) -> int: """ :type n: int :rtype: int ้€š่ฟ‡ๅˆ†ๆž๏ผŒ่ฏฅ้ข˜็š„ๆœฌ่ดจๆ˜ฏๆฑ‚ๆ–ๆณข้‚ฃๅฅ‘ๆ•ฐๅˆ— """ if n <= 2: return n f1, f2, f3 = 1, 2, 3 for i in range(3, n + 1): f3 = f1 + f2 f1 = f2 f2 = f3 return f3 #leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': s = Solution() nums = 3 print(nums) s.climbStairs(nums) print(nums)
528a775c0295ad9bb93f4e47979ffa420622c9e5
TejaswitaW/Advanced_Python_Concept
/Multithreading.py
376
3.515625
4
#Creating thread using any class from threading import* import time print(current_thread().getName()) def disp(): print("I am display function executed by thread") print(current_thread().getName()) ##t=Thread(target=disp)#thread is created t=Thread(target=disp).start() #this is also valid ##t.start()#thread is started time.sleep(5) print(current_thread().getName())
d6c36ab1d0411ba9f7020f6671c8090464b507d1
thebigshaikh/Machine-Learning
/LinearRegressionMultiVariable.py
1,187
3.625
4
import numpy as np import matplotlib.pyplot as plt def import_data(filename): data = np.loadtxt(filename, delimiter=',') x = data[:, :2] y = data[:, 2] m = len(y) return data, x, y.reshape((len(y), 1)), m def plot_data(xx1, xx2, yy): plt.scatter(xx1, xx2, yy) plt.show() d, X, Y, M = import_data("ex1data2.txt") plot_data(X[:, 0], X[:, 1], Y.ravel()) number_of_theta = d.shape[1] X = np.concatenate([np.ones((M, 1)), X], axis=1) # Adds a colimns of ones (X0) to X theta_init = np.array([0 for i in range(number_of_theta)]).reshape(number_of_theta, 1) def cost_function(sizem, xdata, ydata, theta): j = 0 j = 1 / (2 * sizem) * np.sum( (xdata.dot(theta) - ydata) ** 2 ) return j cost_value = cost_function(M, X, Y, theta_init) print(cost_value) j_history = [] def gradient_descent(alpha, size, X, Y, numofiters, theta_init): for i in range(numofiters): theta_init = theta_init - (alpha / size) * (np.dot(X, theta_init) - Y).dot(X) j_history.append(cost_function(size, X, Y, theta_init)) return theta_init, j_history th, jh = gradient_descent(0.01, M, X, Y, 2000, theta_init) print(th, jh)
32a239b35f1b2bb72f4ebd72f70dd2195280305e
yawsonsamuel320/Ames-House-Prices-Prediction
/datacleaning.py
614
4.0625
4
import pandas as pd def print_hello(n=2): '''Prints hello''' return "hello" def missing_percentage(df): '''missing_percentage(dataframe) Return the number and percentage of missing values Parameters ---------- dataframe: Returns ------- out: a Series A Series showing the levels of missing values ''' NaN_count = df.isnull().sum().sort_values(ascending=False) NaN_count = NaN_count[NaN_count!=0] NaN_percent = (NaN_count / len(df)) * 100 NaN_info = pd.concat([NaN_count, NaN_percent], axis=1, keys=["Total", "Percent"]) return NaN_info
3deeefc6ad581fb024755c56abcc6f57b02f45d9
jdht1992/PythonScript
/class/class17.py
528
3.96875
4
class Person: # the self parameter is a reference to the class itself, and is used to access variable that belongs to the class def __init__(mysillyobjects, name, age): mysillyobjects.name = name mysillyobjects.age = age #it does not have to be named self, you can all it wherever you like, but it has to be the first parameter of any function in the class def my_function(abc): print(f'My name is: {abc.name} and my age is : {abc.age}') person = Person('Juan', 26) person.my_function()
5643e320326d1d99fb062e4ce7e0d34227886349
andrewtbanks/EIE-Transport-Models
/EIE_transport_models/reaction_sim.py
16,838
3.625
4
#################################################################### ## reaction_sim.py ## Author: Andy Banks 2019 - University of Kansas Dept. of Geology ##################################################################### # Code to simulate reactive transport using trajectories generated by advection_dispersion_sim.py # Instantaneous reaction C1 + C2 -> C3 is simulated with 1:1 stoichiometric and mass ratio # C1 particles represent treatment solution injected into the aquifer. C2 particles represent contaminated groundwater and C3 particles represent the degradation reaction product. # General process: # - Initially all particles are labeles as either C1 or C2, and assigned a correponding initial mass. # - After each timestep, the positions of all particles are grouped spatiall into 0.625 x 0.625 m bins. # - Within each bin # > The total mass carried by C1 and C2 is computed and the limiting reactant is determined. # > The mass of the limiting reactant is completely subtracted from particles of the limiting reactant # > The mass of the excess reactant is reduced by the same amount # > Remaining mass of the excess reactant is distributed evenly among all reamaining excess reactant particles # > All particles of the limiting reactant are re-labeled as reaction product (C3), and the total mass reacted is distributed evenly among them. # > Mass is conserved, meanaing that all reacted mass (twice the mass of the limiting reactant) is converted into reaction product (C3) ################# Begin Code ########################### # import python packages import os import sys import numpy as np import matplotlib.pyplot as plt import flopy import flopy.utils.reference as srf # load timeseries data output generated by advection_dispersion_sim.py path_data = np.load('modpath'+os.sep+'adv_disp_data_case0.npy') # initialize variables for space and time discretization ntsteps = len(path_data) # number of timesteps L = 25 # distance between each pumping well and origin Ldom = 300.25 # length of the model domain in x and y dirs xul = -150.125 # left limit of model domain in x direction yul = 150.125 # top limit of model domain in y direction ## Build flopy reference grid corresponding to modflow model domain ## Grid is used to identify if particles have been captured by an active well nrows = 1201 # number of rows ncols = 1201 # number of columns delr = (Ldom/nrows)*np.ones(nrows) # row spacing delc = (Ldom/nrows)*np.ones(ncols) # com spacing mf_ref_grid = srf.SpatialReference(delr = delr, delc = delc, xul = xul, yul = yul) # call flopy to construct reference grid for modflow model wellX = [0,0,L,-L] # list of x coordinats for wells wellY = [L,-L,0,0] # list of y coordinats for wells wellRC = mf_ref_grid.get_rc(wellX,wellY) # get row,col position for each well wellR = wellRC[0] # row position of each well wellC = wellRC[1] # col position of each well # list of indicies indicating the active well at each step (0 = North , 1 = South, 2 = East, 3 = West) active_well = [3,2,3,2,3,2,1,0,1,0,1,0] ## Build flopy reference grid for binning reactants (this gris is coarser than the grid for the modflow domain) ## Reaction is simulated in each cell of this grid nrows = 480 # number of rows ncols = 480 # number of cols delr = (Ldom/nrows)*np.ones(nrows) # row spacing (0.625 m) delc = (Ldom/nrows)*np.ones(ncols) # col spacing (0.625 m) ref_grid = srf.SpatialReference(delr = delr, delc = delc, xul = xul, yul = yul)# call flopy to construct reference grid for reaction Xc = ref_grid.xcentergrid # get x coordinate for center of each cell on the grid Yc = ref_grid.ycentergrid # get y coordinate for center of each cell on the grid ## initalize variables for simulating the reaction ntreatment = 1961 # number of treatement solution particles (species C1) ncontaminant = 5884 # number of contaminant solution particles (species C2) npt = ncontaminant + ntreatment # total number of particles used in the simulation treatment_mass = 4 # initial mass assigned to each C1 (treatment) particle contaminant_mass = 1 # initial mass assigned to each C2 (contaminant) particle tot_mass = sum(ntreatment*[treatment_mass] + ncontaminant*[contaminant_mass])# total mass of treatment solution (C1) and contaminant (C2) initially placed in the system rxn_data = [] # list to store reaction data for particles after each timestep conc_grid_data = [] # (currently inactive - easy to add in later) list to store concentration of each species at each point on the grid after each timestep ############## Main loop ################## for tstep in np.arange(0,ntsteps): #print('---') print(tstep) #display current timestep to indicate progress of loop tot_mass_degraded = 0 # term to store the total mass degreaded at each step - used to check mass balance # initialize concentration grid for current timestep - store mass of each species at each point on the grid conc_grid_step = np.zeros([nrows,ncols], dtype=[('mass_c1',float,1), ('mass_c2',float,1), ('mass_c3',float,1)]) # initalize array for storing position, mass, species and the plotting color (C1 = yellow, C2 = blue, C3 = green) for each particle used in the simulation rxn_step = np.zeros(npt, dtype=[('x', float, 1), ('y', float, 1), ('row', float, 1), ('col', float, 1), ('species',str, 2), ('mass',float,1), ('color',str,10)]) # get global x,y positions for all particles at the current timestep rxn_step['x'] = path_data[tstep]['x']# x position (on modflow grid) of all particles at current timestep rxn_step['y'] = path_data[tstep]['y']# y position (on modflow grid) of all particles at current timestep # get the current species and mass of all particles if tstep ==0: # at t=0 (before any reaction occurs), assign treatment and contaminant their respective initial masses and labels rxn_step['species'] = ntreatment*['c1'] + ncontaminant*['c2'] rxn_step['color'] = ntreatment*['yellow'] + ncontaminant*['blue'] rxn_step['mass'] = ntreatment*[treatment_mass] + ncontaminant*[contaminant_mass] else: # for t>0, retrieve the current species and mass of all particles from the end of the previous timestep rxn_step['species'] = rxn_data[tstep-1]['species'] rxn_step['color'] = rxn_data[tstep-1]['color'] rxn_step['mass'] = rxn_data[tstep-1]['mass'] ## identify and relabel any particles that are extracted from a pumping well during the sequence # get row,col positions (on modflow grid) for all particles at the current timestep rxn_step['row'] = path_data[tstep]['row']# row position (on modflow grid) of all particles at current timestep rxn_step['col'] = path_data[tstep]['col']# col position (on modflow grid) of all particles at current timestep rows = [int(rxn_step['row'][i]) for i in np.arange(0,npt)] # convert to integers cols = [int(rxn_step['col'][i]) for i in np.arange(0,npt)] # convert to integers active_wellR = wellR[active_well[tstep]] # row position (on modflow grid) corresponding to the active well at current timestep active_wellC = wellC[active_well[tstep]] # col position (on modflow grid) corresponding to the active well at current timestep # determine what particles have row,col positions matching those of the active well row_canidates = np.where(rows == active_wellR)[0] # index of particle row positions that match the row position (on modflow grid) of the active well col_canidates = np.where(cols == active_wellC)[0] # index of particle col positions that match the col position (on modflow grid) of the active well local_captured_ind = list(set(row_canidates) & set(col_canidates)) # set of indicies for all row,col particle positions that match the row,col position of the active well # relabel particles "extracted" from the pumping well at current timestep as 'ex' and change their plotting color to red rxn_step['species'][local_captured_ind]= 'ex' rxn_step['color'][local_captured_ind]= 'red' ## Bin particles in reactant grid #get row,col positions (on reaction grid) for all particles at the current timestep adj_r,adj_c = ref_grid.get_rc(rxn_step['x'],rxn_step['y']) rxn_step['row'] = adj_r # row position (on reaction grid) of all particles at current timestep rxn_step['col'] = adj_c # col position (on reaction grid) of all particles at current timestep # identify particles labeled as C1 and get row and col positions for each global_c1_ind = np.where(rxn_step['species'] == 'c1')[0] # index for particles labeled C1 at the current timestep c1_rows = [int(rxn_step['row'][i]) for i in global_c1_ind] # row position (on reaction grid) of all C1 particles at current timestep c1_cols = [int(rxn_step['col'][i]) for i in global_c1_ind] # col position (on reaction grid) of all C1 particles at current timestep c1_rc_pairs = np.transpose(np.array([c1_rows,c1_cols])).tolist() #(npt,2) list of row,col pairs for all C1 particles # identify particles labeled as C2 and get row and col positions for each global_c2_ind = np.where(rxn_step['species'] == 'c2')[0]# index for particles labeled C2 at the current timestep c2_rows = [int(rxn_step['row'][i]) for i in global_c2_ind]# row position (on reaction grid) of all C2 particles at current timestep c2_cols = [int(rxn_step['col'][i]) for i in global_c2_ind]# col position (on reaction grid) of all C2 particles at current timestep c2_rc_pairs = np.transpose(np.array([c2_rows,c2_cols])).tolist() #(npt,2) list of row,col pairs for all C2 particles ## For reaction to occur in a given cell, both C1 and C2 particles must be present # The next segement of code identifies the row,col position of all cells that contain both C1 and C2 particles # get unique row,col positions for C1 particles uniq_c1_rc,c1_rc_inds,c1_rc_inv,c1_rc_counts = np.unique(c1_rc_pairs,axis = 0, return_index = True, return_inverse = True,return_counts = True)# generates index for unique row,col pairs for cells containing C1 particles reacting_rc = uniq_c1_rc[np.where(c1_rc_counts>1)[0].tolist()] # retrieve list of unique row,col paris ### loop through each unique row,col pair containing C1 particles for reacting_cell in reacting_rc: # get indicies of all C1 particles in current cell c1_row_canidate = np.where(np.array(c1_rows) == reacting_cell[0])[0] c1_col_canidate = np.where(np.array(c1_cols) == reacting_cell[1])[0] local_c1_ind = global_c1_ind[list(set(c1_row_canidate) & set(c1_col_canidate))] # get indicies of all C1 particles in current cell c2_row_canidate = np.where(np.array(c2_rows) == reacting_cell[0])[0] c2_col_canidate = np.where(np.array(c2_cols) == reacting_cell[1])[0] local_c2_ind = global_c2_ind[list(set(c2_row_canidate) & set(c2_col_canidate))] # check whether C1 and C2 particles are both present local_npt_c1 = len(local_c1_ind) # number of C1 particles in cell local_npt_c2 = len(local_c2_ind) # number of C2 particles in cell check = 1 if local_npt_c1==0: check = 0 if local_npt_c2==0: check = 0 if check == 1:# if C1 and C2 particles are present in current cell -- proceed with reaction simulation # compute mass of each species in the current cell local_c1_mass = sum(rxn_step['mass'][local_c1_ind]) local_c2_mass = sum(rxn_step['mass'][local_c2_ind]) # to check mass conservation at each step initial_reactant_mass = local_c1_mass+local_c2_mass remaining_reactant_mass = local_c1_mass+local_c2_mass product_mass = 0 # complete reaction step depending on limiting reactant # CASE 1 : C2 is the limiting reactant if local_c1_mass>local_c2_mass: # determine reacted mass for each species (1:1 stoichiometric and mass ratios here) reacted_mass_c1 = local_c2_mass reacted_mass_c2 = local_c2_mass remaining_mass_c1 = local_c1_mass - local_c2_mass # amount of c1 mass remaining in cell converted_mass_c3 = 2*local_c2_mass # amount of c1 mass converted to c3 in cell ## redistribute excess c1 mass among c1 particles distributed_mass_c1 = remaining_mass_c1/local_npt_c1 # mass to re-distribute to each c1 particle rxn_step['mass'][local_c1_ind] = distributed_mass_c1 ## convert limiting reactant particles to c3 and distribute converted mass equally among them distributed_mass_c3 = converted_mass_c3/local_npt_c2 # mass to re-distribute to each converted c2->c3 particle rxn_step['species'][local_c2_ind] = 'c3' rxn_step['color'][local_c2_ind] = 'green' rxn_step['mass'][local_c2_ind] = distributed_mass_c3 ## update mass conservation variables remaining_reactant_mass = remaining_reactant_mass - converted_mass_c3 product_mass = product_mass + converted_mass_c3 # CASE 2: c1 is the limiting reactant if local_c2_mass>local_c1_mass: # determine reacted mass for each species (1:1 stoichiometric and mass ratios here) reacted_mass_c1 = local_c1_mass reacted_mass_c2 = local_c1_mass remaining_mass_c2 = local_c2_mass - local_c1_mass # amount of c2 mass remaining in cell converted_mass_c3 = 2*local_c1_mass # amount of c1 mass converted to c3 in cell ## redistribute excess c2 mass among c2 particles distributed_mass_c2 = remaining_mass_c2/local_npt_c2 # mass to re-distribute to each c1 particle rxn_step['mass'][local_c2_ind] = distributed_mass_c2 ## convert limiting reactant particles to c3 and distribute converted mass equally among them distributed_mass_c3 = converted_mass_c3/local_npt_c1 # mass to re-distribute to each converted c1->c3 particle rxn_step['species'][local_c1_ind] = 'c3' rxn_step['color'][local_c1_ind] = 'green' rxn_step['mass'][local_c1_ind] = distributed_mass_c3 ## update mass conservation variables remaining_reactant_mass = remaining_reactant_mass - converted_mass_c3 product_mass = product_mass + converted_mass_c3 # CASE 3: equal amounts of c1 and c2 if local_c2_mass==local_c1_mass: # all mass is converted to c3 converted_mass_c3 = local_c1_mass + local_c2_mass distributed_mass_c3 = converted_mass_c3/(local_npt_c1 + local_npt_c2) # convert all particles in cell to c3 and distribute mass equally among them rxn_step['species'][local_c1_ind] = 'c3' rxn_step['color'][local_c1_ind] = 'green' rxn_step['mass'][local_c1_ind] = distributed_mass_c3 rxn_step['species'][local_c2_ind] = 'c3' rxn_step['color'][local_c2_ind] = 'green' rxn_step['mass'][local_c2_ind] = distributed_mass_c3 ## update mass conservation variables remaining_reactant_mass = remaining_reactant_mass - converted_mass_c3 product_mass = product_mass + converted_mass_c3 # check mass balance after each timestep and raise error if mass is not conserved mass_bal = initial_reactant_mass - product_mass - remaining_reactant_mass if mass_bal != 0: print('MASS NOT CONSERVED') # update reaction data list rxn_data.append(rxn_step) # save output to file np.save('rxn_data_case0',rxn_data)
75dba783f33832dfffebb47272c9f25f338d407a
jackyen2000/workstation
/Rabbits and Recurrence Relations/rabbits3.py
674
3.65625
4
def fibrabbit(n, k): fib_table = [] for i in range(n): if i < 2: fib_table.append(1) else: fib_table.append(fib_table[-1] + fib_table[-2]*k) return fib_table #sample data 5 3 with open('rosalind_fib.txt', 'r') as f: n, k = f.readline().split() print (fibrabbit(int(n), int(k))[-1]) #def fib(n, k): # fib_table = [] # for i in range(n): # if i < 2: # fib_table.append(1) # else: # fib_table.append(fib_table[-1] + fib_table[-2]*k) #return fib_table #with open('rosalind_fib.txt', 'r') as f: # n, k = f.readline().split() # print fib(int(n), int(k))[-1]
985c7f1f0d702579b6ea4d8c61e5ce3172b4670a
freliZh/rf-unbalance-data
/decisiontree.py
4,625
3.53125
4
#encoding:utf8 from __future__ import division import random import numpy as np import time from scipy.stats import mode from utilities import information_gain, entropy from pandas import Series, DataFrame class DecisionTreeClassifier(object): """ A decision tree classifier. A decision tree is a structure in which each node represents a binary conditional decision on a specific feature, each branch represents the outcome of the decision, and each leaf node represents a final classification. """ def __init__(self, max_features=lambda x: x, max_depth=10, min_samples_split=2): """ Args: max_features: A function that controls the number of features to randomly consider at each split. The argument will be the number of features in the data. max_depth: The maximum number of levels the tree can grow downwards before forcefully becoming a leaf. min_samples_split: The minimum number of samples needed at a node to justify a new node split. """ self.max_features = max_features self.max_depth = max_depth self.min_samples_split = min_samples_split def fit(self, X, y): """ Builds the tree by chooseing decision rules for each node based on the data. """ n_features = X.shape[1] n_sub_features = int(self.max_features(n_features)) feature_indices = random.sample(xrange(n_features), n_sub_features) self.trunk = self.build_tree(X, y, feature_indices, 0) def predict(self, X): """ Predict the class of each sample in X. """ #print X num_samples = X.shape[0] y = np.empty(num_samples) for j in xrange(num_samples): node = self.trunk while isinstance(node, Node): if X.ix[j,node.feature_index] <= node.threshold: node = node.branch_true else: node = node.branch_false y[j] = node return y def build_tree(self, X, y, feature_indices, depth): """ Recursivly builds a decision tree. """ #print X if depth is self.max_depth or len(y) < self.min_samples_split or entropy(y) is 0: return mode(y)[0][0] feature_index, threshold = find_split(X, y, feature_indices) X_true, y_true, X_false, y_false = split(X, y, feature_index, threshold) #print str(len(X_true)) +"," +str(len(X_false)) if y_true.shape[0] is 0 or y_false.shape[0] is 0: return mode(y)[0][0] branch_true = self.build_tree(X_true, y_true, feature_indices, depth + 1) branch_false = self.build_tree(X_false, y_false, feature_indices, depth + 1) return Node(feature_index, threshold, branch_true, branch_false) def find_split(X, y, feature_indices): """ Returns the best split rule for a tree node. """ num_features = X.shape[1] X = DataFrame(X) y = DataFrame(y) best_gain = 0 best_feature_index = 0 best_threshold = 0 for feature_index in feature_indices: values = sorted(set(X.ix[:, feature_index])) ### better way for j in xrange(len(values) - 1): threshold = (values[j] + values[j+1])/2 #print "spliting tree %d iter" % j X_true, y_true, X_false, y_false = split(X, y, feature_index, threshold) #print y_false gain = information_gain(y, y_true, y_false) #print "gain " + str(gain) if gain > best_gain: best_gain = gain best_feature_index = feature_index best_threshold = threshold return best_feature_index, best_threshold class Node(object): """ A node in a decision tree with the binary condition xi <= t. """ def __init__(self, feature_index, threshold, branch_true, branch_false): self.feature_index = feature_index self.threshold = threshold self.branch_true = branch_true self.branch_false = branch_false def split(X, y, feature_index, threshold): """ Splits X and y based on the binary condition xi <= threshold. """ X_true_indexes = X[X.ix[:,feature_index] <= threshold].index X_false_indexes = X[X.ix[:,feature_index] > threshold].index X_true = X.ix[X_true_indexes,:] X_false = X.ix[X_false_indexes,:] #print X_true y_true = y.ix[X_true_indexes,:] y_false = y.ix[X_false_indexes,:] return X_true, y_true, X_false, y_false
b3db546bf1a5ee86354a46450eb4e92988b747f3
Kaali09/sunbird-analytics
/platform-scripts/python/main/vidyavaani/utils/find_files.py
649
3.65625
4
# Author: Aditya Arora, adityaarora@ekstepplus.org import os #This function traverses a directory finding all files with a particular substring #Returns a list of files found def findFiles(directory,substrings): ls=[] if (type(directory) == unicode or type(directory) == str) and type(substrings) == list: # assert type(directory)==unicode or type(directory)==str # assert type(substrings)==list if os.path.isdir(directory): for dirname, dirnames, filenames in os.walk(directory): for filename in filenames: string=os.path.join(dirname, filename) for substring in substrings: if(string.find(substring)>=0): ls.append(string) return ls
48d3584d6bc1cd0a0a2c147f58dde64fd4a1deae
pianomanzero/python_scripts
/python2scripts/baks/argv.py.bak
571
3.984375
4
#!/usr/bin/env python from sys import argv script, var1, var2, var3 = argv print "The name of the script is: ", script print "The first var you passed is: ", var1 print "The second var you passed is: ", var2 print "The third var you passed is: ", var3 print "\n" print "Now we're going to work with raw_input\n" prompt='>' print "This is a question" answer1=raw_input(prompt) print "this is another question" answer2 = raw_input(prompt) print "last question" answer3 = raw_input(prompt) print """ Here's your answers: %r, %r, %r """ %(answer1, answer2, answer3)
a6f0a34046b16fade163bc933d8aa03f2c8ef8bf
TestTech0920/cs1520
/week02/py/functions.py
183
3.609375
4
def sum(a, b): return a + b print(sum(4, 5)) print(sum('this is ', 'a sentence')) def product(a, b, c=1): return a * b * c print(product(4, 5)) print(product(2, 3, 4))
0bef1ea39c18887ebad445cad60c244bbe0ebe89
javierobledo/UTFSM-IWI131
/2018/S2/Clases/Clase02102018/hora.py
207
3.65625
4
hora = raw_input("Ingrese la hora en formato hh:mm:ss :") h = int(hora[0]+hora[1]) m = int(hora[3]+hora[4]) s = int(hora[6]+hora[7]) segundos = 3600*h + 60*m + s print "Los cantidad de segundos es", segundos
2e099a8fc1dbf7794e6980c3838a08c567ec527d
MikeLing/GatesMusicPet
/music_pet/utils.py
663
3.5625
4
# -*- coding: utf-8 -*- from codecs import decode def trim_quote(text): if len(text) > 2 and text[0] == '"' and text[-1] == '"': text = text[1:-1] return text def to_unicode(text, encoding="utf8"): if type(text) == unicode: return text elif type(text) == str: return decode(text, encoding) else: return unicode(text) def remove_bom(input_filename, output_filename): fp = open(input_filename, "rb") bom = fp.read(3) if bom != b'\xef\xbb\xbf': raise ValueError("File doesn't have UTF-8 BOM") fo = open(output_filename, "wb") fo.write(fp.read()) fo.close() fp.close()
b33d8bb3f27149f60317c71c4638da0027b4dd97
gabriel-bri/cursopython
/CursoemVideo/ex024.py
145
3.84375
4
cidade = str(input('Digite o nome de sua cidade: ')).strip() verifica = 'SANTO' in cidade[0:5].upper() print('Tem SANTO? {}' .format(verifica))
421ff2d8eb46e94793c3e227a2b520bd5ea9b548
harrisonBirkner/PythonSP20
/Project2/Project2/Project2.py
9,751
4.28125
4
#This program displays a menu with 4 options: SIGN IN, CREATE NEW USER, RESET PASSWORD, AND EXIT PROGRAM. SIGN IN prompts the user to enter a login id and password that is checked against login data in the file. #CREATE NEW USER prompts the user to enter a new login id and password that is added to the file. RESET PASSWORD prompts the user to enter their old password and new password which is added to the file. EXIT PROGRAM # terminates the program. #Harrison Birkner #4/21/2020 #empty lists are created for ids and passwords. They are created globally because of frequency of use idList = [] passwordList = [] #this try/except clause checks for errors opening the dat file try: loginInfo = open('password.dat', 'r') except IOError: #if an error is raised attempting to open the file a message is printed and the program is terminated print("ERROR! There was an issue opening the file 'password.dat'.") exit(0) #mainMenu displays the users options for that menu def mainMenu(): print('\n\n*****MAIN MENU*****') print('*ENTER 1 TO SIGN IN\n') print('*ENTER 2 TO CREATE NEW USER\n') print('*ENTER 3 TO RESET PASSWORD\n') print('*ENTER 4 TO EXIT PROGRAM\n\n') #this loop will run until a valid option is entered while True: try: userOption = int(input('OPTION: ')) if userOption == 1: #on a 1 the sign in option is selected signIn() elif userOption == 2: #on a 2 the new user option is selected newUser() elif userOption == 3: #on a 3 the reset password option is selected resetPassword() elif userOption == 4: #on a 4 the exit program option is selected print('Program terminated') exit(0) else: #if an invaled option is entered an error is raised raise ValueError break except ValueError: print('ERROR! Input must be 1-3') #signIn prompts the user to sign in by entering an existing login id and password def signIn(): print('\n\n*****SIGN IN*****') inputId = input('Enter login id: ') #if the inputted id exists in the file... if inputId in idList: #validation continues, otherwise... pass else: #an error is printed and the user is returned to the main menu print('No matching login id found. Returning to menu...') mainMenu() inputPassword = input('\nEnter password: ') #if the inputted password exists in the file... if inputPassword == passwordList[idList.index(inputId)]: #validation is finished, otherwise... pass else: #an error is printed and the user is returned to the main menu print('Password does not match the login id entered. Returning to menu...') mainMenu() print('You have successfully been logged in!') input('Press enter to return to the main menu...') mainMenu() #newUser allows the user to enter a new login id and password def newUser(): print('\n\n*****NEW USER*****') newId = input('Enter login id: ') valIdFlag = False valPassFlag = False #while the new id is not valid the loop will continue while valIdFlag == False: #validateId is ran with the user's inputted id and the flag for if it is valid passed into it. It returns data into the two same variables newId, valIdFlag = validateId(newId, valIdFlag) print('Login id valid!') newPass = input('Enter password: ') #while the new password is not valid the loop will continue while valPassFlag == False: #validatePass is ran with the user's inputted password and the flag for if it is valid passed into it. It returns data into the two same variables newPass, valPassFlag = validatePass(newPass, valPassFlag, newId) print('Password valid!') #once validated the id and password are added to the list idList.append(newId) passwordList.append(newPass) appendNewLogin() input('login id and password saved! Press enter to return to the main menu...') mainMenu() #resetPassword allows the user to reset an existing password def resetPassword(): print('\n\n*****RESET PASSWORD*****') oldPass = input('Please enter your old password: ') #this loop continues until the password entered is found in the list of existing passwords while True: if oldPass in passwordList: print('password found!') #the position of the old password in the list is found and moved into a variable passIndex = passwordList.index(oldPass) break else: oldPass = input('No matching password found. Try again: ') newPass = input('Please enter new password: ') valPassFlag = False #while the new password is not valid the loop will continue while valPassFlag == False: #validatePass is ran with the user's inputted password, the flag for if it is valid, and the login id matching the password passed into it. It returns data into the new password and password flag variable newPass, valPassFlag = validatePass(newPass, valPassFlag, idList[passIndex]) #once validated the old password is changed to the new password passwordList[passIndex] = newPass appendNewLogin() input('Password successfuly changed! Press enter to return to the main menu...') mainMenu() #this function overwrites password.dat with the current id and password lists def appendNewLogin(): #this try/except clause checks for errors opening the dat file try: loginInfo = open('password.dat', 'w') except IOError: #if an error is raised attempting to open the file a message is printed and the program is terminated print("ERROR! There was an issue opening the file 'password.dat'.") exit(0) #this loop runs for as many times as there are items in the id list (which list is chosen is arbitrary as they have the same number of items) for x in range(0, len(idList)): #the id with an index of x is written to the file concatenated with a newline character loginInfo.write(idList[x] + '\n') #the password with an index of x is written to the file concatenated with a newline character loginInfo.write(passwordList[x] + '\n') #password.dat is closed loginInfo.close #validateId has an id and flag for id validity as arguments. If any validation returns false the id and flag are returned and the function exits def validateId(newId, valIdFlag): #if id's length is 6-10... if len(newId) > 5 and len(newId) < 11: #nothing happens, otherwise... pass else: #an error message is displayed and the funcion exits newId = input('Login id is too short or long. 6-10 characters required. Try again: ') return newId, valIdFlag #counter for # of numbers in id is set to 0 loginIdNumCtr = 0 #this loops through the characters in the id for x in newId: #if the character is a digit... if x.isdigit(): #one is added to the counter loginIdNumCtr += 1 #if the id has at least two numbers... if loginIdNumCtr >= 2: #nothing happens, otherwise... pass else: #an error message is displayed and the funcion exits newId = input('Login id does not have enough numbers. At least two numbers required. Try again: ') return newId, valIdFlag #this loops through the characters in the id for x in newId: #if the character is not a space... if x.isspace: #nothing happens, otherwise... pass else: #an error message is displayed and the funcion exits newId = input('Login id has spaces. No spaces allowed. Try again: ') return newId, valIdFlag #if the id is not in the id list... if newId not in idList: #nothing happens, otherwise... pass else: #an error message is displayed and the funcion exits newId = input('Login id already exists. Try again: ') return newId, valIdFlag #once validation is complete the id validation flag is set to true and the flag and id are returned valIdFlag = True return newId, valIdFlag #validatePass runs a password through validation and exits the function if any return false def validatePass(newPass, valPassFlag, id = None): if len(newPass) > 5 and len(newPass) < 13: pass else: newPass = input('Password is too short or long. 6-12 characters required. Try again: ') return newPass, valPassFlag PassNumCtr = 0 for x in newPass: if x.isdigit(): PassNumCtr += 1 if PassNumCtr >= 1: pass else: newPass = input('Password does not have enough numbers. At least one number required. Try again: ') return newPass, valPassFlag PassUpCtr = 0 for x in newPass: if x.isupper(): PassUpCtr += 1 if PassUpCtr >= 1: pass else: newPass = input('Password does not have enough uppercase letters. At least one uppercase letter required. Try again: ') return newPass, valPassFlag PassLowCtr = 0 for x in newPass: if x.islower(): PassLowCtr += 1 if PassLowCtr >= 1: pass else: newPass = input('Password does not have enough lowercase letters. At least one lowercase letter required. Try again: ') return newPass, valPassFlag for x in newPass: if x.isspace: pass else: newPass = input('Password has spaces. No spaces allowed. Try again: ') return newPass, valPassFlag if newPass not in id: pass else: newPass = input('Password cannot contain login id. Try again: ') return newPass, valPassFlag if newPass not in passwordList: pass else: newPass = input('Password already exists. Try again: ') return newPass, valPassFlag valPassFlag = True return newPass, valPassFlag #createIdList reads a line from the file, strips it of newline character, and adds it to the id list def CreateIdList(): id = loginInfo.readline() id = id.rstrip('\n') if id == '': pass else: idList.append(id) return id #init handles one time operations done at the beginning of the program def init(): id = CreateIdList() while id != '': password = loginInfo.readline() password = password.rstrip('\n') passwordList.append(password) id = CreateIdList() loginInfo.close #main controls the overall structure of the program def main(): init() mainMenu() main()
5fbf66fce05ea2fe5cc044e62657e34ea1a410a6
Sharkuu/PitE-Olaf-Schab
/unittest/zadanie.py
3,396
3.6875
4
#!/usr/bin/env python3.4 from math import acos from math import sin from math import pi import sys #Klasa odpowiedzialna za wczytywanie danych: # - zakres poszukiwan liczby pierwszej # - wysokosc trojkata pascala class InputReader: def __init__(self): self.primal = None self.triangle = None def Initiate(self): a,b = None, None print('Program wczytuje tylko liczby naturalne wieksze lub rowne 1 !') print('----------------') while self.CheckIfIsInt(a): a = input('Podaj zakres szukania liczb pierwszych \n') while self.CheckIfIsInt(b): b = input('Podaj wysokosc trojkata pascala a \n') self.primal = int(a) self.triangle = int(b) #Funkcja sprawdzajaca, czy wprowadzana wartosc jest intem oraz czy nie jest mniejsza od 1 def CheckIfIsInt(self,value): if value is None: return 1 else: try: val = int(value) if int(value) < 1: print("Podana liczba musi byc wieksza lub rowna 1") return 1 except ValueError: print("Wprowadzona wartosc nie jest liczba naturalna. Sprobuj jeszcze raz.") return 1 return 0 def returnValue(self,value): if value == 1: return self.primal if value == 2: return self.triangle else: print('Blad aplikacji') sys.exit(0) return 0 # Wypisuje liczby pierwsze z danego zakresu class Primary: def __init__(self,number): self.x=1 self.number = number; def isPrime(self,n): return n > 1 and all(n%i for i in range(2,n)) def __iter__(self): return self def __next__(self): self.x+=1 while(self.isPrime(self.x)==False): self.x+=1 if self.x > self.number: raise StopIteration return self.x #Wypisuje trojkat pascala dla zadanej ilosci rzฤ™dow class Pascal_Triangle: def __init__(self,rows): self.row=[1.0] self.n=0 self.rows = rows def __iter__(self): return self def __next__(self): line = [1.0] for k in range(self.n): line.append(line[k] * (self.n-k) / (k+1)) self.n+=1 if self.n>self.rows: raise StopIteration return line #Zwraca losowe liczby od 0 do 1 class montecarlo: def __init__(self): self.a=44485709377909 self.m=2**48 self.c = 0 self.x=1 self.n=0.0 def __iter__(self): return self def __next__(self): self.x=(self.a * self.x + self.c)%self.m self.n+=1 return self.x/self.m #Obliczanie caล‚ki metodฤ… montecarlo class monte_use: def __init__(self): TOL = 1e-7 c=0 n=1 mc = montecarlo() integra=100 while abs(2-integra) > TOL: x = next(mc)*pi y = next(mc) if 0<y<=self.func(x): c+=1 if 0>y>=self.func(x): c-=1 integra = pi*(c/n) n+=1 print('\nWynik obliczania calki') print(integra) print('\nIlosc iteracji, potrzebnych do obliczenia') print(n) #Funkcja, ktora obliczamy def func(self,x): return sin(x) # Klasa wywolujaca poszczegolne zadania class Manager: def __init__(self): inputt = InputReader() try: inputt.Initiate() except KeyboardInterrupt: print('\nAplikacja zatrzymana przez uzytkownika') sys.exit(0) print('ZADANIE 1') it1 = Primary(inputt.returnValue(1)) print ('Liczby pierwsze z zadanego zakresu:') for i in it1: print(i) print ('--------------') print('ZADANIE 2') print('Trojkat pascala:') pas = Pascal_Triangle(inputt.returnValue(2)) for i in pas: print(i) print ('--------------') print('ZADANIE 3') print('Monte Carlo:') monte_use() Manager()
31c25e9c3839e13cac5d4f4e2b5a30608f08354e
UWSEDS/homework-4-documentation-and-style-gtalpey
/test_dataframe.py
2,786
4
4
''' This module contains functions that check a DataFrame for various attributes. ''' import csv_to_df # use csv_to_df to create dataframe using Pronto data DF = csv_to_df.create_dataframe( 'https://data.seattle.gov/api/views/tw7j-dfaw/' 'rows.csv?accessType=DOWNLOAD') def test_create_dataframe(): '''test_create_dataframe data frame for conditions specified in homework 2 Test of DF for the following attributes: the columns in columns at least 10 entries that all datatypes in the DataFrame are the same Errors are raised if the conditions are not met Args: none (DataFrame created above) Returns: a_bool (bool): True if df passes tests, False otherwise ''' # create a slice of df and a column list to check against d_f_1 = DF.iloc[:, [4, 11]] columns1 = d_f_1.columns.tolist() # set output to True, then look for conditions to turn False. a_bool = True # check whether data frame contains only the columns listed in input # 'columns' # first, sort column list alaphabetically in case columns is not in same # order as the columns in df if d_f_1.columns.tolist().sort() != columns1.sort(): a_bool = False raise NameError('Columns in data frame do not match supplied' 'columns list') # check number of entries in data frame if len(d_f_1) <= 10: a_bool = False raise ValueError('Less than 10 lines in dataframe') # take 'set' of dypes in df. If length is 1, all data types are the same. if len(set(d_f_1.dtypes)) != 1: a_bool = False raise TypeError('Columns contain different data types') return a_bool # test dataframe for atleast one row def test_dataframe_length(): '''Redundant function to test that the DataFrame above has at least one line. ''' if DF.empty: raise ValueError('dataframe empty!') def test_dataframe_nan(): '''check DataFrame for nan values, raise ValueError if found''' # loop through columns for column in DF.columns.tolist(): for i in range(len(DF[column])): if DF[column][i] != DF[column][i]: raise ValueError('NAN located in %s on line %d' %(column, i)) def test_dataframe_types(): '''check to make sure data types within a column match''' # loop through columns for column in DF.columns.tolist(): # find type of first entry data_type = type(DF[column][0]) # loop through rows to check if the types match that of the first rows for i in range(len(DF[column])): if data_type == type(DF[column][i]): continue else: raise TypeError('data types in %s do not match' %column)
ed589d642ba58b58d86816cc9af1f010b8ac589d
ashrafya/secret_ciphers
/Ch1_A.py
3,023
3.53125
4
import pyperclip alphabets = {'A':0,'B':1, 'C':2, 'D':3, 'E':4, 'F':5, 'G':6, 'H':7, 'I':8, 'J':9, 'K':10, 'L':11, 'M':12, 'N':13, 'O':14, 'P':15, 'Q':16, 'R': 17, 'S':18, 'T':19, 'U':20, \ 'V':21, 'W':22, 'X':23 , 'Y':24, 'Z':25} opp = {0:'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'} def value_reverse_shift(letter, shift): letter = letter.upper() if letter not in alphabets: return letter if letter.upper() in alphabets: value = alphabets[letter] value-=shift while value<0: value+=26 return opp[value] def value_after_shift(letter, shift): letter = letter.upper() if letter not in alphabets: return letter if letter.upper() in alphabets: value = alphabets[letter] value += shift while value >=26: value -= 26 return opp[value] def decrypt_ceasar(string, shift): L=[] empty='' final='' for char in string: empty += value_reverse_shift(char, shift) case = check_case(char) L.append(case) for i in range(len(empty)): if L[i] == 'na' or L[i] == 1: final+=empty[i] else: final+=empty[i].lower() return final def encrypt_caesar(string, shift): L=[] empty ='' final='' for char in string: empty+=value_after_shift(char, shift) case = check_case(char) L.append(case) for i in range(len(empty)): if L[i] == 'na' or L[i] == 1: final+=empty[i] else: final+=empty[i].lower() return final def check_case(letter): upper = letter.upper() if letter not in alphabets and upper not in alphabets: return 'na' elif letter == upper: return 1 else: return 0 def what_shift(string, encrypted): for i in range(len(string)): upper = string[i].upper() upper_fk= encrypted[i].upper() if upper in alphabets: shift = alphabets[upper_fk] -alphabets[upper] if shift<0: shift+=26 return shift def find_set(key_list): i=0 not_done = True tester=[] while not_done: if key_list[i] == None: return None if key_list[i] !=None: tester.append(key_list[i]) i+=1 if key_list[i] == None: return tester if key_list[i] !=None: tester.append(key_list[i]) i+=1 half = int(len(tester)/2) if tester[:half] == tester[half:]: return tester[:half]
c604c320707c1a2ab3b92c9c96548be6eb53a23f
MananKavi/lab-practical
/src/practicals/set4/fourthProg.py
627
4
4
def binary_search(searchList, item): if len(searchList) == 0: return False else: mid = len(searchList) // 2 if searchList[mid] == item: return True else: if item < searchList[mid]: return binary_search(searchList[:mid], item) else: return binary_search(searchList[mid + 1:], item) myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] element = int(input("Enter element to be searched : ")) if binary_search(myList, element): print("Element found!") else: print("Element not found!")
4cd2b9d91d0e4c5cfa803965cc51a315fa10576c
hmok567/Triangle567
/TestTriangle.py
1,280
4.09375
4
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html has a nice description of the framework class TestTriangles(unittest.TestCase): # define multiple sets of tests as functions with names that begin def testRightTriangleA(self): self.assertEqual(classifyTriangle(3,4,5),'Right','3,4,5 is a Right triangle') def testRightTriangleB(self): self.assertEqual(classifyTriangle(5,3,4),'Right','5,3,4 is a Right triangle') def testEquilateralTriangles(self): self.assertEqual(classifyTriangle(1,1,1),'Equilateral','1,1,1 should be equilateral') def testIsoscelesTriangle(self): self.assertEqual(classifyTriangle(2, 2, 3), 'Isosceles', '2, 2, 3 should be isoceles') def testScaleneTriangle(self): self.assertEqual(classifyTriangle(3,4,2), 'Scalene') def testValidInput(self): self.assertEqual(classifyTriangle('Hi', 1, 23), 'InvalidInput') if __name__ == '__main__': print('Running unit tests') unittest.main()
d43d5166029f5ae1a6f25f6f3d4c78c8aebb4a1a
ca3tech/rectangles
/test_rectangles.py
1,020
3.734375
4
import unittest import rectangles as r class test_rectangles(unittest.TestCase): def test_num_rectangles_square(self): self.assertEqual(r.num_rectangles([(0,0), (1,0), (0,1), (1,1)]), 1) def test_num_rectangles_diamond(self): self.assertEqual(r.num_rectangles([(0,1), (1,0), (2,1), (1,2)]), 1) def test_num_rectangles_3rec(self): points = [] for x in range(0, 3): for y in range(0, 2): points.append((x,y)) self.assertEqual(r.num_rectangles(points), 3) def test_num_rectangles_10rec(self): points = [] for x in range(0, 3): for y in range(0, 3): points.append((x,y)) self.assertEqual(r.num_rectangles(points), 10) def test_num_rectangles_20rec(self): points = [] for x in range(0, 4): for y in range(0, 3): points.append((x,y)) self.assertEqual(r.num_rectangles(points), 20) if __name__ == "__main__": unittest.main()
ebd7913e0d97b47724ff9efa8716dc08ff49f96c
DSJL-ML/Find-Shortest-Path
/shortest_path_Dijkstras_Algorithm.py
3,808
3.9375
4
# define Vertice, Edge, Graph class class Vertice(object): def __init__(self, value): self.value = value self.edges = [] class Edge(object): def __init__(self, value, vertice1, vertice2): self.value = value self.vertice1 = vertice1 self.vertice2 = vertice2 class Graph(object): def __init__(self, vertices=[], edges=[], instance=None): self.vertices = vertices self.edges = edges self.instance = instance def insert_vertice(self, new_vertice_value): new_vertice = Vertice(new_vertice_value) self.vertices.append(new_vertice) def insert_edge(self, new_edge_value, vertice1_value, vertice2_value): vertice1_found = None vertice2_found = None for vertice in self.vertices: if vertice1_value == vertice.value: vertice1_found = vertice if vertice2_value == vertice.value: vertice2_found = vertice if vertice1_found == None: vertice1_found = Vertice(vertice1_value) self.vertices.append(vertice1_found) if vertice2_found == None: vertice2_found = Vertice(vertice2_value) self.vertices.append(vertice2_found) new_edge = Edge(new_edge_value, vertice1_found, vertice2_found) vertice1_found.edges.append(new_edge) vertice2_found.edges.append(new_edge) self.edges.append(new_edge) def get_edge_list(self): return [(i.value, i.vertice1.value, i.vertice2.value) for i in self.edges] def shortest_path(Graph): minimum_travel = float("inf") for start in Graph.vertices: # initiate start vertice seen_list = [start] # vertices passed along on shortest path travel = 0 adjacent_dict = {} while len(seen_list) < len(Graph.vertices): # stop while loop when all the vertices being seen minimum_edge = float("inf") for edge in start.edges: if edge.value < minimum_edge: if edge.vertice1 not in seen_list and edge.vertice2 in seen_list: vertice_minimum = edge.vertice1 minimum_edge = edge.value elif edge.vertice1 in seen_list and edge.vertice2 not in seen_list: vertice_minimum = edge.vertice2 minimum_edge = edge.value else: pass else: continue if vertice_minimum == start: # all the connection vertices from current vertice have been seen before start = previous # go back to previous vertice else: if travel == 0: adjacent_dict[start.value] = [] # add adjacent edge value and vertice value for previous vertice adjacent_dict[start.value].append((minimum_edge, vertice_minimum.value)) previous = start # assign previous vertice seen_list.append(vertice_minimum) # add the vertice with the minimum edge start = seen_list[-1] # reset start vertice to be the most recent seen vertice adjacent_dict[start.value] = [] # add adjacent edge value and vertice value for the most recent seen vertice adjacent_dict[start.value].append((minimum_edge, previous.value)) travel+=minimum_edge # add up travel distance if travel <= minimum_travel: # update minimum tree with shortest travel distance minimum_tree = adjacent_dict else: pass return minimum_tree
0c92e96eb7a0c6d2d878e592694496ff5990b788
Delitas/Python-Data-Structure
/convert_to_decimal(Non Use int func).py
571
3.765625
4
""" Data : 2020-12-18 dev : Python 3.8 Auth : Delitas """ print('Ver 1.1') print('Convert to Decimal(Non int() function)') print('Author : Delitas') print('='*20) numbers = int(input('Input number : ')) base = int(input("Input number's base (1<base<11) : ")) base_temp = 1 covert_num = 0 while(1): num_temp = numbers % 10 if num_temp >= base: print('Base Number Error') break covert_num += num_temp * base_temp base_temp *= base numbers //= 10 if numbers == 0: print(covert_num) break
c0bb471a82e9a093ae286bcacdfc54cba4f8858d
DarknessRdg/mat-computacional
/metodos_abertos/newton.py
798
3.5
4
from funcoes_professor import letra_a, derivada_letra_a from utils import preview def newton(inicial, funcao, derivada, tolerancia): x0 = inicial x1 = x0 f_x0 = 1 it = 0 primeira = True while primeira or abs(f_x0) > tolerancia or f_x0 != 0: primeira = False it += 1 f_x0 = funcao(x0) f_derivada_x0 = derivada(x0) x1 = x0 - f_x0 / f_derivada_x0 feedback = ( 'it: {} ' 'xi: {} ' 'f(xi) {} ' "f'(xi): {} " 'xi+1: {}' ) print(feedback.format( it, *map(preview, (x0, f_x0, f_derivada_x0, x1)) )) x0 = x1 return x1 if __name__ == '__main__': res = newton(3.5, letra_a, derivada_letra_a, 0.001) print(res)
43da1ecb3492b209c3c5f9af39cbf541858546d7
niemitee/mooc-ohjelmointi-21
/osa04-08b_lista_kahdesti/src/lista_kahdesti.py
232
3.71875
4
# Kirjoita ratkaisu tรคhรคn lista = [] while True: luku = int(input('Anna luku: ')) if luku == 0: break lista.append(luku) print('Lista:', lista) print('Jรคrjestettynรค:', sorted(lista)) print('Moi!')
e22580f93daca2aad2a80304c3383916663f2e52
kencroker/card_game
/card_system/deck.py
1,275
3.75
4
import random from card_system import hand class Deck: def __init__(self, input_cards: list): assert type(input_cards) == list self.cards = input_cards def get_cards(self): return self.cards def shuffle(self): random.shuffle(self.cards) def remaining_cards(self): return len(self.cards) def deal_card(self): if self.remaining_cards() >= 1: return self.cards.pop() return None def deal_cards(self, num_cards): cards_list = [] if self.remaining_cards() >= num_cards: for i in range(0, num_cards): cards_list.append(self.cards.pop()) return cards_list else: return None def deal_hand(self, num_cards): cards_list = [] if self.remaining_cards() >= num_cards: for i in range(0, num_cards): cards_list.append(self.cards.pop()) dealt_hand = hand.Hand(cards=cards_list) return dealt_hand else: return None def display(self): output = "" for card_i in self.cards: output += card_i.display() output += "\n" output += "\n\nEND OF DECK\n\n" return output
9239edef612b5592b24b2a7aa78704c9ee1ef240
leonardokiyota/Python-Training
/Exercises Python Brasil/01 - Estrutura Sequencial/07.py
327
3.96875
4
# -*- coding: utf-8 -*- """ Faรงa um Programa que calcule a รกrea de um quadrado, em seguida mostre o dobro desta รกrea para o usuรกrio. """ lado = float(input("Digite o lado do quadrado: ")) print("O quadrado de lado {} possui uma รกrea de {} e o seu dobre รฉ {}" .format(lado, lado * lado, lado * lado * 2 ))
936420384282c92b67b9e5da13aa21742bb642d0
AmitUpadhyaya/Python_Task
/task3.py
1,760
4.09375
4
#1. Create a list of the 10 elements of four different types of Data Type like int, string, complex and float x=[2,3,4,5,"amit","riyaz","consultadd",2.34,2.56, 1+6j] print(type(x[-1])) #2 Create a list of size 5 and execute the slicing structure x1=x[:5] x2=x[2:] x3=x[3:6] print(x1, x2,x3) #3 Write a program to get the sum and multiply of all the items in a given list. import math a=[2,3,8,44,5] a1=sum(a) def multiply(list): result=1 for i in list: result= result*i return result print(a1, multiply(a)) #4 Find the largest and smallest number from a given list. print(max(a), min(a)) #5. Create a new list which contains the specified numbers after removing the even numbers from a # predefined list. b=[2,3,4,5,6,7,8,9,10,12,13] b1=[] for i in b: if(i%2!=0): b1.append(i) print(b1) #6. Create a list of first and # last 5 elements where the values are square of numbers between 1 and 30 (both included). c=list(range(1,31)) c1=[] # c1=c[:6] # c2=c[26:] for i in c: c1.append(i*i) print (c1, end=" ") c2=[c1[:5],c1[25:]] print(c2) # Write a program to replace the last element in a list with another list. d=[[1,3,5,7,9,10],[2,4,6,8]] d[0][-1:]=d[1][0:] del(d[1]) print(d) #Create a new dictionary by concatenating the following two dictionaries: e={1:10,2:20} f={3:30,4:40} e.update(f) print(e) #Create a dictionary that contains a number (between 1 and n) in the form(x,x*x). n=int(input("enter a no. ")) g = dict() for x in range(1,n+1): g[x]=x*x print(g) # 10. Write a program which accepts a sequence of comma-separated # numbers from console and generate a list and a tuple which contains every number. h=input("enter the no.") h1= h.split(',') h2= tuple(h1) print(h2,h1)
b555c37529b6e4bd1276c7d0bda51da7d36d4dd7
xiangyang0906/python_lianxi
/zuoye7/ๅ…ƒ็ป„็š„ๅฏๅ˜ๅ‚ๆ•ฐ01.py
199
4.28125
4
# ๅ…ƒ็ป„็š„ๅฏๅ˜ๅ‚ๆ•ฐ *args ๅ…ถไธญargsๅฏไปฅ้šๆ„ๅ‘ฝๅ๏ผŒไฝ†ไธ€่ˆฌ้ƒฝๅทฒargsๅ‘ฝๅ def tuple1(*args): print(args) for i in args: print(i, end=" ") tuple1(1, 3, 5, 6, 7, 8)
c591ee8241a5b5f35f7f49c987eb53b47b5de1b4
Artinto/Python_and_AI_Study
/Week01/Main_HW/Find the Runner-Up Score/Find the Runner-Up Score_BJH.py
703
3.578125
4
if __name__ == '__main__': n=input() arr = list(map(int, input().split())) temp =0 while 1: if len(arr) == int(n): #int(n) ์•ˆํ•˜๋ฉด n์˜ ํ˜•ํƒœ๋ฅผ ๋ชจ๋ฅด๊ธฐ์— else๋กœ ๋„˜์–ด๊ฐ„๋‹ค. for i in arr: if temp <i: temp = i arr.remove(temp) temp =0 for i in arr: if temp <i: temp = i print(temp) break; else: print("""์ฒ˜์Œ ์ž…๋ ฅํ•˜์‹  ์ˆ˜ ๋งŒํผ์˜ ๊ฐฏ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.""") n=input() arr = list(map(int, input().split())) temp =0
79ce59dfcb0bbf5b2a5199e263f27abf44052c27
wednesday5028/ProblemSolving
/binary_search/chap_7_3.py
419
3.515625
4
def make_rice(array, start, end, M): result = [] for i in range(start, end, 1): for rice in array: if rice - i <= 0: continue else: result.append(rice - i) if sum(result) != M: result.clear() else: return i test_arr = [10, 15, 17, 19] print(make_rice(test_arr, test_arr[0], test_arr[-1], 6)) # ์‹œ๊ฐ„์ดˆ๊ณผ
15d23823f1f720dae0f7fe6843dd035221acf1b5
gitter-badger/Printing-Pattern-Programs
/Python Pattern Programs/Numeric Patterns/Pattern 3.py
92
3.53125
4
for x in range(5, 0, -1): for y in range(5, 0, -1): print(x, end="") print()
7dab764f27de6776f4032375861697670031469e
aniket435/pythonprog
/vowelcount.py
265
3.96875
4
a=raw_input('enter the string') vowels = 0 for i in a: if ( i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u' or i == 'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U'): vowels = vowels + 1 print("Number of vowels are:") print(vowels)
dcbfd21d93e474503c053a18371b96451763bff2
renyalvarado/automate_the_boring_stuff_exercises
/src/chapter06/03_print_table.py
760
4.03125
4
#! /usr/bin/env python3 # Table Printer table_data = [["apples", "oranges", "cherries", "banana"], ["Alice", "Bob", "Carol", "David"], ["dogs", "cats", "moose", "goose"]] max_columns = max([len(x) for x in table_data]) max_sizes = [max([0 if i > (len(x) - 1) else len(x[i]) for x in table_data]) for i in range(max_columns)] print(max_sizes) print("Using For") for row in table_data: for i in range(max_columns): my_string = "" if i > (len(row) - 1) else row[i] print(my_string.rjust(max_sizes[i]) + " ", end="") print() print() print("Using comprehension") for row in table_data: print("".join([("" if i > (len(row) - 1) else row[i]).rjust(max_sizes[i]) + " " for i in range(max_columns)])) print()
0af2a913a50fb5d101ce3a54d83f3a2e5b82364e
slagmale/webcrawler
/parsinglibrary/xpath/xpathexamp4.py
2,056
3.640625
4
from lxml import etree # XPath ๆไพ›ไบ†ๅพˆๅคš่Š‚็‚น่ฝด้€‰ๆ‹ฉๆ–นๆณ•๏ผŒ่‹ฑๆ–‡ๅซๅš XPath Axes๏ผŒๅŒ…ๆ‹ฌ่Žทๅ–ๅญๅ…ƒ็ด ใ€ๅ…„ๅผŸๅ…ƒ็ด ใ€็ˆถๅ…ƒ็ด ใ€็ฅ–ๅ…ˆๅ…ƒ็ด ็ญ‰็ญ‰ text = ''' <div> <ul> <li class="item-0"><a href="link1.html"><span>first item</span></a></li> <li class="item-1"><a href="link2.html">second item</a></li> <li class="item-inactive"><a href="link3.html">third item</a></li> <li class="item-1"><a href="link4.html">fourth item</a></li> <li class="item-0"><a href="link5.html">fifth item</a> </ul> </div> ''' html = etree.HTML(text) result = html.xpath('//li[1]/ancestor::*') # ๅฏไปฅ่Žทๅ–ๆ‰€ๆœ‰็ฅ–ๅ…ˆ่Š‚็‚น๏ผŒๅ…ถๅŽ้œ€่ฆ่ทŸไธคไธชๅ†’ๅท๏ผŒ็„ถๅŽๆ˜ฏ่Š‚็‚น็š„้€‰ๆ‹ฉๅ™จ๏ผŒไฝฟ็”จไบ† *๏ผŒ่กจ็คบๅŒน้…ๆ‰€ๆœ‰่Š‚็‚น print(result) result = html.xpath('//li[1]/ancestor::div') # ๅœจๅ†’ๅทๅŽ้ขๅŠ ไบ† div๏ผŒ่ฟ™ๆ ทๅพ—ๅˆฐ็š„็ป“ๆžœๅฐฑๅชๆœ‰ div ่ฟ™ไธช็ฅ–ๅ…ˆ่Š‚็‚นไบ†ใ€‚ print(result) result = html.xpath('//li[1]/attribute::*') # attribute ่ฝด๏ผŒๅฏไปฅ่Žทๅ–ๆ‰€ๆœ‰ๅฑžๆ€งๅ€ผ๏ผŒๅ…ถๅŽ่ทŸ็š„้€‰ๆ‹ฉๅ™จ่ฟ˜ๆ˜ฏ *๏ผŒ่ฟ™ไปฃ่กจ่Žทๅ–่Š‚็‚น็š„ๆ‰€ๆœ‰ๅฑžๆ€ง๏ผŒ่ฟ”ๅ›žๅ€ผๅฐฑๆ˜ฏ li ่Š‚็‚น็š„ๆ‰€ๆœ‰ๅฑžๆ€งๅ€ผใ€‚ print(result) result = html.xpath('//li[1]/child::a[@href="link1.html"]') # child ่ฝด๏ผŒๅฏไปฅ่Žทๅ–ๆ‰€ๆœ‰็›ดๆŽฅๅญ่Š‚็‚น๏ผŒๅœจ่ฟ™้‡Œๆˆ‘ไปฌๅˆๅŠ ไบ†้™ๅฎšๆกไปถ้€‰ๅ– href ๅฑžๆ€งไธบ link1.html ็š„ a ่Š‚็‚นใ€‚ print(result) result = html.xpath('//li[1]/descendant::span') # ๅฏไปฅ่Žทๅ–ๆ‰€ๆœ‰ๅญๅญ™่Š‚็‚น๏ผŒ่ฟ™้‡Œๆˆ‘ไปฌๅˆๅŠ ไบ†้™ๅฎšๆกไปถ่Žทๅ– span ่Š‚็‚น๏ผŒๆ‰€ไปฅ่ฟ”ๅ›ž็š„ๅฐฑๆ˜ฏๅชๅŒ…ๅซ span ่Š‚็‚น่€Œๆฒกๆœ‰ a ่Š‚็‚นใ€‚ print(result) result = html.xpath('//li[1]/following::*[2]') # following ่ฝด๏ผŒๅฏไปฅ่Žทๅ–ๅฝ“ๅ‰่Š‚็‚นไน‹ๅŽ็š„ๆ‰€ๆœ‰่Š‚็‚น๏ผŒ่ฟ™้‡Œๆˆ‘ไปฌ่™ฝ็„ถไฝฟ็”จ็š„ๆ˜ฏ * ๅŒน้…๏ผŒไฝ†ๅˆๅŠ ไบ†็ดขๅผ•้€‰ๆ‹ฉ๏ผŒๆ‰€ไปฅๅช่Žทๅ–ไบ†็ฌฌไบŒไธชๅŽ็ปญ่Š‚็‚นใ€‚ print(result) result = html.xpath('//li[1]/following-sibling::*') # following-sibling ่ฝด๏ผŒๅฏไปฅ่Žทๅ–ๅฝ“ๅ‰่Š‚็‚นไน‹ๅŽ็š„ๆ‰€ๆœ‰ๅŒ็บง่Š‚็‚น๏ผŒ่ฟ™้‡Œๆˆ‘ไปฌไฝฟ็”จ็š„ๆ˜ฏ * ๅŒน้…๏ผŒๆ‰€ไปฅ่Žทๅ–ไบ†ๆ‰€ๆœ‰ๅŽ็ปญๅŒ็บง่Š‚็‚นใ€‚ print(result)
b27afe96af284705abbc67c70bbc6168dca870ca
saintsim/adventofcode-2018
/src/day1/part2.py
426
4.125
4
#!/usr/bin/env python3 def repeating_frequency(lines): totals_found = set() total = 0 while True: for x in lines: total += int(x) if total in totals_found: return total totals_found.add(total) if __name__ == '__main__': with open('input', 'r') as file: lines = file.readlines() print('Result: ' + str(repeating_frequency(lines)))
49604ed874da46ae572a6ac1da1db21fc98eabf0
tomothumb/sandbox
/python/fundamental/dict.py
1,639
3.671875
4
print("######") d = {'x': 10, 'y': 20} print(d) print(type(d)) d['x'] = 100 print(d['x']) print(d) d['x'] = 'XXXX' print(d) d['z'] = 999 print(d) d[1] = 11111 print(d) print("######") dd = dict(xx=10, yy=20) print(dd) ddd = dict([('xxx', 10), ('yyy', 20)]) print(ddd) print("######") # Dictionaly Method # print(help(dict)) d = {'x': 10, 'y': 20} print(d.keys()) print(d.values()) print(d) d2 = {'x': 1000, 'z': 2000} print(d2) d.update(d2) print(d) print(d.get('x')) print(d.get('none')) # print(d['none']) # ERROR print(type(d.get('none'))) pop = d.pop('x') print(pop) print(d) del d['y'] print(d) print("######") d = {'x': 10, 'y': 20} print(d) d.clear() print(d) print("######") d = {'x': 10, 'y': 20} print('a' in d) print('x' in d) print("######") # COPY1 x = {'x': 10, 'y': 20} y = x print(x) print(y) y['x'] = 1000 print(x) print(y) print("######") # COPY2 x = {'x': 10, 'y': 20} y = x.copy() y['x'] = 1000 print(x) print(y) print("######") fruits = { 'apple' : 100, 'banana': 200, 'orange': 300 } print(fruits['apple']) print('########') d = {'x': 100, 'y':200} print(d.items()) for k,v in d.items(): print(k,':', v) print('########') ranking = { 'A': 100, 'B': 85, 'C': 95 } print(sorted(ranking)) print(sorted(ranking,key=ranking.get)) print(sorted(ranking,key=ranking.get, reverse=True)) print('########') s = 'aslfjkhasdfasvouizjxhcvnamfasd' d = {} for c in s: # if c not in d: # d[c] = 0 d.setdefault(c,0) d[c] += 1 print(d) print(d['f']) print('####') from collections import defaultdict d= defaultdict(int) for c in s: d[c] +=1 print(d) print(d['f'])
ecd1cfb6aeef50f2f88920a3121ba3597bc41045
feiyu4581/Leetcode
/leetcode 101-150/leetcode102.py
843
3.890625
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 levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] def inorder(head, depth): if head: inorder(head.left, depth + 1) while depth > len(res): res.append([]) res[depth - 1].append(head.val) inorder(head.right, depth + 1) inorder(root, 1) return res x = Solution() root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.right.left = TreeNode(15) root.right.right = TreeNode(7) print(x.levelOrder(root) == [ [3], [9,20], [15,7] ])
bf5cc68ac1ca29faab1288174c67d3fdad86a910
YongJunLim/python
/practical1/t1.py
161
4.0625
4
fahrenheit = float(input("Enter temperature in fahrenheit: ")) celsius = (5/9) * (fahrenheit - 32) print("The temperature in celsius is {0:.2f}".format(celsius))
634a23e3c41f7bbc69bff1d798b1bc04c9534fb4
pite2020win/mon-14-40-task3-PawelKepka
/task.py
2,690
4.09375
4
# Class diary # # Create program for handling lesson scores. # Use python to handle student (highscool) class scores, and attendance. # Make it possible to: # - Get students total average score (average across classes) # - get students average score in class # - hold students name and surname # - Count total attendance of student # # Please, use your imagination and create more functionalities. # Your project should be able to handle entire school(s?). # If you have enough courage and time, try storing (reading/writing) # data in text files (YAML, JSON). # If you have even more courage, try implementing user interface (might be text-like). # #Try to expand your implementation as best as you can. #Think of as many features as you can, and try implementing them. #Make intelligent use of pythons syntactic sugar (overloading, iterators, generators, etc) #Most of all: CREATE GOOD, RELIABLE, READABLE CODE. #The goal of this task is for you to SHOW YOUR BEST python programming skills. #Impress everyone with your skills, show off with your code. # #Your program must be runnable with command "python task.py". #Show some usecases of your library in the code (print some things) # #When you are done upload this code to your github repository. # #Delete these comments before commit! #Good luck. from dataclasses import dataclass from statistics import mean import datetime import random @dataclass class Grade: grade: float course: str grade_date: datetime class Student: def __init__(self, name): self.name = name self.grades = list() def new_grade(self, course, grade, grade_date): new_grade = Grade(grade, course, grade_date) self.grades.append(new_grade) def average_course_grades(self, course): if not self.grades: return 0 filtered_grades = [g.grade for g in self.grades] print(filtered_grades) return mean(filtered_grades) if __name__ == "__main__": random.seed(a=None, version = 2) file = open("names.txt", "r") students = list() for i in range(12): student_name = file.readline() student = Student(student_name) students.append(student) courses = ["PitE", "C course", "Physics"] grades = [2.0, 3.0, 3.5, 4.0, 4.5, 5.0] today_date = datetime.datetime(2020, 11, 23) for i in range(20): course = courses[random.randrange(2)] grade = grades[random.randrange(5)] student_index = random.randrange(11) students[student_index].new_grade(course, grade, today_date) print("New grade {} for student {} for course {}".format(grade, students[student_index].name, course)) print("Student average grade: {} for PitE".format(students[0].average_course_grades("PitE")))
88605e178a175b83bf0e16c336dfb2270f85b4ea
levleonhardt/guias_Programacion1
/prog1/guia4/ej8_4.py
588
3.578125
4
#Contar la cantidad de letras (no incluir los separadores) s = "Quiero comer manzanas, solamente manzanas." s = s.replace(",", "") s = s.replace(".", "") lista_s = s.split() cantidad_letras = 0 cantidad_letras_lista = [] for i in range(len(lista_s)): cantidad_letras = len(lista_s[i]) cantidad_letras_lista.append(cantidad_letras) cantidad_letras_total = 0 for i in range(len(cantidad_letras_lista)): cantidad_letras_total = cantidad_letras_total + cantidad_letras_lista[i] print("Cantidad de letras en total: " + str(cantidad_letras_total)) print(cantidad_letras_lista)
93f723541a2551f172e3c42e9ea4bf97808af521
kgbking/cs61a_fa11
/hw6.py
7,865
4.25
4
"""Homework 6: Object-oriented programming""" """1) Create a class called VendingMachine that represents a vending machine for some product. A VendingMachine object doesn't actually return anything but strings describing its interactions. See the doctest for examples. In Nanjing, there are even vending machines for crabs: http://www.youtube.com/watch?v=5Mwv90m3N2Y """ class VendingMachine(object): """A vending machine that vends some product for some price. >>> v = VendingMachine('iPod', 100) >>> v.vend() 'Machine is out of stock.' >>> v.restock(2) 'Current iPod stock: 2' >>> v.vend() 'You must deposit $100 more.' >>> v.deposit(70) 'Current balance: $70' >>> v.vend() 'You must deposit $30 more.' >>> v.deposit(50) 'Current balance: $120' >>> v.vend() 'Here is your iPod and $20 change.' >>> v.deposit(100) 'Current balance: $100' >>> v.vend() 'Here is your iPod.' >>> v.deposit(150) 'Machine is out of stock. Here is your $150.' """ "*** YOUR CODE HERE ***" def __init__(self, vending_product, vending_price): self.product=vending_product self.price=vending_price self.stock=0 self.balance=0 self.change=0 def restock(self, stk): self.stock+=stk print('Current {} stock: {}'.format(self.product,self.stock)) def deposit(self, bal): if self.stock>0: self.balance+=bal print('Current balance: ${}'.format(self.balance)) else: print('Machine is out of stock. Here is your ${}.'.format(bal)) def vend(self): if self.stock>0: if self.balance>self.price: self.change=self.balance-self.price self.balance=0 print('Here is your {} and ${} change.'.format(self.product,self.change)) elif self.balance==self.price: self.balance,self.stock=0,0 print('Here is your {}.'.format(self.product)) else: print('You must deposit ${} more.'.format(self.price-self.balance)) else: print('Machine is out of stock.') """2) Create a class called MissManners that promotes politeness among our objects. A MissManners object takes another object on construction. It has one method, called ask. It responds by calling methods on the object it contains, but only if the caller said please. The doctest gives an example. Hint: Your implementation will need to use the *args notation that allows functions to take a flexible number of variables. """ class MissManners(object): """A container class that only forward messages that say please. >>> v = VendingMachine('teaspoon', 10) >>> v.restock(2) 'Current teaspoon stock: 2' >>> m = MissManners(v) >>> m.ask('vend') 'You must learn to say please.' >>> m.ask('please vend') 'You must deposit $10 more.' >>> m.ask('please deposit', 20) 'Current balance: $20' >>> m.ask('now will you vend?') 'You must learn to say please.' >>> m.ask('please give up a teaspoon') 'Thanks for asking, but I know not how to give up a teaspoon' >>> m.ask('please vend') 'Here is your teaspoon and $10 change.' """ "*** YOUR CODE HERE ***" def __init__(self, se_obj): self.obj=se_obj def ask(self,*args): if type(args[0]) is type('s'): text=args[0].split() if 'please' in text: text.remove('please') if len(args)==1 and text[0]=='vend' : self.obj.vend() elif len(args)==2 and text[0]=='deposit' : self.obj.deposit(args[1]) else: print('Thanks for asking, but I know not how to '+' '.join(text)) else: print('You must learn to say please.') else: print('wrong argument type, the 1st parameter must be a string!') """3) Write a class Amount that represents a collection of nickels and pennies. Include a property method value that computes the value of the amount from the nickels and pennies. Do not add a value attribute to each Amount instance. Finally, write a subclass MinimalAmount with base class Amount that overrides the constructor so that all amounts are minimal. An amount is minimal if it has no more than four pennies. """ class Amount(object): """An amount of nickels and pennies. >>> a = Amount(3, 7) >>> a.nickels 3 >>> a.pennies 7 >>> a.value 22 """ "*** YOUR CODE HERE ***" def __init__(self, nic, pen): self.nickels=nic self.pennies=pen @property def value(self): return 5*self.nickels+self.pennies class MinimalAmount(Amount): """An amount of nickels and pennies with no more than four pennies. >>> a = MinimalAmount(3, 7) >>> a.nickels 4 >>> a.pennies 2 >>> a.value 22 """ "*** YOUR CODE HERE ***" def __init__(self, nic, pen): self.nickels=nic+(pen//5) self.pennies=pen%5 """4) Write a class Rlist that implements the recursive list data type from section 2.3, but works with Python's built-in sequence operations: the len function and subscript notation. When len is called on an object with a user-defined class, it calls a method called __len__ and returns the result When a subscript operator is applied to an object with a user-defined class, it calls a method called __getitem__ with a single argument (the index) and returns the result. As an example, here is a container class that holds a single value. """ class Container(object): """A container for a single item. >>> c = Container(12) >>> c Container(12) >>> len(c) 1 >>> c[0] 12 """ def __init__(self, item): self._item = item def __repr__(self): return 'Container({0})'.format(repr(self._item)) def __len__(self): return 1 def __getitem__(self, index): assert index == 0, 'A container holds only one item' return self._item class Rlist(object): """A recursive list consisting of a first element and the rest. >>> s = Rlist(1, Rlist(2, Rlist(3))) >>> len(s) 3 >>> s[0] 1 >>> s[1] 2 >>> s[2] 3 """ "*** YOUR CODE HERE ***" def __init__(self, item, rest=None): self.list = (item,rest) def __len__(self): length = 0 s=self while s != None: s=s.list s, length = s[1], length + 1 return length def __getitem__(self, index): assert index <= len(self.list) s=self.list while index > 0: s, index = s[1], index - 1 s=s.list return s[0] """Extra for experts: 5) Multiple Inheritance Add multiple inheritance to the object system that we implemented in class using dispatch dictionaries. You will need to make the following changes: 1) Allow a class to be created with an arbitrary number of base classes 2) Classes should respond to a message 'mro' that returns the method resolution order for the class 3) Looking up an attribute by name in a class (using the 'get' message) should follow the method resolution order Choose a method resolution order from the three approaches that have been used in Python since its invention: http://python-history.blogspot.com/2010/06/method-resolution-order.html """
c6dbd3fe8ad4436bc6fc53562c27fc18828ea6b4
aidsfintech/Algorithm-and-Query
/Algorithm/python/algorithmjobs/L11/L11_04valparenthesis_plus.py
4,483
3.71875
4
from collections import deque import sys ''' ๋‹ค์Œ์— ํ• ๋•Œ๋Š” ๊ธฐํ˜ธ์—์„œ ์ˆซ์ž ๋ณ€ํ™˜์— ์žˆ์–ด์„œ dict๋”ฐ๋กœ ์„ ์–ธํ•ด๋‘๋ฉด ์ข€๋” ์„ธ๋ จ๋ ๋“ฏ ->do it now ์ข€๋” ํŒจํ„ด์„ ์„ธ๋ถ€๋ถ„์„ํ•˜๋ฉด ๋ถˆํ•„์š”ํ•œ flag=False๋ฅผ ์ค„์ผ์ˆ˜ ์žˆ์„๋“ฏ +์ค‘๊ฐ„์— 2๊ฐœ์˜ ์—ฐ์† ()() ๋˜๋Š” []() ๋“ฑ๋“ฑ์€ ์ปค๋ฒ„๋˜์ง€๋งŒ, 3๊ฐœ ์ด์ƒ์˜ ๊ฒฝ์šฐ ํ˜„์žฌ if๊ตฌ์กฐ๋กœ๋Š” ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค๋Š” ๊ฑธ ๊นจ๋‹ซ, while์ด ํ•„์š”. ->์—ฌ๊ธฐ์„œ๋ถ€ํ„ด ์ƒˆ๋กœ์šด ํŒŒ์ผ์— ''' def aggregate_subsum(stack,top_stack): tmp_list=list() # print(stack, stack[top_stack],type(stack[top_stack]),stack[top_stack].isdecimal()) while(top_stack>=0 and stack[top_stack].isdecimal()): # print('ck') tmp_list.append(int(stack.pop())) top_stack-=1 parent_sum=sum(tmp_list) stack.append(str(parent_sum)) top_stack+=1 return stack,top_stack #parenthesis to string num dictionary # i was going to () to int 2, but to use isdecimal(), so str '2' precode={ '()' : '2' , '[]':'3' } if __name__=="__main__": parenthesis_set=sys.stdin.readline().strip() # print(parenthesis_set) dq_parenthesis_set=deque(parenthesis_set) # print(dq_parenthesis_set) stack=list() top_stack=-1 flag=True sum_point=0 while(dq_parenthesis_set): token=dq_parenthesis_set.popleft() # print('cur token',token,end=' ') if(token=='(' or token=='['): stack.append(token);top_stack+=1 # print('stackin ',stack,'top ',top_stack) else: # ')' or ']' token # ์ˆซ์ž๋“ค์€ ๋‹ค๋นผ๋„ค์•ผ 3๊ฐœ ์ด์ƒ์˜ ()()() ๋“ฑ์˜ ๊ผด์„ ์ปค๋ฒ„๊ฐ€๋Šฅ sub_sum=0 list_nums=list() while(top_stack>=0 and stack[-1].isdecimal()): list_nums.append(int(stack.pop())) top_stack-=1 # given rule, anyway all elements_ 22233 from ()()()[][]_ # should be added, so sum sub_sum=sum(list_nums) # print('stackout, sub_sum',sub_sum,end=' ') # break condtion1 : ์ˆซ์ž ๊ฑฐ๋‘ฌ๋‚ด๊ณ  stack์ด ๋น„์–ด์ง„ ์ƒํƒœ๋กœ # ')',']'์ด push๋˜๊ฑฐ๋‚˜ ์—ฐ์‚ฐ๋˜์„œ๋Š” ์•ˆ๋จ if(top_stack==-1): flag=False # print('ck1') break else: if(sub_sum==0): # ๋Œ€ํ‘œ์ ์œผ๋กœ ์Šคํƒ์— ์ขŒ ํŽธ๋งŒ ์žˆ๋Š” ๊ฒฝ์šฐ, # ๋นˆ์Šคํƒ์€ 72ํ–‰์—์„œ ๋ฐฉ์ง€ํ•˜๊ณ , ๊ทธ ์ƒ์œ„ ifelse์—์„œ (๋ž‘ [ ์ถ”๊ฐ€๋œ ์ƒํ™ฉ # desirable situation are only () or [] topval_stack=stack.pop();top_stack-=1 # print(token, topval_stack,end='/') if(token==')' and topval_stack=='('): stack.append(precode[topval_stack+token]);top_stack+=1 elif(token==']' and topval_stack=='['): stack.append(precode[topval_stack+token]);top_stack+=1 else: flag=False # print('ck3') break # print('sub sum in',stack) else: # duplication of parenthesis like (8) from (()[][]) # sub sum is int 8 topval_stack=stack.pop();top_stack-=1 # print(token, topval_stack,end='/') if(token==')' and topval_stack=='('): # '2'-> 2, 2*8, '16', pushing '16' stack.append( str(int(precode[topval_stack+token])*sub_sum) );top_stack+=1 elif(token==']' and topval_stack=='['): stack.append( str(int(precode[topval_stack+token])*sub_sum) );top_stack+=1 else: flag=False # print('ck5') break # print('sub sum in',stack,'and top', top_stack) #after calcul sub sum, we need to aggregate sub sum stack,top_stack=aggregate_subsum(stack,top_stack) # # after last pop, there is no element in stack candi_sum_point=stack.pop() # print('\nlastcheck',stack,candi_sum_point,type(candi_sum_point)) # print(candi_sum_point.isdecimal()) if(stack): flag=False if(flag==True and candi_sum_point.isdecimal()==True): print(int(candi_sum_point)) else: print(0)
a320a25277dccc0d225079f17fd17613f7c3767e
srimaniteja19/python_projects
/tip_calculator/main.py
467
4.1875
4
print("Welcome to the tip calculator") total_bill = float(input("What was the total bill? $")) number_of_people = float(input("How many people to split the bill? ")) percentage = float(input("What percentage tip would you like to give? 10, 12, or 15? ")) bill_generated = total_bill/number_of_people bill_generated_with_percentage = (bill_generated / 100) * percentage print(f"Each person should pay: ${round(bill_generated_with_percentage + bill_generated)}")