blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d6cb6c3a5adfa1310a5b0c9dc17388241eb54970
Pyr0blad3/advent-of-code-2019
/day12.py
2,346
3.5625
4
import re from math import gcd def lcm(a, b): return (a*b)//gcd(a, b) class Moon: def __init__(self, x, y, z): self.x, self.y, self.z = x, y, z self.vx, self.vy, self.vz = 0, 0, 0 def apply_velocity(self): self.x += self.vx self.y += self.vy self.z += self.vz def compute_velocity(self, moons): for moon in moons: if self.x < moon.x: self.vx += 1 elif self.x > moon.x: self.vx -= 1 if self.y < moon.y: self.vy += 1 elif self.y > moon.y: self.vy -= 1 if self.z < moon.z: self.vz += 1 elif self.z > moon.z: self.vz -= 1 def total_energy(self): return (abs(self.x) + abs(self.y) + abs(self.z)) * (abs(self.vx) + abs(self.vy) + abs(self.vz)) def __str__(self): return "pos=<x={}, y={}, z={}>, vel=<x={}, y={}, z={}>".format(self.x, self.y, self.z, self.vx, self.vy, self.vz) if __name__ == '__main__': moons = [] with open('day12.txt') as f: for line in f.readlines(): x = re.match(r'<x=(-?\d+), y=(-?\d+), z=(-?\d+)>', line.strip()) moons.append(Moon(int(x.group(1)), int(x.group(2)), int(x.group(3)))) # Part 1 """ for i in range(1, 1000+1): for moon in moons: moon.compute_velocity(moons) for moon in moons: moon.apply_velocity() print(sum([moon.total_energy() for moon in moons])) """ #Part 2 x_rep, y_rep, z_rep = -1, -1, -1 xi = tuple(m.x for m in moons) yi = tuple(m.y for m in moons) zi = tuple(m.z for m in moons) for i in range(1, 10000000): for moon in moons: moon.compute_velocity(moons) for moon in moons: moon.apply_velocity() xs = tuple(m.x for m in moons) ys = tuple(m.y for m in moons) zs = tuple(m.z for m in moons) if xs == xi: x_rep = i+1 if x_rep == -1 else x_rep if ys == yi: y_rep = i+1 if y_rep == -1 else y_rep if zs == zi: z_rep = i+1 if z_rep == -1 else z_rep if x_rep != -1 and y_rep != -1 and z_rep != -1: break print(lcm(lcm(x_rep, y_rep), z_rep))
f8c82b77bb7d1c97c556b18fa38c0535e5571d15
chinaxiaobin/python_study
/oldboy2019/day002编码/03 while循环.py
1,396
4.09375
4
# # print("你是不是傻") # print("下路支援,你不来?") # print("xsdfesf3a!@$@") """ while循环 while 条件: 代码块 流程: 判断条件是否为真,如果真,执行代码块,然后再次判断条件是否为真,如果真继续执行代码 直到条件变成了假,循环退出 #死循环 while True: print("!#@#$@!") """ # Count = 0 # while Count <= 100: # print("!#@#$@!1") # Count += 1 #count的作用: 计数 控制循环范围 #从1-100 # count = 1 # while count <= 100: # print(count) # count = count + 1 # 求1+2+3+4+....100 = ? # count = 1 # sum = 0 # while count <= 100: # sum = sum + count #累加运算的思想 # count = count + 1 # print(sum) # 让用户喷的内容,不停的喷 # # while True: # content = input("请输入你要跟对方说的话(输入Q退出): ") # if content == "Q": # #exit(0) #退出程序 # #break #退出本层循环,不会对外层循环产生影响, 毁灭性的 # continue #停止当前本次循环,继续执行下次循环, 暂时性的 # print(content) # print("我去吃饭了") #输入Q是直接全部退出,这句是不执行的 # #换成break退出循环,然后打印print content = input("请输入你的评论信息:") if "金三胖" in content: print("对不起,你的评论包含敏感词汇") else: print(content)
ed94e26adc00fb65ca1786a8af42905c89861343
chinaxiaobin/python_study
/oldboy2019/day003字符串/01 int 和类型转换.py
856
3.984375
4
# # bit_length() 二进制的长度 # # a = 4 # 10进制2 2进制 100 # print(a.bit_length()) # 把字符串转出成int # a = "10" # print(type(int(a))) # # 把int 转换成字符串 # # a = 10 # print(type(a)) # print(type(str(a))) # # # #结论:想转化成xxx数据类型 xxx(目标) # # a = 10 # b = bool(a) # print(b) # # a = True # print(int(a)) # 结论 True 是1 False是 0 # 数字只有0 是False 其他都是 True 无论正整数还是负整数还是空格还是任何字符都是True # 可以当做False来用的数据: 0 "" # 所有的空的东西都是False 0 "" [] () {} None # print(bool(0)) # print(bool("")) # print(bool([])) #空列表 # print(bool(())) #空元祖 # print(bool(None)) # # while 1: # 1 和 True的效率 1的效率比True高一点 因为True多了个转换 1 的过程 # print("还我钱")
16bb361d10f0377ebe61c727eaf53f3bffe1b84f
chinaxiaobin/python_study
/练习Python/第10天 面向对象-2/10-多继承.py
456
4.09375
4
class Base(object): #python3默认都是继承object,写上object就叫新式类,不写就是经典类,不写默认也继承object def test(self): print("----Base") class A(Base): def testA(self): print("-- A") class B(Base): def testB(self): print("--- B") class C(A,B): # 可以继承多个类,拥有多个类的方法和属性 def testC(self): print("--C") c = C() c.testA() c.testB() c.test()
aad8017e394939f766dcc46af1f0c1ee9d8320b2
chinaxiaobin/python_study
/练习Python/第9天 面向对象-1/练习.py
562
3.8125
4
class Cat(): #属性 #初始化对象 def __init__(self,new_name,new_age): self.name = new_name self.age = new_age #描述信息 def __str__(self): return "%s的年龄是:%d" %(self.name,self.age) #方法 def eat(self): print("猫在吃...") def drink(self): print("猫在喝可乐...") def introduce(self): print("%s的年龄是:%d" %(self.name,self.age)) tom = Cat("汤姆",40) tom.introduce() lanmao = Cat("蓝猫",10) lanmao.introduce() print(tom) print(lanmao)
53ae0ef70817819035f07063c7db865308ce96f1
chinaxiaobin/python_study
/oldboy2019/day007 基础数据类型补充/深浅 拷贝.py
1,654
3.671875
4
lst1 = ["太白","日天","哪吒","银王","金王"] lst2 = lst1 lst1.append("女生") print(lst1) print(lst2) #发下lst1和lst2是一样的,是因为都是指向同一个内存地址 #浅拷贝 lst1 = ["太白","日天","哪吒","银王","金王"] lst2 = lst1[:] # 浅拷贝第一种方法, 创建了新的对象,创建对象的速度会很快 lst2 = lst1.copy() #浅拷贝第二种 方法 lst1.append("女生") print(lst1) print(lst2) #发下lst1和lst2是不一样的,是因为指向的不是同一个内存地址 #浅拷贝 lst1 = ["太白","日天",["盖浇饭","锅包肉"],"哪吒","银王","金王"] #lst2 = lst1[:] # 浅拷贝第一种方法, 创建了新的对象,创建对象的速度会很快 lst2 = lst1.copy() #浅拷贝第二种 方法 lst1[2].append("油泼面") print(lst1) print(lst2) #发下lst1和lst2是一样的,是因为这里用的浅拷贝,浅拷贝只会拷贝对象,与对象里的指针指向没有关联,也就是里面的第二个列表 #在lst1是以指针方式存储, 浅拷贝只拷贝指针指向,不会拷贝里面的数据,所以是同一个 数据 #深拷贝 import copy lst1 = ["太白","日天",["盖浇饭","锅包肉"],"哪吒","银王","金王"] lst2 = copy.deepcopy(lst1) lst1[2].append("油泼面") print(lst1) print(lst2) #此时深拷贝,发现结果不一样了,lst1添加就和lst2没关系了 print(id(lst1),id(lst2)) #总结: # 赋值没有创建新对象,多个变量共享同一个对象 # 浅拷贝,会创建新对象,新的对象里面的内容不会被拷贝 # 深拷贝,创建一个一模一样的完全的新的对象,这个对象延伸出来的内容也会跟着复制一份
ccbbeda5e9f600eb58bec8894a1f2118eed329bb
chinaxiaobin/python_study
/练习Python/python-基础-01/08-打印一个名片.py
789
4.34375
4
# 先做啥再做啥,可以用注释搭框架 # 1.使用input获取必要信息 name = input("请输入你的名字:") phone = input("请输入你的电话:") wx = input("请输入你的微信:") # 2.使用print来打印一个名片 print("=====================") print("名字是:%s"%name) print("电话是:%s"%phone) print("微信好是:%s"%wx) print("=====================") """ python2中input是将输入的内容当作代码了,而python3是把输入的内容当作一个字符串 name = input("请输入你的名字:") 如果输入1+4 然后打印name变量会得到结果5 如果输入laowang 会报错,这是因为 name = laowang 表示把laowang这个值赋给name,而laowang在内存中是没有的 Python2中使用 raw_input 才和python3中的input效果一样 """
2ac9dbf48b570ce22a37d4e6f5eb6f07ddadab9f
chinaxiaobin/python_study
/练习Python/第11天 {面向对象3、异常、模块}/设计4s店/test4-使用函数完成解耦.py
871
4.03125
4
""" 需要,如果再加一辆IX35呢, 需要修改商店类和添加下面的品牌类, 这样两个类的耦合性比较高,修改一个必须修改另一段代码 """ """ 利用函数解耦 """ class Car_store(object): def order(self,car_type): return select_car_by_type(car_type) def select_car_by_type(car_type): if car_type == "索纳塔": return Suonata() elif car_type == "名图": return Mingtu() elif car_type = "IX35": return IX35() class Car() def move(self): print("车在移动") def music(self): print("正在听音乐") def stop(self): print("车在停止") class Suanata(Car): pass class Mingtu(Car): pass class IX35(Car): pass car_store = Car_store() car = Car_store.order("索纳塔") car.move() car.music() car.stop()
dc9cc4328cc9230c0f009607f36be57e1fd3bcce
chinaxiaobin/python_study
/oldboy2019/day004/列表的增删改查.py
1,621
3.578125
4
#列表的增删改查 #新增 #注意列表和字符串不一样,列表是可以发生改变的 所以直接在原来的对象上进行了操作,而字符串是不可改变的 lst = [] lst.append("周杰伦") #追加 永远在最后添加 效率比较高 lst.append("周芷若") lst.append("周公瑾") print(lst) lst = [ "刘德华","渣渣辉","古天乐","陈小春"] lst.insert(2,"马德华") #插入 可能会导致元素移动 查找最后位置元素是不移动的 print(lst) #expend 迭代添加, lst = [ "刘昊然","张一山","徐峥","黄渤"] lst.extend("刘能") #是可迭代对象,就是for循环可以遍历 print(lst) # ['刘昊然', '张一山', '徐峥', '黄渤', '刘', '能'] lst.extend(["刘能","赵四","广坤"]) #列表是可迭代的,一个一个的往外拿 #2. 列表的删除 # pop remove clear del lst = [ "刘能","广坤","皮长山","大脚"] print(lst) # # s1 = lst.pop() #默认弹出最后一个 # print(s1) # s2 = lst.pop() # print(s2) lst.remove("广坤") #指定要删除的元素 print(lst) lst = ["语文","数学","英语","化学","历史"] # lst.clear() #清空 # print(lst) del lst[1:3] #可以切片删除 print(lst) # 3. 修改列表的元素 lst = ["功夫","大话西游","少林寺","无间道","战狼","战狼2"] # lst[2] = "西西里的美丽传说" # lst[-3] = "新世界" # lst[1:3] = ["一步之遥"] lst[1:5:2] = ["胡辣汤","烩面"] # 替换两个位置如果只给一个 元素会报错,所以替换的个数要匹配 print(lst) # 4.查询 #列表是一个可迭代对象,可以使用for循环 for e in lst: print(e)
0bcf2c15a6f01a5a4ecb39970c6d3fa9f9c7a722
chinaxiaobin/python_study
/Day1/login.py
270
3.734375
4
import getpass _username = 'alex' _password = 'abc123' user = input("请输入用户名:") password = input("请输入密码:") if user == _username and password == _password: print("Welcome user %s login"% user) else: print("Wrong username or password")
2636d4331c5a07b4a1fa6f89cfa62f746a159a29
chinaxiaobin/python_study
/oldboy2019/day001 python介绍/demo.py
128
3.8125
4
MaHuaTeng = input("请输入麻花藤:") if MaHuaTeng == "麻花藤": print("真聪明") else: print("你是傻逼么")
6b8480eab18fe9405c20ec7e4199d78ce040d983
ankitbhatia8993/parkingservice_python
/src/entity/vehicle.py
444
3.90625
4
from abc import ABC, abstractmethod class Vehicle(ABC): def __init__(self, registration_number, color, vehicle_type): self.registration_number = registration_number self.color = color self.vehicle_type = vehicle_type @abstractmethod def vehicle_type(self): pass def __str__(self): return str(self.__dict__) def __eq__(self, other): return self.__dict__ == other.__dict__
e567bb0a77f50f1b6688ada0ca7101a66bc627da
SurajMalpani/Movie-Trailer-website
/media.py
521
3.546875
4
import webbrowser # Import this module to open webpages in the code class Movie(): """ Class Movie holds all the necessary information like Movie's title, storyline, poster and trailer url. """ def __init__(self, title, storyline, poster, trailer_link): self.title = title self.storyline = storyline self.poster_image_url = poster self.trailer_youtube_url = trailer_link def show_trailer(self): webbrowser.open(self.trailer_youtube_url)
d19a9feae1de85c4c68173d07ea30f616d22959f
mileuc/100-days-of-python
/Day 31: Flash Card Capstone Project/main.py
3,583
3.75
4
from tkinter import * import pandas import random # ---------------------------- CONSTANTS ------------------------------- # BACKGROUND_COLOR = "#B1DDC6" flip_timer = None current_card = {} # ---------------------------- CREATE NEW FLASH CARDS ------------------------------- # try: cards_to_learn = pandas.read_csv("data/words_to_learn.csv") except FileNotFoundError: cards_to_learn = pandas.read_csv("data/french_words.csv") finally: # orient to have a list of dicts where keys=column names cards_to_learn_dict = cards_to_learn.to_dict(orient="records") print(cards_to_learn_dict) def new_flash_card(): global flip_timer, current_card current_card = random.choice(cards_to_learn_dict) canvas.itemconfig(card_background, image=card_front_img) canvas.itemconfig(card_title, text="French", fill="black") canvas.itemconfig(card_word, text=current_card["French"], fill="black") # After delay of 3s(3000ms), the card should flip and display the English translation for the current word. flip_timer = window.after(3000, flip_flash_card, current_card) # ---------------------------- FLIP FLASH CARD ------------------------------- # def flip_flash_card(card): canvas.itemconfig(card_background, image=card_back_img) # To change the text color in a canvas element, use the fill parameter canvas.itemconfig(card_title, text="English", fill="white") canvas.itemconfig(card_word, text=card["English"], fill="white") # get the delay countdown to stop after a new card is shown, next after() call will restart it from 0 window.after_cancel(flip_timer) # cancels the timer previously set up with after() # ---------------------------- UPDATE PROGRESS ------------------------------- # # when checkmark button is clicked, the user knows that word and it should be removed from the list of words to learn def discard_card(): window.after_cancel(flip_timer) # cancels the timer previously set up with after() cards_to_learn_dict.remove(current_card) data = pandas.DataFrame(cards_to_learn_dict) # new dataframe with updated data data.to_csv("./data/words_to_learn.csv", index=False) # don't want indices for new csv on top of the existing ones new_flash_card() # ---------------------------- UI SETUP ------------------------------- # window = Tk() window.title("Flash Cards") window.config(padx=20, pady=20, bg=BACKGROUND_COLOR) canvas = Canvas(width=800, height=526) card_front_img = PhotoImage(file="images/card_front.png") card_back_img = PhotoImage(file="images/card_back.png") # cannot be called inside a function due to limited scope card_background = canvas.create_image(400, 263, image=card_front_img) # create image in canvas, center at this position card_title = canvas.create_text(400, 150, text="Title", font=("Arial", 40, "italic")) # relative to canvas card_word = canvas.create_text(400, 263, text="word", font=("Arial", 60, "bold")) canvas.config(bg=BACKGROUND_COLOR, highlightthickness=0) canvas.grid(column=0, row=0, columnspan=2) # buttons unknown_button_img = PhotoImage(file="images/wrong.png") unknown_button = Button(image=unknown_button_img, command=new_flash_card, bg=BACKGROUND_COLOR, bd=0, relief=GROOVE) unknown_button.grid(column=0, row=1) known_button_img = PhotoImage(file="images/right.png") known_button = Button(image=known_button_img, command=discard_card, bg=BACKGROUND_COLOR, bd=0, relief=GROOVE) known_button.grid(column=1, row=1) new_flash_card() # generate a new flash card when the program starts, after UI is created window.mainloop()
89cb76c58b6814fb2a074d5be82b32d6775f9793
mileuc/100-days-of-python
/Day 22: Pong/ball.py
1,223
4.3125
4
# step 3: create and move the ball from turtle import Turtle class Ball(Turtle): def __init__(self): super().__init__() self.shape("circle") self.color("white") self.penup() self.goto(x=0, y=0) self.x_move = 10 self.y_move = 10 self.move_speed = 0.05 def move(self): new_x = self.xcor() + self.x_move new_y = self.ycor() + self.y_move self.goto(new_x, new_y) def bounce_y(self): # when bounce occurs off top or bottom wall, y_move is changed so the ball moves in opposite way self.y_move *= -1 def bounce_x_left_paddle(self): self.x_move = (abs(self.x_move)) self.move_speed *= 0.9 # step 8: change ball speed every time ball hits paddle def bounce_x_right_paddle(self): self.x_move = -(abs(self.x_move)) self.move_speed *= 0.9 def left_paddle_miss(self): self.goto(x=0, y=0) self.move_speed = 0.05 # reset ball speed when it resets self.bounce_x_left_paddle() def right_paddle_miss(self): self.goto(x=0, y=0) self.move_speed = 0.05 self.bounce_x_right_paddle()
ca9040e2f67a9ef6e1e15e9b5fa73c8df6295877
mileuc/100-days-of-python
/Day 10: Calculator/main.py
1,544
4.3125
4
from art import logo from replit import clear def calculate(operation, first_num, second_num): """Takes two input numbers, a chosen mathematical operation, and performs the operation on the two numbers and returns the output.""" if operation == '+': output = first_num + second_num return output elif operation == '-': output = first_num - second_num return output elif operation == '*': output = first_num * second_num return output elif operation == '/': output = first_num / second_num return output else: return "Invalid operator chosen." print(logo) initial_calc = True while initial_calc == True: num1 = float(input("What's the first number? ")) subsequent_calc = True print("+\n-\n*\n/") while subsequent_calc == True: operator = input("Pick an operation: ") num2 = float(input("What's the second number? ")) result = calculate(operator, num1, num2) print(f"{num1} {operator} {num2} = {result}") if type(result) == float or type(result) == int: y_or_n = input(f"Type 'y' to continue calculating with {result},\nor type 'n' to start a new calculation: ").lower() if y_or_n == "n": subsequent_calc = False clear() elif y_or_n == 'y': num1 = result else: subsequent_calc = False initial_calc = False print("Sorry, you didn't enter 'y' or 'n'.") else: subsequent_calc = False initial_calc = False print("Sorry, you entered an invalid operator.")
546cbeadef5427b74b5b8011e067fce77fb97199
wuge-1996/Python-Exercise
/Exercise 12.py
274
3.796875
4
# 利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。 x=float(input("分数:")) if x>=90: jibie="A" if 60<=x<90: jibie="B" if x<60: jibie="C" print("级别:%s"%jibie)
a880700c0fdcedb9a4e8a92551702abdbbfaaeb9
wuge-1996/Python-Exercise
/Exercise 13.py
416
3.703125
4
# 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 a=str(input("输入一个字符串:")) zimu=0 shuzi=0 kongge=0 qita=0 for i in a: if i.isalpha(): zimu+=1 elif i.isdigit(): shuzi+=1 elif i.isspace(): kongge+=1 else: qita+=1 print("字母有:%d个,数字有%d个,空格有%d个,其他%d个"%(zimu,shuzi,kongge,qita))
3de8ae56f50e418ff4f062399b5af1700189c3e9
wuge-1996/Python-Exercise
/Exercise 19.py
126
3.578125
4
# 利用递归方法求5! def fact(j): if j == 0: return 1 else: return j * fact(j - 1) print(fact(5))
7337e1b66c1d1241dea21f84fb19a582d7ea65c8
AnnaTSW0609/Python_Practice
/017_Mendel_Second_Law.py
1,502
3.5625
4
"""Mendel Second Law Application""" """Start with one AaBb individual""" """Each generation would only mate with AaBb""" """Each generation would have 2 offsprings""" """Given the above, P(N (min. number of AaBb organisms)) in the kth generation""" # if confused, refer to https://www.youtube.com/watch?v=qIzC1-9PwQo&t=554s (jbstatistics explanation) # Binomial distribution # P(anything cross with Aa) = 1/2 Aa # Thus P (anything cross with AaBb) = 1/2 (Aa)*1/2 (Bb) = 1/4 AaBb # Binomial distribution to solve this problem def Mendel_2nd_Law(K, N): # let total offspring in the kth generation be T, where T = 2**k (each offspring in the kth generation has two offspring) T = 2**K P_AaBb = 0.25 # probability that an offspring will be AaBb in any generation that crosses with AaBb = 1/4 from math import comb # import function for combination # Binomial_Coefficient = comb(T, N) # T Choose N, choose N scenarios from a total of T scenario, Combination = (n!)/(r!(n-r)!) Cumulative_Prob = 0 # initialize for adding probability for i in range(N, T+1): # because at least N, so need to consider N+1, N+2, N+3...T, T+1 for python index issue Cumulative_Prob += comb(T, i) * (0.25**i) * (0.75**(T-i)) # P(success)^no. of successes needed * P(failure)^no.of failure, return one possible combination, * binomial coefficient to get all possible combinations return(Cumulative_Prob) ans = Mendel_2nd_Law(5, 9) print(ans) # remember to add the format
5cfe725254381ee79e7390b8a893bfbada496aba
AnnaTSW0609/Python_Practice
/030_Ordering_strings_lex_different_lengths.py
1,459
4
4
"""Ordering different strings of different lengths lexicographically""" with open("/Users/annatswater/Desktop/rosalind_lexv.txt", "r+") as f: for line in f: if line.isdigit() == True: number = int(line) else: char_lst = line.strip().split(" ") # assume alphabet already sorted alphabet = "" # self-defined alphabet # https://stackoverflow.com/questions/26579392/sorting-string-values-according-to-a-custom-alphabet-in-python for item in char_lst: alphabet += item def lexi_perm(char, num): # char = list of characters from itertools import product # native python function, not permutation but Cartesian product ans_lst = [] # an empty list for storing products(i), then outputting in order # https://stackoverflow.com/questions/3099987/generating-permutations-with-repetitions for x in range(1,num+1): for i in product(char, repeat = x):# permutations (list to permutate, length) ans = "".join(i) # product still return tuple, so conconated it into a string first ans_lst.append(ans) with open("/Users/annatswater/Desktop/ans_030.txt", "w+") as file: for y in sorted(ans_lst, key=lambda word: [alphabet.index(c) for c in word]): file.write(y + '\n') # write it to a file saves all the time waiting for it to print lexi_perm(char_lst,number)
afa0b05c48c004549c35e026d79a4e95a1d91801
AnnaTSW0609/Python_Practice
/001_Count_nucleotide_in_string.py
360
3.984375
4
# Rosalind Practice no.1 """Counting the number of each nucleotides in any given string""" DNA = "ATCGATCG" A_count = 0 T_count = 0 C_count = 0 G_count = 0 for letter in DNA: if letter == "A": A_count+=1 elif letter == "T": T_count+=1 elif letter == "C": C_count += 1 else: G_count += 1 print(A_count, C_count, G_count, T_count)
daeaf27666a944e52a214924ac0dcd1ce68023be
ZhaCong2017/Train
/KVectorToOne.py
1,796
3.5625
4
import random import sys import time class item: def __init__(self, a, b, c): self.num = a self.place = b self.position = c def left(x): return x * 2 def right(x): return x * 2 + 1 def minheapify(num, k): n = len(num) k += 1 l = left(k) r = right(k) minest = k if l <= n and num[l - 1].num < num[k - 1].num: minest = l if r <= n and num[minest - 1].num > num[r - 1].num: minest = r if minest != k: tmp = num[minest - 1] num[minest - 1] = num[k - 1] num[k - 1] = tmp minheapify(num, minest - 1) def buildheap(heap): i = len(heap) / 2 while i >= 0: minheapify(heap, i) i -= 1 k = 15 n = 200000 num = [[] for i in range(k)] for i in range(k): for j in range(n): num[i].append(random.randint(0, 100 * n)) num[i].sort() result = [] heap = [] start = time.clock() for i in range(k): heap.append(item(num[i][0], i, 0)) buildheap(heap) i = 0 while i < n * k: result.append(heap[0].num) if heap[0].position + 1 < n: tmp = item(num[heap[0].place][heap[0].position + 1], heap[0].place, heap[0].position + 1) else: tmp = item(sys.maxint, heap[0].place, heap[0].position + 1) heap[0] = tmp minheapify(heap, 0) i += 1 end = time.clock() print end - start # print num # print result print len(result), k * n for i in range(1, k * n): if result[i] < result[i - 1]: print "False" for i in range(k): for j in range(n): a = 0 for x in range(k): a += num[x].count(num[i][j]) b = result.count(num[i][j]) if a != b: print "F", a, b, num[i][j]
dd0f6bbde433352ec16cdf7fa17af004ce97435f
Satyam-detic/The-sparks-foundation-by-satyam-singh
/The sparks foundation task 1.py
3,540
3.921875
4
#!/usr/bin/env python # coding: utf-8 # Data Science & Business Analytics - Task 1: Prediction using Supervised Machine Learning # # Prepared by: Satyam singh # # Aim: To predict the score of a student when he/she studies for 9.25 hours. # In[ ]: import pandas as pd # for manipulating the dataset import numpy as np # for applying numerical operations on the observations import matplotlib.pyplot as plt # for plotting the graphs from sklearn.model_selection import train_test_split # for splitting the dataset into training and testing sets from sklearn.linear_model import LinearRegression # for building the linear regression model from sklearn.metrics import mean_squared_error,mean_absolute_error # for calculating mean squared error # Reading the dataset # Importing the raw dataset from GitHub: # In[2]: dataURL='https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv' # In[3]: df=pd.read_csv(dataURL) # In[4]: df.head() # # Plotting the relationship between hours and score: # In[5]: df.plot(x='Hours',y='Scores',style='x') plt.title('Hours vs Percentage') plt.xlabel('No. of hours') plt.ylabel('Percentage') plt.show() # # By plotting the relationship between the no. of hours studied and the score obtained, we see that there is linear relationship between these two variables. We'll now split the dataset into two parts, to create training and testing sets to build the model. # In[6]: x=df.iloc[:,0:1] y=df.iloc[:,1:] # # Splitting the dataset into training and test sets: # In[7]: x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,random_state=0) # Now we generate the Linear Regression Model by using the following commands: # In[8]: lr=LinearRegression() # In[9]: lr.fit(x_train,y_train) # In[10]: lr.score(x_train,y_train) # In[11]: lr.score(x_test,y_test) # In[12]: pred=lr.predict(x_test) # # After the model is trained, we need to check how accurate the model is. For this we use the mean squared error metric (from Numpy): # In[13]: print(mean_squared_error(pred,y_test)) # In[14]: print(np.sqrt(mean_squared_error(pred,y_test))) # # As we can see, the value of MSE is 4.509. Lower the MSE, higher the accuracy of our model. # Plotting the best fit line to ascertain the relationship betweeen the points in our scatter plot: # In[15]: line = lr.coef_*x + lr.intercept_ plt.scatter(x,y) plt.plot(x,line) plt.show() # # Predicting the values # Now we can use this model to predict upcoming values against the test set. It'll help us in ascertaining the accuracy of the model. # Comparing actual values with predicted values: # In[16]: df2=pd.DataFrame(y_test) df2 # In[23]: df2['Predicted values']=pred # In[26]: df2 # We know that the MSE is 4.509. The dataframe df2, shows this error, by comparing the predicted values against the actual values in the dataset. # # We have created our Linear Regression Model, with the help of which we'll able to predict the score of a child when the number of studying hours is set to 9.25. # # # The Linear Regression Model predicts a numerical variable, when a condition (in the form of numerical variable) is given. So, we'll set the number of hours to 9.25 and predict the score. # In[19]: hours= [[9.25]] # In[27]: prediction=lr.predict(hours) # # The model is able to predict the score which is 93.89272. This means, if a student studies for 9.25 hours, his score will be 93.89272. # In[ ]:
bd68be478ff7c80341c42663f2b39505c1ff311a
indrekots/py-challanges
/charswap/charswap.py
140
3.59375
4
def charswap(input): s = str(input) if len(str(s)) > 1: return s[len(s)-1] + s[1:len(s)-1] + s[0] else: return s
797b203334787440ad0555028dbceabd058e4548
pizzaismyname/KIJ_Programming_1
/DES/main.py
626
3.875
4
import encrypt as enc import decrypt as dec import initial as init key = input("Enter your key (only 8 chars will be used): ") plainText = input("Enter your plain text (only 8 chars will be used): ") key = init.key_check(key) true_len = len(plainText) # if init.key_check(key) == True: if len(plainText) < 8: plainText += '0'*(56//8-len(plainText)+1) elif len(plainText) > 8: plainText = plainText[:8] cipherText = enc.encrypt(key, plainText) print("Cipher text yang dihasilkan> %r" %cipherText) hasilDec = dec.decrypt(key, cipherText) print("Hasil dekripsi menghasilkan> ", hasilDec[:true_len])
d4a4a7a7a133af45077992a992e1a7998061734c
jonggyeong/network_programming
/hw02/hw2-1.py
375
3.578125
4
from random import randint player = 50 while True: coin = randint(1, 2) if player <= 0 or player >= 100: break else: if coin is 1: player = player + 9 else: player = player - 10 if player <= 0: print("플레이어가 돈을 모두 잃었습니다") else: print("플레이어가 100$를 땃습니다")
986dfb8cdc901efc3264c5ecc87a6327c101c603
alexwlchan/docstore
/src/docstore/tint_colors.py
3,080
3.640625
4
import collections import colorsys import math import os import subprocess import wcag_contrast_ratio as contrast def choose_tint_color_from_dominant_colors(dominant_colors, background_color): """ Given a set of dominant colors (say, from a k-means algorithm) and the background against which they'll be displayed, choose a tint color. Both ``dominant_colors`` and ``background_color`` should be tuples in [0,1]. """ # The minimum contrast ratio for text and background to meet WCAG AA # is 4.5:1, so discard any dominant colours with a lower contrast. sufficient_contrast_colors = [ col for col in dominant_colors if contrast.rgb(col, background_color) >= 4.5 ] # If none of the dominant colours meet WCAG AA with the background, # try again with black and white -- every colour in the RGB space # has a contrast ratio of 4.5:1 with at least one of these, so we'll # get a tint colour, even if it's not a good one. # # Note: you could modify the dominant colours until one of them # has sufficient contrast, but that's omitted here because it adds # a lot of complexity for a relatively unusual case. if not sufficient_contrast_colors: return choose_tint_color_from_dominant_colors( dominant_colors=dominant_colors + [(0, 0, 0), (1, 1, 1)], background_color=background_color, ) # Of the colors with sufficient contrast, pick the one with the # highest saturation. This is meant to optimise for colors that are # more colourful/interesting than simple greys and browns. hsv_candidates = { tuple(rgb_col): colorsys.rgb_to_hsv(*rgb_col) for rgb_col in sufficient_contrast_colors } return max(hsv_candidates, key=lambda rgb_col: hsv_candidates[rgb_col][2]) def from_hex(hs): """ Returns an RGB tuple from a hex string, e.g. #ff0102 -> (255, 1, 2) """ return int(hs[1:3], 16), int(hs[3:5], 16), int(hs[5:7], 16) def choose_tint_color_for_file(path): """ Returns the tint colour for a file. """ background_color = (1, 1, 1) cmd = ["dominant_colours", "--no-palette", "--max-colours=12", path] dominant_colors = [ from_hex(line) for line in subprocess.check_output(cmd).splitlines() ] colors = [ (r / 255, g / 255, b / 255) for r, g, b in dominant_colors ] return choose_tint_color_from_dominant_colors( dominant_colors=colors, background_color=background_color ) def choose_tint_color(*, thumbnail_path, file_path, **kwargs): # In general, we use the thumbnail to choose the tint color. The thumbnail # is what the tint color will usually appear next to. However, thumbnails # for animated GIFs are MP4 videos rather than images, so we need to go to # the original image to get the tint color. if file_path.endswith((".jpg", ".jpeg", ".gif", ".png")): return choose_tint_color_for_file(file_path, **kwargs) else: return choose_tint_color_for_file(thumbnail_path, **kwargs)
9a460dc921caa42cb760604514cbb58d34f964b4
potomatoo/TIL
/Programmers/kakao_행렬곱.py
239
3.65625
4
arr1 = [[1, 4], [3, 2], [4, 1]] arr2 = [[3, 3], [3, 3]] import numpy as np def solution(arr1, arr2): arr1 = np.array(arr1) arr2 = np.array(arr2) answer = arr1.dot(arr2) return answer.tolist() print(solution(arr1, arr2))
1dc7c897d287552e9404c7b70587e1b08d680588
potomatoo/TIL
/Programmers/kakao_포켓몬.py
211
3.75
4
def solution(nums): answer = set() N = len(nums) // 2 for num in nums: if len(answer) == N: return N answer.add(num) return len(answer) print(solution([3,3,3,2,2,4]))
8274eb756bae64f001447513fab7ad29b77b96b4
potomatoo/TIL
/Programmers/kakao_뉴스 클러스터링.py
1,389
3.671875
4
def find_set(s): new_s = dict() for i in range(len(s)-1): check = s[i] + s[i+1] if check[0].isalpha() and check[1].isalpha(): if check in new_s: new_s[check] += 1 else: new_s[check] = 1 return new_s def union_set(s1, s2, plus_dic): for key, value in s1.items(): if key in s2: plus_dic[key] = max(value, s2[key]) else: plus_dic[key] = value return plus_dic def subtract_set(s1, s2, subtract_dic): for key, value in s1.items(): if key in s2: subtract_dic[key] = min(value, s2[key]) return subtract_dic def solution(str1, str2): str1 = str1.upper() str2 = str2.upper() new_str1 = find_set(str1) new_str2 = find_set(str2) if not new_str1 and not new_str2: return 65536 plus_dic = dict() plus_dic = union_set(new_str1, new_str2, plus_dic) plus_dic = union_set(new_str2, new_str1, plus_dic) subtract_dic = dict() subtract_dic = subtract_set(new_str1, new_str2, subtract_dic) plus_sum = sum(plus_dic.values()) subtract_sum = sum(subtract_dic.values()) answer = int((subtract_sum / plus_sum) * 65536) return answer print(solution('FRANCE', 'french')) print(solution('handshake', 'shake hands')) print(solution('aa1+aa2', 'AAAA12')) print(solution('E=M*C^2', 'e=m*c^2'))
e4f38645b375838891d63be6bff367b00536f17e
potomatoo/TIL
/CodingTest with Python/그리디 & 구현/곱하기 혹은 더하기.py
641
3.71875
4
''' 각 자리가 숫자(0부터 9)로만 이루어진 문자열 S가 주어졌을 때, 왼쪽부터 오른쪽으로 하나씩 모든 숫자를 확인하며 숫자 사이에 'X' 혹은 '+'연산자를 넣어 결과적으로 만들어질 수 있는 가장 큰 수를 구하는 프로그램을 작성하시오, 단, +보다 x를 먼저 계싼하는 일반적인 방식과는 달리, 모든 연산은 왼쪽에서부터 순서대로 이루어집니다. ''' S = input() result = int(S[0]) for i in range(1, len(S)): if 0 <= result <= 1 or 0 <= int(S[i]) <= 1: result += int(S[i]) else: result *= int(S[i]) print(result)
0360b995ff8aa7150bde24e3252854ae4f77ad07
potomatoo/TIL
/Programmers/kakao_오픈채팅방.py
777
3.53125
4
def solution(record): answer = [] user_dic = dict() name_save = [] behavior_save = [] for i in range(len(record)): one = record[i].split() if one[0] == "Enter": user_dic[one[1]] = one[2] name_save.append(one[1]) behavior_save.append('님이 들어왔습니다.') elif one[0] == "Leave": name_save.append(one[1]) behavior_save.append('님이 나갔습니다.') elif one[0] == "Change": user_dic[one[1]] = one[2] for i in range(len(name_save)): answer.append(user_dic[name_save[i]] + behavior_save[i]) return answer print(solution(["Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"]))
7707f06eabc402f288406ebcd2f5497545f63d39
potomatoo/TIL
/Programmers/kakao_징검다리.py
571
3.53125
4
def solution(distance, rocks, n): answer = 0 start = 0 end = distance rocks.append(distance) rocks.sort() while start <= end: mid = (start+end) // 2 remove_rock = 0 remove_check = 0 for rock in rocks: if rock - remove_check < mid: remove_rock += 1 else: remove_check = rock if remove_rock > n: end = mid - 1 else: answer = mid start = mid + 1 return answer print(solution(25, [1, 19, 11, 21, 17], 1))
2f9a37635a3313a8dc7935a7fc627a317f42ae63
potomatoo/TIL
/Baekjoon/boj_삼성기출_모노미노도미노.py
1,350
3.578125
4
def go_right(y, x, t): if blue[y][x] == 3 or x == 9: if t == 1: board[y][x] = 3 blue[y][x-4] = 1 elif t == 2: board[y][x] = 3 board[y][x-1] = 3 blue[y][x - 4] = 1 blue[y][x - 5] = 1 elif t == 3: board[y][x] = 3 board[y-1][x] = 3 blue[y][x - 4] = 1 blue[y-1][x - 4] = 1 return go_right(y, x+1, t) def go_down(y, x, t): if board[y][x] == 3 or y == 9: if t == 1: board[y][x] = 3 green[y-4][x] = 1 elif t == 2: board[y][x] = 3 board[y][x-1] = 3 green[y-4][x] = 1 green[y-4][x-1] = 1 elif t == 3: board[y][x] = 3 board[y-1][x] = 3 green[y-4][x] = 1 green[y-5][x] = 1 return go_down(y+1, x, t) board = [[0 for _ in range(10)] for _ in range(10)] for y in range(10): for x in range(10): if y > 3 and x < 4: board[y][x] = 1 elif y < 4 and x > 3: board[y][x] = 2 elif y > 3 and x > 3: board[y][x] = 3 for z in range(10): print(board[z]) N = int(input()) blue = [[0 for _ in range(6)] for _ in range(4)] green = [[0 for _ in range(4)] for _ in range(6)] score = 0
321f48a2366bfb3e849d6ef172b36c30d214680e
potomatoo/TIL
/Programmers/kakao_짝지어 제거하기.py
294
3.5
4
def solution(s): stack = [] for i in range(len(s)): if stack: if stack[-1] == s[i]: stack.pop() continue stack.append(s[i]) if not stack: return 1 return 0 print(solution('abccaeeaba')) print(solution('cdcd'))
28aa75b38962e41c8404ce7ab3c43aa126a2e51c
potomatoo/TIL
/Programmers/kakao_숫자의 표현.py
326
3.546875
4
def solution(n): answer = 0 now = 1 while True: if now == n: break check = 0 for i in range(now, n): check += i if check >= n: break if check == n: answer += 1 now += 1 return answer+1 print(solution(15))
b3f67a0816c791043339e775b9099654f2db916f
sudhakar-mnsr/python_examples
/03/readfile.py
208
3.59375
4
total=0 count=0 inFile = open('grade.txt', 'r') grade = inFile.readline() while (grade): total = total + int(grade) count = count + 1 grade = inFile.readline() print ("The average is " + str(total))
a788d38d4029a32ea3d2d9c9d6baa0c7cae6cbe9
sudhakar-mnsr/python_examples
/06/line.py
364
3.5625
4
class Point: def __init__(self,xcor,ycor): self.xcor=xcor self.ycor=ycor def __str__(self): return str(self.xcor) +','+str(self.ycor) class Line: def __init__(self,p1,p2): self.p1=p1 self.p2=p2 def __str__(self): return str(self.p1) + '::' + str(self.p2) p1=Point(1,1) p2=Point(10,10) l1=Line(p1,p2) print l1
6991f595e2aa34f0335d11f975a0aad1ba33d19b
sudhakar-mnsr/python_examples
/01/list.py
199
3.53125
4
marks = [100,20,20,33,44,55] marks1 = [100,20,[20,33],44,55] string = ["hello"] print (marks1[2]) print (len(string)) str1 = ["hai","sudhakar"] str2 = ["hai","mnsr"] print (str1+str2) print (str1*4)
1d7920defc71e5b6ed9ff201546f7a62aca338f1
rubyclaguna/Intro-Python-II
/src/adv.py
3,596
3.640625
4
from room import Room from player import Player from item import Item # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."""), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air."""), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south."""), } # Link rooms together room['outside'].n_to = room['foyer'] room['foyer'].s_to = room['outside'] room['foyer'].n_to = room['overlook'] room['foyer'].e_to = room['narrow'] room['overlook'].s_to = room['foyer'] room['narrow'].w_to = room['foyer'] room['narrow'].n_to = room['treasure'] room['treasure'].s_to = room['narrow'] # # Main # # Make a new player object that is currently in the 'outside' room. player = Player("Ruby", room['outside']) rock = Item("Rock", "Just a rock.") sword = Item("Sword", "A magical sword.") potion = Item("Potion", "Restore's health.") rubies = Item("Rubies", "Not gold but still worth keeping.") scroll = Item("Scroll", "Left over by the previous adventurers.") room["outside"].items.append(rock) room["outside"].items.append(potion) room["foyer"].items.append(sword) room["overlook"].items.append(potion) room["overlook"].items.append(rock) room["narrow"].items.append(rubies) room["treasure"].items.append(scroll) # Write a loop that: # # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. # # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. directions = ['n', 's', 'e', 'w'] print(player.room) while True: cmd = input("Please enter a valid input : ") if cmd in directions: player.move(cmd) elif cmd == 'i': player.display_inventory() elif cmd == 'take rock': player.add_item(rock) player.room.take_item(rock) elif cmd == 'drop rock': player.drop_item(rock) player.room.add_items(rock) elif cmd == 'take sword': player.add_item(sword) player.room.take_item(sword) elif cmd == 'drop sword': player.drop_item(sword) player.room.add_items(sword) elif cmd == 'take potion': player.add_item(potion) player.room.take_item(potion) elif cmd == 'drop potion': player.drop_item(potion) player.room.add_items(potion) elif cmd == 'take rubies': player.add_item(rubies) player.room.take_item(rubies) elif cmd == 'drop rubies': player.drop_item(rubies) player.room.add_items(rubies) elif cmd == 'take scroll': player.add_item(scroll) player.room.take_item(scroll) elif cmd == 'drop scroll': player.drop_item(scroll) player.room.add_items(scroll) elif cmd == 'q': print("Thanks for Playing! :)") break else: print("Oops! Choose a valid input.")
a1a7268958c32a1ab11829c52b98b7b85e4a43c2
cnn911/tmp
/four_model.py
1,801
3.59375
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 16 20:40:33 2018 @author: Administrator """ ''' 状态模式: 当一个对象的状态改变时允许改变其行为,不同的状态就是不同的类 但是却是在同一个方法中实现 当一个对象内在状态改变是允许改变其行为, 这个对象看起来像是改变了类 ''' from state import curr,switch,stateful,State,behavior from state_machine import before,State @stateful class People(object): class Workday(State): default=True @behavior def day(self): print 'work' class weekday(State): @behavior def day(self): print 'week' people=People() while True: for i in xrange(1,8): if i==6: switch(people,People.weekday) if i==1: switch(people,People.Workday) people.day() class State: def writeprogram(self): pass class Work: def __init__(self): self.hour=9 self.current=Noonstate() def SetState(self,temp): self.current=temp def writeprogram(self): self.current.writeprogram(self) class Noonstate(State): def writeprogram(self,w): print 'noon working' if w.hour<13: print 'fun' else: print 'reset' class otherstate(State): def writeprogram(self,w): if w.hour<10: print 'haha' else: w.SetState(Noonstate()) w.writeprogram() if __name__ == '__main__': mywork=Work() mywork.hour=9 mywork.writeprogram() mywork.hour=14 mywork.writeprogram()
75139010a3d582a9b54a77cf3edb28cb3a399907
questsin/cheats
/cheatsheets/py/python.2. pandas (cheat sheet).py
2,089
3.515625
4
#http://pandas.pydata.org/ #Series – for one dimensional array #DataFrame – for 2 dimensional tables (and with multi-indexing can display more dimensions) import numpy as np import pandas as pd df=pd.read_csv('pupils.csv') df.head() df.sample(5) len(df) df.columns df.info() df = pd.read_csv(fname, parse_dates=['time']) df.to_csv('pupils2.csv', index = False) #Select * from df where index between 2 and 6 df[2:6] df['Name'] df[['Name','Age']][2:6] df.loc[2] # index 2 as series df.loc[2:2] # index 2 as dataframe df.loc[2:6] # indexes 2-6 df.loc[2:6:2] # even indexes 2-6 df.loc[2:2]['Age'] # Age where index=2 df.loc[1,'Age'] # Age where index=1 df.loc[1:13:2,'Age':'income':2] # odd rows from 1 to 13 and even cols from Age to income #Select * from df where Age>12 and Height > 130 df[(df['Age']>12) & (df['Height'] > 130)] #Insert into df values (‘eli’,4,’DF’,100,20,20,2000,4,4) df.loc[df.index.size]=['eli',4,'DF',100,20,20,2000,4,4] df.loc[df.index.size]=['eli',4,'DF',100,20,20,2000,4,4] #Insert into df select * from df2 df.append(df2) df.append(df2) #Insert new column with values (alter table df add Inc int; update df set Inc=income*2) df['Inc']=df['income']*2 df['Inc']=df['income']*2 #Update df set Age=20 where income>20000 df.loc[df['income']>20000,'Age']=20 df.loc[df['income']>20000,'Age']=20 for i,v in df.iterrows(): if v.Age > 10: df.loc[i,'Weight'] = 888 #Delete df where Age=6 df.drop(df['Age']==6,inplace=True) df.drop(df['Age']==6,inplace=True) df.describe() df.corr() #Select count(Name), sum(income) , max(Age) from df df.agg({'Name':'count', 'income':'sum' , 'Age':'max'}) df1=df.groupby(['Country','family persons']).count() import numpy as np df1 = pd.DataFrame(np.arange(10).reshape((5,2)), columns=['x', 'y'], index=['a', 'b', 'c', 'd', 'e']) df1 my_simple_series = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) my_dictionary = {'a' : 45., 'b' : -19.5, 'c' : 4444} my_second_series = pd.Series(my_dictionary) data['x'] = data['x'].astype('category').cat.codes data.select_dtypes(['category']).columns
2536d0e3b47cb9542c5344e9318e76debf574ba7
baudm/ee298z
/hw2/transforms.py
1,897
3.5625
4
#!/usr/bin/env python3 import numpy as np def corrupt_mnist_img(rng, img, value): """Corrupt a single MNIST image. Note that the image itself is MODIFIED. :param rng: instance of numpy.random.RandomState :param img: image to modify. ndarray or compatible :param value: pixel value to use for corrupting the image :return: modified image """ # Choose square size s = rng.randint(7, 15) # Choose top-left corner position x = rng.randint(0, 29 - s) y = rng.randint(0, 29 - s) # Draw square img[..., y:y + s, x:x + s] = value # Return object for convenience return img def corrupt_mnist_copy(x_train, value=255, seed=0): """Create a corrupted copy of the MNIST dataset :param x_train: ndarray of images. Shape: (N, ..., H, W) :param value: pixel value to use for corrupting the image :param seed: seed to use for the random number generator :return: ndarray of corrupted images :return: ndarray of corrupted images """ rng = np.random.RandomState(seed) corrupted_x_train = x_train.copy() for img in corrupted_x_train: corrupt_mnist_img(rng, img, value) return corrupted_x_train def corrupt_mnist_generator(x_train, value=255, seed=0): """Generator version of `corrupt_mnist_copy()` :param x_train: :param value: :param seed: :return: """ rng = np.random.RandomState(seed) while True: for img in x_train: yield corrupt_mnist_img(rng, img.copy(), value) class CorruptMNIST(object): """PyTorch transform for corrupting MNIST images Use after ToTensor and before Normalize. """ def __init__(self, seed=0): self._rng = np.random.RandomState(seed) def __call__(self, img): return corrupt_mnist_img(self._rng, img, 1.) def __repr__(self): return self.__class__.__name__ + '()'
e1e4de4ad068dba1d8a54aa67abc336b41fc79cf
Avraj19/monster_inc_uni
/monster_class.py
386
3.546875
4
class Monster(): def __init__(self, name, tax_num, monster_type): self.name = name.title() self.tax_num = tax_num self.monster_type = monster_type.title() # def get_tax_num(self): # return self.__tax_num # # def set_tax_num(self, new_num): # self.__tax_num = new_num # return f'New tax num for {self.name} is {new_num}'
ce328ddfda4122fd86c3343bbdf3374ba56e7a42
AyanUpadhaya/CodeBase
/jsonworkout/movieapi/application.py
889
3.515625
4
# Get tv show data using python and api # site - tvmaze.com/api # script by - Ayan Upadahya # contact -> ayanU881@gmail.com # twitter -> https://twitter.com/ayanupadhaya96 # GitHub -> github.com/AyanUpadhaya # Youtube -> Code Tech :https://www.youtube.com/channel/UCsjnvE4i5Z-VR-lWhODX99w import requests import json print('Enter your Search:') search=input() url="https://api.tvmaze.com/singlesearch/shows?q="+search response = requests.get(url,timeout=6) if response.status_code==200: data= json.loads(response.text) print('Show Name: '+data['name']) print('Language: '+data['language']) print('Genres: '+str(data['genres'])) print('Status: '+data['status']) print("Premiered: "+data['premiered']) print("Rating: "+str(data['rating']['average'])) print('Summary: '+data["summary"]) with open('moviedata.json','w') as f: json.dump(data,f) else: print(f"Error {response.status_code}")
e4f8cfc4dd1a6c269887a1cce00f1183e69bc624
AyanUpadhaya/CodeBase
/Matplotlib/firstplot.py
418
4.03125
4
# matplotlib import matplotlib #print(matplotlib.__version__) #pyplot import matplotlib.pyplot as plt import numpy as np xpoints = np.array([1,8]) ypoints = np.array([3,300]) plt.plot(xpoints,ypoints) plt.show() #By default, the plot() function draws a line from point to point. # ~ Parameter 1 is an array containing the points on the x-axis. # ~ Parameter 2 is an array containing the points on the y-axis.
c3a85d2145abbe3ba9271803d94e2b24d57f72b7
rupajsoni/x9115arn
/hw/code/3/PokerHand.py
4,710
3.71875
4
"""This module contains code from Think Python by Allen B. Downey http://thinkpython.com Copyright 2012 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from Card import * frequency_of_poker_hands = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0} class PokerHand(Hand): def suit_hist(self): """Builds a histogram of the suits that appear in the hand. Stores the result in attribute suits. """ self.suits = {} for card in self.cards: self.suits[card.suit] = self.suits.get(card.suit, 0) + 1 def has_flush(self): """Returns True if the hand has a flush, False otherwise. Note that this works correctly for hands with more than 5 cards. """ self.suit_hist() for val in self.suits.values(): if val >= 5: return True return False def rank_hist(self): """Builds a histogram of the ranks that appear in the hand. Stores the result in attribute ranks. """ self.ranks = {} for card in self.cards: self.ranks[card.rank] = self.ranks.get(card.rank, 0) + 1 #print self.ranks def has_pair(self): """Returns True if the hand has a pair, False otherwise. """ if self.count_pairs() >= 1: return True return False def has_twopair(self): """Returns True if the hand has a pair, False otherwise. """ if self.count_pairs() >= 2: return True return False def count_pairs(self): """Returns True if the hand has two pairs, False otherwise. """ num_of_pairs = 0 for rank in self.ranks: if self.ranks[rank] >= 2: num_of_pairs = num_of_pairs + 1 return num_of_pairs def has_three_of_a_kind(self): """Returns True if the hand has three of a kind, False otherwise. """ for rank in self.ranks: if self.ranks[rank] >= 3: return True return False def has_straight(self): """Returns True if the hand has straight, False otherwise. """ for rank in self.ranks: if rank + 1 in self.ranks and rank + 2 in self.ranks and rank + 3 in self.ranks and rank + 4 in self.ranks: return True #for 10, J, Q, K A if 1 in self.ranks and 10 in self.ranks and 11 in self.ranks and 12 in self.ranks and 13 in self.ranks: return True return False def has_full_house(self): """Returns True if the hand has Full House, False otherwise. """ if self.has_three_of_a_kind() and self.count_pairs() >= 2: return True return False def has_four_of_a_kind(self): """Returns True if the hand has 4 of a kind, False otherwise. """ for rank in self.ranks: if self.ranks[rank] >= 4: return True return False def has_straight_flush(self): """Returns True if the hand has straight flush, False otherwise. """ if self.has_flush() and self.has_straight(): return True return False hand_order = [has_straight_flush, has_four_of_a_kind, has_full_house, has_flush, has_straight, has_three_of_a_kind, has_twopair, has_pair] def classify(self): for i in range(8): if self.hand_order[i](self): frequency_of_poker_hands[i] += 1 break if __name__ == '__main__': #deal the cards and classify the hands for i in range(1000000): #make a deck deck = Deck() deck.shuffle() hand = PokerHand() deck.move_cards(hand, 5) hand.sort() hand.rank_hist() hand.suit_hist() hand.classify() print [float(value)/10000 for value in frequency_of_poker_hands.values()] #print frequency_of_poker_hands # hand = PokerHand() # card1 = Card(1, 1) # card2 = Card(2, 1) # card3 = Card(3, 1) # card4 = Card(0, 1) # card5 = Card(1, 5) # hand.add_card(card1) # hand.add_card(card2) # hand.add_card(card3) # hand.add_card(card4) # hand.add_card(card5) # hand.rank_hist() # hand.suit_hist() # print hand # print hand.has_three_of_a_kind()
585cbda391510437797a5e677fc50b6c27ed8462
rupajsoni/x9115arn
/hw/code/3/bparadox.py
477
3.75
4
from random import randint def has_duplicates(list): list2 = list[:] list2.sort() for i in range(len(list2) - 1): if list2[i] == list2[i + 1]: return True return False def create_birthday_list(): birthday_list = [] for i in range(23): month = randint(1, 12) day = randint(1, 31) birthday_list.append(str(month) + str(day)) return birthday_list print has_duplicates(create_birthday_list())
6057d088cfad0576c06af5673cc254eeddcdf475
JustNulls/text-similarity
/sim/tools/similarity.py
5,259
3.515625
4
#! -*- coding: utf-8 -*- """ Calculate Similarity """ # Author: DengBoCong <bocongdeng@gmail.com> # # License: MIT License from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from typing import Any def euclidean_dist(emb1: np.ndarray, emb2: np.ndarray, axis=-1) -> Any: """ Calculate the Euclidean distance between feature vectors :param emb1: shape = [..., feature] :param emb2: shape = [..., feature] :param axis: dimension of effect :return: Euclidean distance """ return np.sqrt(np.square(emb1 - emb2).sum(axis=axis)) def cosine_similarity(emb1: np.ndarray, emb2: np.ndarray, dist: bool = False, axis: int = -1) -> Any: """ calculate the cosine similarity score between feature vectors :param emb1: shape = [..., feature] :param emb2: shape = [..., feature] :param dist: whether to return the cosine distance (after normalization), [0, 1] :param axis: dimension of effect :return: Cosine similarity """ mod = np.linalg.norm(emb1, axis=axis) * np.linalg.norm(emb2, axis=axis) if np.all(mod == 0): raise RuntimeError("cosine similarity divisor is zero") cos = np.sum(emb1 * emb2, axis=axis, dtype=float) / mod return (1 - cos) / 2.0 if dist else cos def manhattan_dist(emb1: np.ndarray, emb2: np.ndarray, axis: int = -1) -> Any: """ calculate the Manhattan distance between feature vectors :param emb1: shape = [..., feature] :param emb2: shape = [..., feature] :param axis: dimension of effect :return: Manhattan distance """ return np.sum(np.abs(emb1 - emb2), axis=axis) def minkowsk_dist(emb1: np.ndarray, emb2: np.ndarray, p: int, axis: int = -1) -> Any: """ calculate the Minkowsk distance between feature vectors :param emb1: shape = [..., feature] :param emb2: shape = [..., feature] :param p: Norm :param axis: dimension of effect :return: Minkowsk distance """ tmp = np.sum(np.power(emb1 - emb2, p), axis=axis) return np.power(tmp, 1 / p) def hamming_dist(emb1: np.ndarray, emb2: np.ndarray, axis: int = -1) -> np.ndarray: """ calculate the Hamming distance between feature vectors :param emb1: shape = [feature,] :param emb2: shape = [feature,] :param axis: dimension of effect :return: Hamming distance """ if len(emb1.shape) > 1 or len(emb2.shape) > 1: raise RuntimeError("the shape of emb1 and emb2 must be [feature,]") avg1, avg2 = np.mean(emb1, axis=axis), np.mean(emb2, axis=axis) binary1, binary2 = np.where(emb1 < avg1, 0, 1), np.where(emb2 < avg2, 0, 1) return len(np.nonzero(binary1 - binary2)[0]) def jaccard_similarity(emb1: np.ndarray, emb2: np.ndarray) -> float: """ calculate the Jaccard similarity between feature vectors :param emb1: shape = [feature,] :param emb2: shape = [feature,] :return: Jaccard similarity """ up = np.double(np.bitwise_and((emb1 != emb2), np.bitwise_or(emb1 != 0, emb2 != 0)).sum()) down = np.double(np.bitwise_or(emb1 != 0, emb2 != 0).sum()) d1 = (up / down) return d1 def pearson_similarity(emb1: np.ndarray, emb2: np.ndarray, axis: int = -1) -> np.ndarray: """ calculate the Pearson similarity between feature vectors :param emb1: shape = [..., feature] :param emb2: shape = [..., feature] :param axis: dimension of effect :return: Pearson similarity """ diff1, diff2 = emb1 - np.mean(emb1, axis=axis)[..., np.newaxis], emb2 - np.mean(emb2, axis=axis)[..., np.newaxis] up = np.sum(diff1 * diff2, axis=axis) down = np.sqrt(np.sum(np.square(diff1), axis=axis)) * np.sqrt(np.sum(np.square(diff2), axis=axis)) return np.divide(up, down) def mahalanobis_dist(emb1: np.ndarray, emb2: np.ndarray) -> list: """ calculate the Mahalanobis distance between feature vectors :param emb1: shape = [feature,] :param emb2: shape = [feature,] :return: Mahalanobis distance """ x = np.vstack([emb1, emb2]) xt = x.T si = np.linalg.inv(np.cov(x)) n = xt.shape[0] d1 = [] for i in range(0, n): for j in range(i + 1, n): delta = xt[i] - xt[j] d = np.sqrt(np.dot(np.dot(delta, si), delta.T)) d1.append(d) return d1 def kl_divergence(emb1: np.ndarray, emb2: np.ndarray, axis: int = -1) -> np.ndarray: """ calculate the KL divergence between feature vectors :param emb1: shape = [..., feature] :param emb2: shape = [..., feature] :param axis: dimension of effect :return: KL divergence """ return np.sum(emb1 * np.log(np.divide(emb1, emb2)), axis=axis) def levenshtein_dist(str1: str, str2: str): """ Calculate the edit distance between two strings :param str1: string :param str2: string :return: Edit distance """ matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)] for i in range(1, len(str1) + 1): for j in range(1, len(str2) + 1): if str1[i - 1] == str2[j - 1]: d = 0 else: d = 1 matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + d) return matrix[len(str1)][len(str2)]
9cefb7e86c7020b6aad4322e4610edc544b0d8d5
jupibel95/factorial
/factorial.py
189
4.0625
4
numero=int(input("ingrese un numero: ")) factorial = 1 for n in range(1, (numero+1)): factorial = factorial * n print ("El factorial de {0} es: {1}".format(numero, factorial))
cfb447e6ca85ff206706b615bd728a1578ea0333
mohammed-ibrahim/rcfiles
/programs/shortest_path.py
1,830
3.875
4
import sys class Graph(): def __init__(self, V): self.number_of_vertices = V self.graph = [[0 for column in range(self.number_of_vertices)] for row in range(self.number_of_vertices)] # this part can be optimised def find_min_distance(self, distance, already_visited): min = sys.maxint min_index = 0 for i in range(self.number_of_vertices): if already_visited[i] == False and min > distance[i]: min = distance[i] min_index = i return min_index def find_shortest_path(self, src): distance = [sys.maxint] * self.number_of_vertices already_visited = [False] * self.number_of_vertices distance[src] = 0 for i in range(self.number_of_vertices): min_index = self.find_min_distance(distance, already_visited) already_visited[min_index] = True for j in range(self.number_of_vertices): if already_visited[j] == False and self.graph[min_index][j] > 0: if distance[j] > distance[min_index] + self.graph[min_index][j]: distance[j] = distance[min_index] + self.graph[min_index][j] self.printSolution(distance) def printSolution(self, dist): print "Vertex Distance from Source" for node in range(self.number_of_vertices): print("Node: %d distance: %d", node, dist[node]) a = [[0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2], [0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, 0, 0], [0, 0, 4, 14, 10, 0, 2, 0, 0], [0, 0, 0, 0, 0, 2, 0, 1, 6], [8, 11, 0, 0, 0, 0, 1, 0, 7], [0, 0, 2, 0, 0, 0, 6, 7, 0] ]; graph = Graph(9) graph.graph = a graph.find_shortest_path(0)
5117399f4d9488c656de9d3d830b2f423be57e69
mballarin97/RL4Pandemic
/Graph_Evolution/Graph.py
10,886
3.578125
4
import numpy as np import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import matplotlib.pyplot as plt class SimpleNode: """Basic Node in a Graph""" def __init__(self, identifier, position): """Create a node named @identifier, located at 2D @position (only matters for plotting) Parameters ---------- identifier : hashable Name of the node position : ndarray of shape (2,) 2D position of the node, used for plotting """ self.id = identifier self.position = position self.connectedTo = {} #Dictionary of pairs (instance of Node, weight of connection) #Node local information self.degree = 0 self.total_weight = 0 #Plotting parameters self.color = "#FFFFFF" #Color (default is white) self.isolated = False #If True, draw a border around the node def addNeighbour(self, to, weight=0): """Add a single connection from @self to the Node @to, weighted by @weight. Parameters ---------- to : instance of SimpleNode (or any derived class) Node to connect to weight : float, optional Weight of connection, by default 0 """ self.connectedTo[to] = weight self.degree += 1 self.total_weight += weight def removeNeighbour(self, to): """Remove any connection (to and from) node @self and node @to. Parameters ---------- to : instance of SimpleNode (or any derived class) Node to disconnect from. The connection between @self and @to and the one from @to and @self are removed. Returns ------- w : float Weight of removed connection """ if (to in self.connectedTo): self.degree -= 1 w = self.connectedTo[to] self.total_weight -= w del self.connectedTo[to] return w else: return 0 def __str__(self): """Return the string representation of the Node, reporting all of its connections.""" return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) def getConnections(self): """Return list of identifiers of nodes connected to @self""" return [x.id for x in self.connectedTo.keys()] def getWeights(self): """Return the list of weights of connections from @self to other nodes""" return list(self.connectedTo.values()) def getId(self): """Return the @self identifier""" return self.id class Graph: """Represents a collections of Nodes connected by weighted edges""" def __init__(self, adjacency = None, positions = None, node_type = SimpleNode): """Create a new empty graph, with nodes instantiated from @node_type class (must inherit from SimpleNode). If a (N,N) @adjacency matrix is provided, along with (N,) positions, the graph is automatically filled with N nodes, following this specification. Parameters ---------- adjacency : ndarray of shape (N,N), optional Adjacency matrix for initialization, by default None positions : ndarray of shape (N,), optional 2D positions of nodes (for plotting), by default None node_type : class inheriting from SimpleNode, optional Class used for instantiating nodes, by default SimpleNode """ self.vertList = {} #List of pairs (node identifier, node instance) self.numVertices = 0 self.node_type = node_type #Node type self.plotting = False #Whether the graph has been plotted at any time. Needed to open the GUI interface only once. #Initialization if (adjacency is not None) and (positions is not None): #Construct graph from matrix representation self.fromAdjacency(np.array(adjacency), np.array(positions)) def addVertex(self, key, pos, **kwargs): """Add a vertex with identifier @key and 2D pos @pos. Parameters ---------- key : hashable Node identifier pos : ndarray of shape (2,) Node's position (for plotting) Returns ------- node_type The newly created node instance. """ self.numVertices += 1 newVertex = self.node_type(key, pos, **kwargs) self.vertList[key] = newVertex return newVertex def getVertex(self, id): """Return the node with identifier @id""" if id in self.vertList: return self.vertList[id] else: return None def addEdge(self, fromVertex, toVertex, weight=0): """Add an edge from @fromVertex to @toVertex (if they are identifiers of existing nodes in the graph) weighted by @weight""" if (fromVertex in self.vertList) and (toVertex in self.vertList): self.vertList[fromVertex].addNeighbour(self.vertList[toVertex], weight) else: raise ValueError("Cannot create an edge if one or both of the extrema do not exist") def addSymmetricEdge(self, fromVertex, toVertex, weight=0): """Add two edges, representing a 'undirected' link: one from @fromVertex to @toVertex, and the other from @toVertex to @fromVertex (if they are valid identifiers of nodes in the graph). They are both weighted by @weight""" if (fromVertex in self.vertList) and (toVertex in self.vertList): self.vertList[fromVertex].addNeighbour(self.vertList[toVertex], weight) self.vertList[toVertex].addNeighbour(self.vertList[fromVertex], weight) else: raise ValueError("Cannot create an edge if one or both of the extrema do not exist") def getVertices(self): """Returns all identifiers of nodes in the graph""" return self.vertList.keys() def __contains__(self, id): return id in self.vertList def __iter__(self): return iter(self.vertList.values()) def __len__(self): return self.numVertices def __str__(self): return '\n'.join([str(node) for node in self.vertList.values()]) def fromAdjacency(self, adjacency, positions): """Fill the graph from an @adjacency matrix, positioning the nodes at @positions. Parameters ---------- adjacency : ndarray of shape (N,N) Adjacency matrix positions : ndarray of shape (N,) Positions of nodes (for plotting) """ #Check adjacency to be a square 2D matrix a_shape = adjacency.shape pos_shape = positions.shape assert len(a_shape) == 2, "Adjacency matrix must be 2D" assert len(pos_shape) == 2, "Positions must be a 2D array" assert a_shape[0] == a_shape[1], "Adjacency matrix must be a square matrix" N = a_shape[0] assert (pos_shape[0] == N) and (pos_shape[1] == 2), "Positions matrix must be of shape (N,2)" #Add vertices for i, pos in enumerate(positions): self.addVertex(i, pos) #Add edges for i, row in enumerate(adjacency): for j, weight in enumerate(row): if weight != 0: self.addEdge(i, j, weight=weight) def plot(self, nodeSize=1): """Plot the graph with pyqtgraph. @nodeSize is the dimension of nodes in the plot""" if not self.plotting: self.plotting = True #Create new plot pg.setConfigOptions(antialias = True) self.w = pg.GraphicsWindow() #Create a window self.w.setWindowTitle('Graph plot') self.v = self.w.addViewBox() self.v.setAspectLocked() self.g = pg.GraphItem() self.v.addItem(self.g) #Update plot N = len(self.vertList) #number of vertices positions = np.zeros((N, 2)) edges = [] weights = [] colors = [] borderColors = [] for i, node in enumerate(self.vertList.values()): positions[i] = node.position new_edges = [[i, j] for j in node.getConnections()] edges.extend(new_edges) weights.extend(node.getWeights()) colors.append(node.color) if node.isolated: borderColors.append(pg.mkPen(color=(0,0,255), width=5)) #Blue border else: borderColors.append(pg.mkPen(color=(255,255,255), width=5)) #White border lines = plt.cm.rainbow(np.array(weights), bytes=True) self.g.setData(pos=positions, adj=np.array(edges, dtype=int), pen=lines, size=nodeSize, symbol=['o' for i in range(N)], symbolBrush=colors, symbolPen=borderColors, pxMode=False) #pen=lines #symbolSize=500, #If size is too small, some nodes have a weird red square in the background for some reason def test_Graph(): #For testing purposes adj_matrix = np.array([[0,1,0,0,0], [1,0,1,0,0], [0,1,0,1,1], [0,0,1,0,1], [0,0,1,1,0]]) positions = np.array([[0.5,1], [0,0], [1,0], [2,0], [1.5,0.5]]) g = Graph(adj_matrix, positions) #Verify structure assert g.getVertex(0).getConnections() == [1] assert g.getVertex(1).getConnections() == [0, 2] assert g.getVertex(2).getConnections() == [1, 3, 4] assert g.getVertex(3).getConnections() == [2, 4] assert g.getVertex(4).getConnections() == [2, 3] #Verify degrees assert g.getVertex(0).degree == 1 assert g.getVertex(1).degree == 2 assert g.getVertex(2).degree == 3 assert g.getVertex(3).degree == 2 assert g.getVertex(4).degree == 2 if __name__ == "__main__": #Create a simple graph and plot it adj_matrix = np.array([[0,.1,0,0,0], [.1,0,1,0,0], [0,1,0,1,1], [0,0,1,0,1], [0,0,1,1,0]]) positions = np.array([[0.5,1], [0,0], [1,0], [2,0], [1.5,0.5]]) g = Graph(adj_matrix, positions) g.plot(.2) input("Press ENTER to exit...")
6453c83420fdafc7707c475b649c8bd918a3bdd5
alpablo11/Python---V1
/23.Fonksiyonlar.py
1,851
3.921875
4
# AAI Company - Python #! FONKSİYONLAR #! Fonksiyonun Tanımlanması ve Çağırılması: # Fonksiyon tanımlayacağımız zaman kodumuza def ile başlarız. # Ve fonksiyonu print ile değil adı ile çağırırız. # İsterseniz örnekle pekiştirelim; def alperaybakindustries(): print("Alper Aybak\nYazılım\nElektrik-Elektronik Mühendisliği") alperaybakindustries() # # Çıktımız : # Alper Aybak # Yazılım # Elektrik-Elektronik Mühendisliği # Sanırım şimdi eksik kalan taşlar yerine oturmuştur. # Örnekle devam edelim; def aai_company(): ad = "Alper Aybak" depertman = "Yazılım" maas = 100000 print("İsim: {}\nDepertman: {}\nMaaş: {}".format(ad,depertman,maas)) aai_company() # Çıktımız : # İsim: Alper Aybak # Depertman: Yazılım # Maaş: 100000 # Biraz daha ilerieyelim ve örneklere devam edelim; #! Belirli aralıkta girdiğimiz sayıları toplama kodu: def topla(x:list): toplam = 0 for i in x: toplam += i return toplam # Fonksiyona geri dön anlamına gelir. liste = [i for i in range(1,12)] print(topla(liste)) # Çıktımız ==> 66 # İsterseniz kodumuzu açıklayalım; # topla adında bir fonksiyon oluşturdum ("def" ile). Başlangıç olarak toplama 0 değerini verdim x'e i değerini atadım ve her severinde toplam+i kadar artmasını istedim # return parametresi ile toplama işlemine geri dondüm verilerimi girmek için liste oluşturdum. print içerisindeki topla() fonskiyonunu çağırdım ve yazdırdım. # Sanırım şimdi tam anlamıya kafamıza oturmuştur. # İsterseniz burada duralım ve diğer dersimizde daha da pekiştirmek için örnek uygulamalar yazalım. # Anlaşılmayan yerler olursa iletişime geçmeyi unutmayın # Diğer derste görüşmek üzere...
ab5a1b878009397fba44735bcd8979940998b149
alpablo11/Python---V1
/24.Fonksiyonlar Örnek Uygulama.py
2,234
3.703125
4
# AAI Company - Python # Fonksiyonlar ile İlgili Örnek Uygulamalar : #! Asal Sayı Sorgulama: def asal_mi(a: int): dogrulama = "Sayı Asal" if a == 2: return dogrulama # return ==> Geri Dön elif (a % 2 == 0): dogrulama = "Sayı Asal Değil" # Eğer sayı çiftse asal olmayacağı için False veri tipini yolladık. if dogrulama: # Değer False değilse kontrole geçelim for n in range(3, int(a / 2)): if (a % n == 0): print(a, "Sayısının", n, "Sayısına Bölümü:", a / n, "Kalan ise 0'dır.") dogrulama = "Sayı Asal Değil" break return dogrulama a = asal_mi(11) print(a) # Çıktımız ==> Sayı Asal a = asal_mi(68) print(a) # Çıktımız : # 68 Sayısının 4 Sayısına Bölümü: 17.0 Kalan ise 0'dır. # Sayı Asal Değil #! Kesişim Kümesi Bulan Fonksiyon: N = {11,21,"N","NA","Aybak",232,423,544,566,45,22,2,71} A = {13,34,345,3,"Alper","AAI",213,11,2,12,"NA","A"} def kesisim( N: set, A: set): kesisim_kumesi = set() for N_eleman in N: for A_eleman in A: if (N_eleman == A_eleman): kesisim_kumesi.add(N_eleman) if kesisim_kumesi: return kesisim_kumesi else: return False print(kesisim(N,A)) # Çıktımız ==> {2, 11, 'NA'} #! Faktoriyel Hesaplama: def factoriel(numara): faktoriyel=1 for i in range(1,numara+1): faktoriyel*=i print("Faktoriyel: {}".format(faktoriyel)) factoriel(11) # Çıktımız ==> Faktoriyel: 39916800 #! Eğer print kısmını koşuldan çıkarmazsak o sayıya gelene kadar ki yerleri çıktı alırız. # İsterseniz bir de öyle bakalım; def factoriel(numara): faktoriyel=1 for i in range(1,numara+1): faktoriyel*=i print("Faktoriyel: {}".format(faktoriyel)) factoriel(11) # Çıktımız : # Faktoriyel: 1 # Faktoriyel: 2 # Faktoriyel: 6 # Faktoriyel: 24 # Faktoriyel: 120 # Faktoriyel: 720 # Faktoriyel: 5040 # Faktoriyel: 40320 # Faktoriyel: 362880 # Faktoriyel: 3628800 # Faktoriyel: 39916800
d3c232907262b0df29e4272a77714bb6d201f302
wpdud94/pre-education
/quiz/pre_python_11.py
330
3.609375
4
"""11. 최대공약수를 구하는 함수를 구현하시오 예시 <입력> print(gcd(12,6)) <출력> 6 """ def gcd(x, y): if x < y: minnum = x elif x > y: minnum = y for i in range(minnum, 0, -1): if x % i == 0 and y % i == 0: return i break print(gcd(12, 6))
a29f98fed786467391ee6eb9d535e80ead19acfc
braja535/LABFramework
/Implementation/srtmodfier.py
4,354
3.859375
4
import datetime import re import string import os """ We opened input file in readmode and then applying pattern on each line and if pattern found apply "linemodification()" function on each line. linemodifcation function apply regular expression on line and find all the occurances of pattern in line and returns list . then we will replace total string with new string as "time" with "modifed time" on each occurance modification of time is done with "timemodifier_string()" --(have 2 arguments as string with time, and timegap ) and timegap can be get with "timediff()" function else if pattern not found fetched line will be written to the new file """ pattern = re.compile("\d+:\d+:\d+") # These line are enhances for Object oriented programmings #def __init__(self,actual_time,existing_time): # self.actual_time_loc = actual_time # self.existing_time_loc = existing_time # self.difference = self.actual_time_loc - self.existing_time_loc def timediff(): global difference_time timegap_condition =raw_input("Do you have time difference in seconds(Yes/No) : ") if timegap_condition.upper() in ['Y','YES'] : difference_time = input("Enter time gap in seconds (to create delay in display enter as negative number): ") return difference_time else : actual_time = datetime.datetime.strptime(raw_input("Enter actual Subtitle location (HH:MM:SS format): ").strip(),"%H:%M:%S") existing_time = datetime.datetime.strptime(raw_input("where you want to keep your Subtitle in location (HH:MM:SS format): ").strip(),"%H:%M:%S") if actual_time < existing_time : difference_time = actual_time - existing_time else : difference_time = existing_time - actual_time return difference_time.total_seconds() def linemodification(line): strings = pattern.findall(line) for a in strings: line = string.replace(line,a,timemodifier_string(a,timegap)) return line #iterobj = pattern.finditer(line) #for a in iterobj :# #str.replace(line,a.group(),addtime_string(a.group(),timegap)) def timemodifier_string(date_as_string,timegap): try: datestring = datetime.datetime.strftime(datetime.datetime.strptime(date_as_string,"%H:%M:%S") + datetime.timedelta(seconds=timegap),"%H:%M:%S") except : datestring = date_as_string return datestring def main(): inputfile = raw_input("Enter input file name : ") save_path = r"C:\Users\badan\Desktop\\" outputfile = os.path.join(save_path, inputfile + "_new.srt") infsrt = open(inputfile,'r') opfsrt = open(outputfile,'w') global timegap timegap = timediff() for eachline in infsrt.xreadlines(): if pattern.match(eachline): opfsrt.write(linemodification(eachline)) else : opfsrt.write(eachline) infsrt.close() opfsrt.close() if __name__ == '__main__' : main() ###################################################################################################################### # ROUGH WORK for Reference # ###################################################################################################################### """ datetime.datetime.strftime(datetime.datetime.strptime(match.group(),"%H:%M:%S") + datetime.timedelta(seconds=35),"%H:%M:%S") datetime.datetime.now().time().strftime("%H:%M:%S") datetime.datetime.strptime("23:40:15","%H:%M:%S") datetime.datetime.now() - datetime.timedelta(seconds=35) datetime.datetime.strptime(,"%H:%M:%S")+datetime.timedelta(seconds=35) a = rex.finditer("00:00:58,000 --> 00:01:00,640") for match in a : datetime.datetime.strptime(match.group(),"%H:%M:%S") + datetime.timedelta(seconds=35) ef addtime(line) pattern = re.compile("\d+:\d+:\d+") a = rex.finditer(line) for match in a : timestrings = datetime.datetime.strftime(datetime.datetime.strptime(match.group(),"%H:%M:%S") + datetime.timedelta(seconds=35),"%H:%M:%S") """ #######################################################################################################################
db6624eed03b2956d99071a3db39ee291ca8d627
glennpinkerton/csw_master
/csw/python/course/arith_print.py
194
4.03125
4
print ("hello world " + str(2 * 6) + " goodbye") var1 = 1.23 ** 1.23 print ("var1 " + str(var1)) var2 = "This is var2 " var3 = 2 * 3 / 4.0 var4 = "This is var3 " print (var4 + str(var3))
ccb8abaeaca67490627f093da16eb5d6e3b53c7c
Poskj/CP3-Thammanoon-Kitlertphairoj
/Exercise 8.py
1,005
3.609375
4
print("---Welcome to Posh's Gift Shop---") print("----Please Login into System----") usernameInput = input("Username : ") passwordInput = input("Password : ") if usernameInput == "Thammanoon" and passwordInput == "6116" : print("Welcome!") print("---Total Goods List---") print(" 1. Floral Candle : 442 coins") print(" 2. Candy Bouquet : 554 coins") print(" 3. Cloche Hat : 468 coins") print(" 4. Red Scarf : 288 coins") print(" 5. Cotton Shirt : 241 coins") GoodsNumber = int(input("Choose Goods Number :")) if GoodsNumber == 1: price = 442 if GoodsNumber == 2: price = 554 if GoodsNumber == 3: price = 468 if GoodsNumber == 4: price = 288 if GoodsNumber == 5: price = 241 amount = int(input("Amount : ")) sum = price * amount print("Total Price : ", sum,"coins") print("-------- THANK YOU --------") else: print("Incorrect Username or password")
2ee911d204084b19a9f0a2014a6cb123c2e24085
rileythejones/lambdata
/lambdata_rileythejones/df_utils.py
246
3.609375
4
"""" utility functions for working with DataFrames """ import pandas as pd import numpy as np df_null = pd.DataFrame([1, 2, 3, 4, 5, 6, 7, 8, 9, np.NaN, 0, 0]) df_random = pd.DataFrame(np.random.randn(100, 3)) df_random_column = df_random[0]
7e6caaea40c2ca56d00cf95dce934fb338a55ca1
dlingerfelt/DSC-510-Fall2019
/FRAKSO_MOHAMMED_DSC51/loops-week5.py
2,983
4.53125
5
''' File: Loops.py Name: Mohammed A. Frakso Date: 12/01/2020 Course: DSC_510 - Introduction to Programming Desc: This program will contain a variety of loops and functions: The program will add, subtract, multiply, divide two numbers and provide the average of multiple numbers input by the user. Define a function named performCalculation which takes one parameter. The parameter will be the operation being performed (+, -, *, /). This function will perform the given prompt the user for two numbers then perform the expected operation depending on the parameter that's passed into the function. This function will print the calculated value for the end user. Define a function named calculateAverage which takes no parameters. This function will ask the user how many numbers they wish to input. This function will use the number of times to run the program within a for loop in order to calculate the total and average. This function will print the calculated average. ''' import operator # Function to do math operations def calc(number1: float, number2: float, op: str) -> float: operands = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv} return operands[op](number1, number2) # Function to get the valid input number def get_number(message: str) -> float: number = 0 while number == 0: try: number: float = float(input(message)) break except ValueError: print('Invalid input please try again!') continue return number # This function will perform math operations based on operation entered def performCalculation(operation: str): number1 = get_number('Enter first number: ') number2 = get_number('Enter second number: ') output = calc(number1, number2, operation) print("the output is " + str(output), end="\n") # This function will calculate total and average of numbers def calculateAverage(): num = int(input('How many numbers you want to enter? ')) total_sum = 0 for n in range(num): number = get_number('Please enter the number: ') total_sum += number avg = total_sum / num print("the average is " + str(avg), end="\n") # Display the welcome statement def main(): print('Welcome to the math calculator:') print("Enter '+', '-', '*', '/', 'avg' for math operations, and 'cancel' for quiting the program", end="\n") while True: operation: str = input("Enter your choice \n") if operation == 'cancel': break if ("+" == operation) or ("-" == operation) or ("*" == operation) or ("/" == operation): performCalculation(operation) elif operation == 'avg': calculateAverage() else: print("Invalid input entered please try again", end="\n") if __name__ == '__main__': main()
3dc92800af9c9fd0322bd4f5e169e1a3099f0d73
dlingerfelt/DSC-510-Fall2019
/GAGGAINPALI_DSC510/assignment9.1-wordcount_print_to_file.py
3,328
4.46875
4
# File : assignment9.1-wordcount_print_to_file.py # Name : Bhargava Gaggainpali # Date : FEB-9-2020 # Course : Introduction to Programming - python # Assignment : # -Last week we got a taste of working with files. This week we’ll really dive into files by opening and closing files properly. # -For this week we will modify our Gettysburg processing program from week 8 in order to generate a text file from the output rather than printing to the screen. Your program should have a new function called process_file which prints to the file (this method should almost be the same as the pretty_print function from last week. Keep in mind that we have print statements in main as well. Your program must modify the print statements from main as well. # -Your program must have a header. Use the programming style guide for guidance. # -Create a new function called process_fie. This function will perform the same operations as pretty_print from week 8 however it will print to a file instead of to the screen. # -Modify your main method to print the length of the dictionary to the file as opposed to the screen. # -This will require that you open the file twice. Once in main and once in process_file. # -Prompt the user for the filename they wish to use to generate the report. # -Use the filename specified by the user to write the file. # -This will require you to pass the file as an additional parameter to your new process_file function # Desc : Program to input the file and count the words and the occurence of each word and print to file. # Usage : # -Program to input the file and count the words and the occurence of each word and print to file. import string # Create add_word function to count number of words. def add_word (words, wordcount): if words not in wordcount: wordcount[words] = 1 else: wordcount[words] = wordcount[words] +1 # Create process_line function to strip off various characters and split words in line def process_line (eachline, wordcount): eachline = eachline.translate(str.maketrans('', '', string.punctuation)) eachlinewords = eachline.split() for word in eachlinewords: add_word(word, wordcount) #create process_file function to print the output to the file def process_file (wordcount,print_to_file): with open("{}.txt".format(print_to_file),'w') as new_file: # Opens user input file in write mode new_file.write("\nLength of Dictionary is : {0}\n".format(len(wordcount))) new_file.write("\nWord\t\tCount") new_file.write("\n--------------------") for key in sorted(wordcount, key=wordcount.__getitem__, reverse=True): new_file.write("\n{}\t{}".format(key.ljust(10,' '), wordcount[key])) new_file.close() #main() function def main(): wordcount = {} file = open('gettysburg.txt', 'r') print("\nWelcome to the 'WordCount_print_to_file Program'..!!") print_to_file = input('\nPlease Enter the Output File to be created and print work count: ') for line in file.readlines(): process_line(line, wordcount) process_file(wordcount,print_to_file) file.close() print("\nFile with a name '",print_to_file,"' created and the Word-Count is printed in the file Successfully.") print("Thank you for using 'WordCount_print_to_file Program'.") if __name__ == '__main__': main()
88333bcf49ae0f01c6f7d4cca37c1dae5ddb64a2
dlingerfelt/DSC-510-Fall2019
/JALADI_DSC510/final/WeatherDisplay.py
1,791
4.34375
4
# File : WeatherDisplay.py # Name : Pradeep Jaladi # Date : 02/22/2020 # Course : DSC-510 - Introduction to Programming # Desc : Weather Display class displays the weather details to output. class WeatherDisplay: def __init__(self, desc, city, country, temp, feels_like, min_temp, max_temp, lat, lon, wind): """ Initialize the model variables """ self._desc = desc self._city = city self._country = country self._temp = temp self._feels_like = feels_like self._min_temp = min_temp self._max_temp = max_temp self._lat = lat self._lon = lon self._wind = wind def print_report(self): """ Prints the details to the output screen """ print('---------------------------------------------------------------------------------------') print('Current temperature is : %df' % self.__convert_temp(self._temp)) print('outside it looks like : {}'.format(self._desc)) print('Current it feels like : %df' % self.__convert_temp(self._feels_like)) print('Wind outside is : %d miles per hour' % self.__convert_wind(self._wind)) print('City : {}, {}'.format(self._city, self._country)) print('coordinates are : [{}, {}]'.format(self._lat, self._lon)) print('Today the temperatures are High as %df and low as %df' % ( self.__convert_temp(self._max_temp), self.__convert_temp(self._min_temp))) print('---------------------------------------------------------------------------------------') def __convert_temp(self, kelvin: float) -> float: """ converts the temperature from kelvin to f """ return 9 / 5 * (kelvin - 273.15) + 32 def __convert_wind(self, meter: float) -> float: """ converts the wind from meter to miles per hour """ return meter * 2.2369363
7b5792e9a15c79a9d9c8cc195cb66b11b8686b5e
dlingerfelt/DSC-510-Fall2019
/APRIL_MEYER_DSC510/APRIL_Assignment5.py
2,409
4.09375
4
#%% #File: Assignment 5 #Name: April Meyer #Assignment 5 #Date: 9.26.2019 """Desc: This program will prompt the user for an arithmetic operation. It wil then perform the operation and prompt the user for another arithmetic until the user types none.""" #Defines a function named performCalculation which takes one parameter. #The parameter will be the operation being performed (+, -, *, /). def performCalculation (x): userNum_input = int(input('What is your first number?')) userNum_input2 = int(input('What is your second number?')) if x in ('+','add','addition'): print(userNum_input + userNum_input2) elif x in ('-','minus','subtraction'): print(userNum_input - userNum_input2) elif x in ('*','multiply','multiplication'): print(userNum_input * userNum_input2) elif x in ('/','divide','division'): print(userNum_input / userNum_input2) #Define a function named calculateAverage which takes no parameters and prints the average def calculateAverage (): userAvg_input = int(input('How many numbers would you like to average?')) total = 0 for i in range(0, userAvg_input): # set up loop to run the amount from the user number = int(input('Please enter a number: ')) # prompt user for number for total total = total + number print('Your average is ', total/userAvg_input) #prints average cal_set = ['+','add','addition','-','minus','subtraction','*','multiply','multiplication','/','divide','division'] cal_set2 = ['+','add','addition','-','minus','subtraction','*','multiply','multiplication','/','divide','division', 'average'] while True: #loop for user to do calculations & continues until they type none userOp_input = input('What arithmetic operation would you like to perform? \n' 'Addition(+), Subtraction(-), Multiplication(*), Division(/), Average, or None') userOp_input = userOp_input.lower() #converts to lower case if userOp_input in cal_set: #checks if it is in the first list performCalculation (userOp_input) if userOp_input == 'average': #checks the user input to see if it is average calculateAverage() if userOp_input == 'none': #breaks the loop if it is user_input is none break if userOp_input not in cal_set2 : #all other inputs will receive this message print('Invalid Option. Please try again') print('All Done!')
a3ce25380c0f7db366c3cb94a539a5bbfb352ecf
dlingerfelt/DSC-510-Fall2019
/GUPTA_DSC510/assignment_week4_gupta_dsc510.py
7,579
4.25
4
# File: RGupta_wk4.py # Instructor: David Lingerfelt # Date: 09/18/2019 # Course: DSC510-T304 Introduction to Programming # Assignment#: 4.1 # Description: This program perform the cost calculation of fiber optic cable with taxes # User gets a discount on purchase of 100 feet or more cable # Usage: This program requires total length of the optic fiber as the input import datetime # Changes the color of the text to green print("\033[1;32;48m") print('Welcome to DukeNet Optic Fiber - A destination to buy optic fiber ') print("\033[1;30;48m") # actual price per foot = 0.93 cents and tax= 7% act_price = 0.93 tax = 0.07 # Defining a function # act_cst = original cost of the cable # cst_after_disc = cost after deducting the discount # cst_plus_tax = tax added to the cost after discount def caltotcost(ft, prc): act_cst = ft * act_price cst_after_disc = ft * prc cal_tax = cst_after_disc * tax cst_plus_tax = round(cst_after_disc + cal_tax, 2) print("\033[1;33;48m") print("The Original Cost of the Cable : " + '%.2f' % act_cst + "$") if ft > 100: print("Total Cost of Your Purchase with Discount: " + '%.2f' % cst_after_disc + "$") print("Final Cost of Your Purchase with 7% tax: " + '%.2f' % cst_plus_tax + "$") inp_enter = input('Enter Y to print Receipt : \n') # Print receipt with Company name, total cost and time if inp_enter in ('y', 'Y'): print("\033[1;32;48m") print("DukeNet Optic Fiber \n\t\t RECEIPT\n\t") print("\033[1;33;48m") print("\t Buyer : " + inp_comp) ## 'inp_comp' takes input from the user print("Total Optic Fiber Purchased:", + no_of_feet, "ft") print("\t Sub Total : " + "$" + '%.2f' % cst_after_disc) print("\tSales tax(7%): " + "$" + '%.2f' % cal_tax) print("\t Total Cost : " + "$" + '%.2f' % cst_plus_tax) print("\033[1;32;48m") print("\nThank you for shopping at DukeNet..!!") now = datetime.datetime.now() print(now.strftime("%Y-%m-%d %H:%M"), "\n") else: print("Thank you. Bye..!!") return cst_plus_tax # Takes input from the user for company name and feet inp_comp = input('Please Enter Your Company Name: \n') while True: try: print("\033[1;30;48m") no_of_feet = float(input('Enter total length of optic fiber you want to purchase (In Feet) : \n')) break except ValueError: print("\033[1;31;48m") print(''"Please enter a valid number..!!"'') # Calculate discount if no_of_feet <= 100: disc_val = 0 # No discount for <= 100 feet else: if (no_of_feet > 100) and (no_of_feet <= 250): disc_val = 0.07 # 7 cents discount when total feet <= 250 and > 100 else: if (no_of_feet > 250) and (no_of_feet <= 500): disc_val = 0.17 # 17 cents discount when total feet <= 500 and > 250 else: disc_val = 0.37 # 37 cents discount when total feet > 500 # cost per foot = actual price minus discount value aft_dis_prc = act_price - disc_val # call function to calculate the costs caltotcost(no_of_feet, aft_dis_prc) Output: Welcome to DukeNet Optic Fiber - A destination to buy optic fiber Please Enter Your Company Name: Duke Enter total length of optic fiber you want to purchase (In Feet) : 2~ Please enter a valid number..!! Enter total length of optic fiber you want to purchase (In Feet) : 10 The Original Cost of the Cable : 9.30$ Enter Y to print Receipt : y DukeNet Optic Fiber RECEIPT Buyer : Duke Total Optic Fiber Purchased: 10.0 ft Sub Total : $9.30 Sales tax(7%): $0.65 Total Cost : $9.95 Thank you for shopping at DukeNet..!! 2019-09-18 15:21 ...Program finished with exit code 0 Press ENTER to exit console.
433d5b3ed946f1f84893a9eed708b49e902af6c0
dlingerfelt/DSC-510-Fall2019
/NERALLA_DSC510/NERALLA_DSC510_WEEK11.py
2,521
4.15625
4
''' File: NERALLA_DSC510_WEEK10.py Name: Ravindra Neralla Course:DSC510-T303 Date:02/23/2020 Description: This program is to create a simple cash register program. The program will have one class called CashRegister. The program will have an instance method called addItem which takes one parameter for price. The method should also keep track of the number of items in your cart. The program should have two getter methods. getTotal – returns totalPrice getCount – returns the itemCount of the cart The program must create an instance of the CashRegister class. The program should have a loop which allows the user to continue to add items to the cart until they request to quit. The program should print the total number of items in the cart. The program should print the total $ amount of the cart. The output should be formatted as currency. ''' import locale # Creating class of CashRegister to calculate the total cost class CashRegister: def __init__(self): self.__totalItems = 0 self.__totalPrice = 0.0 # Creating a method to return total price of the shopping cart def getTotal(self) -> float: return self.__totalPrice # creating a method to return total number of items in the shopping cart def getCount(self) -> int: return self.__totalItems # Create a method to add items to the shopping cart def addItem(self, price: float): self.__totalPrice += price # Adding each item price in the shopping cart self.__totalItems += 1 # Adding item count in shopping cart def main(): print('Welcome to the cash register. To know your total purchase price please enter q ') # creating an object using CashRegister() class register = CashRegister() locale.setlocale(locale.LC_ALL, 'en_US.utf-8') while True: try: operation: str = input('Enter the price of your item : ') # At the end of shopping, enter q to calcualte total price and total items in cart if operation == 'q': break price = float(operation) register.addItem(price) except ValueError: print('The price is not valid. Please try again') total_price: float = register.getTotal() total_count: int = register.getCount() print('Total number of items added to your shopping cart : {}'.format(total_count)) print('Total price of items is : {}'.format(locale.currency(total_price, grouping=True))) if __name__ == '__main__': main()
78eee39d5b2e07f640f8be3968acdec0b7c8e13f
dlingerfelt/DSC-510-Fall2019
/Safari_Edris_DSC510/Week4/Safari_DSC510_Cable_Cost.py
1,951
4.4375
4
# File : Safari_DSC510_Cable_Cost.py # Name:Edris Safari # Date:9/18/2019 # Course: DSC510 - Introduction To Programming # Desc: Get name of company and length in feet of fiber cable. compute cost at $.87 per foot. display result in recipt format. # Usage: Provide input when prompted. def welcome_screen(): """Print welcome screen""" # Welcome Screen print("Welcome to Fiber Optics One.") # Get Company name print("Please tell us the name of your company") def compute_cost(Cable_Length,CableCostPerFoot): """Compute cable cost""" # Compute Installation cost at CableCostPerFoot cents return float(Cable_Length) * CableCostPerFoot welcome_screen() Company_Name = input('>>>') print("Thank You.") print("Now, please tell us the length in feet of cable you need. Enter 'q' to exit.") Cable_Length = input('>>>') # Use while to run program until user enters 'q' while Cable_Length.lower() != 'q': if not Cable_Length.isnumeric(): # Make sure value is numeric print("PLease enter a valid number.") else: # Compute Installation Installation_Cost = compute_cost(Cable_Length, 0.87) Tax = Installation_Cost*.083 # Tax rate is 8.3% Installation_Cost_PlusTax = Installation_Cost + Tax # Print out the receipt print("Thank You. Here's your receipt.") print("Company Name: " + Company_Name) print("Cable Length: " + Cable_Length) print("Cost for " + Cable_Length + " feet of cable at $.87 per foot is $" + str(format(Installation_Cost, '.2f')) + ".") print("Tax at 8.3% is $: " + str(format(Tax, '.2f')) + ".") print("Total cost for " + Cable_Length + " feet of cable at $.87 per foot is $" + str(format(Installation_Cost_PlusTax, '.2f')) + ".") print("Please enter another length in feet of cable you need. Enter 'q' to exit.") Cable_Length = input('>>>') # Exit the program print("Thank You. Please come back.")
d2587b87036af1d39d478e5db8c6d03b19c6da83
dlingerfelt/DSC-510-Fall2019
/SMILINSKAS_DSC510/Temperatures.py
1,290
4.21875
4
# File: Temperatures.py # Name: Vilius Smilinskas # Date: 1/18/2020 # Course: DSC510: Introduction to Programming # Desc: Program will collect multiple temperature inputs, find the max and min values and present the total # number of values in the list # Usage: Input information when prompted, input go to retrieve the output import sys temperature = [] # list for temperatures to be stored number = [] # list for input variable count = 0 # int variable for keeping count of loops while number != 'go': # go is set up as sentinel value to break the input try: # to not add go or any ineligible value into the program, if error: the exception will run line 17 number = int(input('Enter a temperature or to run program enter go:')) temperature.append(number) # append adds the parameter to the end of temperature count = count + 1 # counts the loops except ValueError: # if line 15 triggers error run the below block of code print('The highest temperature is:' + str(max(temperature))) # max() determines the maximum value print('The lowest temperature is:' + str(min(temperature))) # min() determines the minimum value print('The number of values entered is:' + str(count)) sys.exit() # exits the program
5a3b8e3859ec4f9a5ab2d215a948ce55cd295552
dlingerfelt/DSC-510-Fall2019
/HA_DSC510/Assignment_9_1.py
4,800
4.3125
4
#!/usr/bin/env python3 # File: Assignment_9_1.py # Name: Jubyung Ha # Date: 02/09/2020 # Course: DSC510-T303 Introduction to Programming (2203-1) # Desc: Last week we got a taste of working with files. # This week we’ll really dive into files by opening and closing files properly. # # For this week we will modify our Gettysburg processing program from week 8 # in order to generate a text file from the output rather than printing to the screen. # Your program should have a new function called process_file which prints to the file # (this method should almost be the same as the pretty_print function from last week.) # Keep in mind that we have print statements in main as well. # Your program must modify the print statements from main as well. # # Your program must have a header. Use the programming style guide for guidance. # Create a new function called process_fie. # This function will perform the same operations as pretty_print from week 8 # however it will print to a file instead of to the screen. # Modify your main method to print the length of the dictionary to the file as opposed to the screen. # This will require that you open the file twice. Once in main and once in process_file. # Prompt the user for the filename they wish to use to generate the report. # Use the filename specified by the user to write the file. # This will require you to pass the file as an additional parameter to your new process_file function. # # Your program must have a header. Use the programming style guide for guidance. # Create a new function called process_fie. # This function will perform the same operations as pretty_print from week 8, # however it will print to a file instead of to the screen. # Modify your main method to print the length of the dictionary to the file as opposed to the screen. # This will require that you open the file twice. Once in main and once in process_file. # Prompt the user for the filename they wish to use to generate the report. # Use the filename specified by the user to write the file. # This will require you to pass the file as an additional parameter to your new process_file function. # Usage: The user will run the main() function to create a summary text file. import string def add_word(words, summary): """Add each word to the dictionary. If exist, increment the count by 1. Args: Parameters are the word and a dictionary. Returns: No return value. """ for word in words: if word not in summary: summary[word] = 1 # If not a word exists, add the word and set value as 1 else: summary[word] += 1 # If a word exists, just increase value by 1 def Process_line(line, summary): """Strip off various characters, split out the words, and so on Args: Parameters are a line and the dictionary. Returns: No return value. """ line = line.lower() # lower all words in the line line = line.translate(str.maketrans('', '', string.punctuation)) # Remove all punctuation words = line.split() # Split word from the line add_word(words, summary) # Add word to dictionary def Pretty_print(summary): """Print the total count of words and the count for each word. Args: The parameter is a dictionary Returns: No return value. """ print('Word', ' ', 'Count') print('-------------------------') # Sort the dictionary by value for word, count in sorted(summary.items(), key=lambda kv: kv[1], reverse=True): print("{:17} {:5}".format(word, count)) def process_file(summary, txt_file): """Print to the file. Args: summary: dictionary txt_file: file object :return: None """ header = 'Word Count\n' split_line = '-------------------------\n' txt_file.write(header) txt_file.write(split_line) # Sort the dictionary by value and write to the file. for word, count in sorted(summary.items(), key=lambda kv: kv[1], reverse=True): txt_file.write("{:17} {:5}\n".format(word, count)) def main(): """it will open the file and call process_line on each line. When finished, it will call pretty_print to print the dictionary """ summary = dict() gba_file = open('gettysburg.txt', 'r') for line in gba_file: Process_line(line, summary) # Receive the file name from an user. file_name = input('Please enter file name: ') file_path = "{}.txt".format(file_name) # Write the length of dictionary to the file. txt_file = open(file_path, 'w') txt_file.write('Length of the dictionary: {}\n'.format(len(summary))) # Write the summary to the file. process_file(summary, txt_file) if __name__ == '__main__': main()
7faffa27e0944548717be676c521fcb8ed1653a8
dlingerfelt/DSC-510-Fall2019
/FRAKSO_MOHAMMED_DSC51/week6-lists.py
1,257
4.46875
4
''' File: lists.py Name: Mohammed A. Frakso Date: 19/01/2020 Course: DSC_510 - Introduction to Programming Desc: This program will work with lists: The program will contains a list of temperatures, it will populate the list based upon user input. The program will determine the number of temperatures in the program, determine the largest temperature, and the smallest temperature. ''' # create an empty list temperature_list = [] while True: print('\n Please enter a temperature:') #print('Enter "finished" once you are done with all temparatures: \n') input_temperature = input('please type "finished" when you have entered all temperatures') if input_temperature.lower() == 'finished': break try: temperature_list.append(float(input_temperature)) except ValueError: input_temperature = input('Oops... Please enter a numeric value!') temperature_list.append(float(input_temperature)) # printing argest, smallest temperatures and how many temperatures are in the list. print('The largest temperature is: ', max(temperature_list), 'degrees') print('The smallest temperature is: ', min(temperature_list), 'degrees') print('The total temperatures input is: ', len(temperature_list))
42d37509986bc3233ab711cef2496ab4fa17602a
dlingerfelt/DSC-510-Fall2019
/Ndingwan_DSC510/week4.py
2,921
4.28125
4
# File: week4.py # Name: Awah Ndingwan # Date: 09/17/2019 # Desc: Program calculates total cost by multiplying length of feet by cost per feet # Usage: This program receives input from the user and calculates total cost by multiplying the number of feet # by the cost per feet. Finally the program returns a summary of the transaction to the user cost_per_feet_above_100feet = 0.80 cost_per_feet_above_250feet = 0.70 cost_per_feet_above_500feet = 0.50 length_above_100 = 100.0 length_above_250 = 250.0 length_above_500 = 500.0 # calculate and return cost def calculate_cost(cost, feet): return cost * feet class FiberCostCalculator: def __init__(self, company_name="", num_of_feet=0, installation_cost=0, cost_per_feet=0.87): self.company_name = company_name self.number_of_feet = num_of_feet self.installation_cost = installation_cost self.cost_per_feet = cost_per_feet self.get_input() self.compute_total_cost() self.show_receipt() # Get amd validate input from user def get_input(self): # printing welcome message message = "******** WELCOME ********" print(message) self.company_name = input("Enter Company name: ") while True: try: self.number_of_feet = float(input("Enter number of feet for fiber optic cable(ft): ")) except ValueError: print("Not Valid! length of feet cannot be a String. Please try again.") continue else: break # compute installation cost for user def compute_total_cost(self): if length_above_100 < self.number_of_feet < length_above_250: self.cost_per_feet = cost_per_feet_above_100feet self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet) elif length_above_250 < self.number_of_feet < length_above_500: self.cost_per_feet = cost_per_feet_above_250feet self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet) elif self.number_of_feet > length_above_500: self.cost_per_feet = cost_per_feet_above_500feet self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet) else: self.installation_cost = calculate_cost(self.number_of_feet, self.cost_per_feet) # Print receipt details def show_receipt(self): print('********************') print(' Receipt ') print(' ****************** ') print(f'Company Name: {self.company_name}') print(f'Cost Per Feet: ${float(self.cost_per_feet)}') print(f'Length of feet to be installed: {self.number_of_feet} feet') print("Total cost: $" + format(round(float(self.installation_cost), 2), ',.2f')) if __name__ == "__main__": fiberCostCalculator = FiberCostCalculator()
8c70251443a384255c610a8a96d4977c5da28947
dlingerfelt/DSC-510-Fall2019
/JALADI_DSC510/TEMPERATURE_OPERATIONS.py
1,536
4.53125
5
# File : MATH_OPERATIONS.py # Name : Pradeep Jaladi # Date : 01/11/2020 # Course : DSC-510 - Introduction to Programming # Assignment : # Program : # Create an empty list called temperatures. # Allow the user to input a series of temperatures along with a sentinel value which will stop the user input. # Evaluate the temperature list to determine the largest and smallest temperature. # Print the largest temperature. # Print the smallest temperature. # Print a message tells the user how many temperatures are in the list. def print_values(temperatures): length: int = len(temperatures) # there are couple of ways to determine the min & max of the list -> using max & min function or sort the list and get 0, max length element print('There are total %d temperature values ' % length) print('The lowest temperature is %g and the highest temperature is %g' % (min(temperatures), max(temperatures))) def main(): print("Welcome to temperature calculator program ....") # Declaration of empty temperatures list temperatures = []; # Getting the temperature values while True: temperature: str = input("Enter the temperature [%d] : " % len(temperatures)) if temperature == 'q': break try: temperatures.append(float(temperature)) except ValueError: print("Oops! Invalid temperature. Try again...") # printing the desired calucations print_values(temperatures) if __name__ == '__main__': main()
03bb8bd26bf0fd57b9ce248009c8a616cc977ff3
dlingerfelt/DSC-510-Fall2019
/JALADI_DSC510/RECEIPT_CALCULATOR_V2.py
3,648
4.53125
5
# File : calculator.py # Name : Pradeep Jaladi # Date : 12/09/2019 # Course : DSC-510 - Introduction to Programming # Assignment : # Using comments, create a header at the top of the program indicating the purpose of the program, assignment number, and your name. Use the SIUE Style Guide as a reference. # Display a welcome message for your user. # Retrieve the company name from the user. # Retrieve the number of feet of fiber optic cable to be installed from the user. # Calculate the installation cost of fiber optic cable by multiplying the total cost as the number of feet times by price by feet purchased. # Price is $0.87 if purchased feet is less than are equal to 100 # Price is $0.80 if purchased feet is between 100 and 251 # Price is $0.70 if purchased feet is between 250 and 501 # Price is $0.50 if purchased feet is greater than 500 # Print a receipt for the user including the company name, number of feet of fiber to be installed, the calculated cost, and total cost in a legible format. # Desc : Program to calculate total cost of fiber cable installation # Usage : # The program prompts the user for company name, required feet of fiber optical cable to be installed # The program will calculate the cost of prints the receipt for the user import datetime # This function will return the cost of fiber cable per foot. It will help to change the price quickly and one place. def price_of_cable(length_of_fiber_cable: int): if 100 < length_of_fiber_cable <= 250 : # Purchased feet between 101 to 250 then price is 0.80 return 0.80 elif 250 < length_of_fiber_cable <= 500 : # Purchased feet between 251 to 500 then price is 0.70 return 0.70 elif length_of_fiber_cable > 500 : # More than 500 feet then price is 0.50 return 0.50 else : return 0.87 # default value of $0.87 # This function will calculate the total cost def calculate_total(length_of_fiber_cable: int): price_per_feet = price_of_cable(length_of_fiber_cable) # Getting the price based on length of the feet return length_of_fiber_cable * price_per_feet # This function will print the customer receipt def print_receipt(company_name: str, length_of_fiber_cable: int, sale_price: float): now = datetime.datetime.now() print('Receipt Date : ' + now.strftime("%Y-%m-%d %H:%M:%S")) # printing date & time print('Invoice for : {0}'.format(company_name)) # printing company name print('Purchased length of feet : {:,}'.format(length_of_fiber_cable)) # printing the fiber length print('Total cost is : ',sale_price) # sale price print('Total formatted cost is :','${:,.2f}'.format(sale_price)) # sale formatted price def main(): print("Welcome to the store") company_name: str = input("Enter your company name \n") while True: # making sure the entered input is valid number try: length_of_fiber_cable: int = int(input("Enter the length of fiber cable \n")) if(length_of_fiber_cable < 0 ) : print("Oops! That was no valid number. Try again...") continue else : break except ValueError: print("Oops! That was no valid number. Try again...") # calling function which returns the total price sale_price = calculate_total(length_of_fiber_cable) # printing the receipt to the customer print_receipt(company_name, length_of_fiber_cable, sale_price) if __name__ == '__main__': main()
f5428333663e7da9d39bdff3e25f6a34c07ebd08
dlingerfelt/DSC-510-Fall2019
/Steen_DSC510/Assignment 3.1 - Jonathan Steen.py
1,186
4.34375
4
# File: Assignment 3.1 - Jonathan Steen.py # Name: Jonathan Steen # Date: 12/9/2019 # Course: DSC510 - Introduction to Programing # Desc: Program calculates cost of fiber optic installation. # Usage: The program gets company name, # number of feet of fiber optic cable, calculate # installation cost, bulk discount and print receipt. #welcome statement and get user input print('Welcome to the fiber optic installation cost calculator.') companyName = input('Please input company name.\n') fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n') #if statement to calculate bulk discount fiberOpticCost = 0 if float(fiberOpticLength) > 499: fiberOpticCost = .50 elif float(fiberOpticLength) > 249: fiberOpticCost = .70 elif float(fiberOpticLength) > 99: fiberOpticCost = .80 elif float(fiberOpticLength) < 100: fiberOpticCost = .87 #calculate cost totalCost = float(fiberOpticLength) * float(fiberOpticCost) #print receipt print('\n') print('Receipt') print(companyName) print('Costs: ' + str(fiberOpticLength) + ' ft' + ' @ ' + '${:,.2f}'.format(fiberOpticCost) + ' Per Foot') print('Total: ' + '${:,.2f}'.format(totalCost))
af093e824555df86dc56d2b1b581270fd1671d1c
dlingerfelt/DSC-510-Fall2019
/Stone_DSC510/Assignment2_1/Assignment2_1.py
751
4.21875
4
# 2.1 Programming Assignment Calculate Cost of Cabling # Name: Zachary Stone # File: Assignment 2.1.py # Date: 09/08/2019 # Course: DSC510-Introduction to Programming # Greeting print('Welcome to the ABC Cabling Company') # Get Company Name companyName = input('What is the name of you company?\n') # Get Num of feet feet = float(input('How any feet of fiber optic cable do you need installed?\n')) # calculate cost cost = float(feet*0.87) # print receipt print("********Receipt********") print('Thank you for choosing ABC Cable Company.\n') print('Customer:', companyName) print('Feet of fiber optic cable:', feet) print('Cost per foot:', '$0.87') print('The cost of your installation is', '${:,.2f}'.format(cost)) print('Thank you for your business!\n')
edc28c6d0a7bd72d9a875d7716f8957874455fd0
dlingerfelt/DSC-510-Fall2019
/Steen_DSC510/Assignment 4.1 - Jonathan Steen.py
1,364
4.15625
4
# File: Assignment 4.1 - Jonathan Steen.py # Name: Jonathan Steen # Date: 12/17/2019 # Course: DSC510 - Introduction to Programing # Desc: Program calculates cost of fiber optic installation. # Usage: The program gets company name, # number of feet of fiber optic cable, calculate # installation cost, bulk discount and prints receipt. #welcome statement and get user input print('Welcome to the fiber optic installation cost calculator.') companyName = input('Please input company name.\n') fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n') #if statement to calculate bulk discount fiberOpticCost = 0 if float(fiberOpticLength) > 499: fiberOpticCost = .50 elif float(fiberOpticLength) > 249: fiberOpticCost = .70 elif float(fiberOpticLength) > 99: fiberOpticCost = .80 elif float(fiberOpticLength) < 100: fiberOpticCost = .87 #define function to calculate cost def calculateCost(x, y): global totalCost totalCost = float(x) * float(y) return totalCost #call calcution function calculateCost(fiberOpticLength, fiberOpticCost) #print receipt print('\n') print('Receipt') print(companyName) print('Costs: ' + str(fiberOpticLength) + ' ft' + ' @ ' + '${:,.2f}'.format(fiberOpticCost) + ' Per Foot') print('Total: ' + '${:,.2f}'.format(totalCost))
f70f72b4d449726be0bb53878d32116d999756f5
dlingerfelt/DSC-510-Fall2019
/Steen_DSC510/Assignment 2.1 - Jonathan Steen.py
1,105
4.28125
4
# File: Assignment 2.1 - Jonathan Steen.py # Name: Jonathan Steen # Date: 12/2/2019 # Course: DSC510 - Introduction to Programing # Desc: Program calculates cost of fiber optic installation. # Usage: The program gets company name, # number of feet of fiber optic cable, calculate # installation cost and prints a receipt. print('Welcome to the fiber optic installation cost calculator.') companyName = input('Please input company name.\n') fiberOpticLength = input('Please input number of feet of fiber optic cable to be installed.\n') fiberOpticCost = .87 #define the varible to hold the cost per ft of fiber optic. totalCost = float(fiberOpticLength) * float(fiberOpticCost) #convert user input to float and calculate price. print('\n') print('Receipt') print(companyName) print('Costs: ' + str(fiberOpticLength) + ' ft' + ' @ ' + '$' + str(fiberOpticCost) + ' Per Foot') #convert float varible to string totalCost = totalCost - totalCost % 0.01 #format output to two decimal points without rounding up or down to get accurate amount. print('Total: ' + '$' + str(totalCost))
d1502cfe21c91a68849e70294c62fe6967a264d7
dlingerfelt/DSC-510-Fall2019
/HA_DSC510/Assignment_10_1.py
3,875
4.40625
4
#!/usr/bin/env python3 # File: Assignment_8_1.py # Name: Jubyung Ha # Date: 02/16/2020 # Course: DSC510-T303 Introduction to Programming (2203-1) # Desc: We’ve already looked at several examples of API integration from a Python perspective and # this week we’re going to write a program that uses an open API to obtain data for the end user. # # Create a program which uses the Request library to make a GET request of the following API: Chuck Norris Jokes. # The program will receive a JSON response which includes various pieces of data. # You should parse the JSON data to obtain the “value” key. # The data associated with the value key should be displayed for the user (i.e., the joke). # # Your program should allow the user to request a Chuck Norris joke as many times as they would like. # You should make sure that your program does error checking at this point. # If you ask the user to enter “Y” and they enter y, is that ok? Does it fail? # If it fails, display a message for the user. There are other ways to handle this. # Think about included string functions you might be able to call. # # Your program must include a header as in previous weeks. # Your program must include a welcome message for the user. # Your program must generate “pretty” output. # Simply dumping a bunch of data to the screen with no context doesn’t represent “pretty.” # Usage: Run main() function to call welcome_message() function, and in the following loop, # the program will ask for Y or N to get_joke() and prettify the joke. # When an user ends the program, it will run end_message() function. import requests import textwrap from urllib.error import HTTPError from urllib.error import URLError # Chuck Norris API address url = 'https://api.chucknorris.io/jokes/random' def welcome_message(): print('------------------------------------------------') print('----------Welcome to Chuck Norris Joke----------') print('------------------------------------------------') def end_message(): print('------------------------------------------------') print('-------Thanks for using Chuck Norris Joke-------') print('------------------------------------------------') def get_joke(): """Gets response from API and return a value from the JSON Args: None :return: A String from JSON """ try: response = requests.get(url) return response.json()["value"] except HTTPError as e: # Exception if the page is not found print("The page could not be found!") except URLError as e: # Exception if the server is down print("The server could not be found!") def prettify_joke(joke): """ Prettify a string by wrapping :param joke: :return: NONE """ print('------------------------------------------------') # Create a wrapper object and wrap a string wrapper = textwrap.TextWrapper(width=48) wrapped_string = wrapper.wrap(text=joke) # Print the wrapped string line by line for line in wrapped_string: print(line) print('------------------------------------------------') def isAnswer(answer): """ Test if an answer is in Y or N and return True or False """ if answer.upper() in ('Y', 'N'): return True def main(): welcome_message() while True: print('Do you like to have another Chuck Norris Joke?') answer = input('Y for yes, N for quit the program: ') # If the answer is not in Y or N, then send a warning and continue if not isAnswer(answer): print('Only enter Y or N for your answer!') continue # If the answer is N, then quit the program elif answer.upper() == 'N': break else: prettify_joke(get_joke()) end_message() if __name__ == '__main__': main()
2155f32ff8af7f310124f09964e576fe5b464398
dlingerfelt/DSC-510-Fall2019
/DSC510- Week 5 Nguyen.py
2,139
4.3125
4
''' File: DSC510-Week 5 Nguyen.py Name: Chau Nguyen Date: 1/12/2020 Course: DSC_510 Intro to Programming Desc: This program helps implement variety of loops and functions. The program will add, subtract, multiply, divide two numbers and provide the average of multiple numbers input by the user. ''' def performCalculation(user_operation): # Using list will allow multiple inputs user_input = list(map(int, input("Enter multiple values: (no comma, just space) ").split())) if user_operation =="*": result = user_input[0] * user_input[1] elif user_operation =="%": try: result = user_input[0] / user_input[1] except: print("Error: Cannot Divide %s/%s" %(user_input[0], user_input[1])) return elif user_operation =="-": result = user_input[0] - user_input[1] elif user_operation =="+": result = user_input[0] + user_input[1] else : return float(result,2) print("Your calcualtion result is",result) def calculateAverage(): user_input2 = int(input('How many numbers they wish to input? ')) total_sum = 0 # Define store_input as list store_input = [] for n in range(user_input2): x = (int(input("Enter your value "))) # Store user input into a list store_input.append(x) total_sum = sum(store_input) average = total_sum / user_input2 print("The average is ", average) def main(): # Welcome statement print("Welcome. What program would you like to run today?") user_operation ='' # Asking user to pick the program they want to run while user_operation != 'exist': user_operation = input("pick one of the choices: -,*,+,%,average, or exist ") if user_operation == 'exist': break elif (user_operation == '-') or (user_operation == '+') or (user_operation == '*') or (user_operation == '%'): performCalculation(user_operation) elif (user_operation == 'average'): calculateAverage() else: print("invalid choice try again") if __name__ == '__main__': main()
90d0175b5c46e60927c347156e6469c17a975bf4
DhruvBajaj01/Python
/eight.py
113
3.6875
4
#printing the sum of a container(list,tuple etc) s=sum([20,40,10]) print('The sum of the container is:', s)
ba83368c602a2e913276547ce86dd329b2afa127
DhruvBajaj01/Python
/Numpy/num.py
188
3.59375
4
#aliasing #only one array is created #both have same memory address import numpy as num arr1=num.array([4,7,9]) arr2=arr1 print(arr1) print(arr2) #both give the same output
99674baad6fbcc054de343d40e03fbd2b2cbfb0a
TsigeA/PairProgramming
/Problem_E/solution_E3.py
1,284
3.9375
4
import random print "first move" mycount=0; comp_count=0; while (True): input1 = raw_input("What is your move? ") #if (input1 == 'r' or input1 == 'p' ): if input1 in ['r','p','s','l','k','R','P','S','L','K']: #then it's valid input1 = input1.upper() mylist=['R','P','S','L','K'] comp_input=random.choice(mylist) print"comp move?" print comp_input if (input1==comp_input): print"play again" continue elif ((input1=='S' and comp_input=='P') or \ (input1=='P' and comp_input=='R') or \ (input1=='R' and comp_input=='L') or \ (input1=='L' and comp_input=='K') or \ (input1=='K' and comp_input=='S') or \ (input1=='S' and comp_input=='L') or \ (input1=='L' and comp_input=='P') or \ (input1=='P' and comp_input=='K') or \ (input1=='K' and comp_input=='R') or \ (input1=='R' and comp_input=='S')): print"input1 won" #this means I win mycount=1+mycount else: print"loser:P" #this means computer wins comp_count=1+comp_count else: print"wrong move"#it's not break if (mycount>comp_count): print "you won!" print mycount elif (mycount<comp_count): print "computer wins" print comp_count else: print "it is a draw" #here i'm done
0cab43bf0cf5269bb56ba6f4709225a613c9737f
mun5424/ProgrammingInterviewQuestions
/subarraySum.py
494
3.703125
4
#Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k from typing import List class Solution: def subarraySum(self, nums: List[int], k: int) -> int: count = 0 for i in range(0, len(nums)): curr = 0 j = i + 1 while curr <= k: curr += nums[j] j += 1 if (curr == k): count += 1 return count
7792db4a011bb25c73d467bc62a18efaef04bfa8
mun5424/ProgrammingInterviewQuestions
/orgmodification.py
1,033
3.640625
4
# given an n-ary tree with values E and N, modify it so that the tree is only composed of E values. # E # E N E # E N E # will be # E # E E E # E # class Employee: def __init__(self, empid, isengineer): self.empid = empid self.isengineer = isengineer self.reportees = [] def orgmodification(root): node = root newreportees = [] for emp in root.reportees: newreportees += orgmodification(emp) if not root.isengineer: return newreportees root.reportees = newreportees return [node] emp1 = Employee(1, True) emp2 = Employee(2, True) emp3 = Employee(3, False) emp4 = Employee(4, True) emp5 = Employee(5, False) emp6 = Employee(6, True) emp7 = Employee(7, True) emp1.reportees = [emp2, emp3, emp4] emp2.reportees = [emp5, emp6] emp3.reportees = [emp7] orgmodification(emp1) for e in emp1.reportees: print(e.empid) # E1 # E2 N3 E4 # E5 N6 E7
7bd2456b0c77f97e11f16454bfa9890c28d93f35
mun5424/ProgrammingInterviewQuestions
/MergeTwoSortedLinkedLists.py
1,468
4.15625
4
# given two sorted linked lists, merge them into a new sorted linkedlist class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # set iterators dummy = ListNode(0) current = dummy #traverse linked list, looking for lower value of each while l1 and l2: if l1.val < l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next #traverse rest of the linkedlist if l1: current.next = l1 else: current.next = l2 return dummy.next def printList(self, list1: ListNode): # print a linked list dummy = list1 res = "" while dummy: if dummy.next: res += str(dummy.val) + ", " else: res += str(dummy.val) dummy = dummy.next print(res) # sample test node1 = ListNode(1) node5 = ListNode(5) node8 = ListNode(8) node1.next = node5 node5.next = node8 node4 = ListNode(4) node7 = ListNode(7) node9 = ListNode(9) node4.next = node7 node7.next = node9 s = Solution() list1 = node1 s.printList(list1) list2 = node4 s.printList(list2) result = s.mergeTwoLists(list1, list2) s.printList(result)
8afd0a85e0d3155af190d469617c63fb63dd7ddf
MasonSUn-6270/interesting-python
/装饰器示例和functoolswrags.py
752
3.734375
4
import functools "能将被装饰丢失的元数据弄回来,装饰到闭包中" class Kongjian(): @staticmethod def upper_sugar(func): """ 俺是一个装饰器,我使用闭包会定义一个函数,并返回这个函数对象本身 :param func: 初始函数对象 :return: 处理后的函数对象 """ @functools.wraps(func) def temp(): return func().upper() return temp @staticmethod def upper_sugar_lambada_version(func): pass class Easy(object): @staticmethod @Kongjian.upper_sugar def example(): return 'adassda' print(Easy.example()) 'ADASSDA' print(Easy.example.__name__) 'example' print(str.__name__) 'str'
0ccb3aec02f4bd2d50ab132f1282374ba300b39e
jiqin/leetcode
/codes/037.py
5,075
3.5
4
class Solution(object): def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ data_structure = [] for s in board: data_structure.append([]) for c in s: if c == '.': data_structure[-1].append([None, False, set(list(range(1, 10))), [0] * 10]) else: data_structure[-1].append([int(c), True, None, None]) for i, j in self.iter_all(): value, is_fixed, aviable_set, occupy_times = data_structure[i][j] if is_fixed: can_set = self.try_set_value(data_structure, i, j, value) assert can_set result = self.handle(data_structure, 0, 0) for i, j in self.iter_all(): board[i][j] = str(data_structure[i][j][0]) def print_data_structure(self, data_structure): print '>' * 100 for d1 in data_structure: print d1[0:3] print d1[3:6] print d1[6:9] print '' def handle(self, data_structure, i, j): if i is None: return True value, is_fixed, aviable_set, occupy_times = data_structure[i][j] i1, j1 = self.iter_next(i, j) if is_fixed: return self.handle(data_structure, i1, j1) assert value is None if len(aviable_set) == 0: return False aviable_list = list(aviable_set) for v in aviable_list: try_set = self.try_set_value(data_structure, i, j, v) if try_set: data_structure[i][j][0] = v r = self.handle(data_structure, i1, j1) if r: return r data_structure[i][j][0] = None self.un_try_set_value(data_structure, i, j, v) return False def iter_all(self): for i in range(9): for j in range(9): yield i, j def iter_next(self, i, j): if j < 8: return i, j + 1 elif i < 8: return i + 1, 0 else: return None, None def iter_prev(self, i, j): if j > 0: return i, j - 1 elif i > 0: return i - 1, 8 else: return None, None def iter_affect_indexs(self, i, j): for i1 in range(9): if i1 != i: yield i1, j for j1 in range(9): if j1 != j: yield i, j1 istart = i / 3 * 3 jstart = j / 3 * 3 for i1 in range(istart, istart + 3): for j1 in range(jstart, jstart + 3): if not (i1 == i and j1 == j): yield i1, j1 def try_set_value(self, data_structure, i, j, v): assert 0 <= i < 9 assert 0 <= j < 9 assert 1 <= v <= 9 can_set = True for i1, j1 in self.iter_affect_indexs(i, j): self.remove_value_from_aviable_list(data_structure, i1, j1, v) if not self.has_aviable_value(data_structure, i1, j1): can_set = False return can_set def un_try_set_value(self, data_structure, i, j, v): for i1, j1 in self.iter_affect_indexs(i, j): self.add_value_to_aviable_list(data_structure, i1, j1, v) def add_value_to_aviable_list(self, data_structure, i, j, v): value, is_fixed, aviable_set, occupy_times = data_structure[i][j] if is_fixed: return assert value != v occupy_times[v] -= 1 if occupy_times[v] == 0: aviable_set.add(v) def remove_value_from_aviable_list(self, data_structure, i, j, v): value, is_fixed, aviable_set, occupy_times = data_structure[i][j] if is_fixed: return # assert value != v if v in aviable_set: assert occupy_times[v] == 0 aviable_set.remove(v) occupy_times[v] += 1 def has_aviable_value(self, data_structure, i, j): value, is_fixed, aviable_set, occupy_times = data_structure[i][j] return is_fixed or len(aviable_set) > 0 def test(): for board in ( [ '53..7....', '6..195...', '.98....6.', '8...6...3', '4..8.3..1', '7...2...6', '.6....28.', '...419..5', '....8..79' ], [ "..9748...", "7........", ".2.1.9...", "..7...24.", ".64.1.59.", ".98...3..", "...8.3.2.", "........6", "...2759.." ] ): new_borad = [] for l in board: new_borad.append([c for c in l]) Solution().solveSudoku(new_borad) print '\n'.join([''.join(l) for l in new_borad]) print '' test()
c24194de7885a64a7881a8eb7b638cd86ddbe301
jiqin/leetcode
/codes/380.py
2,475
3.875
4
import random class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self._map = {} self._last_index = -1 self._list = [None] * 10000 self._rand = random.Random() self._rand_index = 0 def insert(self, val): """ Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool """ if val in self._map: return False self._last_index += 1 if self._last_index >= len(self._list): self._list.extend([None] * 1000) self._list[self._last_index] = val self._map[val] = self._last_index return True def remove(self, val): """ Removes a value from the collection. Returns true if the collection contained the specified element. :type val: int :rtype: bool """ if val not in self._map: return False index = self._map.pop(val) value = self._list[self._last_index] if index != self._last_index: self._list[index] = value self._map[value] = index self._last_index -= 1 return True def getRandom(self): """ Get a random element from the collection. :rtype: int """ if self._last_index < 0: return None elif self._last_index == 0: return self._list[self._last_index] else: if self._rand_index > self._last_index: self._rand_index = 0 value = self._list[self._rand_index] self._rand_index += 1 return value # return self._list[self._rand.randint(0, self._last_index)] obj = RandomizedSet() for i in range(100): assert obj.insert(i) for i in range(100): assert not obj.insert(i) for i in range(100): assert obj.remove(i) for i in range(100): assert not obj.remove(i) assert obj.getRandom() is None for i in range(100): assert obj.insert(i) import datetime t1 = datetime.datetime.now() count = [0] * 100 for i in range(1000000): count[obj.getRandom()] += 1 t2 = datetime.datetime.now() print 'time:', (t2-t1).total_seconds() print count obj = RandomizedSet() print obj.insert(1) print obj.insert(1) print obj.remove(1) print obj.getRandom() import timeit timeit.repeat()
eeb2068deeec87798355fe1bdd1e0f3508cbdcab
jiqin/leetcode
/codes/212.py
2,112
3.53125
4
class Solution(object): def findWords(self, board, words): """ :type board: List[List[str]] :type words: List[str] :rtype: List[str] """ word_map = {} for word in words: for i in range(len(word)): word_map[word[0:i+1]] = 0 for word in words: word_map[word] = 1 # print word_map results = [] for i in range(len(board)): for j in range(len(board[0])): tmp_word = '' history_pos = [] heap = [(i, j, 0)] while heap: x, y, l = heap.pop() if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]): continue assert len(history_pos) >= l history_pos = history_pos[0:l] if (x, y) in history_pos: continue assert len(tmp_word) >= l tmp_word = tmp_word[0:l] + board[x][y] history_pos.append((x, y)) # print x, y, tmp_word, heap, history_pos value = word_map.get(tmp_word) if value is None: continue if value == 1: results.append(tmp_word) heap.append((x - 1, y, l + 1)) heap.append((x + 1, y, l + 1)) heap.append((x, y - 1, l + 1)) heap.append((x, y + 1, l + 1)) return list(set(results)) for b, w in ( # ([ # ['o', 'a', 'a', 'n'], # ['e', 't', 'a', 'e'], # ['i', 'h', 'k', 'r'], # ['i', 'f', 'l', 'v'] # ], # ["oath", "pea", "eat", "rain"]), # (['ab', 'cd'], ['acdb']), # (["ab","cd"], ["ab","cb","ad","bd","ac","ca","da","bc","db","adcb","dabc","abb","acb"]), (["abc","aed","afg"], ["abcdefg","gfedcbaaa","eaabcdgfa","befa","dgc","ade"]), ): print Solution().findWords(b, w)
e381c063e594c2f3337c69af42c50c3a880e960b
mateusz5564/AplikacjeInternetowe2
/lab2_GDC.py
106
3.671875
4
def gcd(a, b): while b != 0: (a, b) = (b, a % b) return a print(gcd(10, 25))
925e59807e389fa2e6ee7559319352f446d0240e
EythorB/Assaignment8
/Assaignment8.py
1,520
3.984375
4
#Við ákvuðum að skipta þessu niður í 4 áttir. North, south, east og west. #Við vildum einnig að reitirnir myndu hafa táknið y og x #Eftir það notuðum við þá að north væri + x og south - #og þá west væri - y og east væri + #Síðan gerðum við forritið og allt heppnaðist vel for_low = "" x = 1 y = 1 p = True n = "(N)orth" s = "(S)outh" e = "(E)ast" w = "(W)est" while True: if y == 1: change = n + "." for_low = "n" if x == 1 and y == 2: change = n + " or " + e + " or " + s + "." for_low = "nes" if x == 2 and y == 2: change = s + " or " + w + "." for_low = "sw" if x == 1 and y == 3: change = e + " or " + s + "." for_low = "es" if x == 2 and y == 3: change = e + " or " + w + "." for_low = "we" if x == 3 and y == 3: change = s + " or " + w + "." for_low = "sw" if x == 3 and y == 2: change = n + " or " + s + "." for_low = "sn" if p == True: print("You can travel: " + change) p = False direct = str(input("Direction: ")) low = direct.lower() for l in for_low: if low == l: p = True if p == False: print("Not a valid direction!") if p == True: if low == "n": y += 1 if low == "s": y -= 1 if low == "e": x += 1 if low == "w": x -= 1 if x == 3 and y == 1: break
8883c75c0d2adc200493c43c69832f87dcaa7104
NTNTP/-home-noam-Mypython-.git-
/TD 1-2-3.py
8,260
3.640625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: # Exo 1 x, y, z = 8, 3.6, 5 addition = x + y + z soustraction = x - y - z produit = x * y * z exp = x ** y modulo = z % x div = z / x print("Exo 1 :\n", addition, soustraction, produit, exp, modulo, div,"\n\n") # In[6]: # Exo 2 s = "manger" t = "regnam" conc = s + t rep = conc * 5 extract_l = s[1] extract_last = s[-1] substring = s[0:3] longeur = len(s) # In[7]: # Exo 3 vrai = True faux = False x = 30 y = 15 egalite = vrai == faux difference = vrai != faux petit_ou_egale = y <= x # In[10]: # Exo 4 prenom, nom = "noam", "tkatch" nom_complet = prenom + " " + nom print((nom_complet + " * ") * 25) initiales = "N T" print((initiales + " * ") * 25) # In[11]: # Exo 5 prenom = input("Quel est votre prenom? ") nom = input("Quel est votre nom? ") print(prenom, nom) print(prenom[0] + ".", nom[0] + ".") print("Premiere lettre du nom de famille :", nom[0]) # In[ ]: # Exo 6 temp_c = float(input("Quelle est la temperature ? ")) calcul_c = ((9/5) * temp_c) + 32 calcul_f = (temp_c - 32) * (5/9) print(str(temp_c), "C = ", str(calcul_c), "F") print(str(temp_c), "F = ", str(calcul_f), "C") # In[ ]: # Exo 7 A = bool(input("Entrer une valeur de verite pour A : ")) B = bool(input("Entrer une valeur de verite pour B : ")) C = bool(input("Entrer une valeur de verite pour C : ")) s = input('Entrer une expression Boolenne (exprimee avec des "non", "ou", "et" et des parentheses) : ') new = s.replace("non", "not").replace("ou", "or").replace("et", "and") print(bool(new)) # ### ################################ TD2 # In[2]: c = "xs2536qjjp96j452jd45ssk5" c_num = "" c_alpha = "" for caracters in c: if str.isdigit(caracters) == True: c_num += caracters else: c_alpha += caracters print(c_num, c_alpha) # Exo 1.3 str_find = "s25" c.find(str_find) if c.find(str_find) != -1: new_c = c.replace(str_find, "s26") print(new_c) # Exo 1.4 list = ["p","9","6"] for string in list: first = c.find(string) print(first) print("\n") # In[3]: texte = "Je vais remonter ma note en python" compteur = 0 for lettre in texte: compteur += 1 if compteur == len(texte): print("good") else: print("not good") # Sans les espaces compteur_lettre = 0 for lettre in texte: if lettre == " ": pass else: compteur_lettre += 1 print(compteur_lettre) # Compter tous les mots dans la variable txt mots = len(texte.split()) print(mots) # Exo 2.2 texte2 = "We introduce here the Python language. To learn more about the language, consider going through the excellent tutorial https://docs.python.org/ tutorial. Dedicated books are also available, such as http://www.diveintopython.net/." mots2 = len(texte2.split()) print(mots2) #Oui le script est toujours viable # In[4]: # Exo 3 | 1-2 n = input("Entrer des mots separes par un espace : ") user_list = n.split() list_triee = sorted(user_list) print(list_triee) # In[5]: #Exo 4 couleurs = ["Pique","Trefle","Carreau","Coeur"] valeurs= ["as","2", "3", "4", "5", "6", "7", "8", "9", "10","valet","dame","roi"] jeux=[] for x in couleurs : for y in valeurs : card= y +" de "+ x jeux.append(card) print(jeux) # In[6]: from random import shuffle; couleurs = ["Pique","Trefle","Carreau","Coeur"] valeurs= ["as","2", "3", "4", "5", "6", "7", "8", "9", "10","valet","dame","roi"] shuffle (valeurs),(couleurs) print (valeurs), (couleurs) # In[7]: #Exo 6 prenom = input ("Quel est votre prenom ? ") nom = input("Quel est votre nom ? ") numero = input ("Quel est votre numéro de matricule ? ") print("Mon prénom est " + prenom + " , mon nom est " + nom + " , et mon matricule est " + numero) # In[8]: #Exo7 d = {"boite":"box", "pied":"foot", "main": "hand", "ordinateur":"computer", "souris":"mouse" } d["cerveau"] = "brain"; print (d) for i in d.items(): print(i) d["cerveau"] a = {"box":"boite", "foot":"pied", "hand":"main", "computer":"ordinateur", "mouse":"souris", "brain":"cerveau"} for i in a.items(): print(i) a["brain"] a["chemin"] = ["path","way"]; print (a) del a["chemin"] print (a) # In[9]: #Exo8 prenom = input ("Quel est votre prenom ? ") nom = input("Quel est votre nom ? ") matricule = input ("Quel est votre numéro de matricule ? ") a ={} a["prenom"] = prenom; a["nom"] = nom; a["matricule"] = matricule print (a) # In[ ]: ############################### TD3 # In[10]: # Exo 1.1 personne = int(input("Entrer un nombre à multiplier : ")) for x in range(1,11): print(personne*x) # In[11]: # Exo 1.2 personne = int(input("Entrer un nombre entier à multiplier : ")) for x in range(1, 11): print(personne*x, end=" ") # In[15]: # Exo 1.3 personne = int(input("Entrer un nombre entier pour trouver sa table : ")) for x in range(personne): print("La Table de", int(x) + 1, " est :") for i in range(1, 11): print((x+1)*i,) # In[16]: # Exo 1.4 personne = int(input("Entrer un nombre pour l'afficher en asterisk : ")) for x in range(personne): print("*" * (x+1)) # In[18]: # Exo 1.5 personne = int(input("Entrer un nombre pour l'afficher en asterisk : ")) for x in range(personne): print(" " * ((personne-1)-x) + ("* " * (x+1))) # In[19]: # Exo 2.1 jours = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] mois = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] moisjours = [] longueur = len(jours) - len(mois) if longueur == 0: for x in range(len(jours)): moisjours.append((mois[x], jours[x])) else: print("Je ne peux pas le faire") print (moisjours) # In[20]: # Exo 2.2 annee = [] for month in moisjours: for x in range(month[1]): annee.append((str(x+1)) + " " + month[0]) print (annee) # In[21]: # Exo 2.3 annee2 = [] jours_semaine = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] for jour in range(365): annee2.append(jours_semaine[jour%len(jours_semaine)] + " " + annee[jour]) print (annee2) # In[22]: # Exo 2.4-5 dicionnaire = {} jours_semaine = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] for jour in range(365): dicionnaire[annee[jour]] = jours_semaine[jour%len(jours_semaine)] print(dicionnaire) print(dicionnaire["28 October"]) # In[23]: # Exo 3.1 liste_notes = [] while len(liste_notes) < 3: user = int(input("Entrer une note : ")) liste_notes.append(user) minimum = min(liste_notes) maximum = max(liste_notes) somme = 0 for notes in liste_notes: somme += int(notes) moyenne = float(somme)/len(liste_notes) print("moyenne " + str(moyenne), "minimum " + str(minimum), "maximum " + str(maximum)) #exo3_1() # In[24]: # Exo 3.2 user_nombres = int(input("Entrer le nombre de notes que vous voulez entrer ? ")) liste_notes = [] while len(liste_notes) < user_nombres: personne = int(input("Entrer une note sur 20 : ")) liste_notes.append(personne) mini = min(liste_notes) maxi = max(liste_notes) som = 0 for notes in liste_notes: som += int(notes) moy = float(som) / len(liste_notes) print("moyenne " + str(moy), "minimum " + str(mini), "maximum " + str(maxi)) # In[26]: # Exo 3.3 liste_notes = [] while True: personne = input("Entrer une note : (fin pour finir) ") if personne == "fin": break else: liste_notes.append(float(personne)) mini = min(liste_notes) maxi = max(liste_notes) som = 0 for notes in liste_notes: som += int(notes) moy = float(som) / len(liste_notes) print("moyenne " + str(moy), "minimum " + str(mini), "maximum " + str(maxi)) # In[28]: #Exo 4 from random import * nb_aleatoire1 = randint(1,100) correct = False while not correct: personne = int(input("Devine le nombre entre 1 et 100 ")) if nb_aleatoire1 > personne: print("Trop petit") elif nb_aleatoire1 < personne: print("trop grand") elif nb_aleatoire1 == personne: break if nb_aleatoire1 == personne: rejoue = input ("Bravo magl, tu veux rejouer ? (y or n) ") if rejoue == 'y': #print (nb_aleatoire) # In[ ]:
74ac2b7a759f96da3e8b4b89befd61daf191b427
amanbhal/pythonCodes
/editDistance_DP.py
425
3.53125
4
def editDistance(A,B): matrix = [[0 for i in range(len(A)+1)] for i in range(len(B)+1)] for i in range(len(B)+1): for j in range(len(A)+1): if i==0: matrix[i][j] = j elif j==0: matrix[i][j] = i elif B[i-1]==A[j-1]: matrix[i][j] = matrix[i-1][j-1] else: matrix[i][j] = 1 + min(matrix[i][j-1],matrix[i-1][j],matrix[i-1][j-1]) for i in matrix: print i A = "geek" B = "gesek" editDistance(A,B)
8c9d4f86f361b0595004cef09aecef5d0735d713
MikeConnelly/PasswordManager
/passwordmanager/interface/interface.py
7,552
3.578125
4
from getpass import getpass from passwordmanager.src.password_manager import UserError, AccountError class Interface: """ command line interface for password manager """ def __init__(self, pm): self.pm = pm def get_user(self): """create new user or continue to login""" while self.pm.user is None: print('enter login or newuser') command = input() if command == 'newuser': self.create_user_cmd() elif command == 'login': self.login_cmd() else: print('---invalid command---') self.get_cmd() def get_cmd(self): """main application loop to execute user commands""" while True: print('1: retrieve table') print('2: add an entry') print('3: remove an entry') print('4: change an entry') print('5: add a field') print('6: logout') commands = { '1': self.retrieve_table_cmd, '2': self.add_user_entry_cmd, '3': self.remove_entry_cmd, '4': self.change_entry_cmd, '5': self.add_column_cmd, '6': self.logout_cmd } try: commands[input()]() except KeyError: print('---invalid input---') def create_user_cmd(self): """CLI to create new user""" while self.pm.user is None: print('Enter username: ') username = input() masterpass = '' while not masterpass: print('Create password: ') masterpass = getpass(prompt='') print('Confirm password: ') if getpass(prompt='') != masterpass: print('---Password do not match---') masterpass = '' try: self.pm.create_user_and_login(username, masterpass) except UserError as err: print(str(err)) def login_cmd(self): """CLI to login""" while not self.pm.user: print('Enter username: ') username = input() print('Enter password: ') password = getpass(prompt='') try: self.pm.login(username, password) except UserError as err: print(str(err)) def retrieve_table_cmd(self): """prints the current user's table of accounts""" table = self.pm.retrieve_table() print('---table---') for account in table: index = 1 length = len(account) for field, value in account.items(): end = '\n' if index == length else ', ' print(f"{field}: {value}", end=end) index += 1 print('-----------') def add_user_entry_cmd(self): """CLI to add an account for the current user""" print('---add an entry or type "exit"---') if self.pm.user.custom_cols: custom_cols = self.pm.user.custom_cols.split(',') expansion = {} else: custom_cols = [] expansion = None try: print('Account: ') account = get_input_or_exit() print('Email: ') username = get_input_or_exit() print('Password: ') password = get_input_or_exit(password=True) print('URL (optional): ') url = get_input_or_exit() for col in custom_cols: print(f"{col} (optional): ") value = get_input_or_exit() if value: expansion[col] = value except ExitError: return try: self.pm.add_user_entry(account, username, password, url, expansion) print('---account added---') except AccountError as err: print(str(err)) def select_user_account_cmd(self, mode='remove or change'): """ print user accounts and return the one selected\n raises ExitError """ table = self.pm.retrieve_table() selection = None index = 1 account_map = {} for account in table: account_map[index] = account print(str(index) + ': ' + account['name']) index += 1 while not selection: print(f"Enter the index of the account you want to {mode} or \"exit\"") try: selection = account_map[int(get_input_or_exit())] except (KeyError, ValueError): print('---invalid input---') return selection def remove_entry_cmd(self): """user selects an account to remove""" print('---remove an entry---') try: selection = self.select_user_account_cmd('remove') confirmation = '' while confirmation not in ('y', 'Y'): print(f"are you sure you want to remove {selection['name']}? (y/n):") confirmation = input() if confirmation in ('n', 'N'): return self.pm.remove_entry(selection) except ExitError: return print(selection['name'] + ' successfully removed') def change_entry_cmd(self): """user selects an account and field to update""" print('---change an entry---') try: selection = self.select_user_account_cmd('change') except ExitError: return custom_fields = self.pm.user.custom_cols.split(',') if self.pm.user.custom_cols else [] all_fields = ['name', 'password', 'email', 'url'] all_fields.extend(custom_fields) index = 1 cols = {} for field in all_fields: value = selection[field] if field in selection else '' print(f"{index}. {field}: {value}") cols[str(index)] = field index += 1 col_selection = None while not col_selection: print("Enter the index of the field you want to change or \"exit\"") is_password = col_selection == 'password' try: col_selection = cols[get_input_or_exit(password=is_password)] except (KeyError, ValueError): print('---invalid input---') except ExitError: return print('enter new field') new_field = input() self.pm.change_entry(selection, col_selection, new_field) print('---account successfully updated---') def add_column_cmd(self): """CLI to add a column to the user's table of accounts""" print('---enter new column name or "exit"---') try: name = get_input_or_exit() self.pm.add_column(name) except UserError as err: print(str(err)) except ExitError: return def logout_cmd(self): """logout and exit""" self.pm.logout() exit(0) def run(pm): """starts command line interface""" cli = Interface(pm) cli.get_user() def get_input_or_exit(password=False): """get user input or raise ExitError""" value = getpass(prompt='') if password else input() if value == 'exit': raise ExitError return value class ExitError(Exception): """exception raised when exiting a function through get_input_or_exit"""
248ef272c1b5518bc65b5e1b3bea27c7c0d1e9a8
thabbott/prisoners-dilemma
/TitForTat.py
811
3.953125
4
from Prisoner import Prisoner """ TitForTat: a Prisoner who copies their opponent's last choice. """ class TitForTat(Prisoner): """ This strategy requires remembering the opponent's last choice, so the class overrides the constructor to initialize a field to store this information. The value initially stored in last_strategy will be the strategy picked for the first round. """ def __init__(self): self.last_strategy = True """ This Prisoner always does what their opponent did last """ def pick_strategy(self): return self.last_strategy """ This Prisoner also has to remember their opponent's last strategy """ def process_results(self, my_strategy, other_strategy): self.last_strategy = other_strategy
927c077986634720b228b8478194895e077a381f
thabbott/prisoners-dilemma
/Prisoner.py
944
3.875
4
""" Prisoner superclass """ class Prisoner(): """ Constructor. Called once at the start of each match. If needed, override this method to initialize any auxiliary data you want to use to determine your Prisoner's strategy. This data will persist between rounds of a match but not between matches. """ def __init__(self): pass """ Pick a strategy: return True to cooperate; return False to defect. If not overridden, the Prisoner will always cooperate. """ def pick_strategy(self): return True """ Process the results of a round. This provides an opportunity to store data that preserves memory of previous rounds. Parameters ---------- my_strategy: bool This Prisoner's strategy other_strategy: bool The opponent's strategy """ def process_results(self, my_strategy, other_strategy): pass
52ce201ab2761c9392aeabe85a0fe336d680d415
feldcody/zip-shapefiles
/example_usage.py
5,442
3.796875
4
import zipper def zip_shapefile_simple(): try: ### Inputs input_shapefile = "C:\\Temp\\Shapefiles\\test.shp" # this dir will be searched for shapefiles shape_zipper = zipper.ShapefileZipper() # Create Instance of Class # By only passing an input file, an individual shapefilename.zip will be created # Existing zip file will be deleted if it matches the name of the new .zip to be created.. results = shape_zipper.zip_shapefile(input_shapefile) # returns a string path to the .zip that was created if len(results) > 1: print("SUCCESS! " + str(results)) else: print("WARNING: SHAPEFILE NOT ZIPPED: " + input_shapefile) except: print("ERROR: BIG FAIL!") def zip_shapefile_output_zip(): try: ### Inputs input_shapefile = "C:\\Temp\\Shapefiles\\test.shp" # this dir will be searched for shapefiles output_zip = "C:\\TEMP\\shapefiles\\myZip1.zip" shape_zipper = zipper.ShapefileZipper() # Create Instance of Class # Existing zip file will be deleted if it matches the name of the new .zip to be created.. results = shape_zipper.zip_shapefile(input_shapefile, output_zip) # returns a string path to the .zip that was created if len(results) > 1: print("SUCCESS! " + str(results)) else: print("WARNING: SHAPEFILE NOT ZIPPED: " + input_shapefile) except: print("ERROR: BIG FAIL!") def zip_shapefile_output_zip_append(): try: ### Inputs input_shapefile = "C:\\Temp\\Shapefiles\\test.shp" # this dir will be searched for shapefiles output_zip = "C:\\TEMP\\shapefiles\\myZip2.zip" file_mode = 'a' # this is append mode, so any shapefiles found will be appending to the C:\\TEMP\\myZip.zip, # Warning, using the append mode it's possible to append duplicate files into the .zip... shape_zipper = zipper.ShapefileZipper() # Create Instance of Class results = shape_zipper.zip_shapefile(input_shapefile, output_zip, file_mode) # returns a string path to the .zip that was created if len(results) > 1: print("SUCCESS! " + str(results)) else: print("WARNING: SHAPEFILE NOT ZIPPED: " + input_shapefile) except: print("ERROR: BIG FAIL!") def zip_dir_simple(): try: ### Inputs input_dir = "C:\\TEMP\\Shapefiles" # this dir will be searched for shapefiles shape_zipper = zipper.ShapefileZipper() # Create Instance of Class # By just passing an input directory, individual shapefilename.zip's will be created # Existing zip files will be deleted if they match the name of the new .zip to be created.. results = shape_zipper.zip_shapefile_directory(input_dir) # returns a list of zips that were created, or None if nothing run if results: print("SUCCESS!" + str(results)) else: print("NO SHAPEFILES ZIPPED, MAYBE THERE AREN'T ANY WITHIN " + input_dir) except: print("BIG FAIL!") def zip_dir_output_zip(): try: ### Inputs input_dir = "C:\\TEMP\\Shapefiles" # this dir will be searched for shapefiles output_zip = "C:\\TEMP\\Shapefiles\\myZipDir.zip" # Any shapefiles located within the input directory will be appended into a single zip shape_zipper = zipper.ShapefileZipper() # Create Instance of Class # Existing zip files will be deleted if they match the name of the new .zip to be created.. results = shape_zipper.zip_shapefile_directory(input_dir, output_zip) # returns a list of zips that were created if results: print("SUCCESS!" + str(results)) else: print("NO SHAPEFILES ZIPPED, MAYBE THERE AREN'T ANY WITHIN " + input_dir) except: print("BIG FAIL!") def zip_dir_output_zip_append(): try: ### Inputs input_dir = "C:\\TEMP\\Shapefiles" # this dir will be searched for shapefiles output_zip = "C:\\TEMP\\Shapefiles\\myZipDir2.zip" # Any shapefiles located within the input directory will be appended into a single zip file_mode = 'a' # this is append mode, so any shapefiles found will be appending to the C:\\TEMP\\myZip.zip, # Warning, using the append mode it's possible to append duplicate files into the .zip... shape_zipper = zipper.ShapefileZipper() # Create Instance of Class # Existing zip files will be deleted if they match the name of the new .zip to be created.. results = shape_zipper.zip_shapefile_directory(input_dir, output_zip, file_mode) # returns a list of zips that were created if results: print("SUCCESS!" + str(results)) else: print("NO SHAPEFILES ZIPPED, MAYBE THERE AREN'T ANY WITHIN " + input_dir) except: print("BIG FAIL!") # call example functions for directories # print("Call zip_dir_simple()") zip_dir_simple() print("Call zip_dir_output_zip()") zip_dir_output_zip() print("zip_dir_output_zip_append()") zip_dir_output_zip_append() # call example functions for single shapefiles print("zip_shapefile_simple()") zip_shapefile_simple() print("zip_shapefile_output_zip()") zip_shapefile_output_zip() print("zip_shapefile_output_zip_append()") zip_shapefile_output_zip_append()
e284861b85523ad7457328f1424171ce9c95bcff
netromdk/tbgame
/tbgame.py
1,185
3.828125
4
# -*- Coding: utf-8 -*- # Requires python 3.x+ # tbgame implements turn-based games for making board games easier to # play without requiring a lot of paper and pencils. import sys from games import Assano, Triominos GAMES = {"assano": Assano, "triominos": Triominos} def usage(): print("Usage: {} [-h] <game> [<saved data>]".format(sys.argv[0])) print("Start new game or resume using saved data file.") print("\nAvailable games:") for g in GAMES: print(" {}".format(g)) if __name__ == "__main__": args = len(sys.argv) if args <= 1 or args > 3: usage() exit(-1) cmd = sys.argv[1].strip().lower() if cmd == "-h": usage() exit(0) savedData = None if args == 3: savedData = sys.argv[2] if not cmd in GAMES: print("Game not found: {}".format(cmd)) exit(-1) print("Game: {}".format(cmd)) if savedData: print("Resuming: {}".format(savedData)) print("") game = GAMES[cmd]() if savedData: game.load(savedData) else: game.setup() game.start() while not game.isFinished(): game.nextTurn() game.end()
ba93ce5b67eddaa894b1e386981f0f3844bff3b1
lgruelas/extra-geometria
/segment.py
919
3.953125
4
class Segment: """ Representa un segmento de recta, definido por dos puntos. ATTRS: - _upper_endpoint - _lower_endpoint - _color """ def __init__(self, p1, p2, color=None): """ Asume que necesariamente p1 != p2. ARGS: - p1 (SegmentPoint2D): endpoint. - p2 (SegmentPoint2D): endpoint. RAISES: - ValueError: si p1 y p2 son iguales. """ if p1 == p2: raise ValueError("p1 and p2 can't be equal.") elif p1 > p2: self._upper_endpoint = p1 self._lower_endpoint = p2 else: self._lower_endpoint = p1 self._upper_endpoint = p2 self._lower_endpoint.set_segment(self) self._upper_endpoint.set_segment(self) self._color = color def get_upper(self): return self._upper_endpoint def get_lower(self): return self._lower_endpoint def get_color(self): return self._color
06f2937be9c9b9dfc166b60c1b46787ac843ff1a
eseng4313/pyGame-project
/turtle files/g.py
296
3.6875
4
import turtle bob = turtle.Turtle() bob.speed(11) bob.shape("turtle") for times in range(300): bob.forward(times) bob.right(190) bob.forward(40) bob.forward(times) bob.circle(30) bob.color("green") bob.pencolor("yellow")