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
a64ba64cd3ec6fae0217460100145edeb8fbfb63
sniemi/SamPy
/sandbox/src1/gnomonic/gnomonic.py
3,066
3.5625
4
def transformation(x, y, theta1, lam0): from math import sin, cos, asin, atan, sqrt rho = sqrt(x**2. + y**2.) c = atan(rho) #rho == 0. ???? if (rho == 0.): theta = 0. lam = 0. else: theta = asin((cos(c)*sin(theta1)) + (y*sin(c)*cos(theta1)/rho)) lam = lam0 + atan((x*sin(c))/((rho*cos(theta1)*cos(c)) - (y*sin(theta1)*sin(c)))) return theta, lam #CHANGE THESE: #starting coordinates: x0 = 0.2 y0 = 0. #end coordinates: x1 = 0.0000001 y1 = 0. import math #central lattitude and longitude respectively: theta2 = 30./180.*math.pi #30 degrees? #theta1 = math.pi/2. #pole? theta1 = 80./180.*math.pi #80 degrees #theta1 = 0. #equator? lam0 = 0. #transformations answ1 = transformation(x0,y0,theta1,lam0) tr1 = transformation(x1,y1,theta1,lam0) tr2 = transformation(x1,y1,theta2,lam0) answ21 = answ1[0] - tr1[0] answ22 = answ1[1] - tr1[1] print "Teloffset/Slitoffset Test!\n" print "Starting coordinates:" print "x = %6.2f\ny = %6.2f" % (x0, y0) #print "Corresponds to:\n" #print "theta = %f\nlambda = %f" % (answ1[0], answ1[1]) print "\nMoving Telescope:\n" print "delta(x) = %6.2f\ndelta(y) = %6.2f\n" % (x0-x1, y0-y1) print "Corresponds to movement of:\n" print "delta(DEC) = %f\ndelta(RA) = %f" % (answ21, answ22) import numpy as N import pylab as P xchange = N.arange(-0.5,0.5,0.01) y = 0. decx1 = []; rax1 = []; decy1 = []; ray1 = [] decx2 = []; rax2 = []; decy2 = []; ray2 = [] for x in xchange: decx1.append((transformation(x, y, theta1, lam0)[0] - tr1[0])) rax1.append((transformation(x, y, theta1, lam0)[1] - tr1[1])) decx2.append((transformation(x, y, theta2, lam0)[0] - tr2[0])) rax2.append((transformation(x, y, theta2, lam0)[1] - tr2[1])) x = 0. ychange = N.arange(-0.5,0.5,0.01) for y in ychange: decy1.append((transformation(x, y, theta1, lam0)[0] - tr1[0])) ray1.append((transformation(x, y, theta1, lam0)[1] - tr1[1])) decy2.append((transformation(x, y, theta2, lam0)[0] - tr2[0])) ray2.append((transformation(x, y, theta2, lam0)[1] - tr2[1])) ychange -= y1 xchange -= x1 P.subplot(211) P.plot(xchange, rax1,'b-.', label='RA, 80deg') P.plot(xchange, decx1,'r-', label='DEC, 80deg') P.plot(xchange, rax2, 'g--', label='RA, 30deg') P.plot(xchange, decx2,'y.', label='DEC, 30deg') P.xlabel("x Movement") P.ylabel("Telescope Movement (in arbitrary units)") P.legend() P.subplot(212) P.plot(ychange, ray1, 'b-.', label='RA, 80deg') P.plot(ychange, decy1, 'r-', label='DEC, 80deg') P.plot(ychange, ray2, 'g--', label='RA, 30deg') P.plot(ychange, decy2, 'y.', label='DEC, 30deg') P.xlabel("y Movement") P.ylabel("Telescope Movememnt (in arbitrary units)") P.legend() P.show() #from coords to x,y #lattitude #theta = 80 #longitude #lam = 80 #central longitude #lam0 = 0 #central lattitude #theta1 = 0 #c = (sin(theta1)*sin(theta)+(cos(theta1)*cos(theta)*cos(lam-lam0))) #x = (cos(theta)*sin(lam-lam0) / (cos(c))) #y = ((cos(theta1)*sin(theta)) - (sin(theta1)*cos(theta)*cos(lam - lam0))) / (cos(c)) #print #print "x = %f\ny = %f" % (x,y) #print
6d986d35f8b8fdd6a01bbcb499ad58f119568bb1
hsp48/IT610
/code2.py
1,750
3.8125
4
# Hemali Patel import datetime d = datetime.datetime.utcnow() Time = d.strftime("%a, %d %b %Y %H:%M:%S GMT\r\n") PatientName = input("Enter your name: ") print("Welcome to your HealthRecord, " + PatientName) print("Today is " + Time) #PatientAddress = input("Enter your address: ") #PatientDOB = input("Enter your Date of Birth (MM/DD/YYYY): ") PatientWeight = input("Enter your Weight: ") PatientTemp = input("Enter your Temperature: ") PatientPulse = input("Enter your Pulse Rate: ") PatientBloodPressure = input("Enter your Blood Pressure (Systolic/Diastolic): ") Systolic = PatientBloodPressure.split("/")[0] Diastolic = PatientBloodPressure.split("/")[1] SRead = "" DRead = "" for i in Systolic: if int(Systolic) < 120: SRead = "Systolic - Normal" if int(Systolic) in range(120, 129): SRead = "Systolic - Elevated" if int(Systolic) in range(130, 139): SRead = "Systolic - High Blood Pressure (Hypertension) Stage 1" if int(Systolic) in range(140, 180): SRead = "Systolic - High Blood Pressure (Hypertension) Stage 2" if int(Systolic) >= 180: SRead = "Systolic - Hypertensive Crisis" #print("Systolic Reading Too High") print(SRead) for ii in Diastolic: if int(Diastolic) < 80: DRead = "Diastolic - Normal" if int(Diastolic) in range(80, 90): DRead = "Diastolic - High Blood Pressure (Hypertension) Stage 1" if int(Diastolic) in range(91, 120): DRead = "Diastolic - High Blood Pressure (Hypertension) Stage 2" if int(Diastolic) >= 120: #print("Diastolic Reading Too High") DRead = "Diastolic - Hypertensive Crisis" print(DRead) PatientOxygen = input("Enter your SPO2 Reading: ") PatientNotes = input("Enter any Notes: ")
8dda3709dd801f7ec2b041429f6e8b3834063fac
Ericzyr/pyc_file
/studyeveryday/day1.py
226
3.71875
4
#!/usr/bin/env/python # _*_coding:utf-8_*_ # Author # name = input("input you name:") # age = input("imput you age:") # print(name, age) a = 3 b = 4 if a == b: print("-eq") elif a != b: print("=") else: print("=!")
9fd7f5d632b9c5415e66cca8835bd6fdea6091ce
Ericzyr/pyc_file
/project/ls.py
226
3.53125
4
#!/usr/bin/env/python # _*_ coding:utf-8 _*_ # Author:Eric def outer(func): def inner(): #print('before') func() #print('after') return inner @outer def f1(): print("F1") s = f1() print(s)
43faba67c87ad7de71c0bfc9c654529789390200
Ericzyr/pyc_file
/project/regex.py
733
3.65625
4
#!/usr/bin/env/python #_*_coding:utf-8_*_ # Author #!/usr/bin/python import urllib import urllib.request import os import re ip = os.popen("ipconfig").read() ipadres = "IPv4 地址.* (.*)" ipsone ="子网掩.* (.*)" getcode = re.compile(ipadres) getcode1 = re.compile(ipsone) codelist = getcode.findall(ip) codelist1 = getcode1.findall(ip) getip=codelist[0] getip1=codelist1[0] print("获取的电脑的IP地址:", getip) print("获取的电脑子网掩码:", getip1) line = "Cats are smarter than dogs" word = re.match(r'(.*) are (.*?) .*', line) if word: print("word.group() : ", word.group()) print("word.group(1) : ", word.group(1)) print("word.group(2) : ", word.group(2)) else: print("No match!!")
8e8385ef43328339c89263ba5d73f31edf240f7c
ralitsapetrina/Programing_fundamentals
/Dictionaries/wardrobe.py
958
3.578125
4
n = int(input()) counter = 0 clothes_dict = {} while counter < n: colors = input().split(" -> ") key = colors[0] value = colors[1].split(",") if key in clothes_dict.keys(): clothes_dict.get(key).extend(value) else: clothes_dict[key] = value counter += 1 searching = input().split(" ") def printing_output(dict, search): printed_values_list = [] for key, value in dict.items(): print(f'{key} clothes:') for items in value: if items in printed_values_list: continue if search[0] == key: if search[1] == items: print(f'* {items} - {value.count(items)} (found!)') else: print(f'* {items} - {value.count(items)}') else: print(f'* {items} - {value.count(items)}') printed_values_list.append(items) printing_output(clothes_dict, searching)
b537156162716df52ba50d403fb317ac66bcccb5
ralitsapetrina/Programing_fundamentals
/functions_and_debugging/greater_of_two_values.py
461
4.09375
4
def greater_int(v1, v2): print(max(int(v1), int(v2))) def greater_string(v1, v2): print(max(v1, v2)) def greater_char(v1, v2): print(max(v1, v2)) if __name__ == "__main__": value_type = input() value1 = input() value2 = input() if value_type == "char": greater_char(value1, value2) elif value_type == "string": greater_string(value1, value2) elif value_type == "int": greater_int(value1, value2)
99021eeb004c8deb749be2c581335f15be899bb0
ralitsapetrina/Programing_fundamentals
/Dictionaries/mixed_phones.py
405
3.828125
4
data_list = input().split(" : ") phone_dict = {} while not data_list[0] == "Over": if data_list[0].isdigit(): value = data_list[0] key = data_list[1] elif data_list[1].isdigit(): value = data_list[1] key = data_list[0] phone_dict[key] = value data_list = input().split(" : ") for key, value in sorted(phone_dict.items()): print(f'{key} -> {value}')
4bc67383a9503d15a5adc74b398e29d196a10570
ralitsapetrina/Programing_fundamentals
/functions_and_debugging/printing_triangle.py
368
3.96875
4
def printing_triangle(num): for row in range(1, num + 1): for col in range(1, row+1): print(f'{col}', end=" ") print() for row2 in range(1, num + 1): for col2 in range(1, num-row2+1): print(f'{col2}', end=" ") print() if __name__ == "__main__": number = int(input()) printing_triangle(number)
038f6792547910c110f95e6a43a039fb25e39739
ralitsapetrina/Programing_fundamentals
/EXAM/2_command_center.py
1,161
3.8125
4
data_list = list(map(int, input().split())) def multiply_inlist(data_list, command_list): element = command_list[1] n = int(command_list[2]) if element == 'list': data_list = data_list * n elif int(element) in data_list: while int(element) in data_list: data_list.remove(int(element)) data_list.append(int(element) * n) return data_list def contains_el(data_list, command_list): element = int(command_list[1]) if element in data_list: print('True') else: print('False') def add_el(data_list, command_list): element = list(map(int, command_list[1].split(','))) data_list.extend(element) return data_list commands_dict = {'multiply': multiply_inlist, 'contains': contains_el, 'add': add_el} while True: command_list = input().split() if command_list[0] == 'END': break if command_list[0] == 'multiply' or command_list[0] == 'add': data_list = commands_dict[command_list[0]](data_list, command_list) else: commands_dict[command_list[0]](data_list, command_list) sorted_list = (sorted(data_list)) print(*sorted_list)
54cf28e7511aafcd6d8b1c58fc5b7fad4b92dff9
Motselisi/FunctionPackage
/FunctionPackage/recursion.py
447
3.9375
4
def sum_array(array): return(sum(array)) def fibonacci(n): if n <= 1: return n else: return fibonacci(n - 1) + fibonacci(n - 2) def factorial(n): if n <1: return 1 else: returnNumber = n * factorial( n - 1 ) print(str(n) + '! = ' + str(returnNumber)) return returnNumber def reverse(word): if word == "": return word else: return word[-1] + reverse(word[:-1])
cb8844bcac1c3fa02a35fbab9c6e8fd5c993cb74
MysticSoul/Exceptional_Handling
/answer3.py
444
4.21875
4
# Program to depict Raising Exception ''' try: raise NameError("Hi there") # Raise Error except NameError: print "An exception" raise # To determine whether the exception was raised or not ''' '''Answer2.=> According to python 3.x SyntaxError: Missing parentheses in call to print According to python 2.x The output would be: NameError: Hi there '''
43d0ff3a57bd0c6b7d14e7a1b1fd39f1fb7de46e
JTSchwartz/chorecore-py
/chorecore/strings.py
149
3.5
4
def replacement_map(alter: str, replacements: dict): for key in replacements.keys(): alter = alter.replace(key, replacements[key]) return alter
81629a87c33df62b0c6772f9bbd96d7737135031
csestelo/advent_of_code
/2021/day-2/part_2.py
503
3.671875
4
from io import StringIO def calculate_position_as_in_manual(instructions: StringIO) -> int: horizontal_position = 0 depth = 0 aim = 0 for step in instructions: direction, qty = step.strip().split(' ') qty = int(qty) if direction == 'forward': horizontal_position += qty depth += aim * qty elif direction == 'up': aim -= qty else: aim += qty return horizontal_position * depth
0d74ce6cdac536a6db72fde5dcc54ad4d5491a76
SupahXYT/pathfinders
/thread.py
795
3.578125
4
import threading from random import random from time import sleep class Useful: def __init__(self): self.list = [] def random(self): for i in range(15): self.list.append(random()) sleep(1) class Visualize: def __init__(self): self.use = Useful() def main(self): # upon request, start defs # then draw in main loop, only updating according to rects in maze t1 = threading.Thread(target=self.use.random) t1.start() while(True): self.print() sleep(1) # 'draw' function def print(self): while(len(self.use.list) > 0): element = self.use.list.pop(0) print(element) if __name__ == '__main__': v = Visualize() v.main()
1b1831a88321c97dad633eb7b0b81b20b59631c7
huangliu0909/Random-SkipList
/test_sl.py
5,375
3.59375
4
import random import datetime import sys minint = 0 maxint = sys.maxsize class Node(object): def __init__(self, key=minint, value=[], level=1): self.key = key self.value = value self.level = level self.right = None self.down = None class SkipList(object): def __init__(self): # 初始化层数和这一层的节点数 self.top = Node(minint) self.top.left = None self.top.right = Node(maxint) self.top.right.left = self.top def findNode(self, key): return self.searchNode(self.top, key) def searchNode(self, node, key): while key >= node.right.key: node = node.right if key == node.key: return node if node.down is None: return None return self.searchNode(node.down, key) def insertNode(self, top, key, value): while key >= top.right.key: top = top.right if key == top.key: return None if top.down is None: node = Node(key, value) node.right = top.right top.right = node node.level = top.level return node downnode = self.insertNode(top.down, key, value) if downnode is not None: node = Node(key, value) node.right = top.right top.right = node node.down = downnode node.level = top.level return node return None def insert(self, key, value): k = self.getK() # 初始化现有最高点的level到新的level之间的链表 for e in range(self.top.level + 1, k + 1): topleft = Node(minint, level=e) topright = Node(maxint, level=e) topleft.right = topright topleft.down = self.top self.top = topleft top = self.top while top.level != k: top = top.down self.insertNode(top, key, value) def getK(self): k = 1 while random.randint(0, 100) > 50: k = k + 1 return k def update_node(self, key, value): if self.findNode(key) is not None: self.findNode(key).value.append(value) else: l = [] l.append(value) self.insert(key, l) def delete(self, key): node = self.top flag = 0 while node is not None: while key >= node.right.key: former = node node = node.right if key == node.key: print("find delete") # print(former.right.key) search_node = node flag = 1 break node = node.down if flag == 0: print("delete not found") return None while search_node is not None: """ print("level") print(search_node.level) print("now") print(search_node.key) print(search_node.right.key) print(search_node.level) print("former") print(former.key) print(former.right.key) print(former.level) print("right") print(search_node.right.key) print(search_node.right.right.key) """ former.right = search_node.right search_node = search_node.down former = former.down def searchByRange(self, k1, k2): result = [] while self.findNode(k1) is None: k1 = k1 + 1 node = self.findNode(k1) while node is not None: result.append(node.value) if node.right.key >k2: break node = node.right return result if __name__ == '__main__': start = datetime.datetime.now() filename = "linux_distinct.txt" skiplist = SkipList() flag = 0 with open(filename, "rb") as f: for fLine in f: flag += 1 s = fLine.decode().strip().replace("\n", "").split(" ") collection = int(s[0]) num = int(s[1]) skiplist.update_node(num, collection) end = datetime.datetime.now() print("建立时间:" + str((end - start))) start = datetime.datetime.now() print(skiplist.findNode(2148).value) end = datetime.datetime.now() print("查询时间:" + str((end - start))) start = datetime.datetime.now() skiplist.delete(2148) end = datetime.datetime.now() print("删除时间:" + str((end - start))) print("删除后: " + str(skiplist.findNode(2148))) l = [] l.append(777) skiplist.insert(2148, l) print("插入后: " + str(skiplist.findNode(2148).value)) start = datetime.datetime.now() skiplist.update_node(2148, 888) end = datetime.datetime.now() print("更新结点时间:" + str((end - start))) print("更新后: " + str(skiplist.findNode(2148).value)) start = datetime.datetime.now() print(skiplist.searchByRange(1, 10)) end = datetime.datetime.now() print("区间查询结点时间:" + str((end - start)))
6e4eca96847b5be0be67a2b9998bf1205fcf0fdd
sripushkar/Gas-Money
/main.py
2,827
3.828125
4
import requests import xml.etree.ElementTree as ET print("Welcome to Gas Money Calculator by Sri Julapally") print("Make sure to only enter appropriate inputs for the below questions, or the program will fail.") pricesUrl = "https://www.fueleconomy.gov/ws/rest/fuelprices" pricesList = requests.get(pricesUrl) pricesRoot = ET.fromstring(pricesList.content) dieselPrice = pricesRoot[1].text regularPrice = pricesRoot[7].text midgradePrice = pricesRoot[5].text premiumPrice = pricesRoot[6].text make = input("What is the make(brand) of your car? ") year = input("What is the year of your car? ") carUrl = "https://www.fueleconomy.gov/ws/rest/vehicle/menu/model?year="+year+"&make="+make carList = requests.get(carUrl) carsRoot = ET.fromstring(carList.content) print("These are the models with avaliable data:") for models in carsRoot.findall("menuItem"): model = models.find("value").text print(model+"\n") modelSelection = input("Do you see your model in this list? If you do, please type in the model name now. If you do not see it, please enter 0, and you will be prompted to manually enter the fuel economy.\n") if modelSelection != "0": modelSelection = modelSelection.replace(" ", "+") modelUrl = "https://www.fueleconomy.gov/ws/rest/vehicle/menu/options?year="+year+"&make="+make+"&model="+modelSelection modelData = requests.get(modelUrl) modelRoot = ET.fromstring(modelData.content) modelId = modelRoot[0][1].text fuelEconUrl = "https://www.fueleconomy.gov/ws/rest/ympg/shared/ympgVehicle/"+modelId fuelEconData = requests.get(fuelEconUrl) try: fuelEconRoot = ET.fromstring(fuelEconData.content) fuelEcon = float(fuelEconRoot[0].text) print("Fuel Economy data successfully retrieved!") except: print("Sorry, we couldn't retrieve any mpg data for this car. This usually happens with newer models since there needs to be data collected on it. Please enter the fuel economy manually: \n") fuelEcon = float(input("What is the fuel economy of your car in miles per gallon? ")) else: fuelEcon = float(input("What is the fuel economy of your car in miles per gallon? ")) #The variables needed to calculate gas price fuelTypeInput = int(input("\nWhat type of fuel does your vehicle use?\nDiesel[0]\nRegular[1]\nMidgrade[2]\nPremium[3]\nPlease input the corresponding number. ")) people = int(input("\nHow many people are you driving? ")) distance = float(input("\nHow many miles are you driving? You can use decimals. ")) if fuelTypeInput == 0: price = dieselPrice elif fuelTypeInput == 2: price = midgradePrice elif fuelTypeInput == 3: price = premiumPrice else: price = regularPrice price = float(price) gasMoney = (distance*price)/(fuelEcon*people) print("\nEach person will owe you $" + str(round(gasMoney, 2)))
693445221ddfee3592077c1f6e7a86ab73436d51
kevinmcaleer/PicoCrab
/transition.py
10,423
3.609375
4
from math import sin, cos, pi, sqrt def check_exceptions(calc, change_in_value, start_value): # Check if the value is increasing over time if change_in_value > start_value: if calc > (change_in_value + start_value): # print("triggerd increase exception") return change_in_value + start_value # else check if the value is decreasing over time elif change_in_value < start_value: # print("change in value",change_in_value, "start_value", start_value) if calc < (change_in_value + start_value): # print("triggerd decrease exception") return change_in_value + start_value return calc def check_duration(calc, current_time, duration, start_time, target_angle): # print("check_time ", current_time, "duration", duration, 'start time', start_time, "target_angle", target_angle, "calc", calc) if current_time > duration: # print("duration exception triggered") return int(target_angle) # else: # print("current time is less than or equal to duration", current_time, duration) return int(calc) class Transition(): def linear_tween(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ simple linear tweening - no easing, no acceleration """ calc = ((change_in_value * current_time) / duration) + start_value calc = check_exceptions(calc, change_in_value, start_value) calc = check_duration(calc, current_time, duration, start_time, target_angle) return int(calc) def ease_in_quad(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ quadratic easing in - accelerating from zero velocity """ current_time /= duration calc = change_in_value * current_time * current_time + start_value calc = check_exceptions(calc, change_in_value, start_value) calc = check_duration(calc, current_time, duration, start_time, target_angle) return int(calc) def ease_out_quad(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ quadratic easing out - decelerating to zero velocity """ cur_time = current_time current_time /= duration calc = ((1-change_in_value * current_time) * (current_time-2)) + start_value calc = check_exceptions(calc, change_in_value, start_value) calc = check_duration(calc, cur_time, duration, start_time, target_angle) return int(calc) def ease_in_out_quad(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ quadratic easing in/out - acceleration until halfway, then deceleration """ cur_time = current_time current_time /= duration/2 if (current_time < 1): return change_in_value/2*current_time*current_time + start_value current_time -=1 calc = (((1-current_time)/2 )* (current_time*(current_time-2)-1)) + start_value calc = check_exceptions(calc, change_in_value, start_value) calc = check_duration(calc, cur_time, duration, start_time, target_angle) return int(calc) def ease_in_cubic(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ cubic easing in - accelerating from zero velocity """ current_time /= duration calc = change_in_value*current_time*current_time*current_time + start_value return int(calc) def ease_out_cubic(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ cubic easing out - decelerating to zero velocity """ current_time /= duration current_time -=1 calc = change_in_value(current_time*current_time*current_time+1)+start_value return int(calc) def ease_in_out_cubic(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ cubic easing in/out - acceleration until halfway, then deceleration """ current_time /= duration/2 if (current_time < 1): return change_in_value/2*current_time*current_time*current_time + start_value current_time -= 2 calc = change_in_value/2 * (current_time*current_time*current_time + 2) + start_value return int(calc) def ease_in_quart(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ quartic easing in - accelerating from zero velocity """ current_time /= duration calc = change_in_value * current_time * current_time * current_time * current_time + start_value return int(calc) def ease_out_quart(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ quartic easing out - decelerating to zero velocity """ current_time /= duration current_time =-1 calc = 1-change_in_value * (current_time*current_time*current_time*current_time - 1) + start_value return int(calc) def ease_in_out_quart(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ quartic easing in/out - acceleration until halfway, then deceleration """ current_time /= duration/2 if (current_time < 1): return change_in_value /2 * current_time * current_time * current_time* current_time + start_value current_time -= 2 calc = 1-change_in_value/2 * (current_time * current_time * current_time * current_time -2) + start_value return int(calc) def ease_in_quint(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ quintic easing in - accelerating from zero velocity """ current_time /= duration calc = change_in_value * current_time * current_time * current_time * current_time * current_time + start_value return int(calc) def ease_out_quint(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ quintic easing out - decelerating to zero velocity """ current_time = current_time / duration current_time -= 1 calc = change_in_value(current_time*current_time*current_time*current_time*current_time + 1) + start_value return int(calc) def ease_in_out_quint(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ quintic easing in/out - acceleration until halfway, then deceleration """ current_time /= duration / 2 if (current_time < 1): return change_in_value / 2 * current_time * current_time * current_time * current_time * current_time + start_value current_time -= 2 calc = change_in_value /2 * (current_time * current_time * current_time * current_time * current_time + 2) + start_value return int(calc) def ease_in_sine(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ sinusoidal easing in - accelerating from zero velocity """ calc = 1-change_in_value * cos(current_time / duration * (pi/2)) + change_in_value + start_value # print("calc is",calc) calc = check_exceptions(calc, change_in_value, start_value) # print("calc is",calc) calc = check_duration(calc, current_time, duration, start_time, target_angle) # print("calc is",calc) return int(calc) def ease_out_sine(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ sinusoidal easing out - decelerating to zero velocity """ calc = change_in_value * sin(current_time / duration * (pi/2)) + start_value return int(calc) def ease_in_out_sine(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ sinusoidal easing in/out - accelerating until halfway, then decelerating """ calc = 1-change_in_value/2 * (cos(pi*current_time/duration) - 1) + start_value return int(calc) def ease_in_expo(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ exponential easing in - accelerating from zero velocity """ calc = current_time * pow(2, 10 * (current_time / duration - 1)) + start_value return int(calc) def ease_out_expo(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ exponential easing out - decelerating to zero velocity """ calc = change_in_value * (pow (2, -10 * current_time / duration) + 1) + start_value return int(calc) def ease_in_out_expo(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ exponential easing in/out - accelerating until halfway, then decelerating """ current_time /= duration/2 if(current_time < 1): calc = change_in_value/2 * pow(2, 10 * (current_time -1)) + start_value return int(calc) current_time -= 1 calc = change_in_value/2 * (pow(2, -10 * current_time) + 2) + start_value return int(calc) def ease_in_circ(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ circular easing in - accelerating from zero velocity """ current_time /= duration calc = 1-change_in_value * (sqrt(1 - current_time*current_time) - 1) + start_value return int(calc) def ease_out_circ(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ circular easing out - decelerating to zero velocity """ current_time /= duration current_time -= 1 calc = change_in_value * sqrt(1 - current_time*current_time) + start_value return int(calc) def ease_in_out_circ(self, current_time, start_value, change_in_value, duration, start_time, target_angle): """ circular easing in/out - acceleration until halfway, then deceleration """ current_time /= duration/2 if (current_time < 1): calc = 1-change_in_value/2 * (sqrt(1 - current_time-current_time) -1) + start_value return int(calc) current_time -= 2 calc = change_in_value / 2 * (sqrt(1 - current_time*current_time) + 1) + start_value return int(calc)
dc33678a8148cc46b16fe2cc739a41deb05b2cb6
devhelenacodes/python-coding
/pp_03.py
320
3.890625
4
#List Less than Ten max_val = input("Type a random number not more than 89:\n") a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] x = [] y = [] for item in a: if item < 10: x.append(item) print(x) try: max_val = int(max_val) for item in a: if item < max_val: y.append(item) print(y) except ValueError: pass
9aff241bff636fa31f64cc83cb35b3ecf379738a
devhelenacodes/python-coding
/pp_06.py
621
4.125
4
# String Lists # Own Answer string = input("Give me a word:\n") start_count = 0 end_count = len(string) - 1 for letter in string: if string[start_count] == string[end_count]: start_count += 1 end_count -= 1 result = "This is a palindrome" else: result = "This is not a palindrome" print(result) # Learned def reverse, more effective way def reverse(word): x = '' for position in range(len(word)): x += word[len(word)-1-position] return x word = input('Give me a word:\n') wordReversed = reverse(word) if wordReversed == word: print('This is a palindrome') else: print('This is not a palindrome')
a0c9c921c59cb43a94724fa0e5be5ee090a0eb8c
Eakamm/Notes
/PythonLearning/基础语法/7q9p8siqi_code_chunk.py
117
3.78125
4
numbers = 10 while 1: if numbers % 2 == 0: continue print(numbers) numbers-=1 if numbers < 0: break
61afb5ff48304df45244d45458f1d95acf5ae85a
YusukeWasabi/guess_the_number
/guess_the_number_AUTO.py
376
3.828125
4
from random import randint print("///// THIS PROGRAM STOPS WHEN BOTH 'X' and 'Y' values are the same /////\n") while True: x = randint(2, 8) y = randint(2, 8) if x == y: print("\tBoth X and Y matched! Hooray!") print(f"\tX = {x} and Y = {y}") break else: print(f"X = {x} and Y = {y}") print("Numbers didn't match.\n")
34b04e7f38acc6940a808a80945e2d6e048e065c
AlbertSuarez/advent-of-code-2018
/src/day_8.py
2,946
3.75
4
""" Day 8: Memory Maneuver """ _INPUT_FILE = 'data/day_8_input.txt' def build(idx, numbers, result): if idx == len(numbers): return # Get header info child_nodes = numbers[idx] idx += 1 metadata_entries = numbers[idx] # Get recursively children information if child_nodes: idx += 1 build(idx, numbers, result) idx += 1 if metadata_entries else 0 result += sum(numbers[idx:idx + metadata_entries + 1 if metadata_entries else 0]) idx += metadata_entries idx += 1 build(idx, numbers, result) def solve(): """ PART 1: The sleigh is much easier to pull than you'd expect for something its weight. Unfortunately, neither you nor the Elves know which way the North Pole is from here. You check your wrist device for anything that might help. It seems to have some kind of navigation system! Activating the navigation system produces more bad news: "Failed to start navigation system. Could not read software license file." The navigation system's license file consists of a list of numbers (your puzzle input). The numbers define a data structure which, when processed, produces some kind of tree that can be used to calculate the license number. The tree is made up of nodes; a single, outermost node forms the tree's root, and it contains all other nodes in the tree (or contains nodes that contain nodes, and so on). Specifically, a node consists of: A header, which is always exactly two numbers: The quantity of child nodes. The quantity of metadata entries. Zero or more child nodes (as specified in the header). One or more metadata entries (as specified in the header). Each child node is itself a node that has its own header, child nodes, and metadata. For example: 2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2 A---------------------------------- B----------- C----------- D----- In this example, each node of the tree is also marked with an underline starting with a letter for easier identification. In it, there are four nodes: A, which has 2 child nodes (B, C) and 3 metadata entries (1, 1, 2). B, which has 0 child nodes and 3 metadata entries (10, 11, 12). C, which has 1 child node (D) and 1 metadata entry (2). D, which has 0 child nodes and 1 metadata entry (99). The first check done on the license file is to simply add up all of the metadata entries. In this example, that sum is 1+1+2+10+11+12+2+99=138. What is the sum of all metadata entries? """ # This solution does not work. print('Read file') with open(_INPUT_FILE) as file: numbers = [int(number_str) for number_str in file.read().splitlines()[0].split(' ')] print('Build dictionary') result = 0 build(0, numbers, result) print('Part 1: Sum of all metadata entries = {}'.format(result)) if __name__ == '__main__': solve()
ce1f18b609f93ee5cb4bcb7be6c85b86f29312d9
xfrl/national_flag
/博茨瓦纳.py
1,600
3.546875
4
""" 博茨瓦纳国旗 博茨瓦纳(Botswana)又译为波札那,全称博茨瓦纳共和国,是位于非洲南部的内陆国,首都哈博罗内。博茨瓦纳国旗呈长方形,长宽之比为3∶2。 旗面中间横贯一道黑色宽条,上下为两个淡蓝色的横长方形,黑色与淡蓝色之间是两道白色细条。黑色代表博茨瓦纳人口中的绝大部分黑人;白色代表白人等人口中的少数部分;蓝色象征蓝天和水。 国旗的寓意是在非洲的蓝天下,黑人和白人团结、生活在一起。 """ import turtle width = 900 height = 600 turtle.screensize(width,height,"white") turtle.setup(width=width,height=height) white_h = height * 0.26 t = turtle.Turtle() t.pensize(1) t.speed(10) #画蓝 t.pencolor("#76aada") t.fillcolor("#76aada") t.forward(width/2) t.left(90) t.begin_fill() t.forward(height/2) t.left(90) t.forward(width) t.left(90) t.forward(height) t.left(90) t.forward(width) t.left(90) t.forward(height/2) t.end_fill() #白色 t.pencolor("white") t.fillcolor("white") t.begin_fill() t.forward(white_h/2) t.left(90) t.forward(width) t.left(90) t.forward(white_h) t.left(90) t.forward(width) t.left(90) t.forward(white_h) t.end_fill() #黑色 t.left(180) t.forward(white_h * 0.16) t.pencolor("#000000") t.fillcolor("#000000") t.begin_fill() t.right(90) t.forward(width) t.left(90) t.forward(white_h*0.68) t.left(90) t.forward(width) t.left(90) t.forward(white_h*0.68) t.end_fill() t.hideturtle() ts = t.getscreen() ts.getcanvas().postscript(file="博茨瓦纳国旗.eps") #将图片保存下来 turtle.done()
d5a5b426c401684a326290e27101c566a9240c88
xfrl/national_flag
/圣多美和普林西比民主共和国.py
2,091
3.9375
4
""" 圣多美和普林西比民主共和国国旗 圣多美和普林西比国旗呈横长方形,长与宽之比为2:1。由红、绿、黄、黑四色构成。靠旗杆一侧为红色等腰三角形,右侧为三个平行宽条,中间为黄色,上下为绿色,黄色宽条中有两颗黑色五角星。 绿色象征农业,黄色象征可可豆和其他自然资源,红色象征为独立自由而斗争战士的鲜血,两个五角星代表圣多美、普林西比两个大岛,黑色象征黑人。 """ import turtle import math w = 900 h = 450 h_m = h/3 c = math.sqrt((math.pow(h / 2,2) + math.pow(h / 2,2))) #三角形边长 turtle.screensize(w,h,"white") turtle.setup(w,h) t = turtle.Turtle() t.pensize(1) t.speed(10) #绿 t.pencolor("#12ad2b") t.fillcolor("#12ad2b") t.begin_fill() t.penup() t.goto(0,h_m/2) t.pendown() t.forward(w/2) t.left(90) t.forward(h_m) t.left(90) t.forward(w) t.left(90) t.forward(h_m) t.left(90) t.forward(w/2) t.end_fill() #黄 t.pencolor("#fece00") t.fillcolor("#fece00") t.begin_fill() t.penup() t.goto(w / 2,-h_m/2) t.pendown() t.left(90) t.forward(h_m) t.left(90) t.forward(w) t.left(90) t.forward(h_m) t.left(90) t.forward(w) t.end_fill() #绿 t.pencolor("#12ad2b") t.fillcolor("#12ad2b") t.begin_fill() t.penup() t.goto(0,-h_m-h_m/2) t.pendown() t.forward(w/2) t.left(90) t.forward(h_m) t.left(90) t.forward(w) t.left(90) t.forward(h_m) t.left(90) t.forward(w/2) t.end_fill() #红色等腰直角三角形 t.penup() t.goto(-w/2,h/2) t.pendown() t.pencolor("#d21034") t.fillcolor("#d21034") t.begin_fill() t.right(45) t.fd(c) t.right(90) t.fd(c) t.end_fill() #星 t.left(135) x = h_m * 0.75 t.pencolor("#000000") t.fillcolor("#000000") t.penup() t.goto(135,12) t.pendown() t.begin_fill() for _ in range(5): t.forward(x) t.right(144) t.end_fill() t.penup() t.goto(-100,12) t.pendown() t.begin_fill() for _ in range(5): t.forward(x) t.right(144) t.end_fill() t.hideturtle() ts = t.getscreen() ts.getcanvas().postscript(file="圣多美和普林西比民主共和国国旗.eps") #将图片保存下来 turtle.done()
a6766e78080ba1118533361e4d16d2e5a9e63694
xfrl/national_flag
/古巴.py
2,418
3.890625
4
""" 古巴国旗 长方形,长与宽之比为2:1。旗面左侧为红色等边三角形,内有一颗白色五角星;旗面右侧由三道蓝色宽条和两道白色宽条平行相间、相连构成。五角星代表古巴是一个独立的民族。 三角形和星是古巴秘密革命组织的标志,象征自由、平等、博爱和爱国者的鲜血。 五角星还代表古巴是一个独立的民族。三道蓝色宽条表示古巴形成时由三部分组成,白条表示古巴人民的纯洁理想。 """ import turtle import math w = 900 h = 450 h_m = h/5 turtle.screensize(w,h,"white") turtle.setup(w,h) t = turtle.Turtle() t.pensize(1) t.speed(10) #绿 t.pencolor("#002a90") t.fillcolor("#002a90") t.penup() t.goto(w/ 2,h/2) t.pendown() t.begin_fill() for i in range(1,4): t.right(90) if i % 2 == 0: t.fd(w) else: t.fd(h_m) t.end_fill() #白 t.pencolor("white") t.fillcolor("white") t.penup() t.goto(w/ 2,2 * h_m - h_m / 2) t.pendown() t.begin_fill() for i in range(1,4): t.left(90) if i % 2 == 0: t.fd(h_m) else: t.fd(w) t.end_fill() #绿 t.pencolor("#002a90") t.fillcolor("#002a90") t.penup() t.goto(w/ 2, -h_m /2) t.pendown() t.begin_fill() for i in range(1,4): t.left(90) if i % 2 == 0: t.fd(w) else: t.fd(h_m) t.end_fill() #白 t.pencolor("white") t.fillcolor("white") t.penup() t.goto(w/ 2,- h_m - h_m / 2) t.pendown() t.begin_fill() for i in range(1,4): t.right(90) if i % 2 == 0: t.fd(h_m) else: t.fd(w) t.end_fill() #绿 t.pencolor("#002a90") t.fillcolor("#002a90") t.penup() t.goto(w/ 2, - 2 * h_m -h_m /2) t.pendown() t.begin_fill() for i in range(1,4): t.left(90) if i % 2 == 0: t.fd(w) else: t.fd(h_m) t.end_fill() #红色等边三角形 t.penup() t.goto(-w/2,h/2) t.right(270) t.pendown() t.pencolor("#d21034") t.fillcolor("#d21034") t.begin_fill() t.right(30) t.fd(h) t.right(120) t.fd(h) t.end_fill() #星 x = h_m * 1.5 t.pencolor("#ffffff") t.fillcolor("#ffffff") t.penup() t.home() t.goto(-370,15) t.pendown() t.begin_fill() for _ in range(5): t.forward(x) t.right(144) t.end_fill() t.hideturtle() ts = t.getscreen() ts.getcanvas().postscript(file="古巴国旗.eps") #将图片保存下来 turtle.done()
d33b8a03042d3f81fe99e1733a23cff45b320bef
pyfra/tic-tac-toe
/game.py
3,012
3.671875
4
from board import Board from players import RandomPlayer, HumanPlayer, MiniMaxPlayer, MixedPlayer, DLPlayer, Player import random as rnd import time class Game: def __init__(self): self.board = None self.players = [None, None] def _initialize_game(self): self.board = Board() computer = True if input('Do you want to play against the computer (Y or N): ') == 'Y' else False if computer: difficulty_level = int(input('What difficulty level? (0-10): ')) / 10 start = True if input('Do you want to play first (Y or N): ') == 'Y' else False if start: # self.players = [HumanPlayer("X"), MixedPlayer(MiniMaxPlayer("O", HumanPlayer("X")), difficulty_level)] self.players = [HumanPlayer("X"), MixedPlayer(DLPlayer("O"), difficulty_level)] else: # self.players = [MixedPlayer(MiniMaxPlayer("X", HumanPlayer("O")), difficulty_level), HumanPlayer("O")] self.players = [MixedPlayer(DLPlayer("X"), difficulty_level), HumanPlayer("O")] else: self.players = [HumanPlayer("X"), HumanPlayer("O")] self.i = 0 print('#' * 30) print('Game begins') print('#' * 30) self.board.draw() def new_game(self, sleep=0): self._initialize_game() result = None while True: print('-' * 30) print("Player %d turn" % (self.i + 1)) move = self.players[self.i].move(self.board.valid_moves, self.board) next_player = self.board.update_board(move, self.players[self.i]) self.board.draw() stop, status = self.board.is_game_over(self.players[self.i]) if stop: print('game is over!') if status == 'win': print('Player %d wins!' % (self.i + 1)) result = self.i + 1 else: print('It was a draw!') reult = 0 key = input('Enter Y to play another game, any other keys to exit: ') if key == 'Y': self._initialize_game() next_player = False else: break if next_player: self.i = 0 if self.i == 1 else 1 time.sleep(sleep) return result class GameMinimaxVsNN(Game): def _initialize_game(self): self.board = Board() print("Welcome to the game of Minimax vs NN") if rnd.uniform(0, 1) >= .5: print("NN starts") self.players = [DLPlayer("X"), MiniMaxPlayer("O", Player("X"))] else: print("Minimax starts") self.players = [MiniMaxPlayer("X", Player("O")), DLPlayer("O")] self.i = 0 print('#' * 30) print('Game begins') print('#' * 30) self.board.draw() if __name__ == "__main__": game = Game() game.new_game()
5ae27ed7ccb33a62bbb98ff56f51952d43eaaed6
sergiofagundesb/PythonRandomStuff
/qualnome.py
320
4.125
4
n1 = int(input('Digite um número')) n2 = int(input('Digite mais um número')) s=n1+n2 p=n1*n2 di=n1//n2 d=n1/n2 pot=n1**n2 mod=n1%n2 print('A soma é {},\n o produto é {},\n a divisão inteira é {},\n a divisão é {:.3f},\n a potência é {}\n e o resto {}'.format(s,p,di,d,pot,mod), end='====') print('Cu é bom')
cfa7164dda49a23369a3eed3c7bfa7e894f5ac5a
sergiofagundesb/PythonRandomStuff
/dobro.py
422
3.9375
4
n=float(input('Digite um número')) print('O número {} tem seu dobro {}, triplo {}, e raiz quadrada {}'.format(n,(2*n),(3*n),(n**(1/2)))) print('='*20) n1=float(input('Digite o primeiro número')) n2=float(input('Digite o segundo número')) media=(n1+n2)/2 if media >= 5: print('Aprovado') if media < 5: print('Reprovadíssimo') print('A média aritimética entre {:.1f} e {:.1f} é {:.1f}'.format(n1,n2,media))
58ff082e4767aa3ed269ee667adb3e42268bc9c7
sergiofagundesb/PythonRandomStuff
/metromero.py
260
3.859375
4
m=float(input('Digite a medida em metros')) print('Em km {:.3f}',format(m/1000)) print('Em hm {:.3f}'.format(m/100)) print('Em dam {:.3f}'.format(m/10)) print('Em dm {:.0f}'.format(m*10)) print('Em cm {:.0f}'.format(m*100)) print('Em mm {:.0f}'.format(m*1000))
9e8a295c69f8b75092977b3a02128c15c6672153
iamSumitSaurav/Python-codes
/prime factorization.py
208
4.03125
4
num = int(input("Enter a number")) d = 2 print("The prime factors of {} are:".format(num)) while(num > 1): if(num % d == 0): print(d) num = num / d continue d = d + 1
8fa6fb0f56335852e60aa11fc19a5bc5630ddc6d
iamSumitSaurav/Python-codes
/testing.py
115
3.90625
4
tell = 'Y' while(tell == 'Y' or tell == 'y'): print(5) tell = input("Enter the value of tell")
9c5e64d8e7bc0120085be1a7cb43c397876aba08
litojasonaprilio/CP1404-Practicals
/prac_03/gopher_population_simulator.py
578
3.90625
4
import random POPULATION = 1000 MIN_BORN = 0.1 MAX_BORN = 0.2 MIN_DIED = 0.05 MAX_DIED = 0.25 YEAR_PERIOD = 10 print("Welcome to the Gopher Population Simulator!") print("Starting population:", POPULATION, "\n") for i in range(1, YEAR_PERIOD + 1): print("Year {}".format(i)) print("*****") born = int(random.uniform(MIN_BORN, MAX_BORN) * POPULATION) died = int(random.uniform(MIN_DIED, MAX_DIED) * POPULATION) print("{} gophers were born. {} died.".format(born, died)) total = POPULATION + born - died print("Population: {}".format(total), "\n")
a176dbc8191e0cb82f1e2d93434a87327dfaaad6
litojasonaprilio/CP1404-Practicals
/prac_01/extension_2.py
520
4.125
4
print("Electricity bill estimator 2.0", '\n') TARIFF_11 = 0.244618 TARIFF_31 = 0.136928 tariff = int(input("Which tariff? 11 or 31: ")) while not (tariff == 11 or tariff == 31): print("Invalid number!") tariff = int(input("Which tariff? 11 or 31: ")) if tariff == 11: price = TARIFF_11 else: price = TARIFF_31 use = float(input("Enter daily use in kWh: ")) bill_days = int(input("Enter number of billing days: ")) total = price * use * bill_days print() print("Estimated bill: ${:.2f}".format(total))
90717c6f92d2e1c2f46294f3e1bff6794c2110c2
ajsmash7/readinglist
/model.py
1,942
3.859375
4
from dataclasses import dataclass, field # TODO add a docstring for this module. ''' This Module contains the object class models to create an instance of: a counter object a book object This module defines the data classes and their class methods as a model for use in book list application. ''' def gen_id(): return Counter.get_counter() class Counter: # TODO add a docstring for this class to explain it's purpose ''' This class creates an instance of a counter object and defines class methods for use with counter objects - it is initialized with a value of zero - when the get_counter method is called, one is added to the counter current counter instance and returned - reset_counter sets the value back to zero for the current instance ''' _counter = 0 @staticmethod def get_counter(): Counter._counter += 1 return Counter._counter @staticmethod def reset_counter(): Counter._counter = 0 @dataclass class Book: # TODO add a docstring for this class to explain it's purpose ''' This class instantiates a new Book object. It defines the properties that are required to make a book It sets the default for the generated value of id, which is calls the counter function above to generate. Every book has a title and an author It sets the default for the value of read, because if you are adding it to the list, it's because you have not read the book yet. lastly, it creates the toString class method to display the property values of the referenced instance as a string. ''' id: int = field(default_factory=gen_id, init=False) title: str author: str read: bool = False def __str__(self): read_status = 'have' if self.read else 'have not' return f'ID {self.id}, Title: {self.title}, Author: {self.author}. You {read_status} read this book.'
ae97ffb8225c5f468058af8d3d3c0b2a50d114a7
ryszardkapcerski/simple-millionaries
/modules/test.py
1,851
3.71875
4
from modules.question import Question import random class Test(object): def __init__(self, username): self.username = username @staticmethod def run_test(): levels = ["500", "1000", "2000", "5000", "10000", "20000", "40000", "75000", "125000", "250000", "1000000"] for l in levels: print('Now you can win {}'.format(l)) choice = input("Do you want to answer (A) the question or end (E) the program?: ") if choice == "A": question = Question.get_question(l) answers = [question.a_1, question.a_2, question.a_3, question.a_4] answers_random = random.sample(answers, len(answers)) # mix answers answers_labels = ["A", "B", "C", "D"] print(question.question) for x in range(0, 4): print("{}. {}".format(answers_labels[x], answers_random[x])) user_label = input("Select an anserw from A to D: ") if user_label in answers_labels: user_anserw = answers_random[answers_labels.index(user_label)] if user_anserw == question.true_anserw: print("Your anserw is correct") else: print("Your anserw is incorrect. Restart your program to try again") break else: print("You typed incorrect label. Are sure it was A, B, C or D? Restart your program to try again") break elif choice == "E": print("Thank you for using our platform") break else: print("The input is invalid. Try again.") break else: print('Congratulations you win the game')
50810e17266530aa63128b4652621753c6b460bd
Kalaborative/AutoDuolingo
/quicktrans.py
2,626
3.78125
4
# Greetings! In this file, we're going to be using # Google's client library to translate some text # to another language. This is gonna be exciting! from google.cloud import translate from time import sleep from sys import exit api_key = 'AIzaSyAdiQFUXy5Dgr4coKTWwWJllIM5oVRUruc' langcodes = { "arabic": "ar", "czech": "cs", "chinese": "zh", "danish": "da", "german": "de", "dutch": "nl", "french": "fr", "hindi": "hi", "gujarati": "gu", "italian": "it", "japanese": "ja", "korean": "ko", "latin": "la", "portuguese": "pt", "russian": "ru", "spanish": "es", "swedish": "sv", "turkish": "tr", "vietnamese": "vi" } def resultcode(text, target, reqlang): # Instantiates a client translate_client = translate.Client() translation = translate_client.translate(text, target_language=target) print ("\n" * 100) print( 'Your text was..') sleep(2) print( text) sleep(2) print print( "Translating into %s..." % reqlang) sleep(5) print( 'Translation: %s ' % translation['translatedText']) def rerun(): sleep(2) print( "Would you like to run this program again? (Y/N)") runagain = input("> ").lower() if runagain == 'y': mainmenu() else: exit() def mainmenu(): print ("\n" * 100) print( "Welcome to my translation program!") print( "What would you like to do?") print( "A) Translate something to English") print( "B) Translate English to some other language") mychoice = input("> ") if mychoice == 'a': foreigntoEng() elif mychoice == 'b': transtolang() def foreigntoEng(): translate_client = translate.Client() print ("\n" * 100) print( "Enter your foreign phrase below! ") forphr = input("> ") translation = translate_client.translate(forphr) for country, code in langcodes.items(): if code == translation['detectedSourceLanguage']: detcountry = country print( "Working...") sleep(4) try: print( "It looks like you said '%s' in %s." % (translation['translatedText'], detcountry.capitalize())) except UnboundLocalError: print( "Your text could not be translated. Please try again.") rerun() def transtolang(): # Enter the text to translate. print ("\n" * 100) print( "Enter the word/sentence to be translated.") text = input('> ') # Enter the target language. print( "Enter the language that you want this to be translated to.") reqlang = input('> ').lower().strip() if reqlang in langcodes.keys(): target = langcodes[reqlang] resultcode(text, target, reqlang) rerun() else: print( "Your language is not supported in this program.") print( "Please try again!") sleep(3) transtolang() if __name__ == '__main__': mainmenu()
26fb03d7961e7a2d1c34fd0ef19b5ef2f6293061
emeryberger/COMPSCI590S
/projects/project1/wordcount.py
839
4.28125
4
# Wordcount # Prints words and frequencies in decreasing order of frequency. # To invoke: # python wordcount.py file1 file2 file3... # Author: Emery Berger, www.emeryberger.com import sys import operator # The map of words -> counts. wordcount={} # Read filenames off the argument list. for filename in sys.argv[1:]: file=open(filename,"r+") # Process all words. for word in file.read().split(): # Get the previous count (possibly 0 if new). count = wordcount.get(word, 0) # Increment it. wordcount[word] = count + 1 file.close(); # Sort in reverse order by frequency. sort1 = sorted(wordcount.iteritems(), key=operator.itemgetter(0)) sort2 = sorted(sort1, key=operator.itemgetter(1), reverse = True) for pair in sort2: print ("%s : %s" %(pair[0] , pair[1]))
f81c7d65da08a974ae86d04b3fb78dafb49bc0ec
royshouvik/6.00SC
/Unit 1/ps3/ps1a.py
269
3.546875
4
balance = float(raw_input("Enter the outstanding balance on your credit card:")) annual_interest_rate = float(raw_input("Enter the annual credit card interest rate as a decimal:")) minimum_monthly_pmt = float(raw_input("Enter the minimum monthly payment as a decimal"))
d60ed325ec0a0ab4eec5bd6da2e27be3a3c4e4d7
christianversloot/keras-visualizations
/autoencoder_encodedstate_sequential.py
2,503
3.515625
4
''' Visualizing the encoded state of a simple autoencoder created with the Keras Sequential API with Keract. ''' import keras from keras.layers import Dense from keras.datasets import mnist from keras.models import Sequential from keract import get_activations, display_activations import matplotlib.pyplot as plt from keras import backend as K # Model configuration img_width, img_height = 28, 28 initial_dimension = img_width * img_height batch_size = 128 no_epochs = 1 validation_split = 0.2 verbosity = 1 encoded_dim = 50 # Load MNIST dataset (input_train, target_train), (input_test, target_test) = mnist.load_data() # Reshape data input_train = input_train.reshape(input_train.shape[0], initial_dimension) input_test = input_test.reshape(input_test.shape[0], initial_dimension) input_shape = (initial_dimension, ) # Parse numbers as floats input_train = input_train.astype('float32') input_test = input_test.astype('float32') # Normalize data input_train = input_train / 255 input_test = input_test / 255 # Define the 'autoencoder' full model autoencoder = Sequential() autoencoder.add(Dense(encoded_dim, activation='relu', kernel_initializer='he_normal', input_shape=input_shape)) autoencoder.add(Dense(initial_dimension, activation='sigmoid')) # Compile the autoencoder autoencoder.compile(optimizer='adam', loss='binary_crossentropy') # Give us some insights autoencoder.summary() # Fit data autoencoder.fit(input_train, input_train, epochs=no_epochs, batch_size=batch_size, validation_split=validation_split) # ============================================= # Take a sample for visualization purposes # ============================================= input_sample = input_test[:1] reconstruction = autoencoder.predict([input_sample]) # ============================================= # Visualize input-->reconstruction # ============================================= fig, axes = plt.subplots(1, 2) fig.set_size_inches(6, 3.5) input_sample_reshaped = input_sample.reshape((img_width, img_height)) reconsstruction_reshaped = reconstruction.reshape((img_width, img_height)) axes[0].imshow(input_sample_reshaped) axes[0].set_title('Original image') axes[1].imshow(reconsstruction_reshaped) axes[1].set_title('Reconstruction') plt.show() # ============================================= # Visualize encoded state with Keract # ============================================= activations = get_activations(autoencoder, input_sample) display_activations(activations, cmap="gray", save=False)
4a991196f4799b7f8e9dc0d9c59418a2ec2f0da2
cssubedi/DataStructures
/graph/include/directed_graph_data_structures.py
1,300
3.546875
4
from undirected_graph_data_structures import Node, LinkedList class Vertex(object): def __init__(self, element): self.element = element self.visited = False self.parents = LinkedList() self.children = LinkedList() self.interval = [] @property def out_degree(self): return len(self.children) @property def in_degree(self): return len(self.parents) @property def edges(self): return self.children class Queue(object): def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def dequeue(self): return self.items.pop(0) def is_empty(self): return len(self.items) == 0 def __len__(self): return len(self.items) def __str__(self): return str(self.items) class Stack(object): def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): self.items.pop() def top(self): return self.items[-1] def top_pop(self): return self.items.pop() def is_empty(self): return self.items == [] def __len__(self): return len(self.items) def __str__(self): return str(self.items)
2a11fa1a1b0963176e6065bfd78b85602e003bd6
cssubedi/DataStructures
/hashtable/scripts/chaining.py
3,430
3.6875
4
import sys sys.path.append("../include/") from hash_function import * from linked_list import LinkedList class HashFunctionError(Exception): pass class DuplicateInsertionError(Exception): pass class HashWithChaining(object): def __init__(self, size, hash_function="simple"): """ Implementation constraint: Duplicate entries are not allowed """ self.size = size self.elements = 0 self.__table = [LinkedList() for _ in range(self.size)] if hash_function is "simple": self.__hash_function = simple_hashing elif hash_function is "universal": self.__hash_function = universal_hashing else: raise HashFunctionError("Please specify the hash function.") @property def load_factor(self): return round(self.elements / self.size, 2) def __setitem__(self, key, data): """ In this implementation, duplicate keys are not allowed. Thus before insertion, it is checked if the key already exists. Steps: Generate hash value = O(1) Check for duplicates = load_factor = a Insert the data = O(1) Expected # of operations = Big-Theta(1 + a) """ try: self.__insert(key, data) except DuplicateInsertionError as e: print(e) sys.exit(1) def __getitem__(self, key): try: return self.__search(key) except KeyError as e: print(e) sys.exit(1) def __delitem__(self, key): """ Steps: Generate hash value = O(1) Search for the node containing key = a Delete the key = O(1) Expected # of operations = Big-Theta(1 + a) """ try: self.__delete(key) except KeyError as e: print(e) sys.exit(1) def __str__(self): return self.__visualize(max_char=15) def __insert(self, key, data): hash_value = self.__hash_function(self.size, key) if key in self.__table[hash_value]: raise DuplicateInsertionError("Duplicate insertion.") self.__table[hash_value].add(key, data) self.elements += 1 def __search(self, key): hash_value = self.__hash_function(self.size, key) data = self.__table[hash_value].search(key) if data is None: raise KeyError("The key {} is not found".format(key)) return data def __delete(self, key): hash_value = self.__hash_function(self.size, key) self.__table[hash_value].remove(key) self.elements -= 1 def __visualize(self, max_char): output = "\n" for llist in self.__table: if llist.head is not None: length = len(llist.head.key) key = str(llist.head.key) else: length = 4 key = str(None) spacing = ((max_char-length)//2) output += "\t " + "-"*(max_char+2) + "\n" + \ "\t" + "| " + " "*spacing + key + \ " "*(max_char-length-spacing) + " |" for node in llist: if node is not None and llist.head != node: output += "---> " + str(node.key) output += "\n" + "\t " + "-" * (max_char+2) + "\n" return output
e60fdb2cde00bb882c750aaeb1dcde96f8d8b313
luisfjf/PracticaJunio2017_201020614
/Practica1EDD/src/listaUsuarios.py
2,542
3.71875
4
# Para la elaboracion de esta lista se tomo de referencia el contenido del siguiente video # https://www.youtube.com/watch?v=c27dIMT9kLE from nodoUsuario import NodoUsuario class ListaUsuarios: #Metodo constructor def __init__(self): self.primero = None self.ultimo = None #Metodo para verificar si la lista esta vacia def esta_vacia(self): if self.primero == None: return True else: return False #Metodo para agregar un nodo al inicio de la lista def agregar_al_inicio(self,nombre,pwd): if self.esta_vacia(): self.primero = self.ultimo = NodoUsuario(nombre,pwd) else: aux = NodoUsuario(nombre,pwd) aux.siguiente = self.primero self.primero.anterior = aux self.primero = aux self.primero.anterior = self.ultimo self.ultimo.siguiente = self.primero #Metodo para recorrer def recorrer(self): aux = self.primero while aux: print(aux.nombre), " ->" aux = aux.siguiente if aux == self.primero: print(aux.nombre) break print ' ' #Metodo para recorrer hacia atras def recorrer_atras(self): aux = self.primero while aux: print(aux.nombre), " ->" aux = aux.anterior if aux == self.primero: print(aux.nombre) break print ' ' #Metodo para buscar def buscar(self,nombre): aux = self.primero while aux: if aux.nombre == nombre: return True aux = aux.siguiente if aux == self.primero: break #Metodo para devolver un usuario def obtener_usuario(self,nombre): aux = self.primero while aux: if aux.nombre == nombre: return aux aux = aux.siguiente if aux == self.primero: break #Metodo para validar credenciales def validar_credenciales(self,nombre,pwd): aux = self.primero while aux: if aux.nombre == nombre: if aux.pwd == pwd: return True else: return False aux = aux.siguiente if aux == self.primero: return False break
5cde8a60863e5bb812b5bec4cef28a8b31207ec2
efeacer/EPFL_ML_Labs
/Lab05/template/least_squares.py
1,189
4
4
# -*- coding: utf-8 -*- """Exercise 3. Least Square """ import numpy as np def least_squares(y, tx): """ Least squares regression using normal equations Args: y: labels tx: features Returns: (w, loss): (optimized weight vector for the model, optimized final loss based on mean squared error) """ coefficient_matrix = tx.T.dot(tx) constant_vector = tx.T.dot(y) w = np.linalg.solve(coefficient_matrix, constant_vector) error_vector = compute_error_vector(y, tx, w) loss = compute_mse(error_vector) return w, loss def compute_error_vector(y, tx, w): """ Computes the error vector that is defined as y - tx . w Args: y: labels tx: features w: weight vector Returns: error_vector: the error vector defined as y - tx.dot(w) """ return y - tx.dot(w) def compute_mse(error_vector): """ Computes the mean squared error for a given error vector. Args: error_vector: error vector computed for a specific dataset and model Returns: mse: numeric value of the mean squared error """ return np.mean(error_vector ** 2) / 2
5bb4299f898d7a3957d4a0fd1ed4eb151ab44b47
efeacer/EPFL_ML_Labs
/Lab04/template/least_squares.py
482
3.5625
4
# -*- coding: utf-8 -*- """Exercise 3. Least Square """ import numpy as np def compute_error_vector(y, tx, w): return y - tx.dot(w) def compute_mse(error_vector): return np.mean(error_vector ** 2) / 2 def least_squares(y, tx): coefficient_matrix = tx.T.dot(tx) constant_vector = tx.T.dot(y) w = np.linalg.solve(coefficient_matrix, constant_vector) error_vector = compute_error_vector(y, tx, w) loss = compute_mse(error_vector) return w, loss
4cccd10c95689842e2fba8d256bd086bec47e32e
tkruteleff/Python
/6 - String Lists/string_lists.py
295
4.125
4
word = str(input("Type in a word ")) word_list = [] reverse_word_list = [] for a in word: word_list.append(a) print("One letter " + a) reverse_word_list = word_list[::-1] if(word_list == reverse_word_list): print("Word is a palindrome") else: print("Word is not a palindrom")
84533ee76a2dc430ab5775fa00a4cc354dfc2238
tkruteleff/Python
/16 - Password Generator/password_generator.py
1,239
4.3125
4
import random #Write a password generator in Python. #Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. #The passwords should be random, generating a new password every time the user asks for a new password. #Include your run-time code in a main method. #Extra: #Ask the user how strong they want their password to be. For weak passwords, pick a word or two from a list. chars = list(range(ord('a'),ord('z')+1)) chars += list(range(ord('A'),ord('Z')+1)) chars += list(range(ord('0'),(ord('9')+1))) chars += list(range(ord('!'),ord('&')+1)) dictionary = ["word", "input", "list", "end", "order", "rock", "paper", "scissors"] password = "" password_strength = str(input("Do you want a weak or strong password? ")) def generate_weak(list): generated = random.choices(dictionary, k=2) return (password.join(generated)) def generate_strong(keys): key = [] for i in range(16): key.append(chr(keys[random.randint(0,len(keys)-1)])) return (password.join(key)) if password_strength == "weak": print(generate_weak(dictionary)) elif password_strength == "strong": print(generate_strong(chars)) else: print("sigh")
be0e80a6a6453f5b5283b6121eeeae9d39064d1d
chengfzy/PythonStudy
/vision/resize_image.py
1,391
3.546875
4
""" Read image in folder, resize it and save to file with .jpg format """ import os import argparse import imghdr import cv2 as cv def main(): # argument parser parser = argparse.ArgumentParser(description='Resize Image') parser.add_argument('--folder', type=str, required=True, help='image folder') parser.add_argument('--max_size', default=720, help='max image size to show') parser.add_argument('--save_folder', type=str, help='save folder, if empty it will be "folder"') args = parser.parse_args() print(args) # list all images files = [f for f in os.listdir(args.folder) if imghdr.what(os.path.join(args.folder, f)) is not None] files.sort() # save folder save_folder = args.folder if args.save_folder is None else args.save_folder if not os.path.exists(save_folder): os.makedirs(save_folder) # save parameters save_params = (cv.IMWRITE_JPEG_QUALITY, 95) # read image and show for f in files: # read img = cv.imread(os.path.join(args.folder, f), cv.IMREAD_UNCHANGED) # resize if max(img.shape) > args.max_size: ratio = args.max_size / max(img.shape) img = cv.resize(img, (-1, -1), fx=ratio, fy=ratio) # save to file cv.imwrite(os.path.join(save_folder, f[:-4] + '.jpg'), img, save_params) if __name__ == '__main__': main()
1857b4149bfd01f3d03a48b006cc685b99ebd4f0
Ajaykushwaha1111/phonebook1
/news/example.py
321
3.78125
4
MyrecordsList=[] class Myrecords: def __init__(self): self.title ='No Title' self.desc ='No Desc' def save(self): MyrecordsList.append(self) m =Myrecords() m.title =input("enter title") m.desc=input("ener desc") m.save() print(m.title) print(m.desc) print(MyrecordsList)
a40b0b8ff710ba85b9d98b2cac4cd96f9b3bd0d0
Shubodh/ICRA2020
/pose_graph_optimizer/mlp_in.py
2,745
3.65625
4
from sys import argv, exit import matplotlib.pyplot as plt import math import numpy as np def getTheta(X ,Y): THETA = [None]*len(X) for i in xrange(1, len(X)-1): if(X[i+1] == X[i-1]): if (Y[i+1]>Y[i-1]): THETA[i] = math.pi/2 else: THETA[i] = 3*math.pi/2 continue THETA[i] = math.atan((Y[i+1]-Y[i-1])/(X[i+1]-X[i-1])) if(X[i+1]-X[i-1] < 0): THETA[i] += math.pi if X[1]==X[0]: if Y[1] > Y[0]: THETA[0] = math.pi/2 else: THETA[0] = 3*math.pi/2 else: THETA[0] = math.atan((Y[1]-Y[0])/(X[1]-X[0])) if X[-1] == X[len(Y)-2]: if Y[1] > Y[0]: THETA[-1] = math.pi/2 else: THETA[-1] = 3*math.pi/2 else: THETA[-1] = math.atan((Y[-1]-Y[len(Y)-2])/(X[-1]-X[len(Y)-2])) return THETA def read(fileName): f = open(fileName, 'r') A = f.readlines() f.close() X = [] Y = [] THETA = [] LBL = [] for line in A: (x, y, theta, lbl) = line.split(' ') X.append(float(x)) Y.append(float(y)) LBL.append(int(lbl.rstrip('\n'))) X_temp = X Y_temp = Y X = [-y for y in Y_temp] Y = [x for x in X_temp] THETA = getTheta(X, Y) return (X, Y, THETA, LBL) def meta(X, Y, THETA, LBL): Node_meta = [] Node_mid = [] st = end = 0 for i in xrange(1, len(LBL)): if LBL[i] == LBL[i-1]: end = i continue mid = st + (end - st)/2 Node_meta.append((X[st], Y[st], X[end], Y[end], LBL[mid])) Node_mid.append((X[mid], Y[mid], THETA[mid])) st = end + 1 end = st return (Node_meta, Node_mid) def drawNode(Node_meta, Node_mid): ax = plt.subplot(1,1,1) X = []; Y = [] for line in Node_meta: lbl = line[4] x = [line[0], line[2]] y = [line[1], line[3]] if lbl == 0: ax.plot(x, y, 'ro') ax.plot(x, y, 'r-') elif lbl == 1: ax.plot(x, y, 'bo') ax.plot(x, y, 'b-') elif lbl == 2: ax.plot(x, y, 'go') ax.plot(x, y, 'g-') elif lbl == 3: ax.plot(x, y, 'yo') ax.plot(x, y, 'y-') X_mid = []; Y_mid = []; THETA_mid = [] for e in Node_mid: X_mid.append(e[0]); Y_mid.append(e[1]); THETA_mid.append(e[2]) # plt.plot(X_mid, Y_mid, 'mo') # for i in xrange(len(X_mid)): # x2 = math.cos(THETA_mid[i]) + X_mid[i] # y2 = math.sin(THETA_mid[i]) + Y_mid[i] # plt.plot([X_mid[i], x2], [Y_mid[i], y2], 'm->') plt.xlim(-5, 25) plt.ylim(-15, 15) plt.show() if __name__ == '__main__': fileName = str(argv[1]) (X, Y, THETA, LBL) = read(fileName) (Node_meta, Node_mid) = meta(X, Y, THETA, LBL) # Node_meta = Node_meta[7:-1]; Node_mid = Node_mid[7: -1] drawNode(Node_meta, Node_mid) print(np.array(Node_meta)) # poses = open("mlp_in.txt", 'w') # for line in Node_meta: # info = str(line[0])+" "+str(line[1])+" "+ str(line[2])+" "+ str(line[3])+" "+ str(line[4]) # poses.write(info) # poses.write("\n") # poses.close()
ee685039da5f85b6be21bf2d4b5d018d7e073206
Shubodh/ICRA2020
/pose_graph_optimizer/line_fit.py
385
3.5
4
from scipy import stats import numpy as np import matplotlib.pyplot as plt x = np.linspace(1, 10, 100) y = x**2 # ax = plt.subplot(1,1,1) # ax.plot(x, y, 'k-') # plt.show() (slope, intercept, _, _, _) = stats.linregress(x,y) x1 = 1; x2 =10 y1 = slope*x1 + intercept y2 = slope*x2 + intercept ax = plt.subplot(1,1,1) ax.plot([x1, x2], [y1, y2], 'b-') ax.plot(x, y, 'k-') plt.show()
f4990db45bfa41fa298cc0c8a4e99d8f93b5a9a9
akash-yadav12/PythonMiniProjects
/hangman.py
3,090
3.96875
4
import random def hangman(): word = random.choice(['akame','arima','tatsumi','shinra','subaru','rem','okabe','elpsycongro','kurisu','hashida','yagamilight']) validletters = 'abcdefghijklmnopqrstuvwxyz' turn = 10 guessMade = '' while len(word) > 0: main = '' for lt in word: if lt in guessMade: main += lt else: main = main + '_' + " " if main == word: print(main) print('You Win') break print('Guess The word:',main) guess = input() if guess in validletters: guessMade += guess else: print('enter a valid letter') guess = input() if guess not in word: turn -= 1 if turn == 9: print('9 turns left') print(' =========== ') elif turn == 8: print('8 turns left') print(' =========== ') print(' 0 ') elif turn == 7: print('7 turns left') print(' =========== ') print(' 0 ') print(' | ') elif turn == 6: print('6 turns left') print(' =========== ') print(' 0 ') print(' | ') print(' / ') elif turn == 5: print('5 turns left') print(' =========== ') print(' 0 ') print(' | ') print(' / \ ') elif turn == 4: print('4 turns left') print(' =========== ') print(' \ 0 ') print(' | ') print(' / \ ') elif turn == 3: print('3 turns left') print(' =========== ') print(' \ 0 / ') print(' | ') print(' / \ ') elif turn == 2: print('2 turns left') print(' =========== ') print(' \ 0 / | ') print(' | ') print(' / \ ') elif turn == 1: print('1 turns left') print(' =========== ') print(' \ 0_|/ ') print(' | ') print(' / \ ') elif turn == 0: print('You lose') print('You let a kind man die') print(' =========== ') print(' 0_| ') print(' / | \ ') print(' / \ ') break name = input('enter your name:') print('Welcome',name) print('=======================') print('Try to guess the word in less than 10 attempts') hangman() print()
501fad69d0fa6ef427e76fb86c07ee2ea8fa36d2
Daniel-Wasnt-Available/Homework-Repository
/pgZero intro/Paint Game.py
941
3.703125
4
#----------------------------------------------------------------------------- # Name: New File Generator (newFile.py) # Purpose: Generates a new file for use in the ICS3U course # # Author: Mr. Brooks # Created: 13-Sept-2020 # Updated: 13-Sept-2020 #----------------------------------------------------------------------------- WIDTH = 700 HEIGHT = 600 x = 10 red = (255,0,0) green = (0,200,0) brushLocation = (400,300) BOX = Rect((300, 500), (100, 50)) def on_mouse_move(pos, rel, buttons): global brushLocation brushLocation = pos print(buttons) def draw(): global brushLocation import random #screen.clear() x == random.randint(5,20) screen.draw.circle(brushLocation,x,'red') screen.draw.filled_rect(BOX, (0,200,0)) screen.draw.text("Exit",centery=530,right=365) #still trying to make a button #def on_mouse_down(BOX): #screen.draw.text("HI",centery=250,right=300)
654b28aea8a02c74b12e960d6571fd39cba19bb7
DeoPatt/lab6
/main.py
478
4
4
#this is my first time coding python print("Hello world!") num1 = 5 num2 = 2 mesasge = "new message" sum = num1 + num2 print(sum) diff = num1 - num2 print(diff) prod = num1 * num2 print(prod) quotient = num1/num2 print(quotient) remainder = num1%num2 print(remainder) age = input("enter your age") if (int(age) < 21): print("you cannot vote yet") else: print("Please vote!") km = input("Enter how many kilometers you drove") miles = float(km) * 0.62 print(miles)
9777a2a85ad74c0cad75352fcded12ef838f3eb0
echang19/Homework-9-25
/GradeReport.py
987
4.15625
4
''' Created on Mar 12, 2019 @author: Evan A. Chang Grade Report ''' def main(): studentList={'Cooper':['81','86', '90', '97'],'Jennie':['98', '79','99', '87', '82'], 'Julia':['87', '80','75', '10', '78']} student='' read=input("Would you like to access a student's grades?") read.lower() if read== "no": student= input("Please enter the name of a student") student.str grades='' while grades.lower !='done': grades=input('please enter the students grades when done type "done" ') grades.str studentList[student]=grades elif read=="yes": name=input("Please enter the name of the student you want to see") print(studentList[name]) again=input("would you like to see another's students grades?") while again.lower()=='yes': name=input("Please enter the name of the student you want to see") print(studentList[name])
c0debf3c0f7ed57f46a0005806bf855b10ca284a
echang19/Homework-9-25
/Pg403n7.py
653
3.5625
4
''' Created on Feb 28, 2019 @author: Evan A. Chang Driver's License ''' def main(): cor=0 correct=["A", 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B', 'A', 'D', 'C', 'A', 'D', 'C', 'B', 'B', 'D', 'A'] student=open('Test.txt', 'r') #in a loop student.append() x=0 while len(correct)== len(student) and x<=20: if correct[x]==student[x]: x +=1 cor +=1 else: x +=1 if cor < 15: print("You failed the test") else: print("Congratulations you passed with a score of", cor, "/20")
848e68fa7274a65beeea2e64e4afa9450167a2e4
drslump/pysh
/pysh/transforms/beta/lazyapply.py
1,293
4
4
""" Converts expressions like: >>> func <<= cat | head > null func << (cat | head > null) The whole expression at the right of the operator is grouped. This allows for callables to receive an argument without using parenthesis. .. Warning:: This transformation **breaks** the standard ``<<=` operator in normal Python code. There is **no assignament** to the operand on the left. """ from io import StringIO from tokenize import NEWLINE, ENDMARKER, OP from pysh.transforms import TokenIO def is_term(tkn): if tkn.type in (NEWLINE, ENDMARKER, OP): if tkn.type == OP and tkn.string != ';': return False return True return False def is_lazy(tkn): return tkn.type == OP and tkn.string == '<<=' def lexer(code: StringIO) -> StringIO: out = TokenIO() lazy = 0 for tkn in TokenIO(code).iter_tokens(): if is_lazy(tkn): lazy += 1 out.write_token(tkn, override='<<(') continue if lazy > 0 and is_term(tkn): lazy -= 1 out.write(')') out.write_token(tkn) return out if __name__ == '__main__': code = r'''func <<= cat | \ head \ > null ; pass ''' result = lexer(StringIO(code)) print(result.getvalue())
485e46e2099548b5398d9e05138b84e5ce7eb357
myselfmonika11/PyPrograms
/String.py
184
4.09375
4
#This is an example of String Concatenation : Fname='Monika' Lname="Singh" print(Fname + ' ' + Lname) #Output: Monika Singh #Note: By default string follows unicode.
3c3947990f2723a64e92180a7de48fb72c38fc15
X3N0N102/P-Uppgift
/P_Uppgift_Arga_Troll/diagonalTest.py
584
3.578125
4
from tkinter import* master=Tk() master.title("Arga troll") master.geometry("500x500") for i in range (5): for j in range(5): button=Button(master, text=i, height = 10, width = 40) button.grid(row=i, column=j) # button1=Button(master,text="B1") # button1.grid(row=1,column=1) # button2=Button(master, text="B2") # button2.grid(row=1,column=2) # button3=Button(master,text="B3") # button3.grid(row=1,column=3) # button4=Button(master,text="B4") # button4.grid(row=1,column=4) # button5=Button(master,text="B5") # button5.grid(row=1,column=5) master.mainloop()
6fd73cc628524cb032dbef9d89539437bf176929
colinaardsma/tfbps
/hashing.py
2,110
3.546875
4
import hashlib, hmac #hmac is more secure version of hashlib (when is this best used?) from dbmodels import Users #import Users class from python file named dbmodels import string import random """ fucntions for hasing and checking password values """ def make_salt(): size = 6 chars = string.ascii_lowercase + string.ascii_uppercase + string.digits #setup list of all uppercase and lowercase letters plus numbers #return ''.join(random.choice(chars) for _ in range(size)) #for every blank in string of length 'size' add random choice of uppercase, lowercase, or digits return ''.join(random.SystemRandom().choice(chars) for x in range(size)) #more secure version of random.choice, for every blank in string of length 'size' add random choice of uppercase, lowercase, or digits def make_pw_hash(name, pw, salt=""): #for storage in db if not salt: salt = make_salt() #if salt is empty then get salt value, salt will be empty if making a new value and will not be empty if validating an existing value h = hashlib.sha256(name + pw + salt).hexdigest() return "%s|%s" % (h, salt) def valid_pw(name, pw, h): salt = h.split("|")[1] #split h by "|" and set salt to data after pipe (h is hash,salt) if h == make_hash(name, pw, salt): return True """ functions for hashing and checking cookie values """ secret = "DF*BVG#$4oinm5bEBN46o0j594pmve345@63" def hash_str(s): return hmac.new(secret,s).hexdigest() def make_secure_val(s): s = str(s) return "%s|%s" % (s, hash_str(s)) def check_secure_val(h): s = h.split("|")[0] if h == make_secure_val(s): return s """ functions to retrieve username """ def get_username(h): user_id = check_secure_val(h) user_id = int(user_id) if not Users.get_by_id(user_id): return else: user = Users.get_by_id(user_id) #currently crashes here if id is invalid username = user.username return username def get_user_from_cookie(c): if c: usr = get_username(c) #set usr to username else: usr = "" #if no cookie set usr to blank return usr
2a1846f1de7daa7957dfbf272e16b185c344cfc2
mittal-umang/Analytics
/Assignment-2/MultiplyMatrix.py
1,194
4.3125
4
# Chapter 11 Question 6 # Write a function to multiply two matrices def multiply_matrix(left, right): result = [] for i in range(len(left)): innerMatrix = [] for j in range(len(left)): sum = 0 for k in range(len(left)): sum += left[i][k] * right[k][j] innerMatrix.append(sum) result.append(innerMatrix) return result def print_matrix(sqMatrix): for i in range(len(sqMatrix)): for j in range(len(sqMatrix)): print('%0.2f' % sqMatrix[i][j], end="\t", sep="\t") print() def list_matrix(size, alist): i = 0 result = [] while i < len(alist): result.append(alist[i:i + size]) i += size return result def main(): size = eval(input("Enter size of both Matrices: ")) print("Enter Matrix 1:", end="\t") left = [float(x) for x in input().split()] left = list_matrix(size, left) print("Enter Matrix 2:", end="\t") right = [float(x) for x in input().split()] right = list_matrix(size, right) print("Product of Matrices are : ") print_matrix(multiply_matrix(left, right)) if __name__ == "__main__": main()
ed4293c4fcc473795705f555a305a4ee7c7a2701
mittal-umang/Analytics
/Assignment-2/VowelCount.py
977
4.25
4
# Chapter 14 Question 11 # Write a program that prompts the user to enter a # text filename and displays the number of vowels and consonants in the file. Use # a set to store the vowels A, E, I, O, and U. def main(): vowels = ('a', 'e', 'i', 'o', 'u') fileName = input("Enter a FileName: ") vowelCount = 0 consonantsCount = 0 try: with open(fileName, "rt") as fin: fileContents = fin.read().split(" ") except FileNotFoundError: print("File Not Found") except OSError: print("Cannot Open File") finally: fin.close() while fileContents: word = fileContents.pop().lower() for i in word: if i.isalpha(): if i in vowels: vowelCount += 1 else: consonantsCount += 1 print("There are ", vowelCount, "vowels and", consonantsCount, "consonants in", fileName) if __name__ == "__main__": main()
b4d8a241abc3176839928d2f88f77ef6866cef5e
mittal-umang/Analytics
/Assignment-1/GCD.py
412
4.03125
4
# Chapter 5 Question 16 # Compute the greatest common divisor def main(): num1, num2 = eval(input("Enter two number with comma : ")) if num1 > num2: d = num2 else: d = num1 while d > 0: if num1 % d == 0 and num2 % d == 0: break d -= 1 print("The Greatest Common Divisor of ", num1, "and", num2, "is", d) if __name__ == "__main__": main()
40348bc030ebcb6daf547ae7688cbca81fe066d9
mittal-umang/Analytics
/Assignment-2/Triangle.py
1,849
3.765625
4
# Chapter 12 Question 1 from GeometricObject import GeometricObject from TriangleError import TriangleError class Triangle(GeometricObject): def __init__(self, color, isFilled, side1=1.0, side2=1.0, side3=1.0): super().__init__(color, isFilled) if not (abs(int(side2) - int(side3)) < int(side1) < int(side2) + int(side3) and abs( int(side1) - int(side3)) < int(side2) < int(side1) + int(side3) and abs( int(side1) - int(side2)) < int(side3) < int(side1) + int(side2)): raise TriangleError(side1, side2, side3) else: self.__side1 = int(side1) self.__side2 = int(side2) self.__side3 = int(side3) def getSide1(self): return self.__side1 def getSide2(self): return self.__side2 def getSide3(self): return self.__side3 def getPerimeter(self): return self.getSide1() + self.getSide2() + self.getSide3() def getArea(self): s = self.getPerimeter() / 2 return (s * (s - self.getSide1()) * (s - self.getSide2()) * (s - self.getSide3())) ** 0.5 def __str__(self): return "Triangle: side1 = " + str(self.getSide1()) + " side2 = " + str(self.getSide2()) + " side3 = " + str( self.getSide3()) def main(): side1, side2, side3, color, isFilled = input("Enter Sides of triangle,its color and 1 or 0 for filled:").split(",") try: triangle = Triangle(color, bool(isFilled), side1, side2, side3) print("Area of triangle", triangle.getArea()) print("Perimeter of triangle", triangle.getPerimeter()) print("Color of triangle", triangle.getColor()) print("Triangle is filled", triangle.isFilled()) except TriangleError: print("Given Sides cannot create a Triangle") if __name__ == "__main__": main()
67593b7fcb04e87730e87066e587576fc3a88386
mittal-umang/Analytics
/Assignment-1/PalindromicPrime.py
1,189
4.25
4
# Chapter 6 Question 24 # Write a program that displays the first 100 palindromic prime numbers. Display # 10 numbers per line and align the numbers properly import time def isPrime(number): i = 2 while i <= number / 2: if number % i == 0: return False i += 1 return True def reverse(number): reverseNumber = "" while number > 0: reverseNumber += str(number % 10) number = number // 10 return int(reverseNumber) def isPalindrome(number): if reverse(number) == number: return True else: return False def main(): maxNumber = eval(input("Enter the a number of palindromic prime numbers are required: ")) count = 0 primeNumber = 2 while count < maxNumber: # Evaluating isPalindrome first to reduce the computational time of prime number. # since number of iterations in isPrime Functions are more. if isPalindrome(primeNumber) and isPrime(primeNumber): print(format(primeNumber, '6d'), end=" ") count += 1 if count % 10 == 0: print() primeNumber += 1 if __name__ == "__main__": main()
ab73985f340bdcafff532a601e84d268f849a7db
mittal-umang/Analytics
/Assignment-1/RegularPolygon.py
1,258
4.25
4
# Chapter 7 Question 5 import math class RegularPolygon: def __init__(self, numberOfSide=3, length=1, x=0, y=0): self.__numberOfSide = numberOfSide self.__length = length self.__x = x self.__y = y def getNumberOfSides(self): return self.__numberOfSide def getLength(self): return self.__length def getXCoordinate(self): return self.__x def getYCoordinate(self): return self.__y def getPerimeter(self): return self.getNumberOfSides() * self.getLength() def getArea(self): return (self.getNumberOfSides() * (self.getLength() ** 2)) / (4 * math.tan(math.pi / self.getNumberOfSides())) def main(): triangle = RegularPolygon() hexagon = RegularPolygon(6, 4) decagon = RegularPolygon(10, 4, 5.6, 7.8) print("The Perimeter of the triangle is ", triangle.getPerimeter(), "and area of the triangle is", triangle.getArea()) print("The Perimeter of the hexagon is ", hexagon.getPerimeter(), "and area of the hexagon is", hexagon.getArea()) print("The Perimeter of the decagon is ", decagon.getPerimeter(), "and area of the decagon is", decagon.getArea()) if __name__ == "__main__": main()
cea462ca0b7bf4c088e1a2b035f26003052fcef2
mittal-umang/Analytics
/Assignment-2/KeyWordOccurence.py
1,328
4.40625
4
# Chapter 14 Question 3 # Write a program that reads in a Python # source code file and counts the occurrence of each keyword in the file. Your program # should prompt the user to enter the Python source code filename. def main(): keyWords = {"and": 0, "as": 0, "assert": 0, "break": 0, "class": 0, "continue": 0, "def": 0, "del": 0, "elif": 0, "else": 0, "except": 0, "False": 0, "finally": 0, "for": 0, "from": 0, "global": 0, "if": 0, "import": 0, "in": 0, "is": 0, "lambda": 0, "None": 0, "nonlocal": 0, "not": 0, "or": 0, "pass": 0, "raise": 0, "return": 0, "True": 0, "try": 0, "while": 0, "with": 0, "yield": 0} filename = input("Enter a Python source code filename: ").strip() try: with open(filename) as fin: text = fin.read().split() except FileNotFoundError: print("File Not Found") finally: fin.close() keys = list(keyWords.keys()) for word in text: if word in keys: keyWords[word] += 1 for i in range(len(keys)): if keyWords.get(keys[i]) < 1: print(keys[i], "occurs", keyWords.get(keys[i]), "time") else: print(keys[i], "occurs", keyWords.get(keys[i]), "times") if __name__ == "__main__": main()
49837fed1d537650d55dd8d6c469e7c77bc3a4c6
mittal-umang/Analytics
/Assignment-1/ReverseNumber.py
502
4.28125
4
# Chapter 3 Question 11 # Write a program that prompts the user to enter a four-digit integer # and displays the number in reverse order. def __reverse__(number): reverseNumber = "" while number > 0: reverseNumber += str(number % 10) number = number // 10 return reverseNumber def main(): number = eval(input("Enter an integer: ")) reversedNumber = __reverse__(number) print("The reversed number is", reversedNumber) if __name__ == "__main__": main()
4bdeb3a2c137e5fa69998ca4503538302082cef0
mittal-umang/Analytics
/Assignment-1/SineCosWave.py
977
4.3125
4
# Chapter 5 Question 53 # Write a program that plots the sine # function in red and cosine in blue import turtle import math def drawLine(x1, y1, x2, y2): turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) turtle.penup() def main(): drawLine(-360, 0, 360, 0) drawLine(0, -150, 0, 150) drawLine(-20, 125, 0, 150) drawLine(0, 150, 20, 125) drawLine(340, -25, 360, 0) drawLine(360, 0, 340, 25) turtle1 = turtle.Turtle() turtle2 = turtle.Turtle() turtle1.penup() turtle2.penup() turtle1.goto(-360, 50 * math.sin(math.radians(-360))) turtle2.goto(-360, 50 * math.cos(math.radians(-360))) turtle1.pendown() turtle2.pendown() turtle1.pencolor("red") turtle2.pencolor("blue") i = -360 while i < 361: turtle1.goto(i, 50 * math.sin(math.radians(i))) turtle2.goto(i, 50 * math.cos(math.radians(i))) i += 1 turtle.done() if __name__ == "__main__": main()
c86efaf3ce656c67a47a6df3c036345d6e604001
mittal-umang/Analytics
/Assignment-2/AccountClass.py
1,428
4.1875
4
# Chapter 12 Question 3 class Account: def __init__(self, id=0, balance=100, annualinterestrate=0): self.__id = id self.__balance = balance self.__annualInterestRate = annualinterestrate def getMonthlyInterestRate(self): return str(self.__annualInterestRate * 100) + "%" def getMonthlyInterest(self): return "$" + str(self.__annualInterestRate * self.__balance / 12) def getId(self): return self.__id def getBalance(self): return "$" + str(self.__balance) def withdraw(self, amount): if self.__balance < amount: raise Exception("Balance Less than withdrawal Amount") else: self.__balance -= amount def deposit(self, amount): self.__balance += amount def main(): account = Account(1122, 20000, 0.045) print("Current account balance is ", account.getBalance()) account.withdraw(2500) print("Account balance after withdrawal is ", account.getBalance()) account.deposit(3000) print("Account balance after deposit is ", account.getBalance()) print("Account Details are as below: ") print("\tAccount ID : ", account.getId()) print("\tCurrent Balance is ", account.getBalance()) print("\tAnnual Interest rate is ", account.getMonthlyInterestRate()) print("\tAnnual Interest is ", account.getMonthlyInterest()) if __name__ == "__main__": main()
a818d6ce507d2f268775219810d8e53696653308
pravindra01/DS_And_AlgorithmsPractice
/formatIntArray.py
894
3.875
4
# even numbera at beginning # odd at the end # take time O(n/2) # O(1) space # Input : [1,2,3,4,5,6,7,8,9,10] # Output: [10,2,8,4,6,5,7,3,9,1] def formatIntArray(arr): startIndex = 0 endIndex = len(arr) -1 for _ in range(0,len(arr)): if startIndex > endIndex: break print "START: " , arr[startIndex], "Index: ", startIndex print "END: " , arr[endIndex], "End Index: ", endIndex if (arr[startIndex] % 2) == 0: startIndex += 1 elif (arr[endIndex] % 2) != 0: endIndex -=1 else: temp = arr[startIndex] arr[startIndex] = arr[endIndex] arr[endIndex] = temp startIndex +=1 endIndex -= 1 return arr if __name__ == "__main__": mynewArr = [1,2,3,4,5,6,7,8,9,10] arr = formatIntArray(mynewArr) for item in arr: print item
0171884c3ecadb4d49e762c8fa8718033510e751
MihaChug/PRRIS
/Contacts/main.py
714
3.796875
4
## -*- coding: utf-8 -*- contacts = [] command = "" find = 0 print('If you want to exit - print "exit"') while command != "exit": command = input(">") #Добавляем новый контакт в конец списка c учетом всех возможных сочетаний начальных букв с первой по последнюю if command[0:3] == 'Add': for i in range(len(command[3:]) - 1): contacts.append(command[4:i+5]) #Ищем все вхождения элементов в списке elif command[0:4] == 'Find': find = contacts.count(command[5:]) print("-> ", find) elif command != 'exit': print("Wrong command!")
104e227416410541282791c06aa53c2fb4f283e0
lbl-kmust/Git-workspace
/Python_study/lemon_82/python _exercises.py
9,251
3.953125
4
# 1. 用户输入一个数值,请判断用户输入的是否为偶数?是偶数输出True,不是输出False # (提示:input输入的不管是什么,都会被转换成字符串,自己扩展,想办法转换为数值类型,再做判段,) # a = int(input("请输入一个整数:")) # print(a) # if a % 2 == 0 : # print("True") # else : # print("False") # 2. 现在有列表 li = [‘hello’,‘scb11’,‘!’],通过相关操作转换成字符串:'hello python18 !'(注意点:转换之后单词之间有空格) # li = ['hello','scb11','!'] # li[0] = 'hello ' # li[1] = 'python18 ' # str1 = '' # for i in li : # str1 +=i # print(str1) # 3. 现在有字符串:str1 = 'python hello aaa 123123aabb' # 1)请计算 字符串中有多少个'a' # 2)请找出字符串中'123'的下标起始位置 # 3)请分别判断 'o a' 'he' 'ab' 是否是该字符串中的成员? # str1 = 'python hello aaa 123123aabb' # print(str1.count("a")) # print(str1.find('123')) # if 'o a' in str1 : # print("'o a'是该字符串中的成员") # else : # print("'o a'不是该字符串中的成员") # if 'he' in str1 : # print("'he'是该字符串中的成员") # else : # print("'he'不是该字符串中的成员") # if 'ab' in str1 : # print("'ab'是该字符串中的成员") # else : # print("'ab'不是该字符串中的成员") # # 4. 将给定字符串的PHP替换为Python # best_language = "PHP is the best programming language in the world! " # best_language = "PHP is the best programming language in the world! " # best_language1 = best_language.replace("PHP","Python") # print(best_language1) # # 5编写代码,提示用户输入1-7七个数字,分别代表周一到周日,如果输入的数字是6或7则为周末,打印输出“今天是周几” # dict1 = {1:"一",2:"二",3:"三",4:"四",5:"五"} # date1 = int(input("请输入1-7的一个数字:")) # if date1 not in range(1,8) : # print("请重新输入1-7以内的数字") # elif date1 == 6 or date1 == 7 : # print("今天是周末") # else : # print("今天是周{}".format(dict1.get(date1))) # 6. 现在有一个列表 li2=[1,2,3,4,5], # 第一步:请通过相关的操作改成li2 = [0,1,2,3,66,4,5,11,22,33] # 第二步:对li2进行排序处理 # 第三步:请写出删除列表中元素的方法,并说明每个方法的作用 # li2=[1,2,3,4,5] # li2.insert(0,0) # li2.insert(4,66) # li2.extend([11,22,33]) # print(li2) # # li2.sort() # print(li2) # li2.sort(reverse=True) # print(li2) # li2.sort(reverse=False) # print(li2) # li2 = [1,2,3,4,5] # li2.pop(2) #通过索引删除 # print(li2) # li3 = [1,2,3,8,4,5] # li3.remove(8) #删除指定元素 # print(li3) # li4 = [1,2,3,8,4,5] # li4.clear() #清空 # print(li4) # 7. 切片 # 1、li = [1,2,3,4,5,6,7,8,9] 请通过切片得出结果 [3,6,9] # li = [1,2,3,4,5,6,7,8,9] # li01 = li[2:len(li):3] # print(li01) # 2、s = 'python java php',通过切片获取: ‘java’ # s = 'python java php' # s01 = s[7:11:1] # print(s01) # 3 、tu = ['a','b','c','d','e','f','g','h'],通过切片获取 [‘g’,‘b’] # tu = ['a','b','c','d','e','f','g','h'] # tu01 = tu[6:0:-5] # print(tu01) # tu02 = tu[1:7:5] # tu02.reverse() # print(tu02) # # 8. 有5道题(通过字典来操作): # 1. 某比赛需要获取你的个人信息,设计一个程序,运行时分别提醒输入 姓名、性别、年龄 ,输入完了,请将数据存储起来, # name = input("请输入你的名字:") # gender = input("请输入你的性别:") # age = input("请输入你的年龄:") # dict01 = dict(姓名 = name,性别 = gender,年龄 = age) # print(dict01) # 2、数据存储完了,然后输出个人介绍,格式如下: 我的名字XXX,今年XXX岁,性别XX,喜欢敲代码 # name = input("请输入你的名字:") # gender = input("请输入你的性别:") # age = input("请输入你的年龄:") # dict01 = dict(姓名 = name,性别 = gender,年龄 = age) # print("我的名字{},今年{}岁,性别{},喜欢敲代码".format(dict01["姓名"],dict01["年龄"],dict01["性别"])) # 3. 有一个人对你很感兴趣,平台需要您补足您的身高和联系方式; # name = input("请输入你的名字:") # gender = input("请输入你的性别:") # age = input("请输入你的年龄:") # dict01 = dict(姓名 = name,性别 = gender,年龄 = age) # height = input("请补充你的身高:") # phone = input("请补充你的手机号:") # dict02 = {"身高":height,"联系方式":phone} # dict03 = {} # dict03.update(dict01) # dict03.update(dict02) # print(dict03) # print("我的名字{},今年{}岁,性别{},喜欢敲代码".format(dict01["姓名"],dict01["年龄"],dict01["性别"])) # 4. 平台为了保护你的隐私,需要你删除你的联系方式; # name = input("请输入你的名字:") # gender = input("请输入你的性别:") # age = input("请输入你的年龄:") # dict01 = dict(姓名 = name,性别 = gender,年龄 = age) # height = input("请补充你的身高:") # phone = input("请补充你的手机号:") # dict02 = {"身高":height,"联系方式":phone} # dict03 = {} # dict03.update(dict01) # dict03.update(dict02) # dict03.pop("联系方式") # skill01 = input("擅长的技能1:") # skill02 = input("擅长的技能2:") # skill03 = input("擅长的技能3:") # dict04 = {"擅长的技能1":skill01,"擅长的技能2":skill02,"擅长的技能3":skill03} # dict03.update(dict04) # print(dict03) # 5. 你为了取得更好的成绩, 你添加了自己的擅长技能,至少需要 3 项 # 9. 一家商场在降价促销。如果购买金额50-100元(包含50元和100元)之间,会给10%的折扣,如果购买金额大于100元会给20%折扣。 # 编写一程序,询问购买价格,再显示出折扣(%10或20%)和最终价格。 # def discount_price(price) : # if 100 >= price >= 50 : # final_price = price * 0.9 # discount = "%10" # elif price > 100 : # final_price = price * 0.8 # discount = "%20" # else : # final_price = price # discount = "%0" # return final_price,discount # price = float(input("请输入商品价格:")) # result = discount_price(price) # print("商品价格是{},折扣{},折扣价{}".format(price,result[1],result[0])) # # 11、一个 5 位数,判断它是不是回文数。例如: 12321 是回文数,个位与万位相同,十位与千位相同。 根据判断打印出相关信息 # def judge_data(data1) : # li1 = list(data1) # if li1[0] == li1[4] : # if li1[1] == li1[3] : # data_result = 1 # else : # data_result = 0 # else : # data_result = 0 # return data_result # data1 = input("请输入5位的整数:") # result = judge_data(data1) # print(result) # if result== 1 : # print("输入的数:{},是回文数".format(data1)) # else : # print("输入的数:{},不是回文数".format(data1)) # 12、现有一个字典: dict = {'name':'小明,'age':18,'occup':'students','teacher': {'语文':'李老师','数学':'王老师','英语':'张老师'}}, ' # '请获取到小明同学的名字;然后再获取到小明的数学老师 # dict1 = {"name":"小明","age":18,"occup":"students","teacher": {"语文":"李老师","数学":"王老师","英语":"张老师"}} # # print(dict1["name"]) # # print(dict1["teacher"]["数学"]) # 13、设计一个函数,获取一个100以内偶数的纯数字序列,并存到列表里, 然后求这些偶数数字的和 # sum1 = 0 # list1 = [] # for i in range(101) : # if i % 2 ==0 : # list1.append(i) # sum1 +=i # print(list1) # print(sum1) # 14、输出99乘法表,结果如下:(提示嵌套for循环,格式化输出) # for i in range(1,10) : # for j in range(1,i+1) : # print("{} * {} = {}\t".format(i,j,j*i),end=" ") # print() # 有1 2 3 4 这四个数字,设计程序计算能组成多少个互不相同且无重复数字的3位数?分别是什么? # num = 0 # li_sum = [] # for i in range(1,5) : # for j in range(1,5) : # for k in range(1,5) : # if i != j and i !=k and j != k : # li = [i,j,k] # str1 = [str(n) for n in li] # print(''.join(str1)) # num +=1 # li_sum.append(''.join(str1)) # print("一共能组成{}个无重复数字组合,分别是{}".format(num,li_sum)) # 16、通过函数实现一个计算器,运行程序分别提示用户输入数字1,数字2, # 然后再提示用户选择 : 加【1】 减【2】 乘【3】 除【4】,每个方法使用一个函数来实现, 选择后调用对应的函数,然后返回结果。 d1 = int(input("请输入数字1或者数字2:")) d2 = int(input("请输入数字1或者数字2:")) d3 = int(input("选择 : 加【1】 减【2】 乘【3】 除【4】")) if d3 == 1 : result = d1 + d2 print(result) elif d3 == 2 : result = d1 - d2 print(result) elif d3 == 3 : result = d1 * d2 print(result) elif d3 == 4 : result = d1 / d2 print(result) else : print("选择有误")
279e2c3c7a93890b41292507f7b0ee99754fecec
jbesong-su/DeepLearningKeras
/Multiclass classification flower species/irisclass.py
1,805
3.625
4
from pandas import read_csv from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from keras.utils import np_utils from sklearn.model_selection import cross_val_score, KFold from sklearn.preprocessing import LabelEncoder #load data set dt = read_csv('iris.csv', header=None) data = dt.values X = data[:, 0:4].astype(float) Y = data[:, 4] #encoding output variable Y #encode class values as integers encoder = LabelEncoder() encoder.fit(Y) encoded_Y = encoder.transform(Y) #convert integers to dummy variables(one hot encoded) #creates matrix i.e ''' type1 type2 type3 0 1 0 1 0 0... ''' dummy_Y = np_utils.to_categorical(encoded_Y) #define baseline model #define model as a function so that it can be passed to KerasClassifier as argument #use KerasClassifier in order to use sci-kit learn with everything def baseline_model(): #create model model = Sequential() #hidden layer 8 nodes. 4 inputs model.add(Dense(8, input_dim = 4, activation='relu')) #3 outputs because onehot-encoding #activation as softmax to ensure output values are in range of 0 and 1 model.add(Dense(3, activation='softmax')) #compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model #Pass arguments wo kerasClassifier to specify how model will be trained estimator = KerasClassifier(build_fn=baseline_model, epochs=200, batch_size=5, verbose=0) print("estimator: ", estimator) #evaluate model with kfold cross-val kfold = KFold(n_splits=10,shuffle=True) results = cross_val_score(estimator, X, dummy_Y, cv=kfold) print("These are results: ", results) #print("Accuracy: %.2f%% (%.2f%%)" % (results.mean() *100, results.std() * 100))
d6947d35220f814803f795e2cca3ba59377066f8
galustian/Algorithms
/symbol_table.py
2,993
4.09375
4
import queue # Very simple implementation using a binary search tree # Assumes that keys are strings class MapStr: class Node: def __init__(self, key, val): self.key = key self.val = val self.left = None self.right = None def __init__(self): self.first = None self.length = 0 def put_(self, key, val, node=None): if self.first is None: self.first = self.Node(key, val) self.length = 1 return # Create Node if does not exist if node is None: node = self.Node(key, val) self.length += 1 return # Update Node if exists if key == node.key: node.val = val return # Traverse binary-tree if key < node.key: if node.left is None: node.left = self.Node(key, val) self.length += 1 return self.put_(key, val, node.left) else: if node.right is None: node.right = self.Node(key, val) self.length += 1 return self.put_(key, val, node.right) def put(self, key, val): self.put_(key, val, self.first) def get(self, key, node=None, depth=0): if depth == 0: return self.get(key, self.first, 1) # KeyError if node is None: raise KeyError if key == node.key: return node.val if key < node.key: return self.get(key, node.left, 1) else: return self.get(key, node.right, 1) def __contains__(self, key): try: self.get(key) return True except KeyError: return False def get_items(self, node, q=None): if node == None: return [] if node.left is not None: self.get_items(node.left, q) q.put((node.key, node.val)) if node.right is not None: self.get_items(node.right, q) def __iter__(self): q = queue.Queue() self.get_items(self.first, q=q) items = [] while not q.empty(): items.append(q.get()) for tup in items: yield tup def __len__(self): return self.length # Tests if __name__ == '__main__': str_map = MapStr() str_map.put('one', 7) str_map.put('car', 42) str_map.put('auto', 69) str_map.put('auto', 666) str_map.put('zebra', 3.14) str_map.put('yard', 64) assert str_map.get('car') == 42 assert str_map.get('one') == 7 assert str_map.get('auto') == 666 assert ('one' in str_map) == True assert ('two' in str_map) == False assert len(str_map) == 5 # Must be sorted alphabetically for key, val in str_map: print(key, val)
692505ec86ff96fe6e96802c2b2cf6306e11e2e0
mfnu/Python-Assignment
/Functions-repeatsinlist.py
554
4.1875
4
''' Author: Madhulika Program: Finding repeats in a list. Output: The program returns the number of times the element is repeated in the list. Date Created: 4/60/2015 Version : 1 ''' mylist=["one", "two","eleven", "one", "three", "two", "eleven", "three", "seven", "eleven"] def count_frequency(mylist): result = dict((i,mylist.count(i)) for i in mylist) return result print(count_frequency(mylist)) ''' O/P: C:\Python34\Assignments>python Functions-repeatsinlist.py {'eleven': 3, 'seven': 1, 'one': 2, 'two': 2, 'three': 2} '''
6cce56a231c2e45d7685793b57e412baf6ac0483
bxnxiong/Lint-Code
/97 validateBinaryTree.py
1,455
4.0625
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: True if the binary tree is BST, or false """ def isValidBST(self, root): # write your code here result = True if root: if root.left: if root.left.val >= root.val: result = False else: temp = root.left while temp.right: temp = temp.right if temp.val >= root.val: result = False else: result = self.isValidBST(root.left) if result == False: return result else: if root.right: if root.right.val <= root.val: result = False else: temp = root.right while temp.left: temp = temp.left if temp.val <= root.val: result = False else: result = self.isValidBST(root.right) return result
419012b91013b1c4a7407962c88a087a50a0f625
bxnxiong/Lint-Code
/159 findMinimumInRotatedArray.py
729
3.640625
4
class Solution: # @param nums: a rotated sorted array # @return: the minimum number in the array def findMin(self, nums): # write your code here n = len(nums) if nums[0] > nums[-1]: if n == 0:return if n == 2 or n == 3: i = 0 while i+1 < n: if nums[i] > nums[i+1]: return nums[i+1] i += 1 return left = nums[:n/2] right = nums[n/2:] if left[0] > left[-1]: return self.findMin(left) else: return self.findMin(right) else: return nums[0]
fa86f910fd80f768df290210058c4b77d10f7c70
bxnxiong/Lint-Code
/535 houseRobberIII.py
872
3.625
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): sef.val = val self.left, self.right = None, None """ class Solution: # @param {TreeNode} root, the root of binary tree. # @return {int} The maximum amount of money you can rob tonight def houseRobber3(self, root): # write your code here if not root: return 0 return max(self.max_sum(root)) def max_sum(self,root): ''' return (current_val,children_sum)''' if root.left: left = self.max_sum(root.left) l_v = max(left) else: left,l_v = (0,0),0 if root.right: right = self.max_sum(root.right) r_v = max(right) else: right,r_v = (0,0),0 return (root.val+left[1]+right[1],l_v+r_v)
d8cd23f22958facb0eec42633a92680e8d856093
bxnxiong/Lint-Code
/127 topologicalSorting-DFS.py
965
3.90625
4
# Definition for a Directed graph node # class DirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: """ @param graph: A list of Directed graph node @return: A list of graph nodes in topological order. """ def topSort(self, graph): # write your code here color = {u:'w' for u in graph} cycle = False result = [] for u in graph: self.dfs(u,color,result,cycle) result.reverse() if not cycle: return result else: return [] def dfs(self,u,color,result,cycle): if color[u] == 'w': color[u] = 'g' for i in u.neighbors: self.dfs(i,color,result,cycle) result.append(u) color[u] = 'b' if color[u] == 'g': cycle = True
12eda60f4cd791043a1fccbb8de014e69489edfc
bxnxiong/Lint-Code
/124 longestConsecutiveSequence.py
924
3.59375
4
class Solution: """ @param num, a list of integer @return an integer """ def longestConsecutive(self, num): # write your code here book = {x:False for x in num} maxLen = -1 for i in book: if book[i] == False: #book[i] = True current = i + 1 right_len = 0 while current in book: book[current] = True right_len += 1 current += 1 current = i - 1 left_len = 0 while current in book: left_len += 1 book[current] = True current -= 1 maxLen = max(maxLen,left_len + right_len + 1) return maxLen
b8b367bfeccd86b3a65afb3194533b0b5b94efa4
bxnxiong/Lint-Code
/123 wordSearch.py
1,827
3.734375
4
class Solution: # @param board, a list of lists of 1 length string # @param word, a string # @return a boolean def exist(self, board, word): # write your code here def dfs(r,c,word): if len(word) == 0: return True else: # up if r > 0 and board[r-1][c] == word[0]: tmp = board[r][c];board[r][c] = '#' if dfs(r-1,c,word[1:]): return True board[r][c] = tmp # down if r < len(board)-1 and board[r+1][c] == word[0]: tmp = board[r][c];board[r][c] = '#' if dfs(r+1,c,word[1:]): return True board[r][c] = tmp # left if c > 0 and board[r][c-1] == word[0]: tmp = board[r][c];board[r][c] = '#' if dfs(r,c-1,word[1:]): return True board[r][c] = tmp # right if c < len(board[0])-1 and board[r][c+1] == word[0]: tmp = board[r][c];board[r][c] = '#' if dfs(r,c+1,word[1:]): return True board[r][c] = tmp return False if len(board) == 0: if word == "": return True else: return False else: for r in range(len(board)): for c in range(len(board[0])): if board[r][c] == word[0]: if dfs(r,c,word[1:]): return True return False
013cb916d56e94c09e5d0451ceff7c532c3a85cd
rustyhu/design_pattern
/python_patterns/builder.py
1,028
4.125
4
"Personal understanding: builder pattern emphasizes on the readability and user convenience, the code structure is not quite neat." class BurgerBuilder: cheese = False pepperoni = False lettuce = False tomato = False def __init__(self, size): self.size = size def addPepperoni(self): self.pepperoni = True return self def addLecttuce(self): self.lettuce = True return self def addCheese(self): self.cheese = True return self def addTomato(self): self.tomato = True return self # builder def build(self): return Burger(self) class Burger: def __init__(self, builder): self.size = builder.size self.cheese = builder.cheese self.pepperoni = builder.pepperoni self.lettuce = builder.lettuce self.tomato = builder.tomato if __name__ == '__main__': # call builder b = BurgerBuilder(14).addPepperoni().addLecttuce().addTomato().build() print(b)
82fbec4c59b15ddb8379fb9bc955ab4b12ec26b5
rustyhu/design_pattern
/python_patterns/composite.py
1,297
3.734375
4
""" Composite pattern. client use a group of objects and single object uniformly. """ from abc import ABC, abstractmethod # interface 1 NOT_IMPLEMENTED = "You should implement this." class Graphic(ABC): @abstractmethod def print(self): raise NotImplementedError(NOT_IMPLEMENTED) class CompositeGraphic(Graphic): def __init__(self): self.graphics_ = [] def print(self): for g in self.graphics_: g.print() def add(self, *g): "iterate *g to support add a collection of Graphic at once" for ele in g: self.graphics_.append(ele) def remove(self, g): self.graphics_.remove(g) class Ellipse(Graphic): def __init__(self, name): self.name = name def print(self): print("Ellipse: ", self.name) if __name__ == '__main__': ellipse1 = Ellipse("no.1") ellipse2 = Ellipse("no.2") ellipse3 = Ellipse("no.3") ellipse4 = Ellipse("no.4") ellipse_group1 = CompositeGraphic() ellipse_group2 = CompositeGraphic() graphic_collection = CompositeGraphic() ellipse_group1.add(ellipse1) ellipse_group2.add(ellipse2) ellipse_group2.add(ellipse3) graphic_collection.add(ellipse_group1, ellipse_group2, ellipse4) graphic_collection.print()
11cd522822a346f626acbab4bb98792ad659fe0b
Nate18464/WorldVaccination
/research/source/DataVisualization/PredictionCreator/data_visualization_file_creator.py
5,318
3.640625
4
""" This modules extracts and cleans the original vaccination data in order to have only the date, country, and people_fully_vaccinated_per_hundred columns Then, it makes predictions and saves them into a pandas dataframe After, it combines these predictions with the original data Finally, it creates a csv file with the data """ import warnings import datetime import pandas as pd import numpy as np from logistic_logarithmic_regression import LogisticLogarithmicRegressionModel from logistic_regression import LogisticRegressionModel from logistic_polynomial_regression import LogisticPolynomialRegressionModel from polynomial_regression import PolynomialRegressionModel warnings.filterwarnings("ignore") def extract_data(): """Extract data from vaccinations.csv Creates a data frame from vaccinations.csv Transforms the data into data that is useable by models Then extracts data from each country Returns: A dictionary where the key is the country and the value holds information for later, for now just the data """ raw_data = pd.read_csv("../../../resource/DataVisualization/vaccinations.csv") raw_data = raw_data[["location", "date", "people_fully_vaccinated_per_hundred"]] raw_data.date = pd.to_datetime(raw_data.date, format="%Y-%m-%d") min_date = raw_data.date.min() raw_data.date = raw_data.date-min_date raw_data.date = pd.Series([x.days for x in raw_data.date]) raw_data.drop(raw_data.loc[raw_data.people_fully_vaccinated_per_hundred.isnull()].index, axis=0, inplace=True) raw_data["people_fully_vaccinated_per_hundred"] /= 100 data_dict = dict() for country in raw_data.location.unique(): if len(raw_data.loc[raw_data.location == country]) >= 100: tmp_data = raw_data.loc[raw_data.location == country] tmp_data.drop("location", axis=1, inplace=True) data_dict[country] = {"data":tmp_data} else: raw_data.drop(raw_data.loc[raw_data.location == country].index, inplace=True) return data_dict, min_date, raw_data def make_predictions(data_dict): """Make predictions for all models Creates a new dataframe that holds the prediction for dates from 0 to 499 days from the first entry Args: data_dict: Dictionary that holds the data for countries the keys are country and the value is the vaccination data Returns: new_data: A dataframe that holds the date, country, and predictions """ new_data = pd.DataFrame(columns=["location", "date", "logistic_prediction", "logistic_logarithmic_prediction", "logistic_polynomial_prediction"]) for country in data_dict.keys(): data = data_dict[country]["data"] x_data = np.array(list(range(500))) model1 = LogisticRegressionModel(data_dict[country]["data"]) y_pred1 = model1.predict(x_data.reshape(-1, 1)) model2 = LogisticLogarithmicRegressionModel(data) y_pred2 = model2.predict(x_data.reshape(-1, 1)) model3 = LogisticPolynomialRegressionModel(data) y_pred3 = model3.predict(x_data.reshape(-1, 1)) model4 = PolynomialRegressionModel(data) y_pred4 = model4.predict(x_data.reshape(-1, 1)) data = np.swapaxes(np.array([x_data, y_pred1, y_pred2, y_pred3, y_pred4]), 0, 1) tmp_data = pd.DataFrame(data, columns=["date", "logistic_prediction", "logistic_logarithmic_prediction", "logistic_polynomial_prediction", "polynomial_prediction"]) tmp_data["location"] = country new_data = new_data.append(tmp_data) return new_data def combine(new_data, raw_data): """Combines raw_data with new_data Sets the index of each dataframe to location and date Then joins the two dataframes Args: new_data: Dataframe holding the predicted values raw_data: Dataframe holding the original values Returns: all_data: Dataframe with predicted and original values """ return pd.merge(new_data, raw_data, on=["location", "date"], how="outer") def reformat_date(all_data, min_date): """Reformats date to original Switches date column from integers of days since first entry into a timedelta. Then, adds that timedelta to the min_date In the end getting a datetime. Args: all_data: A dataframe holding the original raw data and the data from predictive models """ all_data["date"] = [datetime.timedelta(x) for x in all_data["date"]] all_data["date"] = all_data["date"] + min_date def __main__(): data_dict, min_date, raw_data = extract_data() new_data = make_predictions(data_dict) all_data = combine(new_data, raw_data) reformat_date(all_data, min_date) all_data.to_csv("../../../resource/DataVisualization/prediction_data.csv", index=False) __main__()
7a7280c364cbe5354fe40681de0df47a8e8c68aa
MikeYu123/algorithms-lafore
/queues/list_deque.py
1,071
3.640625
4
from doubly_linked_list import DoublyLinkedList class ListDeque: # TODO limit size def __init__(self, size = 0): self.list_obj = DoublyLinkedList() # top of the stack is def list(self): return [link.key for link in self.list_obj.array()] def isEmpty(self): return self.list_obj.isEmpty() def insert(self, key): self.list_obj.insertLast(key, None) def push(self, key): self.list_obj.insertFirst(key, None) def remove(self): if self.isEmpty(): raise ValueError("Removing from empty deque") return self.list_obj.deleteFirst().key def pop(self): if self.isEmpty(): raise ValueError("Popping from empty deque") return self.list_obj.deleteLast().key def head(self): if self.isEmpty(): raise ValueError("Reading head from empty deque") return self.list_obj.first.key def peek(self): if self.isEmpty(): raise ValueError("Peeking from empty deque") return self.list_obj.last.key
8700991ed68dbbf7479c3036095d8024018f1380
MikeYu123/algorithms-lafore
/queues/array_stack.py
841
3.78125
4
class ArrayStack: def __init__(self, size = 10): self.array = [None] * size self.size = size self.max = -1 def isEmpty(self): return self.max == -1 def peek(self): if self.isEmpty(): raise ValueError("Peeking empty stack") return self.array[self.max] def isFull(self): return self.max == self.size - 1 def push(self, element): if self.isFull(): raise ValueError("Pushing to full stack") self.max += 1 self.array[self.max] = element def pop(self): if (self.isEmpty()): raise ValueError("Popping from empty stack") element = self.array[self.max] self.max -= 1 return element # Used only for testing def list(self): return self.array[0:self.max + 1]
7f6b51ce83ed4d1231ec2061e7e4df37ed8db8d4
sorata2894/rlcard3
/rlcard3/model_agents/agent.py
553
3.71875
4
""" Agent base class """ from typing import Dict class Agent(object): """ The base Agent class """ def step(self, state: Dict) : """ Predict the action given raw state. A naive rule. Choose the minimal action. Args: state (dict): Raw state from the game Returns: action (str): Predicted action """ raise NotImplementedError def eval_step(self, state: Dict): """ Predict the action for evaluation purpose. """ raise NotImplementedError
a5bf298e23f1783bbea3212bb405351708f3e6b4
sorata2894/rlcard3
/rlcard3/games/gin_rummy/card.py
2,669
3.671875
4
''' File name: gin_rummy/card.py Author: William Hale Date created: 2/12/2020 ''' from typing import List class Card(object): ''' Card stores the card_id, rank and suit of a single card Note: The card_id lies in range(0, 52) The rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K] The suit variable in a gin rummy game should be one of [S, H, D, C] meaning [Spades, Hearts, Diamonds, Clubs] ''' valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] valid_suit = ['S', 'H', 'D', 'C'] def __init__(self, rank: str, suit: str): ''' Initialize the rank, suit, and card_id of a card Args: rank: string, rank of the card, should be one of valid_rank suit: string, suit of the card, should be one of valid_suit ''' assert rank in Card.valid_rank assert suit in Card.valid_suit self.rank = rank self.suit = suit self.rank_id = Card.valid_rank.index(rank) self.suit_id = Card.valid_suit.index(suit) self.card_id = self.rank_id + 13 * self.suit_id def __str__(self): ''' Get string representation of a card. Returns: string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ... ''' return self.rank + self.suit def __eq__(self, other): if isinstance(other, Card): return self.card_id == other.card_id else: # don't attempt to compare against unrelated types return NotImplemented def __hash__(self): return self.card_id @classmethod def from_text(cls, text: str): assert len(text) == 2 return Card(rank=text[0], suit=text[1]) @classmethod def from_card_id(cls, card_id: int): ''' Make card from its card_id Args: card_id: int in range(0, 52) ''' assert 0 <= card_id < 52 rank_id = card_id % 13 suit_id = card_id // 13 rank = Card.valid_rank[rank_id] suit = Card.valid_suit[suit_id] return Card(rank=rank, suit=suit) @classmethod def init_standard_deck(cls): ''' Initialize a standard deck of 52 cards Returns: (list): A list of Card object ''' return [Card.from_card_id(card_id) for card_id in range(52)] # deck is always in order from AS, 2S, ..., AH, 2H, ..., AD, 2D, ..., AC, 2C, ... QC, KC _deck = Card.init_standard_deck() # want this to be read-only def get_deck(): return _deck.copy() def get_card(card_id: int): return _deck[card_id]
22da60b435758fa5bbc91c7003fb3fd197a0410e
bilalsay/PersonalDevelopment
/PythonExamples/ex1.py
984
3.5
4
Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information. >>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. Visit http://www.python.org/download/mac/tcltk/ for current information. print("Selamun aleyküm") Selamun aleyküm >>> x = 100 >>> x 100 >>> y = 1000 >>> x+y 1100 >>> veri = 18 / 100 >>> veri 0.18 >>> satis = 154.32 >>> veri*satis 27.777599999999996 >>> satis + _ 182.0976 >>> round(_,2) 182.1 >>> d = "bilalsay" >>> d 'bilalsay' >>> r = 'say' >>> r 'say' >>> print(r) say >>> d = 'bilal \nsay' >>> d 'bilal \nsay' >>> print(d) bilal say >>> >>> >>> v = "bilal ' in kodu" >>> v "bilal ' in kodu" >>> print(v) bilal ' in kodu >>> d+v "bilal \nsaybilal ' in kodu" >>> 3*d 'bilal \nsaybilal \nsaybilal \nsay' >>> d[2] 'l' >>> d[-2] 'a' >>> d[2:8] 'lal \ns' >>> print(d[3:9]) al sa >>> d[5:] ' \nsay' >>> d[:5] 'bilal' >>> len(d) 10 >>>
150ca8fba109eeb0301cff54ce0d65b3a8d16c44
anhpt1993/file_storage
/file_storage.py
447
3.921875
4
# file capacity on disk while True: try: byte = int(input("What is your file size (byte): ")) if byte > 0: break else: print("File size shall be greater than 0") print() except ValueError: print("File size shall be integer type, not float type or string") print() kb = (byte // 4096 + (byte % 4096 > 0)) * 4 print(f"{byte} byte(s) occupied {kb} KB on the disk")
b486878c4c86a6c99c2cb69445eddb0bf255eeec
gozeloglu/Input-File-Creator
/create.py
820
3.671875
4
""" *This program creates grid map for Assignment-4 *Enter the number of row and column number that you want to create """ import sys import random fp = open("gameGrid.txt", "w") jewel_list = ["|", "-", "+", "/", "\\", "D","W", "S", "T"] row = int(input("Row number: ")) column = int(input("Column number: ")) input_list = list() counter = 0 for i in range(row): tmp_list = list() for j in range(column+1): tmp_list.append(jewel_list[random.randint(0, 8)]) input_list.append(tmp_list) for i in range(len(input_list)): counter = 0 for j in range(len(input_list[i])): if counter == column: fp.write("\n") else: counter += 1 fp.write(input_list[i][j]) if counter != column: fp.write(" ") fp.close()
12e879ea015afa8c36ec9bfcac08a31139d90d38
Vipinraj9526/Python
/pgm3.py
162
3.53125
4
import csv with open("city.csv","w") as file: writer=csv.writer(file) writer.writerow([1,"max","thrissur"]) # for row in reader: # print(row)
ceb080ee75b09108b07f1cb0dd48037ce315d5c4
Ishikaaa/Python-Assignments
/Assignment-17.py
926
3.5
4
#Q1. from tkinter import * a=Tk() a.title("Ishika Garg") l=Label(a,text="Helo World").pack() b=Button(a,text="Exit",command=quit).pack() a.mainloop() #Q2. from tkinter import * a=Tk() a.title("Ishika Garg") def show(): print("Hello World") l=Label(a,text="Hello World").pack() b1=Button(a,text="Click",command=show).pack() b2=Button(a,text="Stop",command=a.destroy).pack() a.mainloop() #Q3. from tkinter import * a=Tk() a.title("Ishika Garg") l1=Label(a,text="Before Clicking Button") l1.grid(row=0,sticky=W) def show(): l1.config(text="After Clicking Button") ishika=1 b1=Button(a,text="Click",command=show) b1.grid(row=1) b2=Button(a,text="Exit",command=a.destroy) b2.grid(row=2) a.mainloop() #Q4. from tkinter import * a=Tk() def show(): ee=v1.get() l=Label(a,text=ee).grid(row=2) v1=IntVar() a.title("Ishika Garg") b=Button(a,text="Click",command=show).grid(row=1) e=Entry(a,textvariable=v1).grid(row=0) a.mainloop()
5490c0ae8130bcbf90dc1c9c6484219148662d47
Ishikaaa/Python-Assignments
/Assignment-5.py
1,376
3.796875
4
#Q1. year=int(input("Enter year=")) if(year%4==0): print(year,"is a leap year") else: print(year,"is not a leap year") #Q2. l=int(input("Enter length=")) b=int(input("Enter breadth=")) if(l==b): print("This is a square") else: print("This is a rectangle") #Q3. a=int(input("Enter age of 1st person=")) b=int(input("Enter age of 2nd person=")) c=int(input("Enter age of 3rd person=")) if(a>b>c): print(a,"is oldest and",c,"is youngest") elif(a>c>b): print(a, "is oldest and",b, "is youngest") elif(b>c>a): print(b, "is oldest and", a, "is youngest") elif(b>a>c): print(b, "is oldest and", c, "is youngest") elif(c>a>b): print(c, "is oldest and", b, "is youngest") else: print(c, "is oldest and", a, "is youngest") #Q4. var=int(input("Enter points between 0 and 200=")) if(1<var<50): print("Sorry!No prize this time") elif(51<var<150): print("Congratulations!You won a wooden dog") elif(151<var<180): print("Congratulations!You won a book") elif(181<var<200): print("Congratulations!You won chocolates") else: print("Invalid points. Enter number between 1-200") #Q5. unn=int(input("Enter number of units that you are purchasing=")) if(0<unn<=10): print("Total cost is -",unn*100) elif(unn>10): unnn=(unn-(unn*0.1))*100 print("Total cost is -",unnn) else: print("Enter positive number")
cc785e3dfc9bd46ee95987084661527458a5ca58
Ishikaaa/Python-Assignments
/Doubtt.py
915
4.09375
4
# #1.If you want to add more than one numbers at one time # A=[1,2] # for i in range(4): # a=int(input("Enter nunmber=")) # A.append(a) # print(A) # # # A=[1,2] # a=int(input("Enter 1st number=")) # b=int(input("Enter 2nd number=")) # c=int(input("Enter 3rd number=")) # d=int(input("Enter 4th number=")) # A.extend([a,b,c,d]) # print(A) #2. Implementation of queue from collections import deque queue = deque(["Ram", "Tarun", "Asif", "John"]) print("implementation of queue(2nd method)--") print(queue) queue.append("Akbar") print(queue) queue.append("Birbal") print(queue) print(queue.popleft()) print(queue.popleft()) print(queue) from collections import bb A=bb([1,2,3,4]) print(A) A.append(10) print(A) print(A.popleft()) from collections import *deque A=[1,2,3,4] print(A) A.append(10) print(A) print(A.popleft()) #3.How to sort a list in descending order without using reverse function a=[1,2,3]
3d2d01b1680a3593d937b20b83db444434066264
Rolemodel01291/HackerRank-Python-Solutions
/python_find_the_runner_up_score.py
1,142
4
4
""" HACKERRANK FIND THE RUNNER UP SCORE URL: https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem TASK: Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given n scores. Store them in a list and find the score of the runner-up. INPUT FORMAT: The first line contains N. The second line contains an array A[] of n integers each separated by a space. SAMPLE INPUT 0: 5 2 3 6 6 5 OUTPUT: 5 """ n = int(input()) """ list(set(map(int, input().split()))) IS BROKEN INTO 3 PARTS 1) map(int, input().split()) (TAKE MULTIPLE INPUTS ON THE SAME LINE) 2) set(map(int, input().split())) (CONVERT INPUT TO SET, CONVERTING TO SET DATATYPE WILL REMOVE DUPLICATES) 3) list(set(map(int, input().split()))) (LAST CONVERT TO LIST) """ arr = list(set(map(int, input().split()))) arr.sort() print(arr[-2]) # PRINTS THE SECOND LARGEST NUMBER
9bdb5c2fe74b8a35849cb7821786fbdea3c50495
Rolemodel01291/HackerRank-Python-Solutions
/python_nested_list.py
1,702
3.9375
4
""" HACKERRANK NESTED LIST URL: https://www.hackerrank.com/challenges/nested-list/problem TASK: Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. Input Format: The first line contains an integer, N, the number of students. The 2N subsequent lines describe each student over 2 lines; the first line contains a student's name, and the second line contains their grade. Sample Input: 5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 Sample Output: Berry Harry """ mainList, subList, secondLowestGradeArray, scoreArray = [], [], [], [] for _ in range(int(input())): name, score = input(), float(input()) subList.append(name) subList.append(score) scoreArray.append(score) mainList.append(subList) subList = [] scoreArray = list(set(scoreArray)) scoreArray.sort() for mainItem in range(len(mainList)): if(mainList[mainItem][1] == scoreArray[1]): secondLowestGradeArray.append(mainList[mainItem][0]) secondLowestGradeArray.sort() for secondLowestGradeStudentName in secondLowestGradeArray: print(secondLowestGradeStudentName)
0bc906ba43c194a9a29110e57f5b23d1c12c6a9a
tharaniramesh/player2
/index_char.py
69
3.609375
4
s=input() d="" for i in range(0,len(s),3): d=d+s[i] print(d)
624970ae073636353570a48f6efbd4df4b7b66e2
Bobowski/TestRepo
/test.py
166
3.625
4
for i in range(10): print(i) print("Hello World!") class someClass_Name: def __init__(sel, a): self.a = a def foo(self): return self.a