blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ef004ba5e244566e6484dd060bd442815ba211e9
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_199/1710.py
934
3.5625
4
# input() reads a string with a line of input, stripping the '\n' (newline) at the end. # This is all you need for most Google Code Jam problems. # 3 # --+-++- 3 # +++++ 4 # -+-+-+ 4 import re t = int(input()) # read a line with a single integer for i in range(1, t + 1): s = input() (pancakes, k) = s.split() k = int(k) #print(s) row = [] for c in pancakes: row.append(c=='+'), # print("Case #{}: {}".format(i, len(s))) #print("Case #{}: INPUT k{} p{} row{}".format(i, k, pancakes, row)) n = 0 for j in range(0, len(row)-k+1): #print("j:%d row:%s" % (j, row)) if not row[j]: # flip for j_ in range(j, j+k): row[j_]=not row[j_] #print("flipped") n += 1 unflipped = [not i for i in row] if any(unflipped): n = 'IMPOSSIBLE' print("Case #{}: {}".format(i, n))
5fbdfb5aed115aa689b6808823d7b3db2716ba24
johnsenaakoto/google_foobar_challenge_lvl1
/reid_solution.py
436
3.5
4
def solution(i): prime_string = makePrimeString() minion_ID = prime_string[i:i+5] return minion_ID def makePrimeString(): s='' prime = 2 while len(s) < 10005: s += str(prime) prime += 1 while not is_prime(prime): prime += 1 return s def is_prime(n): for i in range(2, n): if n % i == 0: return False return True print(solution(10000))
830887a385f1ae3920301fdba4b0426497fdb391
lyz05/Sources
/牛客网/虾皮/23.py
710
3.859375
4
# # Note: 类名、方法名、参数名已经指定,请勿修改 # # # # @param s string字符串 字符串数组 # @param n int整型 需要翻转的字符个数 # @return string字符串 # from re import L class Solution: def longestPalindrome(self, s) : # write code here def judge(s): return s==s[::-1] for length in range(len(s),-1,-1): for i in range(0,len(s)-length): if judge(s[i:i+length+1]): return s[i:i+length+1] return "" S = Solution() ans = S.longestPalindrome("babad") print(ans) ans = S.longestPalindrome("abcbacdcabba") print(ans) ans = S.longestPalindrome("a") print(ans)
92909896fd84b8f976afdc1f212a7327c80ed54f
jakey1610/functions
/inverse.py
449
3.90625
4
from sympy.abc import x,y from sympy import * def inverse(f): func = [] for letters in f: if letters == "x": func.append("y") else: func.append(letters) invfunc = "" for letters in func: invfunc += str(letters) invfunc += "-x" invfunc = solve(invfunc, y) invfunc = "f**-1(x)=" + str(invfunc) print(invfunc) ffunc = input("Please enter a function: ") inverse(ffunc)
254505c88565873d87cae46855e69e35cbb1d129
bhuvaneshkumar1103/talentpy
/difference_in_string.py
1,365
3.90625
4
''' Create a func,on difference which takes a string S and character K. Find the difference between first occurrence of K and last occurrence of K in string S. Convert the input to lower case before processing. Check for following condi,ons : 1. If K not occurred in S, return “K not found in S”. 2. If K occurred only once in S, return “Difference can’t be calculated”. 3. If K occurs more than once, return count of difference. Sample I/O: • Input: S= ‘talentpy', K=‘a’ => output: “Difference can’t be calculated”, • Input: S=“science”, K=‘c’ => output: 3. ''' def difference(s,k): s = s.lower() k = k.lower() # get the first occurence of the character in the given string. firstindex = s.find(k) # get the last occurence of the character in the given string. lastindex = s.rfind(k) # checking the difference between the first and the last occurence and return the respective answer. if firstindex == -1 : return "K not found in the given string." elif lastindex == -1 or lastindex == firstindex : return "Difference can’t be calculated." else: diff = lastindex-firstindex return diff-1 s = str(input("Enter a string: ")) k = str(input("ENter the character to be searched in the given string: ")) result = difference(s,k) print(result)
d455574b490feb3e0a9c43aeccb4cb7214b0c98e
kaidokariste/python
/08_object_oriented_programming/code-class.py
423
3.734375
4
class Student: def __init__(self, studentname, grades): # init can have also parameters self.name = studentname self.grades = grades def average_grade(self): return sum(self.grades) / len(self.grades) student = Student("Bob",(90,90,93,78,90,85)) print(student.name) # Rolf comes out print(student.grades) # (90, 90, 93, 78, 90) print(student.average_grade()) # Calling method inside class
7360184f9f63636823b28ddd6a35f45edf2ae9db
aybidi/Data-Structures
/Stacks/StackArray.py
1,893
3.765625
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 16 15:25:14 2018 @author: Abdullah Mobeen """ class Empty(Exception): """Error that will occur when attempting to access an element from an empty stack""" pass class Stack: CAP =10 """Implementation of Stack using an array""" def __init__(self): """creates an empty stack""" self._stackArray = [] def __len__(self): """returns the length of the stack""" return len(self._stackArray) def top(self): """returns a reference to the top element without removing it. Throws an error if stack is empty""" if not self.is_empty(): return self._stackArray[-1] else: raise Empty('Stack is empty') def is_empty(self): """checks if the stack is empty""" return self.__len__() == 0 def pop(self): """removes the top element from the stack and returns it. Throws an error if stack is empty""" if not self.is_empty(): elem = self._stackArray.pop() return elem else: raise Empty('Stack is empty') def push(self, elem): """adds/pushes an element at the top of the stack""" self._stackArray.append(elem) def display(self): """displays the stack, which is otherwise a private attribute of Stack class""" print(self._stackArray) if __name__ == "__main__": stack = Stack() for i in range(0,20,2): #push even numbers into the stack stack.push(i) stack.display() for i in range(7): #remove the top 7 elements stack.pop() stack.display() top = stack.top() #display the top element print(top) for i in range(7): #check if the code raises an error when you try to delete elements from an empty stack stack.pop()
80c23212d4241881165e5dae4b0ee3f40fdf3c5b
Seidmani64/SemanaTec
/io_utilities.py
787
3.5625
4
import pandas as pd def read_vanilla(filepath): with open(filepath, 'r') as fp: data_unsorted = fp.read() data_lines = data_unsorted.split('\n') data = [f.split(',') for f in data_lines] return data def read_pandas(filepath, names): """ Read a csv in pandas returns a pandas dataframe """ df = pd.read_csv(filepath, names = names) return df if __name__ == "__main__": filepath = "./data/iris.data" names = ['sepal_length','sepal_width', 'petal_length','petal_width', 'class'] df = read_pandas(filepath, names) print(df.head(10)) df['sl+pl'] = df['sepal_length'] + df['petal_length'] df1 = df[['sepal_width','petal_length', 'sl+pl','class']] print(df1) print(df.describe())
4f571c40c6b4b8e418ddee44432ceb4e9c41887d
devathul/prepCode
/coinArrangement.py
2,364
3.59375
4
""" coinArrangement There are N piles of coins each containing Ai (1<=i<=N) coins. Now, you have to adjust the number of coins in each pile such that for any two pile, if a be the number of coins in first pile and b is the number of coins in second pile then |a-b|<=K. In order to do that you can remove coins from different piles to decrease the number of coins in those piles but you cannot increase the number of coins in a pile by adding more coins. Now, given a value of N and K, along with the sizes of the N different piles you have to tell the minimum number of coins to be removed in order to satisfy the given condition. Note: You can also remove a pile by removing all the coins of that pile. Input The first line of the input contains T, the number of test cases. Then T lines follow. Each test case contains two lines. The first line of a test case contains N and K. The second line of the test case contains N integers describing the number of coins in the N piles. Output For each test case output a single integer containing the minimum number of coins needed to be removed in a new line. Constraints 1<=T<=50 1<=N<=100 1<=Ai<=1000 0<=K<=1000 Example Input 3 4 0 2 2 2 2 6 3 1 2 5 1 1 1 6 3 1 5 1 2 5 1 Output 0 1 2 """ def arrangeCoins(coins,n,k): if coins is None: return None minCoins=0 for i in range(1,n): diff=coins[i]-coins[i-1] if abs(diff)>k: minCoins+=(abs(diff)-k) val= -1 if diff>0 else 1 print(coins[i],i) coins[i]+=val*(abs(diff)-k) coins[i-1]-=val*(abs(diff)-k) for i in range(n-2,-1,-1): diff=coins[i]-coins[i+1] print(coins[i],coins[i+1],diff,i) if abs(diff)>k: minCoins+=(abs(diff)-k) val= -1 if diff>0 else 1 print(coins[i],i) coins[i]+=val*(abs(diff)-k) coins[i+1]-=val*(abs(diff)-k) return minCoins """ if __name__=='__main__': noOfInput=int(input()) for i in range(noOfInput): cred=input() n=int(cred.split()[0]) k=int(cred.split()[1]) c_ip=input() coins=[int(i) for i in c_ip.split()] result=arrangeCoins(coins,n,k) print(result) """ n=42 k=468 #2337 c_ip="335 501 170 725 479 359 963 465 706 146 282 828 962 492 996 943 828 437 392 605 903 154 293 383 422 717 719 896 448 727 \ 772 539 870 913 668 300 36 895 704 812 323 334" coins=[int(i) for i in c_ip.split()] result=arrangeCoins(coins,n,k) print(result)
850c9c94d2a4ad781558c283f01184cd4a941fae
hithamereddy/HackerRank
/Guess A Number
504
3.953125
4
#!/usr/bin/python3 import random number=random.randint(1, 50) chances = 0 print("guess a number between 1 and 50: ") while chances <15: guess = int(input()) if guess == number: print("hithit approves™") break elif guess < number : print ("your guess was too low, try again: ") else: print ("your guess was too high, try again: ") chances += 1 if not chances <15 : print("ur still bad and a loser 🌭") print("the number was", number)
5a8355299ac82757099f86215c86fe0673a24d42
wchandler2020/Python-Basics-and-Data-Structures
/built_in_data_structures/lists.py
754
3.6875
4
# def rev_list(new_list): # return [ele for ele in reversed(new_list)] # print(rev_list([1, 2, 3, 4, 5])) # names = ["Liam", "Henry", ] # # def remove_dup(my_list): # new_list = [] # for i in my_list: # if i not in new_list: # new_list.append(i) # return new_list # output = remove_dup([11, 22, 33, 44, 55, 55,]) # print(output) # # # # def rev_list(new_list): # return new_list[::-1] def rev_list(list_nums, k): return list_nums[-k:] output = rev_list([1,2,3,4,5,6,7], 3) print(output) # print("A: ", ord("A")) # print("65: ", chr(65)) # user_input = input("Enter a word: ") # secret_string = "" # # for char in user_input: # secret_string = ord(char.upper()) # print(secret_string)
7067269d642682d4a1ae321042991028726294fa
anonimato404/hacker-rank-python
/exams/03_string_representation_of_objects.py
666
4.1875
4
""" Implement two vehicle classes: - Car and Boat """ class Car: def __init__(self, maximum_speed, notation_units): self.maximum_speed = maximum_speed self.notation_units = notation_units def __str__(self): return ( f"Car with the maximum speed of {self.maximum_speed} {self.notation_units}" ) class Boat: def __init__(self, maximum_speed): self.maximum_speed = maximum_speed def __str__(self): return f"Boat with the maximum speed of {self.maximum_speed} knots" if __name__ == "__main__": my_bot = Boat(82) print(my_bot) my_car = Car(122, "mhp") print(my_car)
8f208b35c7a6fdef3d615deda47695e01d0f10a8
uterdijon/evan_python_core
/week_04/labs/03_exception_handling/Exercise_01.py
538
4.6875
5
''' Create a script that asks a user to input an integer, checks for the validity of the input type, and displays a message depending on whether the input was an integer or not. The script should keep prompting the user until they enter an integer. ''' def ask_for_int(): try: var = input("Please enter an integer: ") assert (type(var) == int), "That is not an integer!" except AssertionError as notint: print(notint) ask_for_int() else: print("That is an integer.") ask_for_int()
257a31c1f540c457cb2e8ef2fc6100f46204efbc
qpxu007/cheetah
/python/lib/streamfile_parser/LargeFile.py
2,222
3.859375
4
# # Author: Dominik Michels # Date: August 2016 # class LargeFile: """ This class provides the ability to handle large text files relatively quickly. This is achieved by storing a table containing the newline positions in the file. Hence it is able to quickly jump to a given line number without scanning the whole file again. Note: The table storing the newline positions is currently deactivated to save memory. Most of the methods reimplement the methods of a python file and will therefore not be further described. """ def __init__(self, name, mode="r"): """ Constructor of the class Args: name: Filepath to the file on the harddrive mode: Mode in which the file should be opened, e.g. "r","w","rw" """ self.name = name self.file = open(name, mode) self.length = 0 """ self.length = sum(1 for line in self.file) self.file.seek(0) self._line_offset = numpy.zeros(self.length) self._read_file() """ def __exit__(self): """ This method implements the desctructor of the class. The Desctructer closes the file when the object is destroyed. """ self.file.close() def __iter__(self): return self.file def __next__(self): return self.file.next() def _read_file(self): """ This method reads the whole file once and creates the table _line_offset which stores the position of the newlines in the file. """ offset = 0 for index, line in enumerate(self.file): self._line_offset[index] = offset offset += len(line) self.file.seek(0) def close(self): self.file.close() def tell(self): return self.file.tell() def seek(self, pos): self.file.seek(pos) def readline(self): return self.file.readline() def fileno(self): return self.file.fileno() """ def read_line_by_number(self, line_number): self.file.seek(self._line_offset[line_number]) return self.file.readline() """
d9875594347e8174e3b106f7588fe9d8990230a5
zxcvbnm123xy/leon_python
/python1808real/day14/day14-2-decorator.py
10,068
4.0625
4
""" 第十三章 迭代器、生成器、装饰器 三、装饰器 #使用装饰器来扩展已有函数或者已有类的功能。 """ # 1. 闭包 # 嵌套函数 def outer(): def inner(): print("innner函数执行") return inner() # a=outer() # print(a.__closure__) # 因为嵌套函数中没有形成闭包__closure__没有这个属性 # 闭包 def outer():# 在outer中有参数,参数 也算外围变量 x=1 # 外围变量 def inner(): # x=2# 不能加 print("innner函数执行,x={}".format(x)) return inner a=outer() a() print(a.__closure__) # __closure__显示当前对象的闭包结构 # 闭包结构要素: # (1)嵌套函数,外部函数的返回内部函数的名字 # (2)在内部函数中必须要访问外围变量。 """ 闭包的作用: (1)当函数被调用后,依然希望使用函数中的变量。 (2)一个函数需要被扩展功能 """ # 案例一:当函数被调用后,依然希望使用函数中的变量。 # 实现bill第几天上班的问题 # 不能成功 # def on_duty(name): # times=0 # times+=1 # print("{}第{}次上班".format(name,times)) # on_duty("bill") # on_duty("bill") # 使用闭包解决 # def on_duty(name): # times=0 # def inner(): # nonlocal times # times+=1 # print("{}第{}次上班".format(name, times)) # return inner # duty=on_duty("bill") # duty() # duty() # duty() # 案例二:一个函数需要被扩展功能 # from datetime import datetime # def on_duty(name): # print("{}上班了".format(name)) # print(datetime.now()) # # def off_duty(name): # print("{}下班了".format(name)) # print(datetime.now()) # on_duty("bill") # off_duty("bill") # 需要在上下班的时候打卡,显示时间 # 将显示时间抽取成函数 # from datetime import datetime # def check_in(): # print(datetime.now()) # def on_duty(name): # print("{}上班了".format(name)) # # # def off_duty(name): # print("{}下班了".format(name)) # # on_duty("bill") # off_duty("bill") # 新定义函数解决 from datetime import datetime # def check_in(): # print(datetime.now()) # def on_duty(name): # print("{}上班了".format(name)) # def off_duty(name): # print("{}下班了".format(name)) # def new_on_duty(name): # check_in() # on_duty(name) # def new_off_duty(name): # check_in() # off_duty(name) # new_on_duty("bill") # new_off_duty("bill") # 使用闭包解决 # def on_duty(name): # print("{}上班了".format(name)) # def off_duty(name): # print("{}下班了".format(name)) # 下面程序也是闭包,但是会出现递归问题。在调用on_duty会继续在内部调用on_duty # def check_in(): # def inner(name): # on_duty(name) # print(datetime.now()) # return inner # on_duty=check_in() # on_duty("bill") # 闭包: # 定义闭包函数,闭包函数的参数是原函数的名字func # 在内部函数调用的时候,直接调用func(参数) 相当于调用原函数 # def on_duty(name): # print("{}上班了".format(name)) # def off_duty(name): # print("{}下班了".format(name)) # def check_in(func): # def inner(name): # func(name) # 原函数的功能调用 # print(datetime.now()) # 新功能的扩展 # return inner # on_duty=check_in(on_duty) # off_duty=check_in(off_duty) # on_duty("bill") # off_duty("bill") # 遗留问题:所有曾经调用on_duty的调用者,必须要在代码前面加 # on_duty=check_in(on_duty) # off_duty=check_in(off_duty) # 否则on_duty、off_duty就不是新功能的 # 解决:使用装饰器解决 # 2. 装饰器 # 装饰器的底层其实就是闭包结构实现的。 # 装饰器:用来处理被装饰函数的,扩展被装饰函数的功能。 """ 装饰器语法: (1)定义装饰器 def decorator(原函数名): def inner(参数): 函数体 return inner (2) 调用装饰器 @装饰器的名字 def 原函数(): pass 当再次调用 原函数() 的时候,相当于fun=decorator(原函数) """ # def check_in(func): # def inner(name): # func(name) # 原函数的功能调用 # print(datetime.now()) # 新功能的扩展 # return inner # @check_in # def on_duty(name): # print("{}上班了".format(name)) # @check_in # def off_duty(name): # print("{}下班了".format(name)) # # # on_duty=check_in(on_duty) # # off_duty=check_in(off_duty) # on_duty("bill") # off_duty("bill") # 装饰器改进之前的问题:直接在函数定义的上方加装饰器。不需要在函数调用的时候,重新命名 # 语法糖:在python中所有提供的便捷使用的方式都叫做语法糖。 # 3.装饰器的优化 # 参数、返回值 # 对于装饰器参数的优化,采用万能参数。这样可以支持更多的原函数扩展。 # def check_in(func): # def inner(*args,**kwargs): # func(*args,**kwargs) # print(datetime.now()) # return inner # @check_in # def on_duty(name): # print("{}上班了".format(name)) # @check_in # def off_duty(name): # print("{}下班了".format(name)) # def outwork(name,place): # print("{}去{}出差".format(name,place)) # on_duty("bill") # off_duty("bill") # outwork("bill","北京") # 返回值 # def check_in(func): # def inner(*args,**kwargs): # result=func(*args,**kwargs) # print(datetime.now()) # return result # 可以在这里篡改返回值 # return inner # @check_in # def on_duty(name): # print("{}上班了".format(name)) # return "success" # @check_in # def off_duty(name): # print("{}下班了".format(name)) # def outwork(name,place): # print("{}去{}出差".format(name,place)) # print(on_duty("bill")) # off_duty("bill") # outwork("bill","北京") # 4.叠加装饰器 # 开发的是,功能可能不断的扩充,需要对装饰器进行叠加 """ # 没扩展一个功能都定义一个新的装饰器就可以实现 # 调用的时候,在原函数定义的位置,需要进行装饰器的累加 @dacorator2 @dacorator1 def fun(): pass fun1=dacorator1(fun) # fun1 是被 dacorator1修饰过的fun fun2=dacorator2(fun1) # fun2是被dacorator2修饰过的fun1 """ # def check_in(func): # def inner(*args,**kwargs): # result=func(*args,**kwargs) # print(datetime.now()) # return result # 可以在这里篡改返回值 # return inner # # 加一个向领导汇报工作的功能 # def record(func): # def inner(*args,**kwargs): # result = func(*args, **kwargs) # print("向领导汇报工作") # return result # return inner # @record # @check_in # def on_duty(name): # print("{}上班了".format(name)) # return "success" # # print(on_duty("bill")) # 装饰器嵌套时执行的顺序 def dec1(func): print("dec1的方法start") def inner(): print("dec1---inner---start") func() print("dec1---inner---end") return inner def dec2(func): print("dec2的方法start") def inner(): print("dec2---inner---start") func() print("dec2---inner---end") return inner @dec1 @dec2 def test(): print("测试test执行") a=dec2(test) # a是dec2的inner b=dec1(a) #b是dec1的inner b() # 5.含有参数的装饰器 # 装饰器的蚕食只能是被装饰的方法名,不能加其他的参数。 # 定义的时候如果希望加入参数,可以在双时期外侧继续定义外部函数 # 使用的时候:在@装饰器(传入参数) # def check_in(func,format): 错误 from functools import wraps def check_in(format,a): def check_in_inner(func): @wraps(func) def inner(*args,**kwargs): print(a) result=func(*args,**kwargs) print(datetime.now().strftime(format)) return inner return check_in_inner @check_in("%Y/%m/%d %H:%M:%S","a") def on_duty(name:str)->None: """ bill 上班的方法 :param name: :return: """ print("{}上班了".format(name)) on_duty("bill") # 6.保留函数的元信息 # 元信息:函数名字,函数文档,函数的注释 # 需要使用functools.wraps解决 print(on_duty.__name__) print(on_duty.__doc__) print(on_duty.__annotations__) # 7.类装饰器 # 实现装饰器可以通过定义装饰器函数(闭包) # 也可以通过类装饰器解决 # 使用类解决闭包的问题 def on_duty(name): times=0 times+=1 print("{}第{}次上班".format(name,times)) # 使用类解决闭包 class OnDuty: def __init__(self,name): self.times=0 self.name=name def __call__(self): self.times+=1 print("{}第{}次上班".format(self.name,self.times)) duty=OnDuty("bill") duty() duty() duty() # 使用类装饰器解决bill打卡的问题 # @类装饰器 # 对象=类装饰器(原函数名) # 对象() # 装饰器函数 # 新的函数名=装饰器函数名(原函数名) # 新函数名() class CheckIn: def __init__(self,func): self.func=func def __call__(self, *args, **kwargs): print(datetime.now()) return self.func(*args, **kwargs) @CheckIn def on_duty(name): print("{}上班了".format(name)) on_duty("bill") # 练习 # 对程序的日志进行记录 """ 思路: (1)实现一个记录日志的装饰器,闭包函数 (2)在原函数定义上使用@ 装饰器 """ import time def log(func): def inner(*args,**kwargs): start=time.time() result=func(*args,**kwargs) end=time.time() print("当前发方法操作的时间{}".format(end-start)) print("当前发方法执行的时间{}".format(datetime.now())) print("当前发方法的返回值{}".format(result)) print("当前发方法的参数{}{}".format(*args,**kwargs)) return result return inner @log def add(user): print("正在执行添加。。。") time.sleep(0.5) @log def modify(user): print("正在执行修改...") add("张三") modify("李四")
9bce9aa288b92a21e97e38c75c3b2bcbb800ee06
AustinArrington87/NLP
/data-tools/lib/frequency.py
4,503
3.53125
4
import nltk from nltk import tokenize from nltk.corpus import stopwords import matplotlib.pylab as plt def wordFreq (tokens): # remove stop words (am, at, the, for) and count frequency sr = stopwords.words('english') chars = ["{", "=", "-", "}", "+", "_", "--", ">", "<", "<=", ">=", "—", "var"] conjunctions = ["but", "But", "and", "or", "nor", "because", "although", "since", "unless", "while", "where"] conjugations = ["Is", "is", "Am", "am", "Are", "are", "Was", "was", "Were", "were", "Being", "being", "Been", "been"] clean_tokens = tokens[:] for token in tokens: if token in sr: clean_tokens.remove(token) # calculate frequency freq = nltk.FreqDist(clean_tokens) wordFreqDic = {} freqDic5 = {} freqDic10 = {} freqDic25 = {} freqDic50 = {} freqDic100 = {} # bucket dictionaries by increasing word frequency for key,val in freq.items(): if val >= 5: #print(key) freqDic5.update({key: val}) removeWord(chars, freqDic5) removeWord(conjunctions, freqDic5) removeWord(conjugations, freqDic5) elif val >= 10: #print(key) freqDic10.update({key: val}) for char in chars: if char in chars: del freqDic10[char] elif val >= 25: #print(key) freqDic25.update({key: val}) for char in chars: if char in chars: del freqDic25[char] elif val >= 50: #print(key) freqDic50.update({key: val}) for char in chars: if char in chars: del freqDic50[char] elif val >= 100: #print(key) freqDic100.update({key: val}) for char in chars: if char in chars: del freq100[char] else: pass wordFreqDic.update({key: val}) #print(str(key) + ":" + str(val)) totalDicLen = len(wordFreqDic) print("------------------FREQ------------------------------------") print("Word Occurrences: " + str(totalDicLen)) # bucket out words by increasing number of occurrences freqDic5Len = len(freqDic5) if freqDic5Len > 0: over5 = freqDic5Len/totalDicLen print(">= 5 Word Occurrences:") print(str(freqDic5Len)+ " words occuring 5 or more times, or " + str(round((100*over5),2)) + "% of the total") print(" ") print(freqDic5) freqDic10Len = len(freqDic10) if freqDic10Len > 0: over10 = freqDic10Len/totalDicLen print(">= 10 Word Occurrences:") print(str(freqDic10Len)+ " words occuring 10 or more times, or " + str(round((100*over10),2)) + "% of the total") print(" ") print(freqDic10) freqDic25Len = len(freqDic25) if freqDic25Len > 0: over25 = freqDic25Len/totalDicLen print(">= 25 Word Occurrences:") print(str(freqDic25Len)+ " words occuring 5 or more times, or " + str(round((100*over25),2)) + "% of the total") print(" ") print(freqDic5) freqDic50Len = len(freqDic50) if freqDic50Len > 0: over50 = freqDic50Len/totalDicLen print(">= 50 Word Occurrences:") print(str(freqDic50Len)+ " words occuring 5 or more times, or " + str(round((100*over50),2)) + "% of the total") print(" ") print(freqDic50) freqDic100Len = len(freqDic100) if freqDic100Len > 0: over100 = freqDic100Len/totalDicLen print(">= 100 Word Occurrences:") print(str(freqDic100Len)+ " words occuring 5 or more times, or " + str(round((100*over100),2)) + "% of the total") print(" ") print(freqDic100) if freqDic5Len == 0 and freqDic10Len == 0 and freqDic25Len == 0 and freqDic50Len == 0 and freqDic100Len == 0: print(" >= 1 Word Occurences: ") print(wordFreqDic) if freqDic5Len != 0: plotWords(freqDic5) if freqDic10Len != 0: plotWords(freqDic10) if freqDic25Len != 0: plotWords(freqDic25) if freqDic50Len != 0: plotWords(freqDic50) if freqDic100Len != 0: plotWords(freqDic100) # function to remove stopwords def removeWord(wordList, wordDic): for word in wordList: if word in wordDic: del wordDic[word] # plot high frequency words def plotWords(wordDic): plt.plot(*zip(*sorted(wordDic.items()))) plt.show()
47cbfb55e9801c3a67d3fbce4c522a216e4d8ec6
karendiz/ex-python
/desafio09.py
359
3.96875
4
# reduce() - Sua utilidade está na aplicação de uma função a todos # os valores do conjunto, de forma a agregá-los todos em um único valor. from functools import reduce lista = [1, 2, 3, 4, 5, 6,7,8,9,10] soma = reduce(lambda x,y: x + y, lista) #retorna o produto de todos os elemento de lista print("lista = ", lista,"\n\nproduto = ", soma)
89397c56d8c3490ba50c0bd80ec97823b97541dc
jojude/program-repo
/HackerEarth/fizzbuzz.py
668
3.578125
4
def fizzbuzz(n): if n % 3 == 0 and n % 5 == 0: return 'FizzBuzz' elif n % 3 == 0: return 'Fizz' elif n % 5 == 0: return 'Buzz' else: return str(n) def print_fizzbuzz(limit): return "\n".join(fizzbuzz(n) for n in xrange(1, limit+1)) def print_fizzbuzz_times(n,seq): for i in range(n): fo = open('Output/fuzzbuzz.txt', 'wb') fo.write(print_fizzbuzz(seq[i])) print print_fizzbuzz(seq[i]) return 0 with open('Input/fuzzbuzz.txt', 'r') as f: lines = f.readlines(1) listed=[] line =lines[1] for u in line.split(' '): listed.append(int(u)) nth=int(lines[0][:-1]) print_fizzbuzz_times(nth,listed)
512717a9a233e96a97c60ae115ea8fbc31ef5fc0
AdamZhouSE/pythonHomework
/Code/CodeRecords/2154/60710/271962.py
237
3.625
4
#判断一个数是不是回文数 def solve(num): s=str(num) for i in range(0,len(s)//2): if s[i]!=s[len(s)-i-1]: return False return True if __name__ == '__main__': a=int(input()) print(solve(a))
44b45530f235b04699932265c9a4b44a686540ae
Ale1120/Learn-Python
/Fase3-Programacion-orientada-a-objetos/tema8-programacion-orientada-a-objetos/atributos-metodos-clases.py
1,806
3.984375
4
class Galleta: pass galleta = Galleta() galleta.sabor = 'Salado' galleta.color = 'Marron' print('El sabor de una galleta es ', galleta.sabor) class Galleta: chocolate = False galleta = Galleta() g.chocolate class Galleta: chocolate = False def __init__ (self): print('Se acaba de crear una galleta') galleta = Galleta() galleta.chocolate # ejemplo class Galleta: chocolate = False def __init__ (self): print('Se acaba de crear una galleta') def chocolatear(self): self.chocolate = True def tiene_chocolate(self): if self.chocolate: print('soy una galleta con chocolate') else: print('soy una galleta sin chocolate') galleta = Galleta() galleta.tiene_chocolate() galleta.chocolatear() galleta.tiene_chocolate() galleta.chocolate class Galleta: chocolate = False def __init__ (self,sabor,forma): self.sabor = sabor self.forma = forma print('Se acaba de crear una galleta {} {}'.format(sabor,forma)) def chocolatear(self): self.chocolate = True def tiene_chocolate(self): if self.chocolate: print('soy una galleta con chocolate') else: print('soy una galleta sin chocolate') galleta('salada','redonda') class Galleta: chocolate = False def __init__ (self,sabor=None, forma=None): self.sabor = sabor self.forma = forma if sabor is not None and forma is not None: print('Se acaba de crear una galleta {} {}'.format(sabor,forma)) def chocolatear(self): self.chocolate = True def tiene_chocolate(self): if self.chocolate: print('soy una galleta con chocolate') else: print('soy una galleta sin chocolate')
2c61bdd440e5e3b6a4bac1f985d6b026c960fa94
abhinavsoni2601/fosk_work
/day 6/ch4.py
570
3.75
4
from functools import reduce people = [{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}, {'name': 'Sam'}] #for person in people: # if 'height' in person: # height_total += person['height'] # height_count += 1 #def fun(x): # height_total = 0 # height_count = 0 # if 'height' in x: # height_total+=x['height'] # height_count+=1 # list1=list(map(lambda y: y['height'],filter(lambda x: x['height'] if 'height' in x else print(''),people ))) reduce(lambda z,x:z+x,list1 ) print(len(list1))
e338ef47cf40fd4f7bb5eeacb6f23db2a24442f0
alex-stephens/project-euler
/euler_80.py
528
3.734375
4
# Project Euler # Problem 80 # Square root digital expansion import sys sys.path.append('..') from euler import isPerfectSquare ''' Calculates the sum of the first d digits of sqrt(num) ''' def sqrtDecimalSum(num, d): target = num n = 1 for i in range(d): while (n+1)**2 < target: n += 1 n *= 10 target *= 100 return str(n) ans = 0 for n in range(1,101): if not isPerfectSquare(n): ans += sum([int(x) for x in sqrtDecimalSum(n,100)]) print(ans)
adca5abf440b34809fbbf436f287408f4b975bd5
Shubhamgawle96/randstad_task
/get_data.py
1,465
3.84375
4
import requests class generic_data_client: """ A class to get and save data from given url in .csv format. ... Attributes ---------- url : str url to download csv from name : str name to save the file with Methods ------- get_data(): downloads data from given url and saves it in data_files_csv folder. """ def __init__(self,url,name): """ Constructs all the necessary attributes for the generic_data_client object. Parameters ---------- url : str url to download csv from name : str name to save the file with """ self.url = url self.name = name def get_data(self): """ downloads data from given url and saves it in data_files_csv folder. Returns ------- 1 or 0 According to when data is fetched and saved or when there was an http error while fetching """ print("Getting {} ".format(self.name)) data = requests.get(url=self.url) if data.status_code == 200: addr = 'data_files_csv/'+str(self.name) + '.csv' open(addr, 'wb').write(data.content) print("Data saved as {} in data_files_csv directory".format(addr)) return 1; else: print("There was an error fetching {} ,code: {}".format(self.name,data.status_code)) return 0;
6f7a8f27db414eadfd4e80a2819f703c9bdaa51a
sankalptambe/datastructures-and-algorithms
/fibonacci.py
1,106
4.1875
4
# fibonacci series # find series upto n number. import sys n = int(input('Please provide a number: ')) # Fibonacci Series using Dynamic Programming def fibonacci(n): # Taking 1st two fibonacci nubers as 0 and 1 FibArray = [0, 1] while len(FibArray) < n + 1: FibArray.append(0) if n <= 1: return n else: if FibArray[n - 1] == 0: FibArray[n - 1] = fibonacci(n - 1) if FibArray[n - 2] == 0: FibArray[n - 2] = fibonacci(n - 2) FibArray[n] = FibArray[n - 2] + FibArray[n - 1] return FibArray[n] ################### def printFib(n): if n <= 0: return 0 if n == 1: return n fib_arr = [0, 1] n1 , n2 = fib_arr for count in range(2, n): nth = n1 + n2 fib_arr.append(nth) n1 = n2 n2 = nth return fib_arr ##################### print('input is:', n) print('{}th in fibonacci sequence is : '.format(n) , fibonacci(n) ) print('Fibonacci series upto {} th number is : {}'.format(n, ' '.join([str(el) for el in printFib(n)])))
81d61bbb0b76b8fb42cc5f3c0cc2bba807b9196a
csgear/python.for.kids
/basic2/loops/boring.py
1,491
3.671875
4
def menu_is_boring(meals): """Given a list of meals served over some period of time, return True if the same meal has ever been served two days in a row, and False otherwise. """ for i in range(1, len(meals)): if(meals[i] == meals[i-1]): return True return False def elementwise_greater_than(L, thresh): """Return a list with the same length as L, where the value at index i is True if L[i] is greater than thresh, and False otherwise. >>> elementwise_greater_than([1, 2, 3, 4], 2) [False, False, True, True] """ return [x > thresh for x in L] def slots_survival_probability(start_balance, n_spins, n_simulations): """Return the approximate probability (as a number between 0 and 1) that we can complete the given number of spins of the slot machine before running out of money, assuming we start with the given balance. Estimate the probability by running the scenario the specified number of times. >>> slots_survival_probability(10.00, 10, 1000) 1.0 >>> slots_survival_probability(1.00, 2, 1000) .25 """ pass def count_negatives(nums): nums.append(0) # We could also have used the list.sort() method, which modifies a list, putting it in sorted order. nums = sorted(nums) return nums.index(0) if __name__ == '__main__': # build elementwise list l = [1, 2, 3, 4] threshold = 2 res = elementwise_greater_than(l, threshold) print(res)
9667c37df789616f9d7afbaa5ccc22133f7daec8
xalumok/proga
/proga1.py
902
3.84375
4
def merge(s, l, m, r): left = [] right = [] for i in range(l, m+1): left.append(s[i]) for i in range (m+1, r+1): right.append(s[i]) i = 0 j = 0 mergedArr = [] while i<len(left) and j<len(right): if (left[i] <= right[j]): mergedArr.append(left[i]) i += 1 else: mergedArr.append(right[j]) j += 1 while i<len(left): mergedArr.append(left[i]) i += 1 while j<len(right): mergedArr.append(right[j]) j += 1 for i in range(len(mergedArr)): s[i+l] = mergedArr[i] def mergeSort(s, l ,r): if r>l: m = (l+r)//2 mergeSort(s, l, m) mergeSort(s, m+1, r) merge(s, l, m ,r) def areAnagrams(s1, s2): s1 = list(s1) s2 = list(s2) if len(s1)!=len(s2): return False mergeSort(s1, 0, len(s1)-1) mergeSort(s2, 0, len(s2)-1) for i in range(len(s1)): if s1[i] != s2[i]: return False return True s1 = input() s2 = input() print(areAnagrams(s1,s2))
a41a499a78fc0dc44174812b5b3b7db1e12239b3
FranVeiga/games
/Sudoku_dep/createSudokuBoard.py
1,654
4.125
4
''' This creates an array of numbers for the main script to interpret as a sudoku board. It takes input of an 81 character long string with each character being a number and converts those numbers into a two dimensional array. It has a board_list parameter which is a .txt file containing the sudoku boards as strings. ''' import random def main(board_file): try: with open(board_file, 'r') as file: boards = file.readlines() file.close() newboards = [] for i in boards: if i.endswith('\n'): i = i.replace('\n', '') newboards.append(i) boards = newboards randomBoard = boards[random.randint(0, len(boards) - 1)] randomBoardArray = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] for i in range(len(randomBoard)): x = i % 9 y = i // 9 randomBoardArray[y][x] = int(randomBoard[i]) return randomBoardArray except FileNotFoundError: print(f'Error loading board {board_file}') if __name__ == '__main__': print(main(input()))
635fa70c7d04161ee6d73b32784ebe0f8f619273
kevin115533/projects
/project4.py
241
4.28125
4
triangle_width = int(input("Enter the base width of the triangle: ")) triangle_height = int(input("Enter the height of the triangle: ")) area = .5 * triangle_width * triangle_height print ("The area of the triangle is",area, "square units")
720226748304712f993c4c5dad0cc4185a2ea719
fillemonn/tasks
/suchar.py
184
3.984375
4
def your_name(): while True: your_name = input('Please type your name ') if your_name == 'your name': print('Thank you') break your_name()
a583d73440744bed80ca2a7139906c4df4807dc1
Runsheng/bioinformatics_scripts
/gbrowser_script/gff_type.py
765
3.78125
4
#!/usr/bin/env python import argparse import sys def type_unique(gfffile): """ read a gff file, output the gff types to stdout mainly used to write the conf file for Gbrowse """ with open(gfffile, "r") as f: lines=f.readlines() type_l=[] for line in lines: if "#" not in line and len(line)>9: type_l.append(line.split("\t")[2]) type_set=set(type_l) print("%d lines in %s." % (len(type_l), gfffile)) print("%d types in %s "% (len(type_set), gfffile)) for i in type_set: sys.stdout.write(str(i)+"\n") if __name__=="__main__": parser = argparse.ArgumentParser() parser.add_argument("gfffile") args = parser.parse_args() type_unique(args.gfffile)
33779c26df41abb716beb705099dc72fb9b67bdb
ChangxingJiang/LeetCode
/LCCI_程序员面试金典/面试16.11/面试16.11_Python_1.py
479
3.65625
4
from typing import List class Solution: def divingBoard(self, shorter: int, longer: int, k: int) -> List[int]: if k == 0: return [] if shorter == longer: return [shorter * k] ans = [] for i in range(k + 1): ans.append(longer * i + shorter * (k - i)) return ans if __name__ == "__main__": print(Solution().divingBoard(1, 1, 0)) # [] print(Solution().divingBoard(1, 2, 3)) # [3,4,5,6]
1a252020c6a5536e57eeeecdabc8dfd6684cb199
greg008/PythonEPS
/W3R/Dictionary/6.py
313
4
4
""" 6. Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). Sample Dictionary ( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} """ x = int(input("podaj liczbe")) dict1 = {} for i in range(1, x+1): dict1[i] = i*i print(dict1)
bb6d6e2f0ee82c4b9c19ba3c47d98637f7ae98f4
vijaypatha/python_sandbox
/vectorploting.py
3,780
4.375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: ''' TODO: Multiply Vector by Scalar and Plot Results For this part of the lab you will be creating vector $\vec{av}$ and then adding to the plot as a dotted cyan colored vector. Multiply vector $\vec{v}$ by scalar $a$ in the code below (see TODO 1.:). Use the ax.arrow(...) statement in the code below to add vector $\vec{av}$ to the plot (see *TODO 2.:). Adding linestyle = 'dotted' and changing color = 'c' in the ax.arrow(...) statement will make vector $\vec{av}$ a dotted cyan colored vector. ''' # Import NumPy and Matplotlib **Only needed for running code in solutions notebook** get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np import matplotlib.pyplot as plt # Define vector v v = np.array([1,1]) # Define scalar a a = 3 # DONE 1.: Define vector av - as vector v multiplied by scalar a av = a*v # Plots vector v as blue arrow with red dot at origin (0,0) using Matplotlib # Creates axes of plot referenced 'ax' ax = plt.axes() # Plots red dot at origin (0,0) ax.plot(0,0,'or') # Plots vector v as blue arrow starting at origin 0,0 ax.arrow(0, 0, *v, color='b', linewidth=2.5, head_width=0.30, head_length=0.35) # DONE 2.: Plot vector av as dotted (linestyle='dotted') vector of cyan color (color='c') # using ax.arrow() statement above as template for the plot ax.arrow(0, 0, *av, color='c', linestyle='dotted', linewidth=2.5, head_width=0.30, head_length=0.35) # Sets limit for plot for x-axis plt.xlim(-2, 4) # Set major ticks for x-axis major_xticks = np.arange(-2, 4) ax.set_xticks(major_xticks) # Sets limit for plot for y-axis plt.ylim(-1, 4) # Set major ticks for y-axis major_yticks = np.arange(-1, 4) ax.set_yticks(major_yticks) # Creates gridlines for only major tick marks plt.grid(b=True, which='major') # Displays final plot plt.show() # In[2]: ''' TODO: Adding Two Vectors and Plotting Results For this part of the lab you will be creating vector $\vec{vw}$ and then adding it to the plot as a thicker width black colored vector. Create vector $\vec{vw}$ by adding vector $\vec{w}$ to vector $\vec{v}$ in the code below (see TODO 1.:). Use the ax.arrow(...) statement in the code below to add vector $\vec{vw}$ to the plot (see *TODO 2.:). Changing linewidth = 3.5 and color = 'k' in the ax.arrow(...) statement will make vector $\vec{vw}$ a thicker width black colored vector. ''' # In[3]: # Define vector v v = np.array([1,1]) # Define vector w w = np.array([-2,2]) # DONE 1.: Define vector vw by adding vectors v and w vw = v + w # Plot that graphically shows vector vw (color='b') - which is the result of # adding vector w(dotted cyan arrow) to vector v(blue arrow) using Matplotlib # Creates axes of plot referenced 'ax' ax = plt.axes() # Plots red dot at origin (0,0) ax.plot(0,0,'or') # Plots vector v as blue arrow starting at origin 0,0 ax.arrow(0, 0, *v, color='b', linewidth=2.5, head_width=0.30, head_length=0.35) # Plots vector w as cyan arrow with origin defined by vector v ax.arrow(v[0], v[1], *w, linestyle='dotted', color='c', linewidth=2.5, head_width=0.30, head_length=0.35) # DONE 2.: Plot vector vw as black arrow (color='k') with 3.5 linewidth (linewidth=3.5) # starting vector v's origin (0,0) ax.arrow(0, 0, *vw, color='k', linewidth=3.5, head_width=0.30, head_length=0.35) # Sets limit for plot for x-axis plt.xlim(-3, 2) # Set major ticks for x-axis major_xticks = np.arange(-3, 2) ax.set_xticks(major_xticks) # Sets limit for plot for y-axis plt.ylim(-1, 4) # Set major ticks for y-axis major_yticks = np.arange(-1, 4) ax.set_yticks(major_yticks) # Creates gridlines for only major tick marks plt.grid(b=True, which='major') # Displays final plot plt.show() # In[ ]:
58697296468ef7df47d44fc64ad45d6caba320d7
ligege12/dighub
/ghanalyzer/utils/datatools.py
391
3.515625
4
from itertools import islice def islide(iterable, size): iterator = iter(iterable) window = tuple(islice(iterator, size)) if len(window) == size: yield window for x in iterator: window = window[1:] + (x,) yield window def slide(sequence, size): stop = len(sequence) - size + 1 for i in xrange(stop): yield tuple(sequence[i:i+size])
61d69b34f6d2b1bc172ab4bae1a39c8901b08b2c
astavnichiy/AIAnalystStudy
/Python_algorithm/Lesson1/Чужое задание 2/les1_task6.py
1,180
4.15625
4
#6. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним. a = int(input("Введите длину первого отрезка: ")) b = int(input("Введите длину второго отрезка: ")) c = int(input("Введите длину третьего отрезка: ")) if (a + b) > c and (a + c) > b and (b + c) > a: print (f'треугольник со сторонами {a} {b} {c} существует') if a == b == c: print (f'и он равносторонний') elif a == b or b == c or a == c: print(f'и он равнобедренный') else: print(f'и он разносторонний') else: print(f'треугольник со сторонами {a} {b} {c} не существует')
9be0b3e7fb29a3e745c0aaa83bac6a915e84e84f
KalinaKa/Explosive-Dragon
/d4/07-range1.py
437
3.75
4
#tu jest inaczej, bo pokazuje nam zakres ten print. aby to wypisac, nalezy go zamienic na liste. #w pythonie 2 mozna bylo tak robic zakres, ale spowalnialo to procesor. #w pythonie 3 to juz generator, generuje liczby na żądanie. dlatego wstepnie generuje "range(0,4)" # wiec musimy skonwertowac do listy. w Pythonie 2 nazywano to xrange. zakres = range(4) print(zakres) print(list(range(4))) #lista inty = [1, 2, 3, 4] print(inty)
d797bc44979edaac69d3e7da0587be9bfd9af7fa
stacybrock/advent-of-code
/2018/11/power.py
1,707
3.546875
4
# solution to Advent of Code 2018, day 11 part one and two # https://adventofcode.com/2018/day/11 # # usage: power.py [inputfile] from collections import defaultdict from collections import namedtuple import fileinput import numpy def main(): serialnumber = int(next(fileinput.input()).strip()) # create a multidimensional array of power levels at each point grid = numpy.zeros((300, 300)) for (x_,y_), power in numpy.ndenumerate(grid): grid[y_][x_] = get_power_level(x_+1, y_+1, serialnumber) # solve part one threes = defaultdict(int) for y in range(0, 298): for x in range(0, 298): threes[(x+1,y+1)] = numpy.sum(grid[y:y+3, x:x+3]) print('largest 3x3:', max(threes, key=threes.get)) # solve part two # definitely not as fast as I'd like it to be, but it's # an improvement over my first attempts squares = defaultdict(int) for size in range(1, 301): max_power = 0 Power = namedtuple('Power', 'x y size power') for y in range(0, 301-size): for x in range(0, 301-size): power = numpy.sum(grid[y:y+size, x:x+size]) if power > max_power: running = Power(x,y,size,power) max_power = power squares[(running.x+1, running.y+1, running.size)] = running.power print('largest overall:', max(squares, key=squares.get)) def get_power_level(x, y, serial): """returns power level for the given x, y, and serial""" rack_id = x + 10 power = (((rack_id*y) + serial) * rack_id) if power > 99: return (power // 100) % 10 - 5 else: return -5 if __name__ == '__main__': main()
214c42cdb7d1bdffde763a0fab4e48933ad87743
limeiyang/python-study
/8.python脚本(备份文件01).py
1,587
3.75
4
#!/usr/bin/python ''' 文件创建备份的程序: 1. 需要备份的文件和目录由一个列表指定。 2. 备份应该保存在主备份目录中。 3. 文件备份成一个zip文件。 4. zip存档的名称是当前的日期和时间。 5. 我们使用标准的zip命令,它通常默认地随Linux/Unix发行版提供。Windows用户可以使 用Info-Zip程序。注意你可以使用任何地存档命令,只要它有命令行界面就可以了,那 样的话我们可以从我们的脚本中传递参数给它。 ''' # 开始 import os import time import zipfile filename = r'F:\backuptest\work' z = zipfile.ZipFile(filename, 'r') print(z.read(z.namelist()[0])) # 权限报错 !!!!!!!!!!!!!!!!!!!!!!!!待解决 ''' # 1. The files and directories to be backed up are specified in a list. source = [r'F:\backuptest\work', r'F:\backuptest\work1'] # If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory target_dir = r'F:\backuptest\work2'# Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The name of the zip archive is the current date and time target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) # Run the backup if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup FAILED') '''
4e0bc2dd3986ed8c3a697f4b7fe3e0e77ed7341a
wujunhui0923/studying
/demo_2.py
3,856
3.984375
4
#!usr/bin/python #-*- coding = utf-8 -*- """ 模块: 包: 1.模块名称--标识符 a.数字、下划线、字母,不能以数字开头,不能是关键字 模块名称一般是下划线的形式命名的, 模块名称不能和python 中的内置模块名称重合, random、time--内置模块,在命名内置模块的时候不可以使用的 """ """ 2.模块导入 from 模块名称.import .类名、函数名、变量名.,适用于项目根目录/内置模块 """ # from time import time # print(time()) # from random import randint # # randint 是函数名称 # print(randint(1,88)) # from modle_1 import run # print(run()) # from (项目的根目录开始)包名.包名.模块名 import 类名、函数名、内置模块 # from (项目的根目录开始)包名.包名.模块名 import 模块名 # 使用的时候,模块名.函数名 # 如果出现函数名称相同的情况,需要取别名 # import 模块名 as,避免名称过长,避免和其他名称重复 # 其中使用import 时仅可以使用模块名称 # 函数调用:模块名称.函数名() # import 包名.包名.模块名 # # 执行导入时,所有顶格的内容 # """ # __file__ :这个是模块的路径 # __name__ :表示运行python 文件的模块名 # """ # 如果想直接执行某个python 文件,自己定义好的函数或则类使用 # if __name__ == '__main__':用于调试用的 # print("一切正常") # from 包名 import *(通配符) # 容易导致名称重复,引起冲突 """ OS 模块是别人写好的,python 内置的 如果不是python 内置的,放到项目下面,作为一个包或模块 主要处理系统相关的 os.path """ # import os # # pwd 显示当前文件路径,匀 # print(os.getcwd()) # # print(os.path.abspath(__file__)) # 获取绝对路径 # a=os.path.dirname(os.path.abspath(__file__)) # print(os.path.dirname(os.path.abspath(__file__))) # # 路径拼接 os.path.join() # # print(os.path.join("a","yuze.txt")) # # 创建文件夹一次仅能创建一个文件夹 # data_path =os.path.join(a,"data") # os.mkdir(data_path) # # # 判断是否是一个文件夹 # print(os.path.isdir(data_path)) # # 判断是否是一个文件 # print(os.path.isfile(data_path)) # 判断路径是否存在 # print(os.path.exists(data_path)) # os,open 的作用,自动生成报告 # 如何读取文件 # 1.打开文件,内置函数open() # 2.open(path/文件名称)--绝对路径 # 3.关闭文件--一定需要关闭文件的。文件丢失或无法正常打开 # 根据指定的编码格式读取------解码 # mode r--读,w---写入 a--追加 # import os # dir_name =os.path.dirname(os.path.abspath(__file__)) # ceshiwenjian = os.path.join(dir_name, "ceshiwenjian.txt") # f = open(ceshiwenjian,encoding='utf-8') # print(f.read()) # f.close() # # # 文件写入 # f= open(ceshiwenjian, mode='w', encoding='utf-8') # f.write('快乐学python') # f.close() # # # f= open(ceshiwenjian, mode='a', encoding='utf-8') # f.write('快n') # f.close() # b # readline ----仅读取一行 # # import os # dir_name =os.path.dirname(os.path.abspath(__file__)) # ceshiwenjian = os.path.join(dir_name, "ceshiwenjian.txt") # f = open(ceshiwenjian,encoding='utf-8') # # while True: # line =f.readline() # if not line: # break # print(line) # a = f.readlines() # for i in a: # print(i, end="") # 异常处理,一旦程序报错,程序便会终止运行 num1 = input("请输入数字1:") num2 = input("请输入数字2:") try: print(num1*num2) except TypeError: print("继续运营") except IndexError: print("继续32323运营") # 异常类型: # importError # NameError # IndexError # TypeError # keyError # SyntaxError--语法错误 # 不适用默认的捕获异常,一般可以使用异常类型 # 总结:os模块,open(),try,except--异常捕获
f8064a4e868abbfbdc4396cc442ee80b7ba56389
xjchenhao/Learn
/python/循环/donesum_break.py
315
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2015-05-17 00:48:03 # @Author : chenhao (wy.chenhao@qq.com) # @Link : http://www.xjchenhao.cn # @Version : $Id$ total=0 while True: s=raw_input('Enter a number (or "done"): ') if s=='done': break total=int(s) print('The sum is '+ str(total))
b8b64d8228e18302e5bd0d4eaecaba6f90aade46
i-Xiaojun/PythonS9
/Day10/9.Day10_作业.py
1,067
4.1875
4
# 1. 写函数,接收n个数字,求这些参数数字的和 # 2. 读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么? # a=10 # b=20 # def test5(a,b): # print(a,b) # c = test5(b,a) # print(c) # 3. 读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么? # a=10 # b=20 # def test5(a,b): # a=3 # b=5 # print(a,b) # c = test5(b,a) # print(c) ################################################################################## # 1. 写函数,接收n个数字,求这些参数数字的和 # def my_sum(*args): # s = 0 # for i in args: # s += i # return s # # print(my_sum(1,4,5)) # 2. 读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么? # a=10 # b=20 # def test5(a,b): # print(a,b) # c = test5(b,a) # print(c) # a=20.b=10,c=None # 3. 读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么? # a=10 # b=20 # def test5(a,b): # a=3 # b=5 # print(a,b) # c = test5(b,a) # print(c) # a=3,b=5,c=None
70b8b1248ef51c17a69df3152c3a18fc9104367d
rboulton/adventofcode
/2017/day3b.py
1,088
3.546875
4
import sys num = int(sys.argv[1]) values = {} dirs = [ (1, 0), (0, 1), (-1, 0), (0, -1), ] def set(x, y, value): values.setdefault(x, {})[y] = value print(x, y, value) def get(x, y): return values.get(x, {}).get(y, 0) def walk(): x = 0 y = 0 set(x, y, 1) while True: for i in range(len(dirs)): dx, dy = dirs[i] next_dx, next_dy = dirs[(i + 1) % len(dirs)] # print(dx, dy, next_dx, next_dy) while True: x += dx y += dy newval = ( get(x - 1, y - 1) + get(x - 1, y) + get(x - 1, y + 1) + get(x, y - 1) + get(x, y + 1) + get(x + 1, y - 1) + get(x + 1, y) + get(x + 1, y + 1) ) set(x, y, newval) if get(x + next_dx, y + next_dy) == 0: break if newval > num: return newval print(walk())
6fae33b869e3d4211fb62706ff86fd590f5ae972
wxdespair/wxdespair.github.com
/programming_language/Python/clutter/小程序(py格式)/猜数字 0.4.py
455
3.828125
4
import random secret = random.randint( 1 , 10 ) print('…………我的…………') temp = input("猜猜现在我想到的是哪个数字:") guess = int(temp) while guess != secret: temp = input("再猜猜:") guess = int(temp) if guess == secret: print("对了") print("对了就对了吧") else : if guess > secret: print("大了") else : print("小了") print("不玩了")
0559783e106458eca12640381af58fade52eb57c
Alex-Padron/personal-projects
/homomorphic_encryption/multiparty_encryption/client.py
2,980
3.53125
4
import os import program import server1 import server2 import time class client: #inputs to the client inputs = [] #inputs encrypted under a encrypted_inputs = [] #outputs outputs = [] a = [] b = [] def __init__(self, inputs): assert (program.input_size > 0) assert (len(inputs) == program.input_size) self.inputs = inputs def generateA(self): for i in range(program.input_size): #pick random secure pad in range(0,m-1) rand = getSecurePad() #encrypt under rand self.encrypted_inputs.append((rand + self.inputs[i]) % program.m) #store the random value in the a array self.a.append(rand) def generateB(self): for i in range(program.output_size): rand = getSecurePad() self.b.append(rand) def decrypt(self, values): assert (len(values) == program.output_size) for i in range(len(values)): values[i] = (values[i] - self.b[i]) % program.m self.outputs = values def pprint(self): print("Printing MPHE Client") print("Unencrypted input is: ", self.inputs) print("a is: ", self.a) print("b is: ", self.b) print("encrypted input is: ", self.encrypted_inputs) def getEncryptedValues(self): return self.encrypted_inputs def getA(self): return self.a def getB(self): return self.b def getInputs(self): return self.inputs def getOutputs(self): return self.outputs """ Helper method to get secure random numbers """ def getSecurePad(): rand = int.from_bytes(os.urandom(8), byteorder="big") / ((1 << 64) - 1) return int(rand * program.m) if __name__ == "__main__": print("Testing time with homomorphic encryption...\n") start_time = time.time() #start client inputs = [getSecurePad(),getSecurePad(),getSecurePad(),getSecurePad()] cl = client(inputs) cl.generateA() cl.generateB() cl.pprint() end_time = time.time() print("Starting client took: ", end_time - start_time, " seconds") start_time = time.time() #start server1 sv1 = server1.Computer(cl.getEncryptedValues()) sv1.compute() #encrypt server1's values under b sv1.encrypt(cl.getB()) end_time = time.time() print("Server 1 computation took: ", end_time - start_time, " seconds") start_time = time.time() #simplify the result with server 2 sv2 = server2.Simplifier(sv1.getOutput()) sv2.simplify(cl.getA()) end_time = time.time() print("Server 2 computation took: ", end_time - start_time, " seconds") start_time = time.time() #client decrypt under b cl.decrypt(sv2.getValues()) end_time = time.time() print("Client decryption took: ", end_time - start_time, " seconds") print("Final decrypted result is: ", cl.getOutputs()) encrypted_results = cl.getOutputs() print("\nTesting time running on client...\n") start_time = time.time() #call the given program with these new functions result = program.compute(inputs) #check that our results are correct assert (result == encrypted_results) end_time = time.time() print("Time running locally was: ", end_time - start_time)
77e8b7ecf920e6a86bfceaa0579346ff4b9e12a0
kelvDp/CC_python-crash_course
/chapter_4/TIY_4-7.py
116
4.28125
4
#to get a list of the multiples of 3: numbers = [] for num in range(3,31): numbers.append(num*3) print(numbers)
8d53c585c3219dc75a0aa298456d85df89f6cde0
deanrivers/hackerRank
/python/libraryFine.py
570
3.65625
4
def fine(d1,m1,y1,d2,m2,y2): return_date = d1 due_date = d2 fine = 0 #check year if(y1>y2): fine = 10000 print(fine) return fine #check month elif(m1>m2 and y1==y2): fine = 500*(m1-m2) print(fine) return fine #check day elif(d1>d2 and y1==y2 and m1==m2): fine = 15*(d1-d2) print(fine) return fine #if returned before the date else: fine = 0 print(fine) return fine fine(9,6,2015,6,6,2015)
58ae34c3d1d18804569e799e9b9e74921a324a7f
nick-fang/pynetwork
/pynetwork/第三,四,五章-TCP和DNS/tcp_deadlock.py
4,330
3.625
4
"""可能造成死锁的TCP服务器和客户端""" import argparse import socket import sys def server(host, port, bytecount): """服务器端;bytecount变量未使用,是为了配合命令行参数的统一,而被强行放在这里""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #双方四次挥手后不再等待4分钟才彻底断开连接,仅Linux下有效 sock.bind((host, port)) sock.listen(1) print('listening at', sock.getsockname()) while True: #负责监听客户端连接请求的循环 conn, sockname = sock.accept() print('processing up to 1024 bytes at a time from', sockname) sent = 0 while True: #服务器端的接收与发送放在了同一个循环中 data = conn.recv(1024) #尝试接收1024字节,但未必能够全部接收到 if not data: #如果客户端发送完毕并关闭它的套接字(实际这里客户端只是通过shutdown()方法关闭了发送方向的通信),则服务器端会收到空字节串,于是跳出循环 break output = data.decode('ascii').upper().encode('ascii') #转字符串转大写,再转回字节串 conn.sendall(output) #将大写的字节串全部发送回客户端 sent += len(data) #记录服务器端已经发送出去的字节数 print('\r {} bytes processed so far'.format(sent), end=' ') #\r是回车符,表示回到行首,从而能够在同一位置刷新输出【已发送的字节数】 sys.stdout.flush() #强制刷新终端窗口的输出 print() #手动换行 conn.close() print(' socket closed') def client(host, port, bytecount): """客户端""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) bytecount = (bytecount + 15) // 16 * 16 #向后取最近的一个16的倍数 message = b'capitalize this!' #正好16个字节 print('sending', bytecount, 'bytes of data, in chunks of 16 bytes') sock.connect((host, port)) #尝试连接服务器 sent = 0 while sent < bytecount: #客户端总共要向服务器端发送bytecount字节的数据,即(bytecount//16)个message sock.sendall(message) #将一个message全部发送给服务器端 sent += len(message) #记录客户端已经发送出去的字节数 print('\r {} bytes sent'.format(sent), end=' ') #\r是回车符,表示回到行首,从而能够在同一位置刷新输出【已发送的字节数】 sys.stdout.flush() #强制刷新终端窗口的输出 print() #手动换行 sock.shutdown(socket.SHUT_WR) #关闭客户端【发送方向】的通信,即告知服务器端自己不再发送数据,服务器端会如同遇到了文件结束符(即客户端的close()调用)一样,接收到一个空字节串 print('receiving all the data the server sends back') received = 0 while True: data = sock.recv(42) #尝试接收42字节,但未必能够全部接收到;为什么是42??? if not received: #只有第一次循环会进入该条件语句 print(' the first data received says', repr(data)) if not data: #如果服务器端发送完毕并关闭它的套接字,则客户端会收到空字节串,于是跳出循环 break received += len(data) #记录客户端已经接收到的字节数 print('\r {} bytes received'.format(received), end=' ') print() #手动换行 sock.close() if __name__ == "__main__": CHOICES = {'client':client, 'server':server} parser = argparse.ArgumentParser(description='get deadlocked over TCP') parser.add_argument('role', choices=CHOICES, help='which role to play') parser.add_argument('host', help='interface the server listens at; host the client sends to') parser.add_argument('bytecount', type=int, nargs='?', default=16, help='number of bytes for client to send(default 16)') #nargs='?'表示即使该命令行参数未提供,它也会存在,且值为16 parser.add_argument('-p', metavar='PORT', type=int, default=1060, help='TCP prot (default 1060)') args = parser.parse_args() function = CHOICES[args.role] function(args.host, args.p, args.bytecount)
49bc2a32682f0665fb5f0b26364329aa1191eab4
venkatsvpr/Problems_Solved
/LC_Shortest_Distance_Calculator.py
995
3.859375
4
""" 821. Shortest Distance to a Character Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string. Example 1: Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] Approach: ======== Keep a count of the character C seen in s with this find the mininum of the character location and return answer. """ class Solution(object): def shortestToChar(self, S, C): """ :type S: str :type C: str :rtype: List[int] """ present_items = [] for i,ch in enumerate(S): if (ch == C): present_items.append(i) Answer = [] for i,ch in enumerate(S): min_val = float('inf') for val in present_items: min_val = min(min_val, abs(i-val)) Answer.append(min_val) return (Answer) mysol = Solution() print (mysol.shortestToChar("loveleetcode","e"))
e16f04c7cdf173a958afd9c5c22fd8e2fa98fc55
EuniceHu/python15_api_test
/week_2/class_0219/if.py
1,132
3.875
4
#-*- coding:utf-8 _*- """ @author:小胡 @file: if.py @time: 2019/02/19 """ # 1:非常简单的条件语句 # if 条件:if 后面的条件运算结果是布尔值 逻辑/比较/成员 各类数据类型 # if代码 只有当if后面的条件成立的时候才会执行 # python 非零非空数据 都是True # 零空数据 False # # s=[] 空数据代表False 不执行 # if s: # print('我今年18岁!') # 2:第二个条件语句 # if..else.. # age=55 # if age>=18: # print('成年') # if age>40: # print('中年人') # else: # print('青少年') # # else: # print('小学生') # 3:多重判断语句:if..elif...elif...else # if 必须要有的 else elif 可有可无 但是else一定是放在最后的 # # 但是如果一定有elif以及else的个数不限定 # 1:elif的个数不限定 # 2:分支顺序一定是if...elif...else # score=int(input("请输入成绩:")) # if score>90: # print("great") # elif score>80: # print("good") # elif score>70: # print("well") # elif score>60: # print("pass") # else: # print("不及格")
7de24ff414e0f5c9970e014ecb348a4c1f6ed778
rux65/Python-Exercises
/python-ProjectEuler/ProjEuler#3.py
1,351
3.9375
4
## first define all the primes till that number ## from 3 onwards ## if number is divisible by prime, then largest prime is that number ## downside is having to go through the cases till till that number while: ## it would be less time consuming to divide by the first prime then result # divide again and if not then next one # the one case it will go through all the iterations if the number itself is a long prime ## and has no choice but to go through all #!/bin/python3 import sys t = int(input().strip()) for a0 in range(t): n= int(input().strip()) if (n==2 or n==1 or n==0): print (n) elif n>2: largest=2 i=2 while i<=n: no=0 for k in range(2,i//2+1): # 0 to halfway +1 # if n is divided to any number then k increases if i%k==0: no+=1 if no<=0 and n%i==0 and largest<i: # if this is a prime largest=i i+=1 print (largest) ## some timeouts # need to make the code quicker to run # almost want to half it - check second half first # if not in the first half then second #!! error: I have case where number 997799 was given where the #highest number is 90709 which is a prime # yet I get 11 # it doesn;t go forward.
ada7642287cd842dae220ebf91c3ad9aeab9c2d6
daniel-reich/ubiquitous-fiesta
/Jm4eKTENReSiQFw9t_10.py
117
3.859375
4
def invert_list(lst): lst2=[] if not len(lst): return [] for i in lst: lst2.append(i * -1) return lst2
a0c80ebf49b9c451af5bd7697ac9e655c5fa4cab
einnar82/python-abc
/dictionaries.py
753
4
4
# Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # just like JS Objects person = { 'first_name': 'john', 'last_name': 'doe', 'age': 30 } print(person, type(person)) # get value print(person['first_name']) print(person.get('last_name')) # add key/value person['phone'] = '555-55-55' # get keys print(person.keys()) # copy dictionary person2 = person.copy() person2['city'] = 'boston' # remove item del person['age'] person.pop('phone') # length of dictionary len(person) # list of dictionary people = [ { 'name': 'martha', 'age': '30' }, { 'name': 'kevin', 'age': '25' } ] # destructuring in dictionaries martha, kevin = people print(kevin)
c137a777fbb9c79f63926d91c7eca7cec03d6c2b
rattlesnailrick/leetcode
/src/task_10.py
5,424
3.671875
4
class Solution(object): def isMatch(self, text, pattern): if not pattern: return not text first_match = bool(text) and pattern[0] in {text[0], "."} if len(pattern) >= 2 and pattern[1] == "*": return ( self.isMatch(text, pattern[2:]) or first_match and self.isMatch(text[1:], pattern) ) else: return first_match and self.isMatch(text[1:], pattern[1:]) def isMatch3(self, s, p): p = self.collapse_patterns(p) if not s and self.empty_pattern(p): return True if s and not p: return False if not s and p: return False if self.lookahead_loop(s, p): return True if self.pattern_match(s[0], p[0]): return self.isMatch(s[1:], p[1:]) return False def lookahead_loop(self, s, p): if not self.asterisk_lookahead(p): return False # EMPTY MATCH if self.isMatch(s, p[2:]): return True # SUBSTRING MATCH for substring in self.string_slicer(s): if self.pattern_match(substring, p[0]): reduced_string = s[len(substring) :] if self.isMatch(reduced_string, p[2:]): return True else: break # EARLY STOPPING BECAUSE PATTERN CANNOT MATCH ANY MORE. return False def collapse_patterns(self, p): idx = 0 while idx < len(p) - 3: if p[idx + 1] == "*" and p[idx + 3] == "*": if [idx] == "." or p[idx] == p[idx + 2]: p = "".join( [ char for i, char in enumerate(p) if i not in [idx + 2, idx + 3] ] ) idx = 0 continue elif [idx + 2] == ".": p = "".join( [char for i, char in enumerate(p) if i not in [idx, idx + 1]] ) idx = 0 continue idx += 1 return p def string_slicer(self, s): """ Slices a string into substrings ( -> generator of substrings ) """ for i in range(1, len(s) + 1): yield s[:i] def pattern_match(self, s, p): """ Checks if a string matches a character (a-z or "." for any character) """ if p[0] == ".": return True if len(set(s)) != 1: return False return s[0] == p[0] # for char in s: # if not p[0] == char: # return False # return True def asterisk_lookahead(self, p): """ Checks if the next character is "*" """ try: return p[1] == "*" except IndexError: return False def empty_pattern(self, p): if not p: return True if len(p) >= 2 and p[1] == "*": return self.empty_pattern(p[2:]) return False def isMatch2(self, s, p): """ :type s: str :type p: str :rtype: bool """ if not s or not p: return False if p[0] in [s[0], "."]: s_reduced = s[1:] p_reduced = p[1:] if not s_reduced and self.empty_pattern(p_reduced): return True if not s_reduced or not p_reduced: return False if p_reduced[0] == "*": p_reduced = p_reduced[1:] if self.isMatchRecurringChar(s_reduced, p_reduced, p[0]): return True if self.isMatch(s_reduced, p_reduced): return True if len(p) >= 2 and p[1] == "*": return self.isMatch(s, p[2:]) return False def isMatchRecurringChar(self, s, p, recurring_char): if recurring_char in [s[0], "."]: s_reduced = s[1:] p_reduced = p if not s_reduced and self.empty_pattern(p_reduced): return True if not s_reduced: return False if self.isMatchRecurringChar(s_reduced, p_reduced, recurring_char): return True else: print(s, p, s_reduced, p_reduced) return self.isMatch(s_reduced, recurring_char + p_reduced) else: return self.isMatch(s, p) if __name__ == "__main__": solution = Solution() print(solution.collapse_patterns("a*a*a*a*a*a*a*a*a*a*c")) assert solution.isMatch("aa", "a") == False assert solution.isMatch("aa", "a*") == True assert solution.isMatch("aab", "a*b") == True assert solution.isMatch("ab", ".*") == True assert solution.isMatch("aab", "c*a*b") == True assert solution.isMatch("mississippi", "mis*is*p*.") == False assert solution.isMatch("mississippi", "mis*is*ip*.") == True assert solution.isMatch("mississippi", "mis*is*a*ip*.") == True assert solution.isMatch("aaa", ".*") == True assert solution.isMatch("aaa", "ab*a*c*a") == True assert solution.isMatch("a", "ab*") == True assert solution.isMatch("bbbba", ".*a*a") == True print("all good")
b9b3faa5e7c2afdc2170c56fdf2c5cdad7a43efc
joedo29/Self-Taught-Python
/OOP.py
4,452
4.65625
5
# Author: Joe Do # Object Oriented Programming in Python # Create a new object type called Sample class Sample(object): # By convention we give classes a name that starts with a capital letter. pass # Instances of Sample x = Sample() print(type(x)) # The syntax of creting an attribute is: # self.attribute = something # use __init__() method to initialize the attributes of an object. For example: class Dog(object): def __init__(self, breed): # Each attribute in a class definition begins with a reference to the instance object. # It is by convention named self. The breed is the argument. The value is passed during the class instantiation. self.breed = breed sam = Dog(breed='Lab') # here we pass the attribute 'Lab' to a dog named 'sam' print(sam.breed) # calling breed of sam will return its attribute 'Lab' frank = Dog(breed='Huskie') # or we can say frank = Dog('Huskie') print(frank.breed) # In Python there are also 'Class Object Attributes'. These Class Object Attributes are the same for any instance of the class. class Person(object): # Class Object Attributes. Also by convention, we place them first before the init. species = 'Homo Sapiens' def __init__(self, first, last, phone): self.first = first self.last = last self.phone = phone personA = Person('Joe', 'Do', '425-449-3635') print(personA.first + ' ' + personA.last + ' ' + personA.species + ' ' + personA.phone) personB = Person('Sang', 'Do', '0909-20-0987') print(personB.first + ' ' + personB.last + ' ' + personB.species + ' ' + personB.phone) # METHODS # Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. # Methods are essential in encapsulation concept of the OOP paradigm. This is essential in dividing responsibilities in programming, # especially in large applications. class Circle(object): # Class Object Attribute pi = 3.14 # Circle get instantiated with a radius (default is 1) def __init__(self, radius = 1): self.radius = radius # Area method calculates the area of the circle. Note the use of self def area(self): return self.radius * self.radius * Circle.pi # Perimeter method def perimeter(self): return 2 * Circle.pi * self.radius # Method for resetting (called setter in Java or C++) radius def setRadius(self, radius): self.radius = radius # Method for getting (called getter in Java or C++) radius (same as just calling .radius def getRadius(self): return self.radius # Create a new Circle object c = Circle() c.setRadius(3) # set radius = 3 print('Radius is: ', c.getRadius()) print('Area is: ', c.area()) print("Perimeter is: ", c.perimeter()) #INHERITANCE # Inheritance is a way to form new classes using classes that have already been defined. # The newly formed classes are called derived classes, the classes that we derive from are called base classes. # Important benefits of inheritance are code reuse and reduction of complexity of a program. # The derived classes (descendants) override or extend the functionality of base classes (ancestors). # For example, let's create an ancestor class called 'Animal' and a derived class call 'Cat' class Animal(object): def __init__(self): print("A new animal is created") def whoAmI(self): print("Animal") def eat(self): print("Eating") class Cat(Animal): def __init__(self): Animal.__init__(self) print("A new cat is created") def whoAmI(self): print("Cat") def bark(self): print("Meooo!") ca = Cat() ca.whoAmI() ca.eat() ca.bark() # SPECIAL METHODS # Classes in Python can implement certain operations with special method names. # These methods are not actually called directly but by Python specific language syntax. # For example Lets create a Book class: class Book(object): def __init__(self, title, author, page): print("A book is created") self.title = title self.author = author self.page = page def __str__(self): return "Title: %s, Author: %s, Pages: %s" %(self.title, self.author, self.page) def __len__(self): return self.page def __del__(self): print("A book is destroyed") b = Book("Intro to Python", "Joe Do", 199) # Special methods print(b) print(len(b)) del b # OOP HOMEWORKS
cc86073d570ec77e3032b7c6854107bb8c69f569
anildoferreira/CursoPython-PyCharm
/exercicios/aula14-ex064.py
203
3.8125
4
soma = 0 c = 0 n = 0 while n != 999: n = int(input('Digite seu número para soma: ')) if n != 999: c = c + 1 soma += n print('Foram {} digitados e a soma é {}'.format(c, soma))
86f0970b6082dc55bd86a8293a28caa1392ff8a3
AndreaMorgan/Python_FinancialAnalysis
/PyPoll/main.py
1,940
3.765625
4
#Importing necessary libraries import csv import os #Locating and reading csv source file currentDir = os.getcwd() #print(currentDir) data = '../Python_Challenge/Resources/election_data.csv' #Create lists, dictionary and populate them with column data voter_id = [] candidates = [] totals = {} #Open CSV file, read data and append values to lists, dictionary with open(data, newline='') as csvfile: csvread = csv.reader(csvfile, delimiter = ',') headers = next(csvread) #print(f'Headers {headers}') for i in csvread: voter_id.append(i[0]) if i[2] not in candidates: candidates.append(i[2]) totals[i[2]] = 1 elif i[2] in candidates: totals[i[2]] += 1 #Calculate the total number of votes, and the max value in dictionary "totals" total_votes = (len(voter_id)) winner = max(totals, key = totals.get) #Print results to the terminal print(" \nElection Results \n") print("----------------------------------- \n") print(f"Total Votes: {total_votes} \n") print("----------------------------------- \n") for key, value in totals.items(): print(f'{key} : {round((((value)/(total_votes))*100), 2)}% ({value})') print("----------------------------------- \n") print(winner) print("----------------------------------- \n") #Print results to a textfile with open('../Python_Challenge/Resources/election_analysis.txt', "w", newline ='\n') as textfile: textfile.write(" \nElection Results \n") textfile.write("----------------------------------- \n") textfile.write(f"Total Votes: {total_votes} \n") textfile.write("----------------------------------- \n") for key, value in totals.items(): textfile.write(f'{key} : {round((((value)/(total_votes))*100), 2)}% ({value}) \n') textfile.write("----------------------------------- \n") textfile.write(f'{winner} \n') textfile.write("----------------------------------- \n")
dc7f53c3b0ed0c188cbc847962af0125044a2fd0
shomah4a/continuation-slide
/cps3.py
452
3.640625
4
#-*- coding:utf-8 -*- def fib_cont(n, cont): u''' 継続渡しスタイルのフィボナッチ数計算 ''' def f1_cont(n1): # fib(n-1) の計算結果の継続 def f2_cont(n2): # fib(n-2) の計算結果の継続 cont(n1+n2) fib_cont(n-2, f2_cont) if n <= 1: cont(1) else: fib_cont(n-1, f1_cont) def p(v): print v for i in range(10): fib_cont(i, p)
d3808671bbd64f75861b78f96aa14a906c7c4c32
shawnhank/chealion-old
/Shell/passwordGen.py
3,920
3.6875
4
"""passwordGen.py This program generates a simple 8 character password containing numbers, symbols, uppercase and lower case letters. Below it will display the NATO Phonetic output as well Usage: paswordGen.py # Can take the following arguments: # -l # (length of password) # -n # (number of passwords to generate) # -s (simple - no symbols) # -c (complex - allow similar looking symbols - i, l, o, 1, 0, I) Sample Usage: # Make 5 passwords with 10 characters with no symbols. passwordGen.py -l 10 -n 5 -s -c hu&89Jki38 hotel - uniform - Ampersand - eight - nine - JULIET - kilo - india - three - eight """ __author__ = "Micheal Jones (chealion@chealion.ca)" __version__ = "$Revision: 1.0.0 $" __date__ = "$Date: 2009/06/29 $" __copyright__ = "Copyright (c) 2009 Micheal Jones" __license__ = "BSD" import sys import os import random import getopt ######################## def usage(error): # Show Usage print error, "\n\nUsage: python passwordGen.py\n\n-l Length of Passwords\n-n Number of Passwords to Create\n-s Simple (Only Alphanumeric)\n-c Complex (Includes ambiguous characters eg. 1,l,o,0,O, etc.)\n\nSample Usage:\npython passwordGen.py -l 10 -n 5 -s\nhu&89Jki38\nhotel - uniform - Ampersand - eight - nine - JULIET - kilo - india - three - eight\n\n" ######################## def createPassword(length, complexity): # Create a random password # Length: Length of Password # Complexity { '0' : Normal, '1' : Simple, '2' : Complex} if length < 0: exit(0) password = "" phonetics = "" #Create Dictionaries phoneticAlphabet = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "juliet", "kilo", "mike", "november", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray", "yankee", "zulu", "ALPHA", "BRAVO", "CHARLIE", "DELTA", "ECHO", "FOXTROT", "GOLF", "HOTEL", "JULIET", "KILO", "MIKE", "NOVEMBER", "PAPA", "QUEBEC", "ROMEO", "SIERRA", "TANGO", "UNIFORM", "VICTOR", "WHISKEY", "XRAY", "YANKEE", "ZULU", "two", "three", "four", "five", "six", "seven", "eight", "nine"] symbolPhonetics = ["Tilde", "At sign", "Hash", "Dollar sign", "Percent sign", "Caret", "Ampersand", "Asterisk", "Dash", "Underscore", "Period"] complexPhonetics = ["india", "INDIA", "lima", "one", "oscar", "OSCAR", "zero"] alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "j", "k", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "2", "3", "4", "5", "6", "7", "8", "9"] symbolAlphabet = ["~", "@", "#", "$", "%", "^", "&", "*", "-", "_", "."] complexAlphabet = ["i", "I", "l", "1", "o", "O", "0"] if complexity == 0: phoneticAlphabet.extend(symbolPhonetics) alphabet.extend(symbolAlphabet) elif complexity == 2: symbolPhonetics.extend(complexPhonetics) phoneticAlphabet.extend(symbolPhonetics) symbolAlphabet.extend(complexAlphabet) alphabet.extend(symbolAlphabet) for count in range(0,length): #Choose a random character character = random.randint(0, len(alphabet) - 1) password += alphabet[character] phonetics += phoneticAlphabet[character] + " " return password, phonetics ######################## def main(argv): #Need to use getopt try: opts, args = getopt.getopt(argv, 'schl:n:') except getopt.GetoptError, err: usage(err) sys.exit(2) length = 8 complexity = 0 iterations = 1 for o, a in opts: if o == "-l": length = int(a) elif o == "-n": iterations = int(a) elif o == "-s": complexity = 1 elif o == "-c": complexity = 2 elif o == "-h": usage('') sys.exit() else: assert False for i in range(0, int(iterations)): password = createPassword(length, complexity) phonetics = password[1] password = password[0] print "\nPassword: " + password + "\nPhonetic: " + phonetics + "\n" ######################## if __name__ == '__main__': main(sys.argv[1:])
65f35e3396547469e84421c3462d0fec12fb9332
BluebloodXXL/python
/pychartmprojects/OperatingSystemAlgorithm/sjfNp.py
1,981
3.625
4
import operator arvTime_burstTime = {} burstTime = [] burstTime_1 = [] arvTime = [] arvTime_1 = [] processNo = int(input("Enter number of process (Must enter the process which arrives at 0th second first)> ")) i = 0 while i < processNo: arvTime_1.append(int(input(f"Enter arrival time for process {i + 1} >"))) burstTime_1.append(int(input(f"Enter execution time for process {i + 1} >"))) if i > 0: arvTime_burstTime = {arvTime_1[i] : burstTime_1[i]} i = i + 1 arvTime_1 = arvTime_1.pop() burstTime_1 = burstTime_1.pop() # pop the dict -------- No need of that as the dict collects from index 1 of the array # sort the dict # sorted(sorted(arvTime_burstTime),key = operator.itemgetter(1)) sorted(arvTime_burstTime.items(),key = lambda x: x[1]) # print(arvTime_burstTime) # Store keys and values for keys,values in arvTime_burstTime: arvTime.append(keys) burstTime.append(values) print(burstTime[2]) print("\n\nprocessID \t burstTime \t waitingTime \t turnAroundTime") i = check = 0 waitingTime = turnAroundTime = totalWT = totalTAT = 0 while i < processNo-1: if check == 0: turnAroundTime = burstTime_1 + waitingTime print("\n {:3d}\t\t\t{:3d}\t\t\t{:3d}\t\t\t\t{:3d}".format(i + 1, burstTime_1, waitingTime, turnAroundTime)) totalWT = totalWT + waitingTime totalTAT = totalTAT + turnAroundTime waitingTime = waitingTime + burstTime_1 check = 1 turnAroundTime = burstTime[i] + waitingTime # print(f"\n\t{i + 1} \t\t\t {exeTime[i]} \t\t\t {waitingTime} \t\t\t\t {turnAroundTime}") print("\n {:3d}\t\t\t{:3d}\t\t\t{:3d}\t\t\t\t{:3d}".format(i + 1, burstTime[i], waitingTime, turnAroundTime)) totalWT = totalWT + waitingTime totalTAT = totalTAT + turnAroundTime waitingTime = waitingTime + burstTime[i] i = i + 1 print("\n\nAverage Waiting time is {:3.5f}".format(totalWT / processNo)) print("Average Turn around time is {:3.5f}".format(totalTAT / processNo))
db3450917e419b101fb977f6f373805607351b3f
Hroque1987/Exercices_Python
/sort_method.py
357
4.40625
4
# sort() method = used with lists # sort() function = used with iterables students = ['Squidward', 'Sandy', 'Patrick', 'Spongbob', 'Mr. Krabs'] #students.sort(reverse=True) # Onlu works with lists #for i in students: # print(i) sorted_students = sorted(students, reverse=True) # works with other iterabels for i in sorted_students: print(i)
888e5330d36ef558e8a3276974bbd279aea9956e
mliang810/itp115
/Assignments/A6-LoopsLists.py
5,438
4.125
4
# Michelle Liang, liangmic@usc.edu # ITP 115, Spring 2020 # Assignment 6 # Description: # This program will assign 10 seats on a plane - first class and economy class def main(): # TOTAL SEATS VARIABLE NOT HERE TO ACCOUNT FOR FIRST CLASS AND SECOND CLASS # seatsLeft variable replaces total_seats and numFilledSeats variables FCseatsLeft = 4 ECseatsLeft = 6 FCseats = [] ECseats = [] # Menu print("1: Assign Seat\n2: Print Seat Map\n3: Print Boarding Pass\n-1: Quit\n") loop = True while loop == True: choice = input("What is your choice?: ") # assign if choice == '1': name = input("Please enter your first name: ") looper = True while looper == True: looper = False tier = input("Type 1 for First Class or type 2 for Economy: ") if tier == '1': if FCseatsLeft > 0: FCseats.append(name.capitalize()) FCseatsLeft -= 1 else: alt = input("Would you like to be placed in Economy instead? (y/n)") if alt.lower() == "y": if ECseatsLeft > 0: ECseats.append(name.capitalize()) ECseatsLeft -= 1 else: print("Next flight leaves in 3 hours") elif tier == '2': if ECseatsLeft > 0: ECseats.append(name.capitalize()) ECseatsLeft -= 1 else: alt = input("Would you like to be placed in First Class instead (y/n)?") if alt.lower() == "y": if FCseatsLeft > 0: FCseats.append(name.capitalize()) FCseatsLeft -= 1 else: print("Next flight leaves in 3 hours") else: print("Please enter a valid value?") looper = True # print seat elif choice == '2': seatnum = 0 if len(FCseats) > 0: for index in range(0, len(FCseats)): seatnum += 1 print("FC", seatnum, end="") print(":", FCseats[index], end=" ") if FCseatsLeft != 0: for num in range(0, FCseatsLeft): seatnum += 1 print("FC", seatnum, end="") print(": EMPTY", end=" ") if len(ECseats) > 0: seatnum = 4 for index in range(0, len(ECseats)): seatnum += 1 print("ECO", seatnum, end="") print(":", ECseats[index], end=" ") if ECseatsLeft != 0: for num in range(0, ECseatsLeft): seatnum += 1 print("ECO", seatnum, end="") print(": EMPTY", end=" ") print() # Print Boarding Pass elif choice == '3': FCseatstemp = [] ECseatstemp = [] # making the ACTUAL full list (isn't dependent on option 1 or 2 happening) if FCseatsLeft != 0: for num in range(0, FCseatsLeft): FCseatstemp = FCseats FCseatstemp.append("EMPTY") if ECseatsLeft != 0: for num in range(0, ECseatsLeft): ECseatstemp = ECseats ECseatstemp.append("EMPTY") allSeats = FCseatstemp + ECseatstemp del FCseatstemp del ECseatstemp # print(allSeats) # can now check if input is within the seat list look = input("What is your name or seat number? We will check if you have a seat: ") if look.isdigit(): look = int(look) if look in range(1, 11): if allSeats[look - 1] != "EMPTY": print("======= BOARDING PASS =======") print("Seat Number:", look) print("Passenger Name:", allSeats[look - 1]) print("=============================") else: if look in range(1, 11): print("Nobody sits here.") else: print("Invalid seat number.") elif look.lower().capitalize() in allSeats: index = allSeats.index(look.lower().capitalize()) print("======= BOARDING PASS =======") print("Seat Number:", (index + 1)) print("Passenger Name:", look.capitalize()) print("=============================") else: print("No passenger with name", look.capitalize(), "was found") # quit, stops the loop elif choice == '-1': print("You quit.") loop = False # happens if none of the menu choices are chosen, will cause it to loop and keep asking else: print("Error, please enter a proper value from the menu above") loop = True # make loop continue main()
83df8d7aa496a802bdf9e9f94c0fbd2dcee0ee99
gnellany/Automate_the_boring
/Table Printer.py
1,047
4.5
4
''' Automate the boring Stuff Chapter 6 question Table Printer. The following code can transpose a matrix or 2D list in python. This code also spaces out the output list to be easily read. ''' tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] #Transpose Grid def transpose(grid): for m in range(len(grid[0])): #Loop the the bottom of Column print() #Print New line for n in range(len(grid)): #Loop to end of row print (grid[n][m],end=",") #Print[X:Y] position of matrix add sep n+=1 #Move to next column in row m+=1 #Move to next row transpose(tableData) #Run transponing Matrix print() for a, b, c in zip(tableData[0], tableData[1], tableData[2]): #space it out print(a.rjust(10), b.rjust(10), c.rjust(10)) #print it out
7c62b21bfa2b0ec3c61dde61f4d9f830d1ef0af1
moralesmaya/practicePython
/practice6.py
370
4.28125
4
#x = x + word ---> x += word def reverse(string): result = "" for letter in range(len(string)): result += string[len(string)-1-letter] return result userInput = input("Enter a word to check if it's a palindrome: ") reversedWord = reverse(userInput) if userInput == reversedWord: print("The word " + userInput + " is a palindrome")
6eb679d5db213a13d1b2141061222250f1a7579a
remichartier/002_CodingPractice
/001_Python/20211127_2311_HackerrankTheFullCountingSortMedium/theFullCountingSort_v00.py
397
4.0625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'countSort' function below. # # The function accepts 2D_STRING_ARRAY arr as parameter. # def countSort(arr): # Write your code here if __name__ == '__main__': n = int(input().strip()) arr = [] for _ in range(n): arr.append(input().rstrip().split()) countSort(arr)
ef3d76f402e72b78730ce5aa8be7f32afde5b89e
MariannaBeg/homework
/OOP3.py
353
3.828125
4
class Person: def __init__(self,name,eyecolor,age): self.name = name self.eyecolor = eyecolor self.age = age my_person1 = Person("Jirayr MElikyan","Brown",19) my_person2 = Person(my_person1.name, my_person1.eyecolor,my_person1.age) print(my_person1.name) print(my_person2.name) my_person1.name="aaaa" print(my_person1.name) print(my_person2.name)
0ef5b9bbfe1ae8a3304af7cb75ea311d157b4096
daniel-reich/ubiquitous-fiesta
/NJw4mENpSaMz3eqh2_10.py
341
3.71875
4
def is_undulating(n): l=len(str(n)) sn=str(n) if (l<3) | len(set(sn))!=2: return False else: for i in range(0,l-2,2): if sn[i]==sn[i+1]: return False elif sn[i]==sn[i+2]: continue else: return False return True
47c1718849cb8e9a63bb9898990cdfcce1eedfaf
CruzAmbrocio/Batalla_Naval
/src/batalla_naval.py
1,363
3.71875
4
# To change this template, choose Tools | Templates # and open the template in the editor. __author__="adela" __date__ ="$22/01/2014 10:32:04 AM$" import random tablero = [] for x in range(0,5): tablero.append(["O"] * 5) def print_tablero(tablero): for fila in tablero: print " ".join(fila) print "Juguemos a batalla naval!" print_tablero(tablero) def fila_aleatoria(tablero): return random.randint(0,len(tablero)-1) def columna_aleatoria(tablero): return random.randint(0,len(tablero[0])-1) barco_fila = fila_aleatoria(tablero) barco_col = columna_aleatoria(tablero) for turno in range(4): adivina_fila = input("Adivina fila:") adivina_columna = input("Adivina columna:") if adivina_fila == barco_fila and adivina_columna == barco_col: print "Felicitaciones! Hundiste mi barco!" break else: if (adivina_fila < 0 or adivina_fila > 4) or (adivina_columna < 0 or adivina_columna > 4): print "Vaya, esto ni siquiera esta en el oceano." elif(tablero[adivina_fila][adivina_columna] == "X"): print "Ya dijiste esa." else: print "No impactaste mi barco!" tablero[adivina_fila][adivina_columna] = "X" print_tablero(tablero) print "Estas en el turno:" + str(turno + 1) + " de 4" if turno == 3: print u"Termino el juego"
1ab7fb9525ec2b1872863b17e7d541163f1e3a20
Chu66y8unny/EP59
/code/item8.py
1,019
4.1875
4
matrix = [[1, 2, 3], [4, 5, 6]] # flat matrix to a list by row # by plain loops vec_by_row = [] for row in matrix: for col in row: vec_by_row.append(col) print(vec_by_row) # by list comprehension vec_by_row.clear() vec_by_row = [x for row in matrix for x in row] print(vec_by_row) # flat matrix to a list by col # by plain loops vec_by_col = [] for ci in range(len(matrix[0])): for row in matrix: vec_by_col.append(row[ci]) print(vec_by_col) # by list comprehension vec_by_col.clear() vec_by_col = [row[ci] for ci in range(len(matrix[0])) for row in matrix] print(vec_by_col) # Matrix transpose t = [[row[ci] for row in matrix] for ci in range(len(matrix[0]))] print(t) # Create 2-D Matrix with * operator m = [[0] * 4] * 3 print(m) # Gotcha: it created one row and created three references to it # row = [0] * 4 # m = [row, row, row] assert m[0] is m[1] and m[1] is m[2] # Solution: name = [[val] * cols for i in range(rows)] # m = [] # for i in range(rows): # m.append([val] * cols)
924a82971e1d9d945a84a8a1c2aa9cf125941c3f
FilipeAPrado/Python
/Paradigmas de linguagem em python/TarefaVotos.py
646
3.609375
4
from enum import Enum class Votes(Enum): firstCandidate = 1 secondCandidate = 2 thirdCandidate = 3 fourthCandidate = 4 nule = 5 inwhite = 6 totalVotes = { Votes.firstCandidate: 0, Votes.secondCandidate:0, Votes.thirdCandidate:0, Votes.fourthCandidate:0, Votes.nule:0, Votes.inwhite:0 } quantity = int(input("How many votes do you want to register: ")) for num in range(quantity): voteUser = int(input("VOTO: ")) optionUser = Votes(voteUser) totalVotes[optionUser] = totalVotes[optionUser] + 1 for vote,quantidade in totalVotes.items(): print(f'{vote.name} QTD:{quantidade}')
cd97d8e83b682b76f9a7be9dd26e2fe1772716a7
Surajit043/Python
/Python_Basic/range_object.py
276
4.0625
4
""" Range range(stop) range(start, stop) range(start, stop, step) step default = 1 start default = 0 stop default XXXXX iterable object """ r = range(5, 10, 3) print(r) # print(type(r)) # print(r.start) # print(r.stop) # print(r.step) for i in range(5, 10, 3): print(i)
cdf43d69315d2c44e3f3661b819b57c7da60522c
chenfu2017/Algorithm
/leetcode/73.SetMatrixZeroes.py
779
3.59375
4
class Solution: def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ if len(matrix)==0: return row = [] col = [] m = len(matrix) n = len(matrix[0]) for i in range(m): for j in range(n): if matrix[i][j]==0: row.append(i) col.append(j) print(row) print(col) for i in row: for j in range(n): matrix[i][j]=0 for i in range(m): for j in col: matrix[i][j]=0 print(matrix) n=[ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Solution().setZeroes(n)
15ae0e5481a39dbc9bd3207b751e236736aa413b
HenryM975/Euler
/4.py
641
3.578125
4
#4 firstlist = [] for i in range(10,100): for j in range(10, 100): a = i*j k = list(str(a)) num1 = k[0] num2 = k[-1] p = len(str(a)) if num1 == num2 : if p <= 3: firstlist.append(a) elif p >= 4: num3 = k[1] num4 = k[-2] if num3 == num4: firstlist.append(a)#возможно усовершенствование путем автоматизации для поиска чисел любого размера o = max(firstlist) print(firstlist) print("max: " , o) print("len: " , p)
99cd0fbaf1c897bada7dc849fc2ac016998a5977
SylviaJitti/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
176
4.28125
4
#!/usr/bin/python3 def search_replace(my_list, search, replace): return[replace if n == search else n for n in my_list] # ternary operator and list comprehension in python
9b902178a3073e520abf813483ca755e2b6dd075
MachFour/info1110-2019
/week12/max/times-tables.py
460
3.875
4
def times_tables(n): # this will be a list of lists table = [] i = 1 while i <= n: new_row = [] j = 1 while j <= n: new_row.append(i*j) j += 1 table.append(new_row) i += 1 return table def print_table(table): for row in table: for number in row: print("{:3d} ".format(number), end='') print() print() t = times_tables(10) print_table(t)
72f8ff0405420d0dbc483a22674666c95b5a6625
Achyutha18/College_Sample_1
/Sample1_5.py
167
4.375
4
#Python Program to Print Odd Numbers Within a Given Range ran = int(input("Enter the range : ")) for i in range(1,ran,2): print(i,end=" ") #to print in single line
916f831e2768abc697832eba3e3f7a0e741c051b
Baistan/FirstProject
/function_tasks/Задача8.py
292
3.859375
4
def Quad(): import math a = [] b = [] num = int(input()) while num != 0: a.append(num) num = int(input()) for digit in a: result = math.sqrt(digit) if (result - int(result)) == 0: b.append(int(result)) print(a,b) Quad()
61d074bbda6e9708f4058ed28123c14e6d34d648
Nivaldotk/CalcuDelta-
/main.py
236
3.921875
4
def delta(a, b, c): r = ((a ** 2) - 4 * a* c) return r a = int(input("Digite o valor de B")) b = int(input("Digite o valor de A")) c = int(input("Digite o valor de C")) print("O resultado de Delta é ", delta(a, b, c))
dae214d8380a9c807b7acdd917a619a9906f7cc8
HarmlessHarm/Heuristieken
/modules/Objects.py
9,201
4.09375
4
# -*- coding: utf-8 -*- from __future__ import division import pprint import copy import numpy as np class Board(object): """ Board object in which all data is stored """ def __init__(self, x_dim, y_dim, z_dim=10): """ Creates a Board object with certain dimensions and initializes a 3d numpy array which represents the circuit. Also contains a dictionary for where all gates and nets are stored with their id as key Args: x_dim (int): Width of the circuit y_dim (int): Height of the circuit z_dim (int, optional): Maximum depth of the circuit. Defaults to 10 """ super(Board, self).__init__() self.x_dim = x_dim self.y_dim = y_dim self.z_dim = z_dim self.board = np.zeros((x_dim, y_dim, z_dim), dtype=object) self.gates = {} self.nets = {} def getElementAt(self, x, y, z): """ Returns the object that is positioned at a certain position on the board. Args: x,y,z (int): x,y,z coordinate. Returns: Object at certain coordinate. Returns False if one of the provided coordinates are out of bound of the board. """ if 0 <= x < self.x_dim and 0 <= y < self.y_dim and 0 <= z < self.z_dim: return self.board[x, y, z] return False def isEmpty(self, xyz): """ Checks if board at a certain position is empty. Args: xyz (int tuple): Contains the x, y and z coordinates. Returns: bool: True if cell is empty, False otherwise. """ x, y, z = xyz if self.getElementAt(x, y, z) is 0: return True else: return False def setElementAt(self, obj, x, y, z=0): """ Puts an object in a cell at a certain coordinate if the cell is empty. This function can be used to set Gate and Net objects. Args: obj (object): Object that is set at position. x,y,z (int): x,y,z coordinate. Z Defaults at 0 Returns: bool: True if element is set. False if target """ if self.isEmpty((x, y, z)): self.board[x, y, z] = obj return True else: return False def removeElementAt(self, xyz): """ Deletes object from cell at certain coordinate. Args: xyz (int tuple): Contains the x, y and z coordinates. Returns: bool: True when finished. """ self.board[xyz] = 0 return True def getDimensions(self): """ Returns x, y and z dimensions of the board. """ return (self.x_dim, self.y_dim, self.z_dim) def getAllNeighbours(self, x, y, z): """ Returns a list with all neighbours of a cell at certain coordinate. Uses a difference vector to get neighbours in x,y,z directions. Checks if neighbour is in bound of the board. Args: x,y,z (int): x,y,z coordinates Returns: neighbours (tuple list): List of all coordinates of the neighbours of the cell. """ xyz = (x, y, z) neighbours = [] xs = [-1, 1, 0, 0, 0, 0] ys = [0, 0, -1, 1, 0, 0] zs = [0, 0, 0, 0, -1, 1] for dif_tuple in zip(xs, ys, zs): (nx, ny, nz) = [sum(x) for x in zip(xyz, dif_tuple)] if 0 <= nx < self.x_dim and 0 <= ny < self.y_dim and \ 0 <= nz < self.z_dim and xyz != (nx, ny, nz): neighbours.append((nx, ny, nz)) return neighbours def getOpenNeighbours(self, x, y, z): """ Returns a list of all empty neighbours of a cell at a certain coordinate. Args: x,y,z (int): x,y,z coordinates Returns: openNeighbours (tuple list): List of all coordinates of the empty neighbours of the cell. """ neighbours = self.getAllNeighbours(x, y, z) openNeighbours = [] for n in neighbours: if self.isEmpty(n): openNeighbours.append(n) return openNeighbours def getScore(self): """ Returns the number of paths and the score of the board. Calculates the score by summing the length of each path of a net on the board. The number of paths represents the amount of completed nets. Optimally this should be the same as the length of the netlist. Returns: pathCount (int): Number of paths score (int): Score of a board """ score = 0 pathCount = 0 for i in self.nets: path = self.nets[i].path if type(path) is list and path != []: pathCount += 1 score += len(path)-1 return pathCount, score def getMinimumScore(self): """ Returns the minimum score a board can have. Calculates the score by using the manhattan distance between the start and end points of each net in the board. This score is used as a comparison for the real score. Returns: score (int): """ score = 0 for netID, netObject in self.nets.iteritems(): # returns all net objects startId = netObject.start_gate endId = netObject.end_gate startGate = self.gates[startId] endGate = self.gates[endId] # get x, y, z coordinates both gates startCor = startGate.getCoordinates() endCor = endGate.getCoordinates() score += abs(startCor[0] - endCor[0]) + abs(endCor[1] - endCor[1]) return score def getRelativeScore(self): """ Returns the relative score between minimum and actual score. """ minimum = self.getMinimumScore() current = self.getScore() # check how many times current score fits into min. score return current[1] / minimum def setNetPath(self, net): """ Iterates through the path in a net and sets the corresponding cells. Sets Net objects at the corresponding cells. Args: net (Net): net that is iterated. Returns: bool: True if completed. False if a position isn't valid. """ toremove = net.path[1:-1] for i, (x, y, z) in enumerate(toremove): if not self.setElementAt(net, x, y, z): print 'False @:', (x, y, z) if i != 0: for coord in toremove[:i]: self.removeElementAt(coord) return False return True def removeNetPath(self, net): """ Removes all objects from the board at the corresponding path. Iterates over the path and removes objects from the board. Empties the path attribute of the Net opbject. Args: net (Net): net that is used. Returns: bool: True if completed. False if not removed. """ if net.path != []: for (x, y, z) in net.path[1:-1]: self.removeElementAt((x, y, z)) net.path = [] return True else: return False class Gate(object): """ Gate object with coordinates and identifier Attributes: gate_id (int): Unique identifier of the gate. x, y, z (int): Coordinates of the gate. """ def __init__(self, gate_id, x, y, z=0): super(Gate, self).__init__() self.gate_id = gate_id self.x = x self.y = y self.z = z def getCoordinates(self): """ Returns coordinates of gate """ return (self.x, self.y, self.z) class Net(object): """ Net object with identifier, start and end gate identifiers ano ffd the path. Attributes: start_gate, end_gate (int): Gate identifiers of the start and end gates. net_id (int): Unique Net identifier. path (tuple list): List of coordinates that make up the path of a net. """ def __init__(self, start_gate, end_gate, net_id): super(Net, self).__init__() self.net_id = net_id self.start_gate = start_gate self.end_gate = end_gate self.path = [] def addPos(self, xyz): """ Adds a new coordinate to the path attribute Args: xyz (int tuple): New coordinate to add to path """ x, y, z = xyz self.path.append((x, y, z)) class TreeNode(object): """ Node in search tree Attributes: board (Board): Board object in node previousNode (TreeNode): Parent of the TreeNode object netlist (tuple list): Netlist in node """ def __init__(self, board, previousNode, netlist): super(TreeNode, self).__init__() self.board = board self.previousNode = previousNode self.netlist = netlist
68c15c551dab4fdf225b50080b5592b68cee4a21
nilesh-patil/digit-classification-fully-connected-neural-nets
/code/layer.py
3,888
3.546875
4
"""All the layer functions go here. """ from __future__ import division, print_function, absolute_import import numpy as np class FullyConnected(object): """Fully connected layer 'y = Wx + b'. Arguments: shape(tuple): the shape of the fully connected layer. shape[0] is the output size and shape[1] is the input size. Attributes: W(np.array): the weights of the fully connected layer. An n-by-m matrix where m is the input size and n is the output size. b(np.array): the biases of the fully connected layer. A n-by-1 vector where n is the output size. """ def __init__(self, shape): self.W = np.random.randn(shape[0],shape[1]) self.b = np.random.randn(shape[0], 1) def forward(self, x): """Compute the layer output. Args: x(np.array): the input of the layer. Returns: The output of the layer. """ # TODO: Forward code linear_combination = np.dot(self.W,x)+self.b return(linear_combination) def backward(self, x, dv_y): """Compute the gradients of weights and biases and the gradient with respect to the input. Args: x(np.array): the input of the layer. dv_y(np.array): The derivative of the loss with respect to the output. Returns: dv_x(np.array): The derivative of the loss with respect to the input. dv_W(np.array): The derivative of the loss with respect to the weights. dv_b(np.array): The derivative of the loss with respect to the biases. """ # TODO: Backward code dv_b = dv_y dv_W = np.dot(x,dv_y.T).T dv_x = np.dot(self.W.T,dv_y) out = [dv_x,dv_W,dv_b] return(out) def update(self,W_new,b_new): self.W = W_new self.b = b_new class Sigmoid(object): """Sigmoid function 'y = 1 / (1 + exp(-x))' """ def __init__(self): self.W=None self.b=None def forward(self, x): """Compute the layer output. Args: x(np.array): the input of the layer. Returns: The output of the layer. """ # TODO: Forward code z = 1.0/(1.0+np.exp(-x)) return(z) def backward(self, x, dv_y): """Compute the gradient with respect to the input. Args: x(np.array): the input of the layer. dv_y(np.array): The derivative of the loss with respect to the output. Returns: The derivative of the loss with respect to the input. """ y = self.forward(x) dv_x = y*(1-y)*dv_y dv_w = False dv_b = False out = [dv_x,dv_w,dv_b] return(out) class tanh(object): """Rectilinear unit : f(x) = {(1-e^(−2x))}/{1+e^(−2x)} """ def __init__(self): self.W=None self.b=None def forward(self, x): """Compute the layer output. Args: x(np.array): the input of the layer. Returns: The output of the layer. """ z = (1-np.exp(-2*x))/(1+np.exp(-2*x)) return(z) def backward(self, x, dv_y): """Compute the gradient with respect to the input. Args: x(np.array): the input of the layer. dv_y(np.array): The derivative of the loss with respect to the output. Returns: The derivative of the loss with respect to the input. """ z = self.forward(x) dv_x = (1-np.square(z))*dv_y dv_w = False dv_b = False out = [dv_x,dv_w,dv_b] return(out)
969e8af5e0a089a78a6ffc9d6cefba8b4a6996f4
code-tamer/Library
/Business/KARIYER/PYTHON/Python_Temelleri/assignments.py
364
3.609375
4
# x = 5 # y = 16 # z = 20 x, y, z = 5, 16, 20 # x, y = y, x x += 5 # x = x + 5 x -= 5 # x = x - 5 x *= 5 # x = x * 5 x /= 5 # x = x / 5 x %= 5 # x = x % 5 y //= 5 # y = y // 5 y **= 5 # y = y ** 5 y *= z # y = y * z # print(x, y, z) values = 1, 2, 3, 4, 5 # print(values) # print(type(values)) x, y, *z = values print(x, y, z) print(x, y, z[1])
b051f9ac3a265b70ee53710a582e8f4f95716a4b
jeansabety/learning_python
/sumfac.py
476
4.1875
4
#!/usr/bin/env python3 # Write a program that computes the running sum from 1..n # Also, have it compute the factorial of n while you're at it # No, you may not use math.factorial() # Use the same loop for both calculations n = 5 sum=0 fac=1 #need to start at one or we will multiply by zero every time we go through the loop for i in range(1, n+1): sum=sum+i #sum changes every time we go through the loop fac=fac*i print(sum, fac) """ python3 sumfac.py 5 15 120 """
aab2b9e8bd50e45d0a5bacc1b24ad170a26edecb
kb0008/MAE_623
/Project1.py
8,719
3.578125
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ ####Run this block first to initiate functions############ ##no input needed in this block## #import libraries import numpy as np import matplotlib.pyplot as plt import time #define implicit method function def implicit(init_grid,FO,N,m): #Set length of coefficient matrix for looping M = (m+1)**2 nx = m+1 #create coefficient matrix of zeroes to start A = np.zeros([(m+1)**2,(m+1)**2]) #counter k = 0 while k<M-1: #set boundary conditions with set values if k == 0: A[k,k] = 1 elif (k>=1) and (k<=nx): A[k,k] = 1 elif k > nx*(nx-1): A[k,k] = 1 elif k%nx == 0: A[k,k] = 1 #insulated boundary condition elif (k+1)%(nx) == 0: A[k,k-1] = -FO A[k,k+nx] = -FO A[k,k-nx] = -FO A[k,k] = (1+3*FO) #interior nodes else: A[k,k+1] = -FO A[k,k-1] = -FO A[k,k+nx] = -FO A[k,k-nx] = -FO A[k,k] = (1+4*FO) k+=1 #flatten original matrix for 'k' references temperature_grid_n = init_grid.copy().flatten() #create inverse of A for solving linear algebra equations A =(np.linalg.pinv(A)) #start at time step 1 n = 1 #loop through all time steps in set run time while n<=N: #solve for unknown matrix B temperature_grid_nplus1 = np.matmul(A,temperature_grid_n) #reset boundary nodes except insulated boundary k = 0 while k<M-1: if k == 0: temperature_grid_nplus1[k] = 0 elif (k>=1) and (k<nx): temperature_grid_nplus1[k] = 100 elif k > nx*(nx-1): temperature_grid_nplus1[k] = 0 elif k%nx == 0: temperature_grid_nplus1[k] = 0 k+=1 temperature_grid_nplus1[-1] = 0 #find difference in temperatures for steady state checks diff = temperature_grid_nplus1 - temperature_grid_n #set n+1 values to n values for next look temperature_grid_n = temperature_grid_nplus1.copy() #check for steady state if diff.max()<=1e-5: break else: n+=1 #reshape final temperatures into mxm grid end_grid = temperature_grid_nplus1.copy().reshape([m+1,m+1]) return end_grid,n, diff #define explicit method function def explicit(init_grid,FO,N): #stability flag unstable = False #set n_grid to intial grid n_grid = init_grid #set n to first time step out n = 1 N_diff = [] #define midpoint reference mid = int((m+1)/2) #start the loop while n<=N: #set temperature_grid_n equal to old grid for calculations temperature_grid_n = n_grid.copy() #set temperature_grid_nplus1 equal to old grid for reassignment temperature_grid_nplus1 = n_grid.copy() #set i and j to start at first interior nodes i = 1 while i<=m-1: j = 1 while j<=m: #interior node equations if j == m: Temperature_nplus1 = FO*(temperature_grid_n.item(i,j-1)+ temperature_grid_n.item(i-1,j)+ temperature_grid_n.item(i+1,j)- 3*temperature_grid_n.item(i,j)) + temperature_grid_n.item(i,j) temperature_grid_nplus1[i,j] = Temperature_nplus1 j+=1 #insulated boundary equations else: Temperature_nplus1 = FO*(temperature_grid_n.item(i+1,j)+ temperature_grid_n.item(i-1,j)+ temperature_grid_n.item(i,j-1)+ temperature_grid_n.item(i,j+1)- 4*temperature_grid_n.item(i,j)) + temperature_grid_n.item(i,j) temperature_grid_nplus1[i,j] = Temperature_nplus1 j+=1 i+=1 #difference matrix for stability and steady state checks diff = temperature_grid_nplus1 - n_grid #creating list of mid-grid values for plotting N_diff.append(temperature_grid_nplus1[mid,mid]) #set new grid to n grid for next iteration n_grid = temperature_grid_nplus1.copy() #check for stability, flatten matrix for easier handling diff_check = diff.copy().flatten() #check each difference value for a negative number, if negative set unstable to True, report time model went unstable if [x for x in diff_check if x<0]: print('Model is unstable at current time step. \nInstability reached at time {:.3} seconds.'.format(n*FO*(1/m)**2/alpha)) unstable = True break #check if steady state has been acheived if diff.max()<=1e-4: break else: n+=1 n+=1 return n_grid,n,N_diff,unstable #define main function def _main(m,alpha,method,time_run,time_step,FO): #intialize the grid with initial Temperature conditions at n=0 print('Grid size '+str(m)+'x'+str(m)) initial_grid = np.zeros([m+1,m+1]) initial_grid[0,1:m+1] = 100 #Set delx with grid size, assign ystep=xstep to show uniform grid x_step = y_step = 1/m #Assign time step if time_step: FO = alpha*time_step/x_step**2 print('FO : {}'.format(FO)) if not time_step: time_step = FO*x_step**2/alpha print('Time step : {:.6} seconds'.format(time_step)) #Calculate Fourier number (FO) N = time_run/time_step if method == 'Explicit': final_grid,N_end,diff,unstable = explicit(initial_grid,FO,N) #calculate steady state time ss_time = N_end*time_step if N_end < N: if not unstable: print('Steady state reached at Time = {:.3} seconds'.format(N_end*time_step)) else: print('Steady state not reached') if method == 'Implicit': final_grid,N_end,diff = implicit(initial_grid,FO,N,m) #calculate steady state time ss_time = N_end*time_step if N_end < N: print('Steady state reached at Time = {:.3} seconds'.format(N_end*time_step)) else: print('Steady state not reached') #make line for cleaner print statements print(40*'*'+'\n') #return final temperature grid return final_grid #%% ####Change variables here and run block to set variables####### alpha_var = 1.0 method_var = 'Explicit' #'Explicit' #'Implicit' <--choose one, copy and paste time_step_var = '' #<-- #can be set or left as is time_run_var = 1.8 #<-- #vary to see 0.05 s results, currently at ss time FO_var = .25 #<-- #can be varied, will compute time step #%% #### Run this block last to execute ### plt.close('all') #grid sizes, will loop through this list steps = [10,20,40] #lists for plot legends and time grids = [] times = [] #initiate x-axis and y-axis plots fig1, ax1 = plt.subplots() ax1.set_title('Temperatures across mid x-axis for all grid sizes') fig2, ax2 = plt.subplots() ax2.set_title('Temperatures across mid y-axis for all grid sizes') for step in steps: grids.append(step) m = step #m is the grid size for both axes alpha = alpha_var method = method_var #'Explicit' #'Implicit' time_step = time_step_var time_run = time_run_var FO = FO_var now = time.time() final_grid = _main(m,alpha,method,time_run,time_step,FO) #print('Time to run model : {:.3}'.format(time.time()-now)) <-this doesn't work right in jupyter notebook? #plot heatmap for each grid plt.matshow(final_grid) plt.colorbar() plt.title('Heat map for grid size {}x{}'.format(step,step)) #plot x- and y- axis plots ax1.plot(final_grid[int(step/2),:]) ax2.plot(final_grid[:,int(step/2)]) #format plots ax1.grid(True) ax1.legend(grids) ax1.set_xlabel('Time Steps') ax1.set_ylabel('Mid x-axis Temperatures') ax2.grid(True) ax2.legend(grids) ax2.set_xlabel('Time Steps') ax2.set_ylabel('Mid y-axis Temperatures')
d81ccd9d70373a78df994c6c33d351f6c8f4398e
KocUniversity/comp100-2021f-ps0-ekaramustafa
/main.py
169
3.578125
4
import math x = int(input("Enter number x: ")) y = int(input("Enter number y: ")) myid = 76289 print("x**y = " , x ** y) print("log(x) =" , math.log(x,2)) print(myid)
48ebc281704b8abe1ccefea9c558f4c7e557f358
sabrinachen321/LeetCode
/python/0234-isPalindrome.py
911
3.84375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ def iterative(head): newHead = ListNode(-1) node = head while node: nextNode = node.next node.next = newHead.next newHead.next = node node = nextNode return newHead.next fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next secondHalf = iterative(slow) node1, node2 = head, secondHalf while node1 and node2: if node1.val != node2.val: return False node1, node2 = node1.next, node2.next iterative(secondHalf) return True
17402a3d88da1e771aefaa15f87842b7fdab7202
daniel-reich/turbo-robot
/5Q2RRBNJ8KcjCkPwP_17.py
974
4.125
4
""" Create a function that takes a list of character inputs from a Tic Tac Toe game. Inputs will be taken from player1 as `"X"`, player2 as `"O"`, and empty spaces as `"#"`. The program will return the **winner** or **tie** results. ### Examples tic_tac_toe([ ["X", "O", "O"], ["O", "X", "O"], ["O", "#", "X"] ]) ➞ "Player 1 wins" tic_tac_toe([ ["X", "O", "O"], ["O", "X", "O"], ["X", "#", "O"] ]) ➞ "Player 2 wins" tic_tac_toe([ ["X", "X", "O"], ["O", "X", "O"], ["X", "O", "#"] ]) ➞ "It's a Tie" ### Notes N/A """ def tic_tac_toe(inputs): a = check(inputs) b = check(zip(*inputs)) c = [[inputs[i][i] for i in range(3)], [inputs[i][2 - i]for i in range(3)]] c = check(c) return a or b or c or "It's a Tie" def check(x): for i in x: if len(set(i)) == 1: return "Player {} wins".format(["2", "1"][set(i) == {"X"}]) return ""
c4d46bb744b47b773e981fa1261ba997fac31199
SeanIvy/Learning-Python
/ex17.py
1,144
3.578125
4
# ------------------------------------------------ # Header # ------------------------------------------------ # http://learnpythonthehardway.org/book/ex17.html # ------------------------------------------------ # I like to add line breaks into my output, # these variables allow me to do that easily # and cohesively. separation = "-" *50 line = "\n%s\n" % separation # ------------------------------------------------ from sys import argv from os.path import exists scripts, from_file, to_file = argv print "%s\n" % separation print "Copying from %s to %s" % (from_file, to_file) print line # we could do these two on one line as well, how? input = open(from_file) indata = input.read() print "The input file is %d bytes long" % len(indata) print separation print "Does the output file exist? %r" % exists(to_file) print "Ready to copy. hit RETURN to continue, CTRL-C (^C) to abort." raw_input(">") output = open(to_file, 'w') output.write(indata) print "Alright, all done." output.close() input.close() # ------------------------------------------------ # End Script # ------------------------------------------------
99efe65e7c55e594396cd8211f292ad214384de9
dgehani86/PythonDS
/py1.py
2,304
3.8125
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import pandas as pd import numpy as np #-------Number data type----- value1 = 12 value2 = 10 resultsum = value1+ value2 resultdiv = value1 / value2 resultexp = value1**value2 resultmul = value1*value2 result_float = float(value1*value2) salary = 1000.00 intsal = int(salary) #-------String data type single or double quotes----- name = "Deepak Gehani" print(name[0]) print(name[1:5]) #sliceoperator print(name[1:]) print(name*2) string2= name[-1] + name[+1] "G" in name age = 32 print(name + " has age " + str(age)) sample = """it is very good day today we enjoyed""" print(sample) a,b,c = 1,2,"Dpk" print(str(b) + c) #-------List data type----- students = ["Rishab", "Kumar","Maria", "Nitin", "Rahul"] list1 = ['deepak', 716 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print (list1) print (students[0] + list1[0]) print (list1[2:]) students.append("Amit") print (students) students.extend([1,23,34,55,67]) print (students) tinylist.pop print(tinylist) print(list1) list1[3] = "Rahul" print(list1) tinylist.clear print(tinylist) students.append("Rahul") print(students) x = students.count("Rahul") print (x) student2 = ["abc", "defk", "geh", "ijk","Rahul"] student2.remove("Rahul") student2.sort() print(student2) student2.reverse() print(student2) allstudent = students + student2 print(allstudent) marks = [5, 99,11, 32,44] print (max(marks)) #-------Tuple data type-----immutable cannot changed in paranthesis--- tuple1 = ("a", "b", "c") tuple2 = (1,2,3) tuple3 = tuple1 + tuple2 #concatenation print(tuple3) print(tuple1*2) #repetition print(tuple2[1]) #indexing print(tuple1[1:]) #slicing #tuple1[1] = "f" print (tuple1) #----------python dictionary------- #hashtype, curly brackets tinydict = {'name': 'john','empid': 6234, 'dept': 'sales'} dictblk = {} print (tinydict.keys()) print (tinydict.values()) dictblk["age"] = 31 dictblk["college"] = "hindu_college" print(dictblk) del dictblk["college"] print(dictblk) print(len(tinydict)) type(tinydict) tinydict.update(dictblk) print(tinydict) dictblk.clear print(dictblk) print(tinydict['dept']) len(tinydict)
c6c592ace1d15979ee5d0a5f6b13d065f0dfa44e
cvaz2021/GradebookStudentProject
/main.py
1,593
4.09375
4
flag=True gradebook = {} testGradebook = {} while flag == True: print (""" 1.Add a Student 2.Delete a Student 3.Look Up Student Record 4.Add Grade 5.Get Class Average 6.Exit/Quit """) ans = input("What would you like to do? ") if ans == "1": name = input("Enter a name") gradebook[name] = {} print(gradebook) print("\n Student Added") elif ans=="2": name = input("What is the students name") del gradebook[name] print(gradebook) print("\n Student Deleted") elif ans=="3": name = input("What student do you want to look up") try: print(gradebook[name]) except: print("Student doesnt exist") elif ans=="4": name = input("Enter a name") assignment = input("enter assignment name") grade = int(input("enter assignment grade")) gradebook[name][assignment] = grade print(gradebook) print("grade added") elif ans == "5": studentAverages = [] for student in gradebook: print(gradebook[student]) studentGrades = [] for grade in gradebook[student]: print(gradebook[student][grade]) studentGrades.append(gradebook[student][grade]) print(studentGrades) average = sum(studentGrades)/len(studentGrades) print(average) elif ans == "6": flag = False print("\n Goodbye") elif ans !="": print("\n Not Valid Choice Try again")
f6ca106ffb9c744ad0e97e689c2bf7df62fd13b9
gabrielbessler/EulerProblems
/EulerPr21.py
1,556
4.21875
4
''' === Problem Statement === Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. ''' # An easy brute force approach would be to first find all of the amicable # numbers, and then summing them all up. # The most obvious approach is to go through each number from 1-10000 and see # if it has an amicable pair. This would require us to check # 999 number per number, giving us 999,000. Each check would consist of # finding all of the divisors of the number we are comparing it with, # summing the divisors, etc. # An easier way is to go through 10,000 numbers, finding all of their divisors # once, and sum the disivors for each number. Then, the ones that # have matches in the list are amicable numbers. # Yet another way to look at it is to loop through all of the combinations of # divisors. For example, for a total of 1, we can only have the number 1. # For a total of 2, nothing exists. For a total of 3, we could have 2*1. For # total of 4, we could have 3*1 and 2*2. Etc.... (This one may be more # mathematically involved) # METHOD TWO: divisorsSumL = [] for i in range(1, 10000): disivorsSumL.append(divisorsSum)
bccfc2c8eaf9d11742fc898904393f1efc04a148
russpj/GolfTee
/apptest.py
1,730
3.6875
4
''' apptest.py Tests the golf tees game. ''' from GolfTees import Rule from GolfTees import Solve from GolfTees import Solution from GolfTees import CreateTriangleBoard ''' This is the classic 10-hole triangular board 0 1 2 3 4 5 6 7 8 9 ''' def PegChar(peg): if peg: return 'X' else: return 'O' def PrintHexBoard(board): rowStrings = [] pumpNeedsPriming = True currentRow = 0 minCol = 100000000 for hole in board.holes: if pumpNeedsPriming or hole.row != currentRow: rowStrings.append([hole]) currentRow = hole.row firstCol = hole.col if firstCol < minCol: minCol = firstCol pumpNeedsPriming = False else: rowStrings[-1].append(hole) for rowString in rowStrings: colDiff = rowString[0].col - minCol for space in range(colDiff): print(' ', end='') for hole in rowString: print ('{} '.format(PegChar(hole.filled)), end='') print() return def PrintSolution(solution): for rule in solution: print ('{} jumps over {} to {}'.format(rule.start, rule.over, rule.end)) def TestBoard(board, diagnose=False): print ('Running Test') PrintHexBoard (board) solution = [] for result in Solve(board.holes, board.rules, solution): if result == Solution.Solved or diagnose: print ('{} at level {}'.format(result, len(solution))) PrintSolution(solution) PrintHexBoard (board) return def Test(): print ('Running Tests') testBoards = [] testBoards.append(CreateTriangleBoard(4, 0)) testBoards.append(CreateTriangleBoard(4, 1)) testBoards.append(CreateTriangleBoard(4, 4)) testBoards.append(CreateTriangleBoard(5, 4)) for board in testBoards: TestBoard(board) return if __name__ == '__main__': Test()
73a6de5e9f1a14bed2248af0a1f02ab4ac9d17a9
rodrigocruz13/holbertonschool-interview
/0x00-lockboxes/0-lockboxes.py
2,517
4.0625
4
#!/usr/bin/python3 """ Module used to add two arrays """ def canUnlockAll(boxes): """ Method that determines if all the boxes can be opened. Args: boxes (lst): List of all the boxes. Returns: True (bool): for success, False (bool): In case of failure. """ if (type(boxes) is not list): return False if (len(boxes) == 0): return False n_boxes = len(boxes) unlocked_lst = ["Locked"] * n_boxes # List of all unlocked boxes unlocked_lst[0] = "Unlocked" # The first box boxes[0] is unlocked next = boxes[0] while (unlocked_lst.count("Unlocked") < n_boxes and next is not None): open_me = next next = go_open(open_me, boxes, unlocked_lst) if (unlocked_lst.count("Unlocked") == n_boxes): return True # All boxes were open return False def go_open(open_me, boxes, unlocked_lst): """ Opens a single box (open_me), and check it as unlocked in unlocked_list. If open_me is a list, then opens recursively each box (open_me_i) Args: open_me (lst): List with the info of the current boxes to be opened. boxes (lst): List with all the boxes. unlocked_lst (lst): List of Locked / Unlocked boxes. Returns: next_boxes (lst): In case of success, a list of next boxes to open. None: If open_me is None or empty """ if (open_me is None): # There are no current boxes to be opened return None elif (len(open_me) == 0): # Empty. There are no current boxes to open return None elif (len(open_me) == 1): # 1 box to be open. i = open_me[0] if (len(boxes) <= i): # crazy position return None if (unlocked_lst[i] == "Unlocked"): # Already been there return None else: unlocked_lst[i] = "Unlocked" if(boxes[i] == open_me): # Same position return None return boxes[i] else: # More than 1 box to be opened next_boxes = [None] * len(open_me) i = 0 for box_i in open_me: if (type(box_i) == int): open_me_i = [box_i] else: open_me_i = box_i next_boxes[i] = go_open(open_me_i, boxes, unlocked_lst) i += 1 if len(next_boxes) == 0: # No more routes to take return None if next_boxes.count(None) == i: # All routes are taken return None return next_boxes
f96e36117c6fcf3e6591c926b105cc27be16a9cb
michaelnutt2/cvAssignment
/cvcode.py
3,929
4.4375
4
# -*- coding: utf-8 -*- ''' In this assignment: · You learn how build a Convolution Neural Network for image classification a computer vision task using KERAS . The image classification task is the handwritten digit classification using the MNIST dataset Dataset The MNIST dataset is an acronym that stands for the Modified National Institute of Standards and Technology dataset. It is a dataset of 60,000 small square 28×28 pixel grayscale images of handwritten single digits between 0 and 9. The task is to classify a given image of a handwritten digit into one of 10 classes representing integer values from 0 to 9, inclusively. ''' import subprocess import sys def install(package): try: __import__(package) except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", package]) install("keras") install("pandas") install("sklearn") install("numpy") import numpy as np from tensorflow import keras from tensorflow.keras import layers #Prepare the data # Model / data parameters num_classes = 10 input_shape = (28, 28, 1) # the data, split between train and test sets (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() # Scale images to the [0, 1] range x_train = x_train.astype("float32") / 255 x_test = x_test.astype("float32") / 255 # Make sure images have shape (28, 28, 1) x_train = np.expand_dims(x_train, -1) x_test = np.expand_dims(x_test, -1) print("x_train shape:", x_train.shape) print(x_train.shape[0], "train samples") print(x_test.shape[0], "test samples") # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) # Set the model to be a simple feed-forward (layered) architecture # See https://keras.io/api/models/ and https://keras.io/api/models/sequential/ # not to be confused with a sequence-based alg/model to process sequential data model = keras.Sequential() # Add an input layer with shape=(28, 28, 1) # See https://keras.io/api/layers/core_layers/input/ model.add(keras.Input(shape=(28,28,1))) # Add a Conv2D hidden layer with 32 relu activation units and kernel_size of 3*3 # See https://keras.io/api/layers/convolution_layers/convolution2d/ model.add(layers.Conv2D(32, kernel_size=(3, 3), activation='relu')) # Add a MaxPooling hidden layer and set pool_size of 2*2 # See https://keras.io/api/layers/pooling_layers/max_pooling2d/ model.add(layers.MaxPooling2D(pool_size=(2, 2))) # Add a Conv2D hidden layer with 64 relu activation units and kernel_size of 3*3 # See https://keras.io/api/layers/convolution_layers/convolution2d/ model.add(layers.Conv2D(64, kernel_size=(3,3), activation='relu')) # Add a MaxPooling hidden layer and set pool_size of 2*2 # See https://keras.io/api/layers/pooling_layers/max_pooling2d/ model.add(layers.MaxPooling2D(pool_size=(2,2))) # Add a Flatten hidden layer # See https://keras.io/api/layers/reshaping_layers/flatten/ model.add(layers.Flatten()) # Add a Dropout hidden layer and set rate=0.5 # See https://keras.io/api/layers/regularization_layers/dropout/ model.add(layers.Dropout(rate=0.5)) # Add a dense output layer with units=10 and softmax activation unit # https://keras.io/api/layers/core_layers/dense/ model.add(layers.Dense(units=10, activation='softmax')) model.summary() # Compile the model, specifying (1) the Adam optimizer, # (2) the 'categorical_rossentropy' loss function, and (3) metrics=['accuracy'] # See https://keras.io/api/models/model_training_apis/ model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # fit the keras model on the _TRAIN_ dataset set epochs to 15, batch_size to 16, validation_split = 0.1 model.fit(x_train, y_train, batch_size=16, epochs=15, validation_split=0.1) score = model.evaluate(x_test, y_test, verbose=0) print("Test loss:", score[0]) print("Test accuracy:", score[1])
dfd8bbaff55630ae7c721de9cedd0554bfae0f84
stephalexandra/lesson7
/problem2.py/problem2.py
215
3.96875
4
print ('-' * 65) x = input ('Pick a number: ') x = int(x) y = input ('Pick another number: ') y = int(y) total = (x * y) total = str(total) print('When you multiply these numbers, you get ' + total) print ('-' * 65)
3a1b5a287dbd4b5b905517e2061fce62a35f54c7
febacc103/febacc103
/functions/calculator.py
259
3.859375
4
def calc(): n1=int(input("enter first number")) n2=int(input("enter second number")) add=n1+n2 sub=n1-n2 mul=n1*n2 print("enter your choice") print("1.add") print("2.sub") print("3.mul") if() print(n1+n2) calc()
b7fe479f010694f71b4dbc5df0e07cd3a3c08449
DMRathod/_RDPython_
/Simple_estimation_CrowdComputing.py
894
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 16 12:53:40 2019 @author: Dharmraj Rathod """ from statistics import mean #from scipy import stats #let we have the bottle filled with marbels and we have to guess how many number of marbles are #there in the bottle """total number of marbles in the bottle is 36""" #implementation of trim_mean function from scipy Guess = [30,35,20,15,40,45,38,45,50,50,70,37,15,55,25,28,26,28,20,30] #for guess we use the trimmed percentage%(should be in 100) def Rdtrim_mean(percentage,Guess): if(percentage > 100 or Guess == []): print("Please Enter the valid Arguments") percentage = percentage/100 Guess.sort() trimmed_value =int( percentage*len(Guess) ) #m = stats.trim_mean(Guess,0.1) Guess = Guess[trimmed_value:] Guess = Guess[:len(Guess)-trimmed_value] print("Actual Value May Near About = ",mean(Guess)) #print(m)
02c8ff63993add66fe8f444234bf283461999a92
Simik31/KIP-7PYTH
/Úkol 8/main.py
3,006
3.859375
4
class Date: def __init__(self, date): self.split_sep = ["", ""] self.date = date self.monthNumber = 0 for sep in separators: if sep in self.date: self.split_sep[0] = sep self.day = self.date.split(self.split_sep[0])[0] self.date = self.date.replace(self.day + self.split_sep[0], "") break for sep in separators: if sep in self.date: self.split_sep[1] = sep self.month, self.year = self.date.split(self.split_sep[1]) break def test(self): # PŘESTUPNÝ ROK - UPRAVENÝ KÓD Z https://www.programiz.com/python-programming/examples/leap-year if (int(self.year) % 4) == 0: if (int(self.year) % 100) == 0: if (int(self.year) % 400) == 0: daysInMonth[1] = 29 else: daysInMonth[1] = 29 # MĚSÍC if self.month.isdigit(): if int(self.month) in range(1, len(czech_months) + 1): self.monthNumber = int(self.month) else: if int(self.month) < 1: print(f"Wrong month. Correcting {self.month} -> 1\nCORRECTED ", end="") self.month = self.monthNumber = 1 else: print(f"Wrong month. Correcting {self.month} -> ", end="") self.month = self.monthNumber = len(czech_months) print(self.month, "CORRECTED ", sep="\n", end="") else: for x in range(0, len(czech_months)): if self.month == czech_months[x]: self.monthNumber = x + 1 if self.monthNumber == 0: print(f"Wrong month. Correcting {self.month} -> {czech_months[0]}\nCORRECTED ", end="") self.month = czech_months[0] # DEN if int(self.day) < 1: print(f"Wrong day. Correcting {self.day} -> 1\nCORRECTED ", end="") self.day = 1 elif int(self.day) > daysInMonth[self.monthNumber - 1]: print(f"Wrong day. Correcting {self.day} -> ", end="") self.day = daysInMonth[self.monthNumber - 1] print(self.day, "CORRECTED ", sep="\n", end="") print(f"DATE IS: {self.day}{self.split_sep[0]}{self.month}{self.split_sep[1]}{self.year}\n") separators = ["/", ". ", ".", " "] daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] czech_months = ["ledna", "února", "března", "dubna", "května", "června", "července", "srpna", "září", "října", "listopadu", "prosince"] if __name__ == "__main__": # DATA Z MOODLE date_1 = Date("29. června 2020") date_2 = Date("29. 6. 2020") date_3 = Date("29.6.2020") date_4 = Date("29/6/2020") # DATUM Z EMAILU date_5 = Date("31. 4. 2020") date_1.test() date_2.test() date_3.test() date_4.test() date_5.test()
1bf6f5cbf6a326de1ec845adc6d8cb7807e34860
binchen15/leet-python
/tree/prob1325.py
667
3.6875
4
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: if not root: return None if root.val == target and self.isLeaf(root): return None root.left = self.removeLeafNodes(root.left, target) root.right = self.removeLeafNodes(root.right, target) if root.val != target: return root if self.isLeaf(root): return None return root def isLeaf(self, node): """is a node a leaft node?""" return node and not node.left and not node.right
00c6ad5169e5f90f918de416dc288740c79ee4ca
AdamZhouSE/pythonHomework
/Code/CodeRecords/2452/59140/259780.py
175
3.96875
4
row=int(input()) str='' for i in range(row): str+=input() str+="," str=str[:len(str)-1].split(',') target=input() if str.count(target)!=0:print(True) else:print(False)
f1c920a5ea4182205ac4347dbefdc49382b92531
GrantWils23/Texas_Hold_Em_Poker_Project
/tests/validators/test_two_pair_validator.py
1,314
3.703125
4
import unittest from poker.card import Card from poker.validators import TwoPairValidator class TwoPairValidatorTest(unittest.TestCase): def setUp(self): self.three_of_clubs = Card(rank = "3", suit = "Clubs") self.three_of_hearts = Card(rank = "3", suit = "Hearts") self.nine_of_diamonds = Card(rank = "9", suit = "Diamonds") self.nine_of_hearts = Card(rank = "9", suit = "Hearts") self.king_of_clubs = Card(rank = "King", suit = "Clubs") self.cards = [ self.three_of_clubs, self.three_of_hearts, self.nine_of_diamonds, self.nine_of_hearts, self.king_of_clubs ] def test_validates_that_cards_have_exactly_two_pair(self): validator = TwoPairValidator(cards = self.cards) self.assertEqual( validator.is_valid(), True ) def test_returns_two_pair_from_card_collection(self): validator = TwoPairValidator(cards = self.cards) self.assertEqual( validator.valid_cards(), [ self.three_of_clubs, self.three_of_hearts, self.nine_of_diamonds, self.nine_of_hearts ] )
48dcaac2b4c552aa9cfab5e641a4fc6d0cb64182
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4384/codes/1811_2567.py
62
3.8125
4
n=int(input("digite um valor:" )) for i in n: s=n+1 print(s)