blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c0e105e191c7f3bcf76dc9e01115ba8adf74a260
theotarr/primes
/primes.py
1,324
4.25
4
# Lets find the largest prime possible # This program will print out prime numbers, sexy primes, and triple sexy primes def is_prime(prime): for i in range(2, int(prime/2)+1): if prime % i == 0: return False return True # Change this to the largest prime number you know highest_prime = 0 + 1 counter = 0 double_counter = 0 triple_counter = 0 while (True): if is_prime(highest_prime): print("#" + str(counter) + ": " + str(highest_prime)) counter = counter + 1 if is_prime(highest_prime + 6): print("#" + str(double_counter) + ": (" + str(highest_prime) + ", " + str(highest_prime+6) + ")") double_counter = double_counter + 1 if is_prime(highest_prime - 6): if not(is_prime(highest_prime - 5) or is_prime(highest_prime -4) or is_prime(highest_prime -3) or is_prime(highest_prime -2) or is_prime(highest_prime-1)): if not(is_prime(highest_prime + 5) or is_prime(highest_prime +4) or is_prime(highest_prime +3) or is_prime(highest_prime +2) or is_prime(highest_prime +1)): print("#" + str(triple_counter) + ": (" + str(highest_prime-6) + ", " + str(highest_prime) + ", "+str(highest_prime+6)+")") triple_counter = triple_counter + 1 highest_prime = highest_prime + 1
3ee748ba0d1a9b0730bdcfcb5263554bdc954e56
cshweeti77/Backup
/text.py
404
3.609375
4
pcount = 0 ncount = 0 inp = input("Enter a text::") inp = inp.split(" ") data1 = open("pos.txt").read() data1 = data1.split(",") data2 = open("neg.txt").read() data2 = data2.split(",") for count in inp: if count in data1: pcount += 1 if count in data2: ncount += 1 if pcount > ncount: print("Positive sentence") elif ncount > pcount: print("Negative sentence") else: print("Neutral Sentence")
cbdde55117391d6e3ac3d8940f61188e66068ef8
deplanty/mini-games
/Stars/src/objects/star.py
563
3.8125
4
import tkinter as tk class Star: def __init__(self, canvas:tk.Canvas, x:int, y:int, radius:int, mass:int): self.r = radius self.x = x self.y = y self.mass = mass self.iid = None self.canvas = canvas def init(self): """ Initalizes the star and draw it """ self.iid = self.canvas.create_oval( self.x - self.r, self.y - self.r, self.x + self.r, self.y + self.r, fill="yellow" )
4f75dbc407d7582b3d91486c2ceeeaa281169f2b
AlexDingSZ/myse
/homework/0510/6.4zuoye-2_limeng.py
895
3.546875
4
#创建一个config。txt文件,w为权限 f = open("config.txt","w") #文件写入字符串 f.write("username=xiaoming\n") f.write("password=123456\n") f.write("mobile=1581864666\n") f = open("config.txt","r+") content_list = f.readlines() print (content_list) a_dict = {} for eachvalue in content_list: split_list= eachvalue.split("=") print(split_list) if split_list[0]=="password": a_dict[ split_list[0]]="654321" content_list[content_list.index(eachvalue)]="password=654321\n" else: a_dict[split_list[0]]= split_list[1][:-1] print(a_dict) f.seek(0) f.truncate() f.writelines( content_list) f.close() # dict ={} # for line in f.readline(): # a = line.split("=") # if a[0]=="password": # dict[a[0]]=="654321" # a[a.index(line)]="password=654321\n" # else: # dict[a[0]]=a[0][:-1] # print d
881b782f4b7fe3ad9e0b14d2c48b7f9af7de150e
Tech-Interview-YT/Python
/Sorting_Algorithms/Bubble_Sort/BubbleSort.py
833
4
4
def bubble_sort(lst: [int]) -> [int]: """ :param lst: List that is to be sorted :return: List that is sorted """ list_length = len(lst) for i in range(list_length-1): for j in range(list_length-i-1): if lst[j] > lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] return lst def test_bubble_sort(): assert bubble_sort([]) == [] assert bubble_sort([1]) == [1] assert bubble_sort([1, 2, 3, 4]) == [1, 2, 3, 4] assert bubble_sort([4, 3, 2, 1]) == [1, 2, 3, 4] assert bubble_sort([1, 2, 1, 2]) == [1, 1, 2, 2] assert bubble_sort([1, 1, 2, 2, 2]) == [1, 1, 2, 2, 2] assert bubble_sort( [21, 1, 27, 30, 12, 17, 20, 28, 16, 4, 11, 5, 8, 2, 38, 26, 10, 25, 23] ) == [1, 2, 4, 5, 8, 10, 11, 12, 16, 17, 20, 21, 23, 25, 26, 27, 28, 30, 38]
a3abaca0d4c273f0f8c736de5659887366a42212
WBZSX/python-learning
/multiplication sheet.py
112
3.765625
4
for x in range(1,10): for y in range(1,10): a = x * y print ("%d * %d = %d " % (x,y,a)) print('\n')
139f07d2470048a648fae66b17b4dba67d839741
oganesyankarina/GB_Python
/Урок 3 Функции/Задание 2.py
960
3.75
4
# 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: # имя, фамилия, год рождения, город проживания, email, телефон. # Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой. name = input('Введите имя: ') surname = input('Введите фамилию: ') birth_year = input('Введите год рождения: ') city = input('Введите город проживания: ') email = input('Введите email: ') tel = input('Введите телефон: ') def get_user_info(**kwargs): return kwargs print(get_user_info(name=name, surname=surname, birth_year=birth_year, city=city, email=email, tel=tel))
187955c1a17790d6af024567b0d2496f77f37ced
ProgrammerFreshers/ProgrammerFreshers
/file.py
449
3.96875
4
# open file myFile=open('myFile.txt','w+') # get some information print('name:', myFile.name) print('is closed:',myFile.closed) print('opening mode:',myFile.mode) # write to file myFile.write(' i love python') myFile.write(' i am java') myFile.close() # append to file myFile= open('myFile.txt','W') myFile.Write(' i also like php') myFile.close() # read from file myFile=open('myFile.txt','r+') text=myFile.read(12) print(text)
8b155a83cae5b90ea9a300c567648bb83da1bc4e
4c4a4a/python_learning
/python_work/practice/practice_5.py
1,984
4.15625
4
# 5-2 if 'banana' == 'banana': print('yes') if 'banana' == 'apple': print('no') name = 'ToYota' if name.lower() == 'toyota': print('yes') # 5-3 color = 'green' if color == 'green': print("You get 5 scores.") color = 'red' if color == 'green': print("You get 5 scores.") # 5-4 color = 'green' if color == 'green': print("You get 5 scores.") else: print("You get 10 scores.") color = 'red' if color == 'green': print("You get 5 scores.") else: print("You get 10 scores.") # 5-5 if color == 'green': print("You get 5 scores.") elif color == 'yellow': print("You get 10 scores.") else: print("You get 15 scores.") # 5-6 age = 32 if age < 2: print("He is a baby.") elif age < 4: print("He is a child.") elif age < 13: print("He is a kid.") elif age < 20: print("He is a teenager.") elif age < 65: print("He is an adult.") else: print("He is an old man.") # 5-8,5-9 # accounts = [] accounts = ['admin', '4c4a4a', 'gamma', 'new_bee', 'god'] if accounts: for account in accounts: if account == 'admin': print("Hello admin, would you like to see a status report?") else: print(f"Hello {account}, thank you for logging in again.") else: print("We need to find some users!") # 5-10 current_users = ['John', 'jAck', 'Gamma', 'XXX', 'god'] new_users = ['JOHN', 'may', 'horse', 'xXx', 'NONE'] current_users_lower = [] for user in current_users: current_users_lower.append(user.lower()) for new_user in new_users: if new_user.lower() in current_users_lower: print(f"'{new_user}' is used.") else: print(f"'{new_user}' is unused.") # 5-11 numbers = list(range(1, 10)) for number in numbers: if number == 1: print("1st") elif number == 2: print("2nd") elif number == 3: print("3rd") else: print(f"{number}th")
d5d85589308ca0c9ae43f9d1704f97451c21adf6
rodvei/Academy2021
/week3_python/ex3_numb_input/my_throw.py
1,049
3.8125
4
import math GRAVITY = 9.81 print('Calculate Throw length') angle_degree = float(input('Type angle (in degrees): ')) velocity_kmh = float(input('Type velocity (in km/h): ')) throw_hight = float(input('Type throw height (in meter): ')) angle_radians = math.radians(angle_degree) velocity_ms = velocity_kmh/3.6 velocity_ms_x = velocity_ms * math.cos(angle_radians) velocity_ms_y = velocity_ms * math.sin(angle_radians) sqrt_parth = math.sqrt(velocity_ms_y ** 2 + 2 * GRAVITY * throw_hight) airtime = (velocity_ms_y + sqrt_parth)/GRAVITY throw_length = velocity_ms_x * airtime print(round(angle_radians, 2)) print(round(velocity_ms, 2)) print(round(velocity_ms_x, 2)) print(round(velocity_ms_y, 2)) print(round(airtime, 2)) print(round(throw_length, 2)) print(throw_length) # less angles is optimal # set velocity_kmh = 50 and throw_hight = 2 # then, throw_length is: # angle_degree=44.9: # throw_length -> 21.499248422912817 # angle_degree=45: # throw_length -> 21.493474365706778 # angle_degree=45.1: # throw_length -> 21.4874765380616
949114ae8bda1d4b6355555d21bcf001ab2c0e8e
woodenToaster/euler
/p4.py
442
3.828125
4
n1 = 999 n2 = 999 def is_palindrome(n): n_str = str(n) length = len(n_str) odd = length % 2 first_half = n_str[:length // 2] second_half = n_str[length // 2 + odd:] for i, j in zip(first_half, reversed(second_half)): if i != j: return False return True print(max(i * j for i in reversed(range(n1 + 1)) for j in reversed(range(n2 + 1)) if is_palindrome(i * j)))
5d85437883a8f6f23b22a7fe1aba2f4a6ffe1652
Kacyk27/python-unittest-learning
/100+ Exercises course/098.py
389
3.71875
4
import unittest from solution98 import Person class TestPerson(unittest.TestCase): def setUp(self): self.person = Person('John', 'Smith') def test_person_repr_method(self): msg = 'Popraw implementację metody __repr__().' actual = repr(self.person) expected = "Person(fname='John', lname='Smith')" self.assertEqual(actual, expected, msg)
dd7eab6d0b8ffd9a46b32e17936eb5db7e0a1a52
ucefizi/KattisPython
/trik.py
313
3.671875
4
# Problem statement: https://open.kattis.com/problems/trik strg = input() x = 1 for i in strg: if i == "A" and x == 1: x = 2 elif i == "A" and x == 2: x = 1 elif i == "B" and x == 2: x = 3 elif i == "B" and x == 3: x = 2 elif i == "C" and x == 1: x = 3 elif i == "C" and x == 3: x = 1 print(x)
9d73288626e1f6147c013d6ba87ba8a8be262661
sanmaru11/Python_Practice
/input.py
244
3.765625
4
# 사용자 입력을 받음 name = input("이름을 입력하세요: ") print(name) # input 함수는 문자열을 받아옴, 숫자를 받으려면 자료형을 바꿔주어야 함 x = int(input("숫자를 입력하세요: ")) print(x + 5)
d9b3b67c867a445cdd1f15a549e0375905a4c997
rockpz/leetcode-py
/algorithms/totalHammingDistance/totalHammingDistance.py
1,665
3.734375
4
# Source : https://leetcode.com/problems/total-hamming-distance/ # Author : Ping Zhen # Date : 2017-04-17 '''*************************************************************************************** * * The Hamming distance between two integers is the number of positions at which the * corresponding bits are different. * * Now your job is to find the total Hamming distance between all pairs of the given * numbers. * * Example: * Input: 4, 14, 2 * * Output: 6 * * Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just * showing the four bits relevant in this case). So the answer will be: * HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. * * Note: * Elements of the given array are in the range of 0 to 10^9 * Length of the array will not exceed 10^4. ***************************************************************************************''' ''' * Solution 1 - O(N) * * The total Hamming Distance is equal to the sum of all individual Hamming Distances * between every 2 numbers. However, given that this depends on the individual bits of * each number, we can see that we only need to compute the number of 1s and 0s for each * bit position. For example, we look at the least significant bit. Given that we need to * calculate the Hamming Distance for each pair of 2 numbers, we see that the answer is * equal to the number of 1s at this position * the number of 0s(which is the total number * of numbers - the number of 1s), because for each 1 we need to have a 0 to form a pair. * Thus, the solution is the sum of all these distances at every position. '''
ad3db8a7f8283b7c805013995099860312576e5c
quynguyen2303/python_programming_introduction_to_computer_science
/Chapter9/pi.py
1,832
4.125
4
# pi.py # Calculation pi with Monte Carlo ''' Input: The program prompt for and gets the number of game to be simulated. Output: The program prints out the pi calculated by Monte Carlo approach ''' from random import random import time def main(): printIntro() n = getInput() pi = simNThrown(n) printOutput(pi) def printIntro(): print('This program simulates the Monte Carlo experiment'\ ' and calculates pi number with this method.') def getInput(): # Return the n number of games to be simulated n = int(input('How many games to simulate? ')) return n def simNThrown(n): # Simulates the n number of throwing to the dart board. # Calculate the pi number with formula pi = 4(h/n) # which h is the number of time the dart inside the board. h = 0 for i in range(n): board = simOneThrown() if board: h += 1 pi = 4 * (h / n) return pi def simOneThrown(): # Simulates One Throwing Game # Return True if the dart inside the board, otherwise False board = False # Get the coordinates of x and y after threw the dart x, y = throwDart() # Check the dart inside the board if checkDart(x, y): board = True return board def throwDart(): # Simulates the throw active # Return coordinates of x and y x = 2 * random() - 1.0 y = 2 * random() - 1.0 return x, y def checkDart(x, y): # Check the dart is inside the board (0,0), r = 1 # Return True if inside, otherwise False if x**2 + y**2 <= 1: return True else: return False def printOutput(pi): print('The approximate pi number by Monte Carlo is {:.4f}.'.format(pi)) if __name__ == '__main__': startTime = time.time() main() print('{:.4f}'.format(time.time() - startTime))
da476345468412f347137863e401388c0d0ea950
kumarisneha/practice_repo
/techgig/techgig_min_number.py
132
3.5
4
def main(): a=int(raw_input()) b=int(raw_input()) c=int(raw_input()) print min(a,b,c) # Write code here main()
56bbf9d7b3eeab36cf7cfb44be920436229e4fca
talola612/foundations_homework
/10-building_server/DS_Forecast.py
2,488
3.5
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Using APIs/Data Structures # Using the Dark Sky Forecast API at https://developer.forecast.io/, generate a sentence that describes the weather that day. # Right now it is TEMPERATURE degrees out and SUMMARY. Today will be TEMP_FEELING with a high of HIGH_TEMP and a low of LOW_TEMP. RAIN_WARNING. # TEMPERATURE is the current temperature # SUMMARY is what it currently looks like (partly cloudy, etc - it's "summary" in the dictionary). Lowercase, please. # TEMP_FEELING is whether it will be hot, warm, cold, or moderate. You will probably use HIGH_TEMP and your own thoughts and feelings to determine this. # HIGH_TEMP is the high temperature for the day. # LOW_TEMP is the low temperature for the day. # RAIN_WARNING is something like "bring your umbrella!" if it is going to rain at some point during the day. # In[2]: import requests from bs4 import BeautifulSoup import dotenv import datetime # In[3]: from dotenv import load_dotenv load_dotenv() import os API_KEY = os.getenv("DARKSKY_API_KEY") MAIL_API = os.getenv('MAILGUN_API_KEY') # In[4]: response = requests.get(f'https://api.darksky.net/forecast/{API_KEY}/40.7128,-74.0060?units=si') new_york_weather = response.json() # In[5]: new_york_weather.keys() # In[6]: currently = new_york_weather['currently'] today = new_york_weather['daily']['data'][0] TEMPERATURE = currently['temperature'] SUMMARY = currently['summary'].lower() HIGH_TEMP = today['temperatureHigh'] LOW_TEMP = today['temperatureLow'] if HIGH_TEMP > 30: TEMP_FEELING = 'hot' elif HIGH_TEMP > 25: TEMP_FEELING = 'warm' elif HIGH_TEMP > 15: TEMP_FEELING = 'moderate' else: TEMP_FEELING = 'cold' if today['icon'] == 'rain': RAIN_WARNING = 'bring your umbralla' else: RAIN_WARNING = '' text = f'Right now it is {TEMPERATURE} degrees out and {SUMMARY}. Today will be {TEMP_FEELING} with a high of {HIGH_TEMP} and a low of {LOW_TEMP}. {RAIN_WARNING}.' # In[7]: import datetime right_now = datetime.datetime.now() date_string = right_now.strftime("%B %d, %Y") title = f'8AM Weather forecast: {date_string}' # In[8]: response = requests.post( "https://api.mailgun.net/v3/sandboxa3143f679f974eb882f4c0b75d815986.mailgun.org/messages", auth=("api", MAIL_API ), data={"from": "Excited User <mailgun@sandboxa3143f679f974eb882f4c0b75d815986.mailgun.org>", "to": ["taylorlau.yee@hotmail.com", "hl3289@columbia.edu"], "subject": title, "text": text}) response.text # In[ ]:
c87680bdc4dbc24007e0b9ac954063d7a54ee08d
MrCordero/testgithub2
/ejercicio_11.py
643
3.921875
4
#Permita ingresar edades. El programa debe estar pidiendo edades hasta que ingrese la #edad -100. Decir cuántas personas son de la tercera edad (mayor a 50) y cuantas #edades se ingresaron cont_edad = 0 cont_vueltas = 0 cont_mayedad = 0 while(True): edad = int(input("Ingrese edades : ")) if(edad >= 50): cont_mayedad = cont_mayedad + 1 print("Pertenece a la Tercera edad. ") cont_vueltas = cont_vueltas + 1 if(edad == -100): break print("La cantidad de edades ingresadas es de : ", cont_vueltas) print("La cantidad de personas que pertenecen a la Tercera edad es de :", cont_mayedad)
ef7919bcea6fa196d7d856124700943cf1c039af
swatia-code/data_structure_and_algorithm
/trees/diameter_of_binary_tree.py
4,125
4.28125
4
''' PROBLEM STATEMENT ----------------- The diameter of a tree is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes). Input: First line of input contains the number of test cases T. For each test case, there will be only a single line of input which is a string representing the tree as described below: The values in the string are in the order of level order traversal of the tree where, numbers denotes node values, and a character “N” denotes NULL child. For example: For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N Output: For each testcase, in a new line, print the diameter. Your Task: You need to complete the function diameter() that takes node as parameter and returns the diameter. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 1 <= T <= 100 1 <= Number of nodes <= 10000 1 <= Data of a node <= 1000 Example: Input: 2 1 2 3 10 20 30 40 60 Output: 3 4 Explanation: Testcase1: The tree is 1 / \ 2 3 The diameter is of 3 length. Testcase2: The tree is 10 / \ 20 30 / \ 40 60 The diameter is of 4 length. LOGIC ----- The diameter of a tree T is the largest of the following quantities: * the diameter of T’s left subtree * the diameter of T’s right subtree * the longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T) SOURCE ------ geeksforgeeks CODE ---- ''' def diameter_helper(ans, root): #calculating diameter with height approach if root == None: return 0 left_height = diameter_helper(ans, root.left) right_height = diameter_helper(ans, root.right) ans[0] = max(ans[0], 1 + left_height + right_height) return 1 + max(left_height, right_height) def diameter(root): # Code here ans = [-1] res = diameter_helper(ans, root) return(ans[0]) from collections import deque import sys sys.setrecursionlimit(50000) class Node: def __init__(self, val): self.right = None self.data = val self.left = None def buildTree(s): #Corner Case if(len(s)==0 or s[0]=="N"): return None # Creating list of strings from input # string after spliting by space ip=list(map(str,s.split())) # Create the root of the tree root=Node(int(ip[0])) size=0 q=deque() # Push the root to the queue q.append(root) size=size+1 # Starting from the second element i=1 while(size>0 and i<len(ip)): # Get and remove the front of the queue currNode=q[0] q.popleft() size=size-1 # Get the current node's value from the string currVal=ip[i] # If the left child is not null if(currVal!="N"): # Create the left child for the current node currNode.left=Node(int(currVal)) # Push it to the queue q.append(currNode.left) size=size+1 # For the right child i=i+1 if(i>=len(ip)): break currVal=ip[i] # If the right child is not null if(currVal!="N"): # Create the right child for the current node currNode.right=Node(int(currVal)) # Push it to the queue q.append(currNode.right) size=size+1 i=i+1 return root if __name__=="__main__": t=int(input()) for _ in range(0,t): s=input() root=buildTree(s) k=diameter(root) print(k)
1e4280b3241382fa7f9289fd254a6b9742dce181
ZimingGuo/MyNotes01
/MyNotes_01/Step02/4-Concurrent/day02_08/demo_process_attr.py
576
3.546875
4
# author: Ziming Guo # time: 2020/3/29 ''' demo Process 的几个属性 ''' from multiprocessing import Process import time def tm(): for i in range(3): time.sleep(2) print(time.time()) p = Process(target=tm, name='Haha') p.daemon = True # 再有的程序里面,希望主进程结束之后,其他进程也随之结束,这时就会用到 daemon p.start() print("Name:", p.name) # 打印进程名称,也可以重新赋值 print("PID:", p.pid) # 对应子进程的PID print("is alive:", p.is_alive()) # 判断p的进程是否在生命周期
6a0593df65dc0e898c2ced7ba55b39015c51588d
Zahidsqldba07/competitive-programming-1
/Leetcode/Problems/p17.py
973
4.09375
4
# 17. Letter Combinations of a Phone Number ''' Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. ''' class Solution: mapping = {"2": ['a', 'b', 'c'], "3": ['d', 'e', 'f'], "4": ['g', 'h', 'i'], "5": ['j', 'k', 'l'], "6": [ 'm', 'n', 'o'], "7": ['p', 'q', 'r', 's'], "8": ['t', 'u', 'v'], "9": ['w', 'x', 'y', 'z']} def letterCombinations(self, digits: str) -> List[str]: return [i for i in self.yieldCombos(digits)] def yieldCombos(self, digits): if not digits: return elif len(digits) == 1: yield from Solution.mapping[digits[0]] else: for option in Solution.mapping[digits[0]]: for rest in self.yieldCombos(digits[1:]): yield option + rest
550956a875611f3eda9993ca8333bae3bfc702af
darkeclipz/project-euler
/Eulerlib/digit_fifth_powers.py
264
3.625
4
import eulerlib def digit_powers(n): numbers = [i for i in range(2, 9**n*n + 1) if sum(map(lambda x: x**n, eulerlib.digits(i))) == i] print('Numbers found: {}'.format(numbers)) return sum(numbers) eulerlib.time_it(digit_powers, [5])
a5a06f4c29c6ac46777806a667b62eeb7617883d
JohannSaratka/AdventOfCode
/AoC_2015/Day12/solution.py
3,167
4
4
''' --- Day 12: JSAbacusFramework.io --- Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting software uses a peculiar storage format. That's where you come in. They have a JSON document which contains a variety of things: arrays ([1,2,3]), objects ({"a":1, "b":2}), numbers, and strings. Your first job is to simply find all of the numbers throughout the document and add them together. For example: [1,2,3] and {"a":2,"b":4} both have a sum of 6. [[[3]]] and {"a":{"b":4},"c":-1} both have a sum of 3. {"a":[-1,1]} and [-1,{"a":1}] both have a sum of 0. [] and {} both have a sum of 0. You will not encounter any strings containing numbers. What is the sum of all numbers in the document? --- Part Two --- Uh oh - the Accounting-Elves have realized that they double-counted everything red. Ignore any object (and all of its children) which has any property with the value "red". Do this only for objects ({...}), not arrays ([...]). [1,2,3] still has a sum of 6. [1,{"c":"red","b":2},3] now has a sum of 4, because the middle object is ignored. {"d":"red","e":[1,2,3,4],"f":5} now has a sum of 0, because the entire structure is ignored. [1,"red",5] has a sum of 6, because "red" in an array has no effect. ''' import unittest import json class Test(unittest.TestCase): def test_sum_of_all_numbers(self): self.assertEqual(solve('[1,2,3]'), 6) self.assertEqual(solve('{"a":2,"b":4}'), 6) self.assertEqual(solve('[[[3]]]'), 3) self.assertEqual(solve('{"a":{"b":4},"c":-1}'), 3) self.assertEqual(solve('15'), 15) self.assertEqual(solve('{"a":[-1,1]}'), 0) self.assertEqual(solve('[-1,{"a":1}]'), 0) self.assertEqual(solve('[]{}'), 0) def test_ignore_red_property(self): self.assertEqual(solve_part_two('[1,2,3]'), 6) self.assertEqual(solve_part_two('[1,{"c":"red","b":2},3]'), 4) self.assertEqual(solve_part_two('{"d":"red","e":[1,2,3,4],"f":5}'), 0) self.assertEqual(solve_part_two('[1,"red",5]'), 6) def solve(document): chars = '{}[],":' for c in chars: document = document.replace(c, ' ') numbers = [int(s) for s in document.split() if not s.isalpha()] return sum(numbers) def get_sum(json_obj): if isinstance(json_obj, int): return json_obj elif isinstance(json_obj, str): return 0 elif isinstance(json_obj, list): total = 0 for element in json_obj: total += get_sum(element) return total elif isinstance(json_obj, dict): total = 0 for value in json_obj.values(): if value == "red": return 0 else: total += get_sum(value) return total def solve_part_two(document): test = json.loads(document) return get_sum(test) if __name__ == "__main__": with open("input.txt", 'r') as inFile: puzzle_input = inFile.read().splitlines()[0] print(f"Solution Part 1: {solve(puzzle_input)}") print(f"Solution Part 2: {solve_part_two(puzzle_input)}")
dbc86eac15d954cece1893cac126012806fab678
unassuminglily/Build-10-Real-World-Apps-in-Python
/TheBasics/Sec4_OperationswDataTypes/basics.py
3,741
4.15625
4
# List operations # codng exercise 1 Append Item to list seconds = [1.2323442655, 1.4534345567, 1.023458894] current = 1.10001399445 seconds.append(current) print(seconds) # Coding Exercise 2 remove item from list seconds = [1.2323442655, 1.4534345567, 1.023458894, 1.10001399445] seconds.remove(seconds[1]) print(seconds) # fix this with a loop. Exercise 3-- remove three items second = [1.2323442655, 1.4534345567, 1.023458894, 1.10001399445] second.remove(second[1]) second.remove(second[1]) second.remove(second[1]) print(second) #Coding exercise 4 -- Access Item, complete the script so that it prints out the 3rd item of the list serials serials = ["RH80810A", "AA899819A", "XYSA9099400", "OOP8988459", "EEO8904882", "KOC9889482"] print(serials[2]) #Coding exercise 5, complete the script so that it prints out the 1st, 3rd and 6th items of the luts serials = ["RH80810A", "AA899819A", "XYSA9099400", "OOP8988459", "EEO8904882", "KOC9889482"] print(serials[0], serials[2], serials[5]) #Coding exercise 6, access and append. Append the first item of weekend to workdays workdays = ["Mon", "Tue", "Wed", "Thu", "Fri"] weekend = ["Sat", "Sun"] workdays.append(weekend[0]) #Accessing List Slices monday_temperature = [9.1,8.8, 7.5] monday_temperature[1:3] #the upper limit is never included in a python slice mon_temps = ['hello', 1, 2, 3] mystring = 'hello' mystring[1] mystring[3] mystring[-3] #Coding exercise 7; Slicing a list, 2nd to 4th letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print(letters[1:4]) #Coding exercise 8: Slicing a list, first three letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print(letters[:3]) #Coding exercise 9: Slicing a list, last 3 letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print(letters[-3:]) #Coding Exercise 10: #DICTIONARIES """ A dictionary is made of pairs of keys and values. For example, the first pair is "google": 1000000000 where "google" is the key and 1000000000 is the value of that key. """ #Accessing items in dictionaries student_grades = {"Mary": 9.1, "Sim": 8.8, "lily": 10.0, "John": 7.5} student_grades("lily") #"Converting b/n datatypes" """ From tuple to list: >>> data = (1, 2, 3) >>> list(data) [1, 2, 3] From list to tuple: >>> data = [1, 2, 3] >>> tuple(data) (1, 2, 3) From list to dictionary: >>> data = [["name", "John"], ["surname", "smith"]] >>> dict(data) {'name': 'John', 'surname': 'smith'} Note that the original data type needs to have the data structured in a way that can be understood by the new data type. """ #CHEATSHEET Operations w Data """ In this section, you learned that: Lists, strings, and tuples have a positive index system: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] 0 1 2 3 4 5 6 And a negative index system: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] -7 -6 -5 -4 -3 -2 -1 In a list, the 2nd, 3rd, and 4th items can be accessed with: days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] days[1:4] Output: ['Tue', 'Wed', 'Thu'] First three items of a list: days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] days[:3] Output:['Mon', 'Tue', 'Wed'] Last three items of a list: days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] days[-3:] Output: ['Fri', 'Sat', 'Sun'] Everything but the last: days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] days[:-1] Output: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] Everything but the last two: days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] days[:-2] Output: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] A single in a dictionary can be accessed using its key: phone_numbers = {"John Smith":"+37682929928","Marry Simpsons":"+423998200919"} phone_numbers["Marry Simpsons"] Output: '+423998200919' """
c18a810eade1f3061c7a1787459bea4b3caae647
jarombra/codecademy_Python
/lessonSeries/12_listsAndFunctions/18_usingAListOfListsInAFunction.py
551
4.0625
4
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]] def flatten(lists): results = [] for numbers in lists: results += numbers return results print flatten(n) # Or this method works too: def flatten(lists): results = [] for lst in lists: for num in range(len(lst)): results.append(lst[num]) return results print flatten(n) # Or this method works too: def flatten(lists): results = [] for numbers in lists: for i in numbers: results.append(i) return results print flatten(n)
8f685fc25f3eb757018a24c22e8d44704c1a6b62
gossamr/lifx_circ
/convert.py
1,489
3.765625
4
# -*- coding: utf-8 -*- #!/usr/bin/env python """ @author: Noah Norman n@hardwork.party """ import datetime from math import floor def secs_to_day_frac(secs): """ accepts seconds and returns TOD as fraction """ if secs: return float(secs) / 86400 else: return 0 def day_frac_to_secs(day_frac): """ accepts TOD as fraction and returns seconds """ return float(day_frac) * 86400 def datetime_to_day_frac(dt): hrs = dt.time().hour mins = dt.time().minute secs = dt.time().second return secs_to_day_frac((hrs * 60 * 60) + (mins * 60) + secs) def secs_to_hr_min_sec(secs): """ accepts seconds and returns (h,m,s) tuple """ if secs: hrs = int(floor(secs / 60 / 60)) mins = int(floor(secs / 60 % 60)) secs = int(floor(secs % 60)) return (hrs, mins, secs) else: return (0, 0, 0) def secs_into_day(): """ returns the number of seconds since midnight """ now = datetime.datetime.now().time() return ((now.hour * 60 * 60) + (now.minute * 60) + now.second) def time_from_day_frac(day_frac): """ accepts TOD as fraction and returns time string as h:m:s """ secs = day_frac_to_secs(day_frac) c_hr, c_min, c_sec = secs_to_hr_min_sec(secs) fmt_str = '{}:{}:{}'.format(c_hr, c_min, c_sec) return fmt_str def interp(start, end, frac): return frac * (end - start) + start def current_time(): ct = secs_to_day_frac(secs_into_day()) return ct
7c10deae923fbe01b2b8c578f12b6e809f72f1cd
ArunPrasad017/python-play
/coding-exercise/Day21-shortestDistance.py
414
4
4
def shortestDistance(words, word1, word2): res = {} i = 0 dist = len(words) for i, c in enumerate(words): if c == word1 or c == word2: res[c] = i if word1 in res.keys() and word2 in res.keys(): dist = min(dist, abs(res[word1] - res[word2])) return dist words = ["a", "c", "b", "a"] word1 = "b" word2 = "a" print(shortestDistance(words, word1, word2))
ab80b805c1637b949b18be41d6801fc5608c3b92
soucevi1/ecdlp-babystep-giantstep
/elliptic_curve.py
6,787
3.96875
4
# Module for elliptic curve operations. # Author: Vit Soucek from math import inf, sqrt from finite_field import FiniteFieldElement class EllipticCurve: """ Class representing an elliptic curve in the simplified form. Inspired by: https://github.com/j2kun/elliptic-curves-finite-fields """ def __init__(self, a, b, ff): """ Elliptic curve in the simplified form. y^2 = x^3 + ax + b :param a: Coefficient a :param b: Coefficient b :param ff: FiniteField of the curve """ if isinstance(a, int): a = ff.get_element(a) if isinstance(b, int): b = ff.get_element(b) self.a = a self.b = b self.finite_field = ff if 4 * a ** 3 + 27 * b ** 2 == 0: raise ValueError('Bad curve: 4a^3 + 27b^2 mustn\'t be 0') def is_point(self, x, y): """ Test whether the point [x,y] belongs to the curve. :param x: X coordinate :param y: Y coordinate :return: bool """ if isinstance(x, int): x = self.finite_field.get_element(x) if isinstance(y, int): y = self.finite_field.get_element(y) return y ** 2 == x ** 3 + self.a * x + self.b def __str__(self): return f'y^2 = x^3 + {self.a}x + {self.b}' def __eq__(self, other): """ Overloaded == operator :param other: Other elliptic curve :return: Bool """ return (self.a, self.b) == (other.a, other.b) def order_approx(self): """ Approximation according to Hasse theorem. :return: Upper bound of the order. """ return self.finite_field.modulo + 1 + 2 * sqrt(self.finite_field.modulo) class ECPoint: """ Class representing a point on an elliptic curve """ def __init__(self, x, y, curve): self.curve = curve self.x = FiniteFieldElement(x, self.curve.finite_field.modulo) self.y = FiniteFieldElement(y, self.curve.finite_field.modulo) if not curve.is_point(x, y): raise ValueError(f'The point {self} is not on the curve {curve}!') def __str__(self): return f'[{self.x}, {self.y}]' def __neg__(self): """ Negation of the point. -P = (x,-y) :return: ECPoint """ return ECPoint(self.x, - self.y, self.curve) def __add__(self, other): """ Add operation of two EC points as defined in the handouts. :param other: Other EC point :return: ECPoint """ if self.curve != other.curve: raise ValueError('Cannot add points on different curves!') # P + 0 = P if isinstance(other, ECPointAtInfinity): return self # 0 + P = P if isinstance(self, ECPointAtInfinity): return other # x1 = x2 AND y1 = -y2 => P + Q = 0 if (self.x, self.y) == (other.x, -other.y): return ECPointAtInfinity(self.curve) # P = Q if (self.x, self.y) == (other.x, other.y): try: lam = (3 * (self.x ** 2) + self.curve.a) / (2 * self.y) except ZeroDivisionError: return ECPointAtInfinity(self.curve) # P != Q else: try: lam = (other.y - self.y) / (other.x - self.x) # x1 == x2 except ZeroDivisionError: return ECPointAtInfinity(self.curve) r1 = lam ** 2 - self.x - other.x r2 = lam * (self.x - r1) - self.y return ECPoint(r1, r2, self.curve) def __sub__(self, other): """ Difference of two EC points. :param other: Other EC point :return: ECPoint """ return self + (-other) def __mul__(self, n): """ Calculate A = n*B using double-and-add algorithm. :param n: Factor of multiplication :return: ECPoint """ if not isinstance(n, int): raise TypeError(f'Cannot multiply an ECPoint by {type(n)}!') else: if n < 0: return -self * -n if n == 0: return ECPointAtInfinity(self.curve) point_q = self point_r = self if n & 1 == 1 else ECPointAtInfinity(self.curve) i = 2 while i <= n: # double point_q = point_q + point_q if n & i == i: # add point_r = point_q + point_r i = i << 1 return point_r def __rmul__(self, n): """ Multiplication with point as the value on the right. :param n: Factor :return: ECPoint """ return self * n def __eq__(self, other): """ Overloaded == operator :param other: Other ECPoint :return: True if self == other, False otherwise """ return (self.x, self.y, self.curve) == (other.x, other.y, other.curve) def order_approx(self): """ The upper bound of the EC point order is the order of the EC itself. :return: Approx. of the order of the EC """ return self.curve.order_approx() def __lt__(self, other): """ Overloaded less-than operator for sorting purposes. :param other: Other ECPoint :return: Bool """ if self.x < other.x: return True if self.x > other.x: return False return self.y < other.y class ECPointAtInfinity(ECPoint): """ Special case of "zero" point on the elliptic curve. """ def __init__(self, curve): self.x = inf self.y = inf self.curve = curve def __neg__(self): """ Negated PaI is PaI :return: ECPointAtInfinity """ return self def __str__(self): return 'Point at infinity' def __add__(self, Q): """ PaI + Q = Q :param Q: Other point :return: Point Q """ if self.curve != Q.curve: raise ValueError('Can\'t add points on different curves!') return Q def __mul__(self, n): """ Multiplied PaI is PaI :param n: Multiplication factor :return: ECPointAtInfinity """ if not isinstance(n, int): raise TypeError(f'Cannot multiply a point by {type(n)}!') return self def __eq__(self, other): """ Test whether other point is also PaI :param other: Other point :return: bool """ return type(other) is ECPointAtInfinity
460ceebe6fa4a3c4c4ef1fa2cd69a010f4809678
dmcphers/python
/pycharm_unit_tests/test_numeric_functions_unittest.py
4,078
3.59375
4
import unittest import math import random # Class to handle numeric functions class NumericFunctions: ceil_fun = None abs_fun = None floor_fun = None max_fun = None min_fun = None pow_fun = None round_fun = None sqrt_fun = None randrange_fun = None random_fun = None to_int = None to_float = None bitlength_fun = None type_fun = None x = None y = None z = None def __init__(self): pass # Ceil function def ceilfun(self, x): self.x = x self.ceil_fun = math.ceil(x) return self.ceil_fun # Abs function def absfun(self, x): self.x = x self.abs_fun = abs(x) return self.abs_fun # Floor function def floorfun(self, x): self.x = x self.floor_fun = math.floor(x) return self.floor_fun # Max function def maxfun(self, x, y, z): self.x = x self.y = y self.z = z self.max_fun = max(x, y, z) return self.max_fun # Min function def minfun(self, x, y, z): self.x = x self.y = y self.z = z self.min_fun = min(x, y, z) return self.min_fun # Pow function def powfun(self, x, y): self.x = x self.y = y self.pow_fun = pow(x, y) return self.pow_fun # Round function def roundfun(self, x, y): self.x = x self.y = y self.round_fun = round(x, y) return self.round_fun # Square root function def sqrtfun(self, x): self.x = x self.sqrt_fun = math.sqrt(x) return self.sqrt_fun # Random range function # def randrangefun(self, x, y, z): # self.x = x # self.y = y # self.z = z # self.randrange_fun = random.randrange(x, y, z) # return self.randrange_fun # Random function # def randomfun(self): # self.random_fun = random.random() # return self.random_fun # int() function for coercing to type int def intfun(self, x): self.to_int = int(x) return self.to_int # float() function for coercing to type float def floatfun(self, x): self.to_float = float(x) return self.to_float # bit_length() function for finding number of bits required to represent an integer def bitlengthfun(self, x): self.x = x self.bitlength_fun = x.bit_length() return self.bitlength_fun # type() function for displaying type of object # def typefun(self, x, y): # self.x = x # self.type_fun = isinstance(x, y) # return self.type_fun class TestNumericFunctions(unittest.TestCase): def setUp(self): self.numfun = NumericFunctions() def test_ceil_neg(self): self.assertEqual(self.numfun.ceilfun(-34.23), -34) def test_abs_neg(self): self.assertEqual(self.numfun.absfun(-34), 34) def test_floor_neg(self): self.assertEqual(self.numfun.floorfun(-34.23), -35) def test_max_neg(self): self.assertEqual(self.numfun.maxfun(-34, -24, -14), -14) def test_min_neg(self): self.assertEqual(self.numfun.minfun(-34, -24, -14), -34) def test_pow_neg(self): self.assertEqual(self.numfun.powfun(-3, 2), 9) def test_round_neg(self): self.assertEqual(self.numfun.roundfun(-3.445, 2), -3.44) def test_sqrt(self): self.assertEqual(self.numfun.sqrtfun(25), 5) # def test_randrange(self): # print(self.numfun.randrangefun(0, 100, 1)) # # def test_random(self): # print(self.numfun.randomfun()) def test_intfun(self): self.assertEqual(self.numfun.intfun(23.8), 23) def test_floatfun(self): self.assertEqual(self.numfun.floatfun(23), 23.0) def test_bitlengthfun(self): self.assertEqual(self.numfun.bitlengthfun(7), 3) # def test_type(self): # string = 'hello' # self.assertIsInstance(self.numfun.typefun(string, str)) if __name__ == '__main__': unittest.main()
24d8a98c49a03eccfd117a180a9f5386ab47b43a
FatmaElZahraaSamir/Project
/earn.py
864
3.578125
4
EMPTY, BLACK, WHITE, OUTER = '.', 'B', 'W', "@" def squares(): return [i for i in xrange(11, 89) if 1 <= (i % 10) <= 8] def NEW_board(): board = [OUTER] * 100 for i in squares(): board[i] = EMPTY #The middle four squares board[44], board[45] = WHITE, BLACK board[54], board[55] = BLACK, WHITE return board # def printf_board(board): # for row in xrange(0,100 ): # # if (row % 10 == 0) : # # print '\n' # print ( '%s ' % board[row]) def Board(board): rep = '' rep += ' %s\n' % ' '.join([OUTER]*8) for row in xrange(1, 9): begin, end = 10*row + 1, 10*row + 9 rep += '%s %s %s \n' % (OUTER, ' '.join(board[begin:end] ),OUTER) if (row == 8 ) : rep += ' %s\n' % ' '.join([OUTER] * 8) return rep print (Board(NEW_board()))
5e90f7be871b60dfd4d88f47609968ce24a01108
OlegZhdanoff/algorithm
/lesson_4/task_1.py
4,283
3.90625
4
# 1. Проанализировать скорость и сложность одного любого алгоритма из разработанных в рамках домашнего задания первых # трех уроков. # Для анализа было взято задание 3.1 - Определить, какое число в массиве встречается чаще всего. import random import timeit import cProfile import functools SIZE = 1_000 MIN_ITEM = 0 MAX_ITEM = 10 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] # print(array) # первый вариант def max_cnt_double_cycle(array): max_ = 0 max_idx = 0 for i, num in enumerate(array): cur = 0 for el in array: if num == el: cur += 1 if cur > max_: max_ = cur max_idx = i # print(array[max_idx]) # второй вариант def max_cnt_cycle(array): num_dict = dict() max_cnt = 0 max_ = None for num in array: if num in num_dict: num_dict[num] += 1 else: num_dict[num] = 1 if num_dict[num] > max_cnt: max_cnt = num_dict[num] max_ = num # print(max_, max_cnt) # третий вариант def max_cnt(array): num_dict = dict() for num in array: if num not in num_dict: num_dict[num] = array.count(num) final_dict = dict([max(num_dict.items(), key=lambda k_v: k_v[1])]) # print(final_dict) print(timeit.timeit('max_cnt_double_cycle(array)', globals=globals(), number=100)) # 0.042807152 -- > SIZE = 100 MAX_ITEM = 10 # 3.69860931 -- > SIZE = 1_000 MAX_ITEM = 10 # 345.360979906 -- > SIZE = 10_000 MAX_ITEM = 10 print(timeit.timeit('max_cnt_cycle(array)', globals=globals(), number=1000)) # 0.184185388 -- > SIZE = 1_000 MAX_ITEM = 10 # 0.179933717 -- > SIZE = 1_000 MAX_ITEM = 100 # 1.922109166 -- > SIZE = 10_000 MAX_ITEM = 10 # 19.30097967 -- > SIZE = 100_000 MAX_ITEM = 10 print(timeit.timeit('max_cnt(array)', globals=globals(), number=1000)) # 0.25346568999999997 -- > SIZE = 1_000 MAX_ITEM = 10 # 1.662260649 -- > SIZE = 1_000 MAX_ITEM = 100 # 2.0468984349999997 -- > SIZE = 10_000 MAX_ITEM = 10 # 21.641872013 -- > SIZE = 100_000 MAX_ITEM = 10 cProfile.run('max_cnt_double_cycle(array)') # 1 89.548 89.548 89.548 89.548 task_1.py:16(max_cnt_double_cycle) -- > SIZE = 50_000 MAX_ITEM = 10 cProfile.run('max_cnt_cycle(array)') # 1 0.009 0.009 0.009 0.009 task_1.py:31(max_cnt_cycle) -- > SIZE = 50_000 MAX_ITEM = 10 # 1 1.818 1.818 1.818 1.818 task_1.py:31(max_cnt_cycle) -- > SIZE = 10_000_000 MAX_ITEM = 10 # 1 0.245 0.245 0.245 0.245 task_1.py:31(max_cnt_cycle) -- > -- > SIZE = 1_000_000 MAX_ITEM = 1000 cProfile.run('max_cnt(array)') # 1 0.002 0.002 0.010 0.010 task_1.py:47(max_cnt) -- > -- > SIZE = 50_000 MAX_ITEM = 10 # 1 0.340 0.340 2.024 2.024 task_1.py:47(max_cnt) -- > SIZE = 10_000_000 MAX_ITEM = 10 # 1 0.056 0.056 16.254 16.254 task_1.py:47(max_cnt) -- > SIZE = 1_000_000 MAX_ITEM = 1000 # Первый вариант max_cnt_double_cycle очень медленный из-за вложенного цикла и имеет квадратичную сложность О(n**2) # Второй вариант max_cnt_cycle самый оптимальный, т.к. за один проход массива решает поставленную задачу. # Третий вариант max_cnt использует встроенные функции и сильно зависит от количества разных цифр (MAX_ITEM) в массиве, # при низких значениях MAX_ITEM (например 10) скорость совсем немного ниже чем у второго варианта, хотя в третьем # используется встроенная функция count, которая перебирает все элементы массива, но за счет того, что встроенные # функции написаны на С и скомпилированы, они выполняются довольно таки быстро.
55653844d8a498ace9f7b4ceaa18cab1efef6f7b
anitrajpurohit28/PythonPractice
/python_practice/List_programs/14_second_largerst_number.py
1,005
4.03125
4
# 14 Python program to find second largest number in a list import random list1 = random.sample(range(1, 300), 11) print(list1) # by sorting temp_list = sorted(list1) first_max = temp_list[-1] sec_max = temp_list[-2] print(f"First Largest: {first_max}\tSecond Largest: {sec_max}") # By manually calculating first_max = list1[0] sec_max = list1[1] if sec_max > first_max: first_max, sec_max = sec_max, first_max for i in range(2, len(list1)): if list1[i] > first_max: sec_max = first_max first_max = list1[i] elif list1[i] > sec_max and list1[i] != first_max: sec_max = list1[i] else: pass # case where first and second are both same numbers # if sec_max == first_max: # sec_max = list1[i] print(f"First Largest: {first_max}\tSecond Largest: {sec_max}") # by removing max element first_max = max(list1) temp_list = list1.remove(max(list1)) sec_max = max(list1) print(f"First Largest: {first_max}\tSecond Largest: {sec_max}")
dcabca33b869888c3e0ceaac807cef760c403562
vohrakunal/python-problems
/level1prob10.py
612
4.25
4
#Read a given string, change the character at a given index and then print the modified string. # #Input Format #The first line contains a string, #Output Format #Using any of the methods explained above, replace the character at index with character . # #Sample Input # #abracadabra #5 k #Sample Output # #abrackdabra # #### Solution #### def mutate_string(string, position, character): strlist = list(string) strlist[position] = character return("".join(strlist)) if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate_string(s, int(i), c) print(s_new)
61f55f4cfbf9989792f8030f7822ff8e02c546b7
BotsByNikki/ME-599-Solid-Modeling-Homeworks
/HW1/599Q2.py
3,535
4.15625
4
#!/usr/bin/env python #Nicole Guymer and Niklas Delboi #ME 599: Solid Modeling #Homework 1 #1/21/2019 """Question 2: Write a function that takes four points of a tetrahedron as input (4 3-element arrays), and shows the resulting solid. Also, print out the surface area and volume of the tetrahedron.""" #Online calculator for volume, vert, and edge functions: # http://tamivox.org/redbear/tetra_calc/index.html #Area of triangles: # https://www.mathsisfun.com/geometry/herons-formula.html %matplotlib inline import numpy as np from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import matplotlib.pyplot as plt def vert (p1, p2): """This function finds the edges between the given points. I initial called it "verticies" originally, but I'm too lazy to change it """ vx = p2[0]-p1[0] vy = p2[1]-p1[1] vz = p2[2]-p1[2] return [vx, vy, vz] def Tetra(p1, p2, p3, p4): """This function takes four 3D points of a tetrahedron to calculate the volume and surface area, and plots the shape in 3D. """ #Solve for the surface area. #This is done by finding the area of each triangular face of the tetrahedron, # and adding them together. #Area of triangle 1 d = vert(p2,p4) mag = np.sqrt(d[0]**2+d[1]**2+d[2]**2) d_norm = [d[0]/mag, d[1]/mag, d[2]/mag] sub = np.subtract(p1,p2) q = np.add(p2,np.multiply(np.dot(sub,d_norm),d_norm)) h = np.linalg.norm(q-p1) g = np.linalg.norm(d) tri1 = g*h/2 #Area of triangle 2 d = vert(p1,p2) mag = np.sqrt(d[0]**2+d[1]**2+d[2]**2) d_norm = [d[0]/mag, d[1]/mag, d[2]/mag] sub = np.subtract(p3,p1) q = np.add(p1,np.multiply(np.dot(sub,d_norm),d_norm)) h = np.linalg.norm(q-p3) g = np.linalg.norm(d) tri2 = g*h/2 #Area of triangle 3 d = vert(p2,p4) mag = np.sqrt(d[0]**2+d[1]**2+d[2]**2) d_norm = [d[0]/mag, d[1]/mag, d[2]/mag] sub = np.subtract(p3,p2) q = np.add(p2,np.multiply(np.dot(sub,d_norm),d_norm)) h = np.linalg.norm(q-p3) g = np.linalg.norm(d) tri3 = g*h/2 #Area of triangle 4 d = vert(p3,p4) mag = np.sqrt(d[0]**2+d[1]**2+d[2]**2) d_norm = [d[0]/mag, d[1]/mag, d[2]/mag] sub = np.subtract(p1,p3) q = np.add(p3,np.multiply(np.dot(sub,d_norm),d_norm)) h = np.linalg.norm(q-p1) g = np.linalg.norm(d) tri4 = g*h/2 #Find surface area by summing all the 4 above triangle areas SA = tri1+tri2+tri3+tri4 #Volume V = np.abs(np.dot(vert(p1,p2),np.cross(vert(p1,p3),vert(p1,p4))))/6 #Plot the tetrahedon : https://stackoverflow.com/questions/44881885/python-draw-3d-cube fig = plt.figure() ax = fig.add_subplot(111, projection = '3d') #plot points points = np.array([p1,p2,p3,p4]) #plot vertices ax.scatter3D(points[:,0], points[:,1], points[:,2], color = 'k') verts = [[points[0], points[1], points[3]], [points[0], points[1], points[2]], [points[0], points[2], points[3]], [points[1], points[2], points[3]]] ax.add_collection3d(Poly3DCollection(verts, facecolors='w', linewidths=1, edgecolors='k', alpha = .1)) #Label the plot plt.title('Tetrahedron Plot') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show() return ("Volume of Tetrahedron = %s" % V, "Surface Area of Tetrahedron = %s" % SA) if __name__ == '__main__': #Replace the values for x1, x2, x3, x4 below with the desired test cases x1 = [0.0 ,0.0 ,-2.0] x2 = [5.0 ,0. ,0. ] x3 = [0. ,5. ,0. ] x4 = [2. ,2. ,4. ] print (Tetra(x1,x2,x3,x4))
aad3994e0fcab4a700519b51ef677ea358859515
wnsgur1198/python_practice
/ex37.py
443
3.59375
4
# 지정된 위젯을 클릭했을 때 함수 호출 from tkinter import * from tkinter import messagebox def clickImage(event): messagebox.showinfo('마우스','토끼에서 마우스가 클릭됨') window=Tk() window.geometry('400x400') photo=PhotoImage(file='C:/kjh-dev/kjh-python/파이썬 수업/rabbit.gif') pLabel=Label(window,image=photo) pLabel.bind('<Button>',clickImage) pLabel.pack(expand=1,anchor=CENTER) window.mainloop()
1d088f3f89e9b2ba98dfae11f1d91b4e20953a83
brighamandersen/cs180
/Python Labs/lab2_word_counts.py
807
3.875
4
import argparse import json import string def main(input_str): # Make entire string lowercase input_str = input_str.lower() # Remove punctuation (besides spaces) from string translator = str.maketrans("","",string.punctuation) input_str = input_str.translate(translator) # Make list of strings separated by space words = input_str.split(" ") # Create & populate dictionary with words and counts output_dict = {} for word in words: output_dict[word] = words.count(word) with open("lab2_word-counts.json", "w") as f: f.write(json.dumps(output_dict)) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-str", "--string", type=str, help="Provide an input string", required=True) args = parser.parse_args() main(args.string)
4db86742f11f8366161e2349ce155986b5d1bd04
OctopusHugz/holbertonschool-interview
/0x22-primegame/0-prime_game.py
253
3.640625
4
#!/usr/bin/python3 """ This module implements the isWinner function """ def isWinner(x, nums): """ Returns the winner of the Prime Game """ if x == 0 or x == -1: return None elif x == 10000: return "Maria" return "Ben"
9cf814066efb5f942fa7bdc119ae59a32861f01a
bazhenov4job/Algorithms_and_structures
/Task_6.py
2,511
4.21875
4
""""6. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним.""" a = float(input("Введите длину отрезка a: ")) b = float(input("Введите длину отрезка b: ")) c = float(input("Введите длину отрезка c: ")) if a > b: if a > c: if b + c > a: print("Треугольник может существовать...") if b == c: print("Треугольник равнобедренный...") else: print("Треугольник разносторонний...") else: print("Треугольник не может существовать...") else: if a + b > c: print("Треугольник может существовать...") if a == b or a == c : print("Треугольник равнобедренный...") else: print("Треугольник разносторонний...") else: print("Треугольник не может существовать...") else: if b > c: if a + c > b: print("Треугольник может существовать...") if a == c or a == b: print("Треугольник равнобедренный...") else: print("Треугольник разносторонний...") else: print("Треугольник не может существовать...") else: if a + b > c: print("Треугольник может существовать...") if a == b: print("Треугольник равнобедренный...") if a == b and a == c: print("Треугольник равносторонний...") else: print("Треугольник разносторонний...") else: print("Треугольник не может существовать...")
ea2561e19d47c7c90d5c335e90972b312586a6fc
chb2mn/InquestTests
/style/hashbang.py
448
3.59375
4
import sys def hashbang(start, end): for i in xrange(start, end): #newline is added for some prettiness newline = False if i % 3 == 0: print "hash", newline = True if i % 5 == 0: print "bang", newline = True if newline: print "" if __name__ == '__main__': first = int(sys.argv[1]) last = int(sys.argv[2]) hashbang(first, last)
956303cc74a2bd1d1533c4521848eddcc686a4b0
Spider251/python
/pbase/day15/code/price03.py
616
4
4
# price03.py # 练习: # 1. 写一个生成器函数,给出开始值begin,和终止值end,此生成器函数生成begin~end 范围内的全部素数(不包含end) # 如: # def prime(begin, end): # ... # L = list(prime(10, 20)) # print(L) #[11, 13, 17, 19] def prime(begin, end): for i in range(begin, end): isprime = True if begin < 2: isprime = False else: for j in range(2, i): if i % j ==0: isprime = False if isprime: yield i L = list(prime(2, 50)) print(L)
04a27f6ee0e7d0763290de5c0a6b027503ba9ef9
upjohnc/gilded-rose-kata
/python/gilded_rose.py
3,476
3.6875
4
from typing import List class Item: def __init__(self, name, sell_in, quality): self.name = name self.sell_in = sell_in self.quality = quality def __repr__(self): return "%s, %s, %s" % (self.name, self.sell_in, self.quality) class GildedRose: def __init__(self, items: List[Item]): self.items = items @staticmethod def aged_brie_quality(item_: Item) -> None: """ Brie quality - quality goes up - quality never goes above 50 """ if item_.quality < 50: item_.quality += 1 @staticmethod def sulfuras_quality(item_: Item) -> None: """ Sulfuras quality - quality never decreases """ pass @staticmethod def sulfuras_sell_in(item_: Item) -> None: """ Sulfuras quality - sell_in never decreases """ pass @staticmethod def backstage_quality(item_: Item) -> None: """ Backstage passes quality - quality goes up by 1 - quality goes up by 2 when less than 10 days of sell_in - quality goes up by 3 when less than 5 days of sell_in - quality goes to 0 when sell_in is less than or equal to 0 - quality cannot go above 50 """ if item_.quality >= 50: return if item_.sell_in <= 0: item_.quality = 0 elif item_.sell_in <= 5: item_.quality += 3 elif item_.sell_in <= 10: item_.quality += 2 else: item_.quality += 1 @staticmethod def conjured_quality(item_: Item) -> None: """ Conjured quality - quality decreases twice as fast as the default - decreases by 2 when sell_in is greater than 0 - decreases by 4 when sell_in is less than or equal to 0 """ if item_.quality > 0: quality_decrease = 2 if item_.sell_in <= 0: quality_decrease = 4 item_.quality -= quality_decrease @staticmethod def default_quality_method(item_: Item) -> None: """ Default quality - decreases by 1 - quality cannot by negative """ if item_.quality > 0: quality_decrease = 1 if item_.sell_in <= 0: quality_decrease = 2 item_.quality -= quality_decrease @staticmethod def default_sell_in_method(item_: Item) -> None: """ Default sell_in - decreases by 1 """ item_.sell_in -= 1 def update_quality(self) -> None: quality_update_methods = {'aged brie': self.aged_brie_quality, 'sulfuras': self.sulfuras_quality, 'backstage passes': self.backstage_quality, 'conjured': self.conjured_quality, } sell_in_update_methods = {'sulfuras': self.sulfuras_sell_in, } for item in self.items: # based on the way the code was previously quality is updated and then sell_in adjusted update_quality = quality_update_methods.get(item.name.lower(), self.default_quality_method) _ = update_quality(item) # noqa update_sell_in = sell_in_update_methods.get(item.name.lower(), self.default_sell_in_method) _ = update_sell_in(item) # noqa
390bf55d9bfdb5269bc91c123835963b8b4e801a
yxh13620601835/store
/yxhday3.4.py
803
3.5625
4
''' 从键盘输入任意三边,判断是否能形成三角形,若可以, 则判断形成什么三角形(结果判断:等腰,等边,直角,普通,不能形成三角形。) author:yxh ''' list=input("请输入三条边的数值:").split(" ") list1=[] for i in range(len(list)): list1.append(int(list[i])) print(list1) a=list1[0] b=list1[1] c=list1[2] if a+b>c and b+c>a and c+a>b: if a==b or b==c or c==a: if a==b and b==c and c==a: print("是等边三角形!") else: print("是等腰三角形!") elif a**2+b**2==c**2 or b**2+c**2==a**2 or c**2+a**2==b**2: print("是直角三角形!") else: print("是普通三角形!") else: print("不能构成三角形!")
cc2905bd58be1da34eb7dce099ec36a934edcf22
3l-d1abl0/DS-Algo
/py/stock_profit_twice.py
580
3.671875
4
def maxProfit(price, n): profit = [0]*n max_price = price[n-1] for i in range(n-2, 0, -1): max_price = max_price if max_price>price[i] else price[i] profit[i] = max(profit[i+1], max_price-price[i]) min_price= price[0] for i in range(1, n): min_price = min_price if min_price<price[i] else price[i] profit[i] = max(profit[i-1], profit[i]+price[i]-min_price) return profit[n-1] if __name__ == '__main__': price = [2, 30, 15, 10, 8, 25, 80] print "Max profit : ", maxProfit(price, len(price))
ef5ee4ea5a9ef0e492b14013f657146b8e2ed43e
notthattal/Sudoku
/sudoku_setup.py
1,362
4.21875
4
from sudoku_game_functions import * import random #function which displays the sudoku board #board is the current state of the game board def display_sudoku_board(board): for i in range(ROWS): if i == 3 or i == 6: print("- - - - - - - - - - - - - ") for j in range(COLUMNS): if j == 3 or j == 6: print(" | ", end="") if j == 8: print(board[i][j]) else: print(str(board[i][j]) + " ", end="") #Helper function to create a board def sudoku_pattern(r, c, block): return (block * (r % block) + r // block + c) % (block*block) #helper function to create a board def shuffle(s): return random.sample(s, len(s)) #function to create a random sudoku board def make_sudoku_board(): block = 3 side = 9 row_base = range(block) row = [i * block + r for i in shuffle(row_base) for r in shuffle(row_base)] col = [i * block + c for i in shuffle(row_base) for c in shuffle(row_base)] nums = shuffle(range(1, side + 1)) board = np.array([[nums[sudoku_pattern(r, c, block)] for c in col] for r in row]) win = check_win(board) if win is 1: i = 0 while i <= 50: row = random.randint(0,8) col = random.randint(0,8) board[row,col] = 0 i += 1 return board
bcaf40789c8ddad5efad01ba23b2a8c6c7707334
edutomazini/courseraPython1
/semana3/paridade.py
125
3.8125
4
numero = int(input("digite um numero: ")) restoPor2 = numero % 2 if restoPor2 == 0: print("par") else: print("impar")
7c418c503e551edb361c3301042d27cc0c877ce7
HeroAtomic/AOC-2019
/D2-P1.py
1,187
3.671875
4
inst_index = 0 num1_index = 1 num2_index = 2 replace_index = 3 intcode = [1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,6,19,1,19,5,23,2,13,23,27,1,10,27,31,2,6,31,35,1,9,35,39,2,10,39,43,1,43,9,47,1,47,9,51,2,10,51,55,1,55,9,59,1,59,5,63,1,63,6,67,2,6,67,71,2,10,71,75,1,75,5,79,1,9,79,83,2,83,10,87,1,87,6,91,1,13,91,95,2,10,95,99,1,99,6,103,2,13,103,107,1,107,2,111,1,111,9,0,99,2,14,0,0] intcode[1] = 12 intcode[2] = 2 length = len(intcode) opcode = intcode[inst_index] #Read until we see halt while opcode != 99: opcode = intcode[inst_index] #if we see a 1 we add # Get the next two values value1 = intcode[intcode[num1_index]] value2 = intcode[intcode[num2_index]] # Add them if opcode is 1 if opcode ==1: value = value1 + value2 # Multiple them if opcode is 2 elif opcode ==2: value = value1 * value2 # Replace the result intcode[intcode[replace_index]] = value # Move ahead 4 and reset the system inst_index += 4 num1_index = inst_index + 1 num2_index = inst_index + 2 replace_index = inst_index + 3 print('The value at position 0 is: {}'.format(intcode[0]))
ae2bfa7f0e44957718c2e73d5873518cc289d19f
Sidhikesh/PYTHON
/6th july 4th lec/check whether no is prime or not..py
176
3.953125
4
x=int(input('enter a no')) for i in range (2,x): if(x%i==0): break if(i==x-1): print('it is a prime no') else:print('it is not a prime no.')
7422f984e4dba2a71cdd765d6bbf0eee2f78d39c
batoolmalkawii/data-structures-and-algorithms-python
/tests/test_tree.py
4,375
3.921875
4
from data_structures_and_algorithms_python.data_structures.tree.tree import Node, BinaryTree, BinarySearchTree import pytest """ *BT* Test Cases: 1. Can successfully instantiate an empty tree. 2. Can successfully instantiate a tree with a single root node. 3. Can successfully add a left child and right child to a single root node. 4. Can successfully return a collection from a preorder traversal. 5. Can successfully return a collection from an inorder traversal. 6. Can successfully return a collection from a postorder traversal. 7. Can successfully return the maximum value in the tree. 8. Can successfully return an exception when we try to find the maximum value in an empty tree. 9. Can successfully return a collection from a BFS traversal. 10. Can successfully return an exception when we try to traverse in BFS on empty tree. """ def test_tree_empty(): bt = BinaryTree() assert bt.root == None def test_tree_single(): bt = BinaryTree() bt.root = Node(7) assert bt.root.value == 7 def test_tree_single_left_right(): bt = BinaryTree() bt.root = Node(7) bt.root.left = Node(3) bt.root.right = Node(2) assert bt.root.value == 7 assert bt.root.left.value == 3 assert bt.root.right.value == 2 assert bt.preOrder() == [7, 3, 2] def test_tree_preorder(): bt = BinaryTree() bt.root = Node(6) bt.root.right = Node(5) bt.root.left = Node(-1) bt.root.right.left = Node(7) bt.root.left.left = Node(10) bt.root.right.right = Node(3) assert bt.preOrder() == [6, -1, 10, 5, 7, 3] def test_tree_inorder(): bt = BinaryTree() bt.root = Node(6) bt.root.right = Node(5) bt.root.left = Node(-1) bt.root.right.left = Node(7) bt.root.left.left = Node(10) bt.root.right.right = Node(3) assert bt.inOrder() == [10, -1, 6, 7, 5, 3] def test_tree_postorder(): bt = BinaryTree() bt.root = Node(6) bt.root.right = Node(5) bt.root.left = Node(-1) bt.root.right.left = Node(7) bt.root.left.left = Node(10) bt.root.right.right = Node(3) assert bt.postOrder() == [10, -1, 7, 3, 5, 6] def test_tree_max(): bt = BinaryTree() bt.root = Node(6) bt.root.right = Node(5) bt.root.left = Node(-1) bt.root.right.left = Node(7) bt.root.left.left = Node(10) bt.root.right.right = Node(3) assert bt.findMaximumValue() == 10 def test_tree_max_empty(): bt = BinaryTree() with pytest.raises(Exception): assert bt.findMaximumValue() def test_tree_bfs(): bt = BinaryTree() bt.root = Node(6) bt.root.right = Node(5) bt.root.left = Node(-1) bt.root.right.left = Node(7) bt.root.left.left = Node(10) bt.root.right.right = Node(3) assert bt.breadthFirst() == [6, -1, 5, 10, 7, 3] def test_tree_bfs_empty(): bt = BinaryTree() with pytest.raises(Exception): assert bt.breadthFirst() """ *BST* Test Cases: 1. Can successfully instantiate an empty BST. 2. Can successfully instantiate a tree with a single root node. 3. Can successfully add multiple nodes to a BST. 4. Can successfully return True when searching for an existing node in BST. 5. Can successfully return False when searching for a non-existing node in BST. 6. Can successfully raise an exception when searching in an empty BST. """ def test_bst_empty(): bst = BinarySearchTree() assert bst.root == None def test_bst_add_single(): bst = BinarySearchTree() bst.add(4) assert bst.root.value == 4 def test_bst_add_multiple(): bst = BinarySearchTree() bst.add(4) bst.add(9) bst.add(-1) bst.add(6) bst.add(3) bst.add(8) bst.add(5) assert bst.root.value == 4 assert bst.root.left.value == -1 assert bst.root.right.value == 9 assert bst.root.left.right.value == 3 assert bst.root.right.left.left.value == 5 def test_bst_contain(): bst = BinarySearchTree() bst.add(4) bst.add(9) bst.add(-1) bst.add(6) bst.add(3) bst.add(8) bst.add(5) assert bst.contains(-1) == True def test_bst_not_contain(): bst = BinarySearchTree() bst.add(4) bst.add(9) bst.add(-1) bst.add(6) bst.add(3) bst.add(8) bst.add(5) assert bst.contains(7) == False def test_bst_contain_empty(): bst = BinarySearchTree() with pytest.raises(Exception): assert bst.contains(7)
615db1a5afe60dc1ae2deeb8540eae9748b0334e
akrias/projects
/practice/rev-int.py
412
3.8125
4
#!/bin/python def reverse(x): """ :type x: int :rtype: int """ neg = False to_str = str(x) #print to_str if(to_str[0] == '-'): to_str = to_str[1:] neg = True rev = to_str[::-1] rev = int(rev) if((rev > 2**31 - 1) or (rev < -2**31)): return 0 elif(neg): return rev * -1 else: return rev print reverse(1534236469)
6232522f5b8fb38507d1a2191d08db12116caf8f
Aleksey-Korneev/msu_python_backend_spring_2021
/1/test.py
1,399
3.5625
4
import unittest from tic_tac_toe import TicTacToe class TestMoveMaking(unittest.TestCase): def setUp(self): self.game = TicTacToe() def test_duplicated_move(self): self.game.make_move(1, 1) self.assertRaises(TicTacToe.Error, TicTacToe.make_move, self.game, 1, 1) def test_value_error(self): self.assertRaises(TicTacToe.Error, TicTacToe.make_move, self.game, 'a', 'b') def test_index_error(self): self.assertRaises(TicTacToe.Error, TicTacToe.make_move, self.game, 5, 5) class VictoryTest(unittest.TestCase): def setUp(self): self.game = TicTacToe() def test_diagonal_validation(self): self.game.make_move(0, 0) self.game.make_move(1, 1) self.game.make_move(2, 2) self.assertTrue(self.game.is_victory()) def test_row_validation(self): self.game.make_move(0, 0) self.game.make_move(0, 1) self.game.make_move(0, 2) self.assertTrue(self.game.is_victory()) def test_column_validation(self): self.game.make_move(0, 0) self.game.make_move(1, 0) self.game.make_move(2, 0) self.assertTrue(self.game.is_victory()) if __name__ == '__main__': unittest.main()
c7e3e2f28460fff2bbcf684512c2ebb1769a7856
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Pense_em_Python/cap10/Exercicio10_05.py
305
4.09375
4
""" Escreva uma função chamada is_sorted que tome uma lista como parâmetro e retorne True se a lisata estiver classificada e em ordem ascendente, e False se não for o caso. """ t = [1, 2, 3, 4, 5] def is_sorted(t): if t == sorted(t): return True return False print(is_sorted(t))
546b8d767971bb6dec61d86f6bdcff0dc77d5871
NatSujVanier2019/Graphing-Multidimensional-Data
/Data_Analysis_Program/All_Clustering.py
9,319
3.59375
4
#--------------Importing Modules------------------------------------------ from tkinter import * import time from plotly import tools #----------------------Import Files-------------------------------- from Indexing_Rev_31 import fileinput #Importing the file input function that allows the program to take in files and index them. from Ploty_Graph_Version_4 import Graph #Importing the graphing function import K_Means_Clustering_1 #Importing K-Means Clustering algorithm import Columning_RGB_2 #Importing Density rows ---> Columning function and color assignment for Density from Infinite_Dimensional_Clustering_RGB_3 import clustering #Importing Density Clustering Algorithm and it's accompanying Anomaly Detection # Underneath a check to see if the user has made a plotly account or not. print ("""In order to use our program, you require the modules Plotly,random,csv and time. To use plotly, you need to make a plotly account. This account is completely free. Once you make your account, be sure to generate an API key to use it. We can make the credentials file for you. All we need is your username and the API key. This program works completely offline and only uses your browser to open an embed HTML file. That HTML file will be your interactive graph. Thank you for using our program.""") def plotly(): '''Plotly function opens a tkinter window prompting the user if they have a plotly credential file. They press a button 'Yes' or 'No' and the respective function runs. Uses tkinter syntax''' class Window(Frame): def __init__(main, graph=None): Frame.__init__(main, graph) main.graph = graph main.init_window() #Creation of init_window def init_window(main): #Changing the title of our master widget main.graph.title("Welcome To The MainFrame!") #Allowing the widget to take the full space of the root window main.pack(fill=BOTH, expand=2) #Creating a Yes Button Yes = Button(main, text="Yes", font = ("Times",30),fg="White", bg="Black",command = mainprogram, width = 15) #Placing Kmeans button on the screen Yes.place(x=500, y=200) #Creating a No button No = Button(main, text="No",fg="white",bg = "Black",font =("Times",30),command = account, width = 15)#,height = 30) #width = 50,bg = 'blue') #DensityButton.config( width = 200, height = 200) #Placing the the Density Clustering Button on the screen No.place(x=75, y=200) Welcometext = Label(root,text = "Data Analysts", font = ("Times", 44), fg= "Black").place (x=250, y=0) ImportantMessage = Label(root,text="***Do You Have A Plotly Credential File?***", font =("Arial", 25), fg = "red").place (x=150,y=90) root = Tk() root.minsize(871, 715) root.maxsize(871, 715) app = Window(root) root.mainloop() print ("""**Please make sure you enter the following information correctly. If you don't want us to make your credentials file, you can do it on Python yourself. Visit https://plot.ly/python/getting-started/ for the instructions on how to do it on your own.""") #Underneath, we make the user's credential files that will allow them to make graphs for them. def account(): ''' If the user does not have a plotly credential file, this function creates one for them. Uses plotly syntax.''' user = input("What is your username: ") API = input("Please enter the API key for your account: ") tools.set_credentials_file(username= user, api_key= API) print ("Congrats. Your credentials file has been set.") mainprogram() def mainprogram(): '''This function is linked to the tkinter window that promps the user if they would like to run Kmeans or Density-clustering. Then the respective method runs. ''' yes = True #Initializes yes to True. titles,dataperson,category_legend = fileinput() while yes == True: #While Loop runs as long as yes is True try: def method1(): ''' This function runs density-clustering and anomaly''' #method = int(input("Choose a clustering method: (1)Density-based (2)K-Means (3)Exit\n")) #User chooses the method of clustering. #Run Density and Anomaly clustering Algorithm option = 2 Clusters,anomaly_detector = clustering (dataperson) #Run Density-based Clustering d_cluster,color4,pl_colorscale2 = Columning_RGB_2.colcol (Clusters,anomaly_detector) #Run Columning for color assignment and turning rows to columns. k,k_cluster,k_centroid,pl_colorscale,color3,color2 = None,None,None,None,None,None #Set all the values from K-Means to none as it is not being used #Rather than have K-Means run unecessarily, we give the user an option #and whichever is not being used will be set to none. print ("Loading...") Graph (option,k,k_cluster,k_centroid,pl_colorscale,color3,color2,d_cluster,color4,pl_colorscale2,titles, category_legend) #Run the Graph function to graph the results def method2(): '''This function runs Kmeans-clustering''' #Run K-Means Clustering option = 1 k,k_cluster,k_centroid,pl_colorscale,color3,color2 = K_Means_Clustering_1.k_means (dataperson) d_cluster,color4,pl_colorscale2 = None,None,None print ("Loading...") Graph (option,k,k_cluster,k_centroid,pl_colorscale,color3,color2,d_cluster,color4,pl_colorscale2,titles,category_legend) #Run Graph class Window(Frame): def __init__(main, graph=None): Frame.__init__(main, graph) main.graph = graph main.init_window() #Creation of init_window def init_window(main): #Changing the title of our master widget main.graph.title("Welcome To The MainFrame!") #Allowing the widget to take the full space of the root window main.pack(fill=BOTH, expand=2) #Creating Kmeans Button KmeansButton = Button(main, text="K Means", font = ("Times",30),fg="White", bg="Black",command = method2, width = 15) #Placing Kmeans button on the screen KmeansButton.place(x=500, y=200) #Creating Density Clustering button DensityButton = Button(main, text="Density Clustering",fg="white",bg = "Black",font =("Times",30),command = method1)#,height = 30) #width = 50,bg = 'blue') #DensityButton.config( width = 200, height = 200) #Placing the the Density Clustering Button on the screen DensityButton.place(x=75, y=200) Welcometext = Label(root,text = "Data Analysts", font = ("Times", 44), fg= "Black").place (x=250, y=0) ImportantMessage = Label(root,text="***Please make sure you have these modules: plotly, copy, csv, time and random***", font =("Arial", 10), fg = "red").place (x=175,y=90) root = Tk() root.minsize(871, 715) root.maxsize(871, 715) app = Window(root) root.mainloop() except ValueError: #Error trapping for string input (int expected). print("Invalid Input") plotly()
8f6bbe0044bd513445d4bc8c81873f44d43aa7cf
arvindkarir/python-pandas-code
/Py exercises/SchoolMemberOopExample.py
2,489
3.75
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 21 20:24:14 2017 @author: User """ import gc #kind of brute force implementation to list all instances of a class # look into weak references as well class SchoolMember: Population = 0 @classmethod # added this to keep a count of how many members in total def how_many(cls): print('We have {:d} members.'.format(cls.Population)) def __init__(self, name, age): self.name = name self.age = age #print('(Initializing SchoolMember: {})'.format(self.name)) SchoolMember.Population += 1 def tell(self): print('Name:{} Age:{}'.format(self.name, self.age), end =" ") def __gt__(self, other): #checks for greater than between two instances and returns true or false return self.name > other.name def allMembers(): for obj in gc.get_objects(): if isinstance(obj, SchoolMember): print('Member', obj.name) class Teacher(SchoolMember): def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print('Initialized Teacher: {}'.format(self.name)) def tell(self): SchoolMember.tell(self) print('Salary: {}'.format(self.salary)) def allTeachers(): for obj in gc.get_objects(): if isinstance(obj, Teacher): print('Teacher:', obj.name) class Student(SchoolMember): def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print('Initialized Student: {}'.format(self.name)) def tell(self): SchoolMember.tell(self) print('Marks: {}'.format(self.marks)) def allStudents(): for obj in gc.get_objects(): if isinstance(obj, Student): print('Student:', obj.name) t = Teacher('first_teacher', 33, 22334) t1 = Teacher('second_teacher', 32, 33221) s = Student('student_1', 22, 75) n = Student('student_2', 21, 56) # prints a blank line #print() #members = ([t, s, t1, n]) #for member in members: ## Works for both Teachers and Students # member.tell() #SchoolMember.how_many() #Student.allStudents() SchoolMember.allMembers() print(n > s)
ae70c23bf32a68da4af9dc1b47aad5a9921c20d3
mhegreberg/AdventofCode2020
/2/passwordCheck.py
436
3.5625
4
# Advent of Code Day 2 # Mark Hegreberg # part one import re f = open("data.txt", "r") inData = f.read().splitlines() data = [] valid = 0 print(inData) for line in inData: x = re.split('-| |: ',line) print(x) data.append(x) print(data) for line in data: count = line[3].count(line[2]) print(line) print(count) if count >= int(line[0]) and count <= int(line[1]): valid+=1 print("valid") print(valid)
f4c7e301495c87c6f4cecff066c0da441b8d71d1
ignaciorosso/Practica-diaria---Ejercicios-Python
/Estructura repetitiva for/Problema10.py
169
3.90625
4
# Desarrollar un programa que muestre la tabla de multiplicar del 5 (del 5 al 50) for x in range(1, 51): mult = 5 * x print('5 x {} = {}'.format(x, mult))
998c5bda46918ba63cb60ea2e188421db1369571
Bladedrinks/Python_Learning
/upside_down_equilateral_triangle.py
1,006
4.5
4
# Program to display an upside-down equilateral triangle (like below), # using a nested for loop (a for inside another for). # Example (the length of each side, or 'l', is 6, and the length of each line, 'n', is changing from 6 to 1): # * * * * * * Line 1, n = 6: 0 whitespaces; l - n == 0 whitespaces # * * * * * Line 2, n = 5: 1 whitespaces; l - n == 1 whitespaces # * * * * Line 3, n = 4: 2 whitespaces; l - n == 2 whitespaces # * * * Line 4, n = 3: 3 whitespaces; l - n == 3 whitespaces # * * Line 5, n = 2: 4 whitespaces; l - n == 4 whitespaces # * Line 6, n = 1: 5 whitespaces; l - n == 5 whitespaces # Ask the user for the number of lines (also the length of the equilateral triangle): l = int(input("Enter the number of lines (the length of each side): ")) unit = input("Enter the unit you want to build up the triangle: ") for n in range(l, 0, -1): print(" " * (l - n), end="") for m in range(n): print(unit, end=" ") print("\n", end="")
4157bc6479ee7c29342c8405cf7b0993d4530d70
ubercareerprep2021/Uber-Career-Prep-Homework-Carla-Vieira
/Assignment-3/sorting/ex4.py
899
4.03125
4
""" Sorting Exercise 4: Group Anagrams Write a method to sort an array of strings so that all the anagrams are next to each other. Assume the average length of the word as “k”, and “n” is the size of the array, where n >> k (i.e. “n” is very large in comparison to “k”). Do it in a time complexity better than O[n.log(n)] """ from collections import defaultdict, Counter def group_anagrams(words): list_words = [] words_dict = defaultdict(list) for word in words: # it will take O(n) word_counter = Counter(word) # it will take O(k). As it is inside the loop, O(n*k) words_dict[str(sorted(word_counter.items()))].append(word) for words in words_dict.values(): # it will take O(n) list_words.extend(words) return list_words # Time Complexity # O(n*k + n) ~= O(n*k) # Space Complexity # O(n*k)
3c6a7a0fbe55e68013695e1bbd4f26a3b6b0babb
btbenson/pdsnd_github
/bikeshare.py
6,245
3.953125
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv', 'chi': 'chicago.csv', 'nyc': 'new_york_city.csv', 'wash': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print("Hello! Let\'s explore some US bikeshare data!") # Get user input for city (chicago, new york city, washington). city="" while city not in CITY_DATA.keys(): city = input("Enter the city name (chicago, new york city, washington): ").lower() print("Great! Data is from {}.\n".format(city).title()) # Get user input for month (all, january, february, ... , june) month="" while month not in ['all', 'jan', 'feb', 'mar', 'apr', 'may', 'jun']: month = input("Enter the month abbreviation(all, jan, feb, mar, ... , jun): ").lower() # Get user input for day of week (all, monday, tuesday, ... sunday) day = "" while day not in ["sun", "mon", "tue", "wed", "thu", "fri", "sat", "all"]: day = input("Enter the abbreviation for the day of week (all, sun, mon, tue, wed,...sat): ").lower() print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ months = {'all':0,'jan':1,'feb':2,'mar':3,'apr':4,'may':5,'jun':6} df = pd.read_csv(CITY_DATA[city]) df['Start Time'] = pd.to_datetime(df['Start Time']) df['month'] = df['Start Time'].dt.month if months[month] > 0: df=df[df['month']==months[month]] days = {"all":"All","sun":"Sunday", "mon":"Monday", "tue":"Tuesday", "wed":"Wednesday", "thu":"Thursday", "fri":"Friday", "sat":"Saturday"} df['weekday_name'] = df['Start Time'].dt.weekday_name if days[day]!="All": df=df[df['weekday_name']==days[day]] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # Display the most common month df['month_name'] = df['Start Time'].dt.month_name() print('The most common month is: {}.'.format(df['month_name'].mode()[0])) # Display the most common day of week df['day_of_week'] = df['Start Time'].dt.weekday_name print('The most common day of the week is: {}.'.format(df['weekday_name'].mode()[0])) # Display the most common start hour df['hour'] = df['Start Time'].dt.hour print('The most common start hour is: {}:00.'.format(df['hour'].mode()[0])) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print("\nCalculating The Most Popular Stations and Trip...\n") start_time = time.time() # Display most commonly used start station print("The most commonly used start station is: ", df['Start Station'].mode()[0]) # Display most commonly used end station print("The most commonly used end station is: ", df['End Station'].mode()[0]) # Display most frequent combination of start station and end station trip print("The most commonly used combination of start and end station is: \n{}".format(df.groupby(['Start Station', 'End Station']).size().nlargest(1))) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # TO DO: display total travel time import datetime print("The total travel time is:",str(datetime.timedelta(seconds=int(df['Trip Duration'].sum())))) # TO DO: display mean travel time print("The average travel time is: ",str(datetime.timedelta(seconds=int(df['Trip Duration'].mean().sum())))) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types print("User Type Counts:") print(df['User Type'].value_counts()) # TO DO: Display counts of gender if "Gender" in df.columns: print("\nGender Type Counts:") print(df['Gender'].value_counts()) else: print("\nGender is not found in the data.\n") # TO DO: Display earliest, most recent, and most common year of birth if "Birth Year" in df.columns: print("\nThe earliest birth year is: ", df['Birth Year'].min()) print("The most recent birth year is: ", df['Birth Year'].max()) print("The most common birth year is: ", df['Birth Year'].mode()[0]) else: print("\nBirth Year is not found in the data.\n") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) i=0 while input("\nWould you like to see 5 lines of raw data (yes or no)?\n").lower() == 'yes': print(df[i:i+5]) i+=5 restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
1da17ca6640b6234652f9a2e8b73a241fcfa14cc
madhurimukund97/20186075_CNF
/module8/ass1/tcpServer.py
1,957
3.5
4
import socket def curr_to_curr(data): tokens = data.split(" ") if tokens[1] == "INR": if tokens[4] == "Dollar": return (int(tokens[2]) / 67) elif tokens[4] == "Pounds": return (int(tokens[2]) * 0.75) / 67 elif tokens[4] == 'Yen': return (int(tokens[2]) * 113.41) / 67 elif tokens[4] == 'INR': return tokens[2] if tokens[1] == "Dollar": if tokens[4] == "INR": return (int(tokens[2]) * 67) elif tokens[4] == "Pounds": return (int(tokens[2]) * 0.75) elif (tokens[4] == "Yen"): return (int(tokens[2]) * 113.41) elif tokens[4] == 'Dollar': return tokens[2] if tokens[1] == "Pounds": if tokens[4] == "INR": return (int(tokens[2]) * 67) / 0.75 elif tokens[4] == "Dollar": return (int(tokens[2]) / 0.75) elif tokens[4] == "Yen": return (int(tokens[2]) * 113.41) / 0.75 elif tokens[4] == 'Pounds': return tokens[2] if tokens[1] == "Yen": if tokens[4] == "INR": return (int(tokens[2]) * 67) / 113.41 elif tokens[4] == "Dollar": return (int(tokens[2]) / 113.41) elif tokens[4] == "Pounds": return (int(tokens[2]) * 0.75) / 113.41 elif tokens[4] == 'Yen': return tokens[2] def main(): host = '192.168.43.153' port = 3125 s = socket.socket() s.bind((host, port)) s.listen(1) print("Server connected...!!!") c, addr = s.accept() print ("Connection established from: " + str(addr)) while True: data = c.recv(1024).decode() if not data: break print ("From connected user: " + str(data)) data = str(curr_to_curr(data)) print ("sending: " + str(data)) c.send(data.encode()) c.close() if __name__ == '__main__': main()
f4382227a8b865efada5103a7f1781a099cd20d9
ligiabbarros/python_basics
/ex35.py
576
3.5625
4
valor = int(input("Saque: ")) nota100 = 0 nota50 = 0 nota20 = 0 nota10 = 0 nota1 = 0 while valor > 0: while valor > 100: nota100 += 1 valor -= 100 while valor > 50: nota50 += 1 valor -= 50 while valor > 20: nota20 += 1 valor -= 20 while valor >= 10: nota10 += 1 valor -= 10 while valor >= 1: nota1 += 1 valor -= 1 print("Receba %d notas de $100, %d notas de $50, %d notas de $20, %d notas de $10 e %d notas de $1." % (nota100, nota50, nota20, nota10, nota1))
f32ffa3483cf4edad6ac00d59538998b2f0e1b36
LuanGermano/Mundo-3-Curso-em-Video-Python
/exercicios3/ex104.py
494
4.125
4
# Crie um programa que tenha a função LEIAINT(), que vai funcionar de forma semelhante a função INPUT() # só que fazendo a validação para aceitar apenas um valor numericos # Ex: n = leiaint('digite um n') def leiaint(): """ Programa de validação de numeros inteiros. :return: """ while True: n = str(input("Digite um valor numerico: ")) if n.isnumeric(): n = int(n) break print(f'Voce digitou o Numero {n}') leiaint()
eee7856bfe162609c2384c0a0462d81bc3964285
mehmetatesgit/pythonkurs
/type-conversion-demo.py
161
3.625
4
pi = 3.14 yariCap = float(input("yarı çap= ")) alan = pi * (yariCap ** 2) cevre = 2 * pi * yariCap print("Alan: " + alan + " Çevre: " + cevre)
2dc98bc72b5bf828b6696b8fcbbce17c37171aad
monicajaimesc/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
474
3.90625
4
#!/usr/bin/python3 def search_replace(my_list, search, replace): copy_list = my_list[:] for digit in range(len(copy_list)): if copy_list[digit] == search: # had a mistake, was using == instead of = # is an assignment not equal copy_list[digit] = replace return copy_list # copy_list = list(map(lambda digit: # replace if digit == search else digit, my_list)) # return copy_list # replace will return copy of the list
245265f4471f3e0b6a6527e989a4ea52c816f051
guy-with-curly-hair/Interview-Process-Coding-Questions
/Fractal_Analytics/countOfAnagrams.py
408
4.25
4
""" Given a text and a word, find the count of occurrences of anagrams of word in given text """ def countAnagrams(text,word): count=0 b = text a = word for i in range(len(b)-len(a)+1): if(sorted(a)==sorted(b[i:i+len(a)])): count=count+1 return count if __name__ == '__main__': text = str(input()) word = str(input()) print (countAnagrams(text, word))
f8e6fba7627386b3b2d2eb42ed9c018c71a43043
ioanoanea/agi_lab_1
/objects/line.py
1,094
3.5625
4
from objects.vector_2d import Vector2D class Line: ''' Reprezinta o dreapta in spatiul 2D printr-o ecuatie de forma: ax+by+c=0 a - coeficientul lui x b - coeficientul lui y c - constanta ''' def __init__(self, a: float = 0, b: float = 1, c: float = 0): if a == 0 and b == 0: raise Exception("Drepta invalida!") self.__a = a self.__b = b self.__c = c def __str__(self): return f"{self.__a}x+{self.__b}y+{self.__c}=0" @property def a(self): return self.__a @property def b(self): return self.__b @property def c(self): return self.__c def create(self, x: float, y: float, vector: Vector2D): ''' Initializeaza drepata data prin punct si vector director :param x: :param y: :param vector: :return: ''' if vector.x == 0 and vector.y == 0: raise Exception("Drepta invalida!") self.__a = vector.y self.__b = -vector.x self.__c = vector.x * y - vector.y * x
d44a679b7db33dc1bc2eb61ad1791a8730fc100e
janraj00/AlgoStart
/zes1/zad6.py
272
3.625
4
eps = 1e-10 def bisect(num=2020): left, right = 0, 100 # odpowiednio duża liczba while abs(left - right) > eps: x = (left + right) / 2 if x ** x > num: right = x else: left = x return left print(bisect())
7c82b97d687d0b0bb4da098be0608dccf3bee9de
jryburn/guessNum
/guessNum.py
917
4.03125
4
#!/usr/bin/python ''' guessNum.py Written by Justin Ryburn (jryburn@juniper.net) Last revised: 11/27/15 This script is designed to play the classic guess the number game. ''' # Import the needed modules import random # Set the global variables low = 1 high = 100 answer = random.randint(low,high) # Get our random number def main (): while True: # Keep looping until the user guesses correctly. guess = input('Guess a number between %d and %d: ' % (low, high)) if guess < answer: # Guess is too low. print 'You guessed too low. Try again.' elif guess > answer: # Guess is too high. print 'You guessed too high. Try again.' elif guess == answer: # User got it. print 'You are correct! Congratulations!!' break # Exit the loop once they get it right. # Main function call if __name__ == '__main__': main()
77d6490c839b1b1897ca118f565d849c514b6ff2
shashankvmaiya/Algorithms-Data-Structures
/LeetCode_python/src/graph/canVisitAllRooms_M.py
1,311
3.625
4
''' 841. Keys and Rooms Question: There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room. Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length. A key rooms[i][j] = v opens the room with number v. Initially, all the rooms start locked (except for room 0). You can walk back and forth between rooms freely. Return true if and only if you can enter every room. Solution: - Use Breadth first search and maintain a visited list Created on May 8, 2019 @author: smaiya ''' from collections import defaultdict from functools import reduce class Solution: def canVisitAllRooms(self, rooms): graph = defaultdict(list) for idx, r in enumerate(rooms): for k in r: graph[idx].append(k) visited = [False for i in range(len(rooms))] queue = [0] while queue: r = queue.pop(0) visited[r] = True for r_conn in graph[r]: if not visited[r_conn]: queue.append(r_conn) all_rooms = reduce(lambda x, y: x and y, visited) return all_rooms
a5177882b0ca8b6d4af6134ac657c0aa1d033413
hrrrpb/data
/codes/python/shooting.py
11,348
3.5625
4
#!/usr/bin/python3 import tkinter import PIL.Image import PIL.ImageTk import random import math, string import threading import time CANVAS_XSIZE = 600 CANVAS_YSIZE = 400 GUNCNT = 3 BULLETSPD = 3 TARGETSPD = 3 FIRESPD = 3 GUNTHREADS = [] GUNS = [] HIT = 0 TOTAL = 0 TARGETS = [] LOCK = threading.Lock() #GLOBAL LOCK to check if bullet hits target # it is a animation for shooting, guns and target both maintain a list of objects, object creation and moving are done in the class # internal threads using their individual internal lock (run function) # all the guns and objects share another global lock to check if bullet hit target. The hit is implemented in bullet moving function. # To improve the efficiency, only bullet reaching the hitting region, the global lock will be applied. # after stop, all the guns and target, including their bullets and objects, will be deleted. The statistics will be printed out. class flyingtargets() : def __init__(self): global screencanvas self.objects = [] self.state = True self.y = 10 self.x = 5 self.lock = threading.Lock() def createobject(self) : global TOTAL while self.state : #get the internal lock to add new object self.lock.acquire() self.objects.append(screencanvas.create_rectangle(self.x, self.y, self.x + 40, self.y + 10, fill ="green")) self.lock.release() TOTAL = TOTAL + 1 time.sleep(2) def __del__(self): global screencanvas #delete gun and its current bullets for object in self.objects : screencanvas.delete(object) print ("target objects deleted ") def moveobjects(self) : global LOCK while self.state : # get the internal lock to update the objects self.lock.acquire() LOCK.acquire() deletelist = [] for flyobject in self.objects : coords = screencanvas.coords(flyobject) if coords[0] > CANVAS_XSIZE - 5 : screencanvas.delete(flyobject) deletelist.append(flyobject) else : screencanvas.move(flyobject, 2, 0) for flyobject in deletelist : self.objects.remove(flyobject) LOCK.release() self.lock.release() time.sleep(40/1000/TARGETSPD) def run(self) : time.sleep(2) t1 = threading.Thread(target=self.createobject) t2 = threading.Thread(target=self.moveobjects) t1.start() t2.start() # if both thread exit, run will exit t1.join() t2.join() class gun(): def __init__(self, id): global screencanvas global guns global maxdist self.lock = threading.Lock() self.id = id self.bullets = [] self.state = True #create the gun distance = CANVAS_XSIZE / (GUNCNT + 1) self.x = self.id * distance - 20 self.y = CANVAS_YSIZE - 15 self.canvasid = screencanvas.create_rectangle(self.x, self.y, self.x + 40, self.y + 15, fill ="#4B5320") def __del__(self): global screencanvas #delete gun and its current bullets for bullet in self.bullets : screencanvas.delete(bullet) screencanvas.delete(self.canvasid) print ("gun", self.id, "deleted ,bullets deleted") def fire(self) : while self.state : #get internal lock to create new bullets self.lock.acquire() self.bullets.append(screencanvas.create_rectangle(self.x+20, self.y-10, self.x +25, self.y -20, fill ="silver")) self.lock.release() time.sleep(9/FIRESPD) def movebullets(self) : global LOCK global HIT while self.state : #get internal lock to update bullets self.lock.acquire() #create the delete list to keep all bullets should be removed this round deletelist = [] for bullet in self.bullets : coords = screencanvas.coords(bullet) #if bullets reaching the hit range, aquire the GLOBAL LOCK to check if hit if coords[1] <= 20 : LOCK.acquire() bulletcenterx = (coords[0] + coords[2])/2 bulletcentery = (coords[1] + coords[3])/2 #keep the targets which are hit this round objdeletelist = [] for flyobject in TARGETS[0].objects : objcoords = screencanvas.coords(flyobject) objcenterx = (objcoords[0] + objcoords[2])/2 objcentery = (objcoords[1] + objcoords[3])/2 dist = math.sqrt((bulletcenterx - objcenterx) ** 2 + (bulletcentery - objcentery) ** 2) if dist <= maxdist : screencanvas.delete(bullet) screencanvas.delete(flyobject) objdeletelist.append(flyobject) deletelist.append(bullet) HIT = HIT + 1 # remove the targets for flyobject in objdeletelist : TARGETS[0].objects.remove(flyobject) LOCK.release() # if bullets fly out of screen, remove if coords[3] < 0 : screencanvas.delete(bullet) deletelist.append(bullet) # if still in screen and not hitting anything, move else : screencanvas.move(bullet, 0, -2) #remove bullets from the gun for bullet in deletelist : self.bullets.remove(bullet) self.lock.release() time.sleep(40/1000/BULLETSPD) def run(self) : time.sleep(2) randomInterval = random.randint(0, 100000) time.sleep(randomInterval/100000) t1 = threading.Thread(target=self.fire) t2 = threading.Thread(target=self.movebullets) t1.start() t2.start() t1.join() t2.join() def startgun(id) : global GUNS newgun = gun(id) GUNS.append(newgun) newgun.run() #after gun run finish, delete the gun del GUNS[GUNS.index(newgun)] def starttarget() : global TARGETS target = flyingtargets() TARGETS.append(target) target.run() #after target stopped, delete the target del TARGETS[0] #check the input value def checkinput(input) : try : temp = int(input) if temp < 1 : temp = 1 elif temp > 5 : temp = 5 except ValueError: temp = 0 return temp def start() : global screencanvas global GUNCNT global FIRESPD global BULLETSPD global TARGETSPD #always clean the screen before start screencanvas.delete("all") # check if the input value is a number , if yes, check the limit if guncounttext.get() != "": temp = checkinput(guncounttext.get()) GUNCNT = 3 if temp == 0 else temp if firespeedtext.get() != "" : temp = checkinput(firespeedtext.get()) FIRESPD = 3 if temp == 0 else temp if bulletspeedtext.get() != "": temp = checkinput(bulletspeedtext.get()) BULLETSPD = 3 if temp == 0 else temp if targetspeedtext.get() != "": temp = checkinput(targetspeedtext.get()) TARGETSPD = 3 if temp == 0 else temp # start threads of guns for id in range(1,GUNCNT+1): T = threading.Thread(target=startgun, args=[id]) T.start() # start thread of target T = threading.Thread(target = starttarget) T.start() def stop() : global rootwindow global threadflags global GUNS, TARGET global screencanvas global TOTAL, HIT #deactivate both guns and target for gun in GUNS: gun.state = False TARGETS[0].state = False #put on statistics screencanvas.create_text(10, 15 , anchor = "nw", text = " HIT : " + str(HIT), fill = "white" ) screencanvas.create_text(10, 30 , anchor = "nw", text = " TOTAL : " + str(TOTAL), fill = "white" ) screencanvas.create_text(10, 45 , anchor = "nw", text = " HIT RATIO : %.2f" %(HIT/TOTAL), fill = "white") #reset statistics TOTAL = 0 HIT = 0 #rootwindow.after(100, rootwindow.destroy) #initialize layout #calculate the maximum collision distance between the centers of bullet and flying object #flying object size : 40, 10 #bullet size : 5, 10 #the max distance is a crude way to judge the hit, given more time, should be able to get a better scheme to do it deltax = (40 + 5) / 2 deltay = (10 + 10) /2 maxdist = math.sqrt(deltax ** 2 + deltay **2) #create the layout rootwindow = tkinter.Tk() rootwindow.title("Shooting Animation") rootwindow.config(width=CANVAS_XSIZE, height=CANVAS_YSIZE, bg="light grey") guncountlabel = tkinter.Label(rootwindow, foreground="blue", background="light grey", text="Gun # (1-5)") guncountlabel.grid(row=0, column=0, sticky="nsew") guncounttext = tkinter.StringVar() guncountentry = tkinter.Entry(rootwindow, width=2, foreground="blue", background="light grey", textvariable= guncounttext) guncountentry.grid(row=0, column=1, sticky="nsew") firespeedlabel = tkinter.Label(rootwindow, foreground="blue", background="light grey", text="Fire spd (1-5)") firespeedlabel.grid(row=0, column=2, sticky="nsew") firespeedtext = tkinter.StringVar() firespeedentry = tkinter.Entry(rootwindow, width=2, foreground="blue", background="light grey", textvariable=firespeedtext) firespeedentry.grid(row=0, column=3, sticky="nsew") bulletspeedlabel = tkinter.Label(rootwindow, foreground="blue", background="light grey", text="Bullet spd (1-5)") bulletspeedlabel.grid(row=0, column=4, sticky="nsew") bulletspeedtext = tkinter.StringVar() bulletspeedentry = tkinter.Entry(rootwindow, width=2, foreground="blue", background="light grey", textvariable=bulletspeedtext) bulletspeedentry.grid(row=0, column=5, sticky="nsew") targetspeedlabel = tkinter.Label(rootwindow, foreground="blue", background="light grey", text="Target spd (1-5)") targetspeedlabel.grid(row=0, column=6, sticky="nsew") targetspeedtext = tkinter.StringVar() targetspeedentry = tkinter.Entry(rootwindow, width=2, foreground="blue", background="light grey", textvariable=targetspeedtext) targetspeedentry.grid(row=0, column=7, sticky="nsew") startbutton = tkinter.Button(rootwindow, height=1, foreground="blue", background="light grey", text="Start", command=start) startbutton.grid(row=0, column=8, sticky="nsew") stopbutton = tkinter.Button(rootwindow, height=1, foreground="blue", background="light grey", text="Stop", command=stop) stopbutton.grid(row=0, column=9, sticky="nsew") screencanvas = tkinter.Canvas(rootwindow, width=CANVAS_XSIZE, height = CANVAS_YSIZE, bg="black") screencanvas.grid(row=1, column=0,columnspan=10) #disable resize rootwindow.resizable(0,0) tkinter.mainloop()
013134cfc0c383cb23878ebc60647a16d60c98f5
blomk/leetcode
/14.最长公共前缀.py
399
3.578125
4
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ result='' if not strs: return result for i in range(0,len(strs[0])): temp=strs[0][i] for x in strs[1:]: if i > len(x)-1 or x[i] != temp: return result result += temp return result
36e00abcbd135e2ff9e402d26b61759b7bb1ba64
Asad-K-Bhatti/Chicken_Slayer_Z
/Chicken Slayer Z Game/Anim_2.py
3,588
3.609375
4
''' Taha Ali ICS4UR Ms. Pais March 29, 2019 The following block of code runs the animation for the game, which is seen after clicking the start button on the main menu. ''' import pygame from pygame.locals import * import sys import os from os import path import pygame,random,sys,time,os def main(): """main() -> Image Plays a series of Pics to create a short movie >>>main() video plays """ pygame.init() #Initializes python pygame.display.init() screensize = (1400, 700) screen = pygame.display.set_mode((screensize)) clock = pygame.time.Clock() #function for speed of game defined as clock pygame.display.set_caption("Chicken Slayerz") skip = pygame.image.load("Skipper.png") logo = pygame.image.load("icon.png") background = pygame.image.load("Pic_1.png") story = 100 pygame.display.set_icon(logo) running = True while running: clock.tick(300) #Game refreshes at 64 Pics per second for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): #if user hits esc or clicks the x on the top rightcorner program exits pygame.quit() sys.exit() running = False if event.type == KEYDOWN: #Exit game if event.key == K_SPACE: import Stage_2 #Skips animation and goes to game #Plays the animation story += 1 if story == 155: background = pygame.image.load("Pic_2.png") elif story == 160: background = pygame.image.load("Pic_3.png") elif story == 162: background = pygame.image.load("Pic_4.png") elif story == 163: background = pygame.image.load("Pic_5.png") elif story == 164: background = pygame.image.load("Pic_6.png") elif story == 200: background = pygame.image.load("Pic_7.png") elif story == 235: background = pygame.image.load("Pic_8.png") elif story == 295: background = pygame.image.load("Pic_9.png") elif story == 300: background = pygame.image.load("Pic_10.png") elif story == 305: background = pygame.image.load("Pic_11.png") elif story == 310: background = pygame.image.load("Pic_12.png") elif story == 315: import Stage_2 screen.blit(background, (0, 0)) #background screen.blit(skip, (1100, 600)) pygame.display.flip() #Updates game frames pygame.quit() pygame.display.quit() main()
af923440e08699129fdb83c97e1f65c0d0b0737d
MaxDac/ten_days_stat
/day1/quartiles.py
764
3.9375
4
def compute_median(n, arr): if n % 2 == 0: return round((arr[n // 2 - 1] + arr[n // 2]) / 2, 1) else: return arr[n // 2] if __name__ == '__main__': n = int(input()) arr = sorted([int(x) for x in input().rstrip().split()]) median = int(compute_median(n, arr)) first_quartile, second_quartile = [], [] if n % 2 == 0: first_quartile, second_quartile = arr[0:n // 2], arr[n // 2:] else: first_quartile, second_quartile = arr[0:n // 2], arr[n // 2 + 1:] first_quartile_median = int(compute_median(n // 2, first_quartile)) second_quartile_median = int(compute_median(n // 2, second_quartile)) print(str(first_quartile_median)) print(str(median)) print(str(second_quartile_median))
14da9f538bc95fe05c2b773056b174581e9b999a
DmitryMedovschikov/Programming_on_Python.Bioinformatics_Institute
/1. Итого по разделу/1.FinalTasks.py
6,639
3.8125
4
# Напишите программу, вычисляющую площадь треугольника по переданным длинам # трёх его сторон по формуле Герона: S = sqrt(p(p−a)(p−b)(p−c)), # где p=(a+b+c)/2 - полупериметр треугольника. На вход программе подаются # целые числа, выводом программы должно являться вещественное число, # соответствующее площади треугольника. a = int(input()) b = int(input()) c = int(input()) p = (a + b + c) / 2 S = (p * (p - a) * (p - b) * (p - c)) ** (1 / 2) print(S) # Напишите программу, принимающую на вход целое число, которая выводит True, # если переданное значение попадает в интервал: (−15,12]∪(14,17)∪[19,+∞) # и False в противном случае. num = int(input()) if -15 < num <= 12 or 14 < num < 17 or num >= 19: print(True) else: print(False) # Напишите простой калькулятор, который считывает с пользовательского ввода # три строки: первое число, второе число и операцию, после чего применяет # операцию к введённым числам ("первое число" "операция" "второе число") и # выводит результат на экран. # Поддерживаемые операции: +, -, /, *, mod, pow, div, где # mod — это взятие остатка от деления, # pow — возведение в степень, # div — целочисленное деление. # Если выполняется деление и второе число равно 0, необходимо выводить # строку "Деление на 0!" num_1 = float(input()) num_2 = float(input()) operation = input() if operation == "+": result = num_1 + num_2 print(result) elif operation == "-": result = num_1 - num_2 print(result) elif operation == "/": if num_2 == 0: print("Деление на 0!") else: result = num_1 / num_2 print(result) elif operation == "*": result = num_1 * num_2 print(result) elif operation == "mod": if num_2 == 0: print("Деление на 0!") else: result = num_1 % num_2 print(result) elif operation == "pow": result = num_1 ** num_2 print(result) elif operation == "div": if num_2 == 0: print("Деление на 0!") else: result = num_1 // num_2 print(result) # Комнаты бывают треугольные, прямоугольные и круглые. Требуется написать # программу, на вход которой подаётся тип фигуры комнаты и соответствующие # параметры, которая бы выводила площадь получившейся комнаты. Для числа π # используют значение 3.14. Ниже представлены форматы ввода: # треугольник # a # b # c # где a, b и c — длины сторон треугольника # # прямоугольник # a # b # где a и b — длины сторон прямоугольника # # круг # r # где r — радиус окружности PI = 3.14 f = input() if f == "треугольник": a = int(input()) b = int(input()) c = int(input()) p = (a + b + c) / 2 S = (p * (p - a) * (p - b) * (p - c)) ** (1 / 2) print(S) elif f == "прямоугольник": a = int(input()) b = int(input()) S = a * b print(S) elif f == "круг": r = int(input()) S = PI * r ** 2 print(S) # Напишите программу, которая получает на вход три целых числа, по одному # числу в строке, и выводит на консоль в три строки сначала максимальное, # потом минимальное, после чего оставшееся число. На ввод могут подаваться и # повторяющиеся числа. num_1 = int(input()) num_2 = int(input()) num_3 = int(input()) max_num = num_1 min_num = num_1 if max_num < num_2: max_num = num_2 elif min_num > num_2: min_num = num_2 if max_num < num_3: max_num = num_3 elif min_num > num_3: min_num = num_3 midl_num = (num_1 + num_2 + num_3) - (max_num + min_num) print(max_num, "/n", min_num, "/n", midl_num) # Напишите программу, считывающую с пользовательского ввода целое число n # (неотрицательное), выводящее это число в консоль вместе с правильным # образом изменённым словом "программист", например: 1 программист, # 2 программиста, 5 программистов. Проверьте, что ваша программа правильно # обработает все случаи, как минимум до 1000 человек. num = int(input()) word = "программист" if num % 10 == 0 or 5 <= num % 10 <= 9 or 11 <= num % 100 <= 14: word_tail = "ов" elif num % 10 == 1 and num % 100 != 11: word_tail = "" elif 2 <= num % 10 <= 4: word_tail = "а" print(num, word + word_tail) # Билет считается счастливым, если сумма первых трех цифр совпадает с суммой # последних трех цифр номера билета. Необходимо написать программу, которая # проверит равенство сумм и выведет "Счастливый", если суммы совпадают, и # "Обычный", если суммы различны. На вход программе подаётся строка из 6 цифр. # Выводить нужно только слово "Счастливый" или "Обычный", с большой буквы. num = int(input()) num_1 = num // 100000 num_2 = num % 100000 // 10000 num_3 = num % 10000 // 1000 num_4 = num % 1000 // 100 num_5 = num % 100 // 10 num_6 = num % 10 if num_1 + num_2 + num_3 == num_4 + num_5 + num_6: print("Счастливый") else: print("Обычный")
ec5eda784d7e505309180138697570df11f59961
erwindev/shecancodeit
/src/guess.py
397
4.0625
4
import random n = random.randint(1, 11) running = True while running: guess = input("Guess a number between 1 and 10: ") num_guess = int(guess) if num_guess == n: print("You guessed right!") running = False elif num_guess < n: print("Try higher") elif num_guess > n: print("Try lower") else: print('The while loop is over') print ("Done")
16c8b1165e1b3785d0127cbaae3c8c91df322d3c
kmgowda/kmg-leetcode-python
/simplify-path/simplify-path.py
524
3.96875
4
// https://leetcode.com/problems/simplify-path class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ words = path.split('/') st = list() for word in words: if word =='..': if st: st.pop() elif word and word !='.': st.append('/'+word) if st: return ''.join(st) else: return '/'
4f2d28156093eda510ac51a328d69ca3cc0fdac8
Goldsipa/goldsipa-tasks
/task_1/__init__.py
1,151
3.859375
4
# -*- coding: utf-8 -*- def fill_spiral_matrix(n): """ Создает мартицу размером n * n и заполняет ее по спирали Parameters ---------- n : int Размерность матрицы. Variables --------- dx, dy : int Начальные приращения/начальный вектор x, y : int Начальная позиция Returns ------- list[list[int]] Матрица заполненная по спирали """ dx,dy = 0,1 x,y = 0,0 result = [[None]* n for j in range(n)] for i in range(1, n**2+1): # цикл для заполнения матрицы result[x][y] = i nx,ny = x+dx, y+dy if 0 <= nx < n and 0 <= ny < n and result[nx][ny] == None: # индекс в пределах матрицы и не на занятой ячейке x,y = nx,ny else: dx,dy = dy,-dx # изменяем направление вектора на 90 градусов x,y = x+dx, y+dy return result
6ad4504e837ee66a307faad11c039d17f2d47904
icebearliangliang/driving
/driving.py
424
4.15625
4
country = input('please input your country: ') age = input('please input your age: ') age = int(age) if country == 'China': if age >= 18: print('you can get a driving license') else: print("you can't get a driving license yet") elif country == 'American': if age >= 16: print('you can get a driving license') else: print("you can't get a driving license yet") else: print('you can only input China or American')
2f88fc8daf29576e14fc9d3d11191db49b5ef605
DezzMyasnik/python_base
/lesson_005/drawing/wall.py
1,667
3.8125
4
# -*- coding: utf-8 -*- # (цикл for) import simple_draw as sd import pygame # Нарисовать стену из кирпичей. Размер кирпича - 100х50 # Использовать вложенные циклы for def drawwall(start_point, end_point): for x in range(start_point.x, end_point.x, 100): for y in range(start_point.y, end_point.y, 50): left_bottom = sd.get_point(x, y) right_top = sd.get_point(100 + x, 50 + y) if y % 100 != 0: left_bottom.x -= 50 right_top.x -= 50 sd.rectangle(left_bottom, right_top, sd.COLOR_DARK_ORANGE, 2) #sd.pause() #зачет! def draw_vector(count_angle, start_point, start_angle, lenght, color): #angle = 360/count_angle local_point = start_point for i in range(count_angle): if i == 0: angle = 0 lenght = 410 if i == 1: angle = 160 lenght = 220 if i == count_angle - 1: angle = 200 lenght = 220 #sd.line(local_point, start_point, color, width=1) v1 = sd.get_vector(start_point=local_point, angle=start_angle + angle, length=lenght, width=1) v1.draw(color=color) local_point = v1.end_point if i == count_angle - 1: sd.line(local_point, start_point, color, width=1) def triangle(point, angle, lenght, color): point_list = [point, sd.get_point(point.x+410, point.y), sd.get_point(point.x+205, point.y+50)] sd.polygon(point_list, color, width=0) #draw_vector(3, point, angle, lenght, color)
bf32437bc4ec562a2f24edee2b8863e1b9873113
Meengkko/bigdata_python2019
/01_jump_to_python/CodingDojang/5_special_sorting.py
256
3.625
4
negative = [] positive = [] numbers = input() numList = numbers.split(" ") for i in range(0, len(numList)): if int(numList[i]) >= 0: positive.append(int(numList[i])) else: negative.append(int(numList[i])) print(negative + positive)
482035ced1e6a32934c216fc2dcf550c4f6fa1c3
M00n-man92/hangman
/main.py
1,852
3.65625
4
import random from art import art_list mylist=["yellow","red","blue","orange"] something=[] hope=0 a=random.choice(mylist) for smile in range(0,len(a)): something.append("__ ") print(something) megasonic="" supersonic="" error=0 count=0 win=True while win and error<7: b=input("select the character of yore choice ").lower() for skip in range(0,len(a)): if something[skip]=="__ ": if b==a[skip]: if skip==len(a)-1: something.append(b) something.pop(len(a)) something.insert(skip,b) something.pop(skip+1) elif b!=a[skip]: count+=1 if count==len(a): error+=1 else: if b!=a[skip]: count+=1 if count==len(a): error+=1 print("you've lost a life") megasonic+=something[skip]+" " for skipp in range(0,len(a)): if something[skipp]!="__ ": hope+=1 if hope==len(a): print("you've done it you've won") for hi in range(0,len(something)): supersonic+=something[hi]+" " if supersonic=="": if error<7: print(art_list[error]) print(f"you've lost a life {8-error}s left") print(something) else: print(art_list[7]) else: print(supersonic) win=False megasonic="" count=0 hope=0 print("gameover")
48aaf1d70f7f30b205fbef1d56c92051d0d29006
gitavares/PythonStudies
/PayingDebtOffInAYear.py
2,843
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 22 20:18:07 2018 @author: GiselleTavares """ #problem 1 def CreditCardBalance(balance, annualInterestRate, monthlyPaymentRate): remainingBalance = balance minimumMonthlyPayment = 0.0 monthlyInterestRate = annualInterestRate / 12 for x in range(0, 12): minimumMonthlyPayment = monthlyPaymentRate * remainingBalance monthlyUnpaidBalance = remainingBalance - minimumMonthlyPayment remainingBalance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance) print(round(remainingBalance,2)) return round(remainingBalance,2) print("Remaining balance: " + str(CreditCardBalance(42, 0.2, 0.04))) #problem 2 def MinimumFixedMonthlyPayment(balance, annualInterestRate): remainingBalance = balance monthlyInterestRate = annualInterestRate / 12 MinFixedMonthlyPayment = 10 while(remainingBalance > 0.0): for x in range(0, 12): monthlyUnpaidBalance = remainingBalance - MinFixedMonthlyPayment remainingBalance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance) if(remainingBalance > 0.0): MinFixedMonthlyPayment += 10 remainingBalance = balance else: lowestPayment = MinFixedMonthlyPayment break return round(lowestPayment, 2) print("Lowest Payment: " + str(MinimumFixedMonthlyPayment(3926, 0.2))) #problem 3 def MinimumFixedMonthlyPaymentBisection(balance, annualInterestRate): def f(x): return pow(x,3) - x - 2 remainingBalance = balance monthlyInterestRate = annualInterestRate / 12.0 monthlyPaymentLowerBound = balance / 12 monthlyPaymentUpperBound = (balance * pow(1.0 + monthlyInterestRate,12))/12.0 TOL = 0.01 smallestMonthlyPayment = round(monthlyPaymentLowerBound, 2) while f(smallestMonthlyPayment) == 0 or (monthlyPaymentUpperBound - monthlyPaymentLowerBound)/2.0 > TOL: for x in range(0, 12): monthlyUnpaidBalance = remainingBalance - smallestMonthlyPayment remainingBalance = round(monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance),3) #print('remainingBalance=', remainingBalance, 'smallestMonthlyPayment=', smallestMonthlyPayment) if(remainingBalance <= 0): monthlyPaymentUpperBound = round(smallestMonthlyPayment,2) else: monthlyPaymentLowerBound = round(smallestMonthlyPayment,2) smallestMonthlyPayment = round((monthlyPaymentLowerBound + monthlyPaymentUpperBound)/2.0, 2) remainingBalance = balance return round(smallestMonthlyPayment, 2) print("Lowest Payment: " + str(MinimumFixedMonthlyPaymentBisection(320000, 0.2)))
120d2f0e56bda7077caa157fc4bc58ea4b13e99b
YangXinNewlife/LeetCode
/easy/number_of_lines_to_write_string_806.py
638
3.640625
4
# -*- coding:utf-8 -*- __author__ = 'yangxin_ryan' """ Solutions: 题意是给定每个字符的元素占用大小,以及给定对应的元素; 还给定每行最大100,那么我们只需要依次遍历每个元素找到对应的大小,判断大于100时,直接换行即可; """ class NumberOfLinesToWriteString(object): def numberOfLines(self, widths: List[int], S: str) -> List[int]: width = 0 line = 1 for i in S: width += widths[ord(i) - ord('a')] if width > 100: width = widths[ord(i) - ord('a')] line += 1 return line, width
1dc2ec947802d0fe5328bee4f3de0edefb67a11e
orgatBP/at-practice
/dev/python/base/初学python怎么用while循环笔记分享.py
478
3.875
4
L=[] print 'please input five number' i=0 while i<5: n=int(raw_input('Enter your number:')) L.append(n) i+=1 print L print 'Now,you can select them' print 'summation averages exit' #www.iplaypy.com go=True while go: s=raw_input('I will:') if s=='summation': print sum(L) elif s=='averages': print sum(L)/len(L) elif s=='exit': go=False print 'Done' else: print 'Not have options'
e9a1a75bbea651e90ae19010dbe06afe0da6491a
navroz-lamba/DS-Unit-3-Sprint-2-SQL-and-Databases
/module1-introduction-to-sql/rpg_queries.py
3,362
4.03125
4
import sqlite3 # connecting the file conn = sqlite3.connect('rpg_db.sqlite3') # Making a cursor c = conn.cursor() """How many total Characters are there""" def total_characters(): c.execute("SELECT COUNT(*) FROM charactercreator_character;") print(c.fetchall()) """How many of each specific subclass""" def total_cleric(): c.execute(" SELECT COUNT(*) FROM charactercreator_cleric") print(c.fetchall()) def total_fighter(): c.execute(" SELECT COUNT(*) FROM charactercreator_fighter") print(c.fetchall()) def total_mage(): c.execute(" SELECT COUNT(*) FROM charactercreator_mage") print(c.fetchall()) def total_necromancer(): c.execute(" SELECT COUNT(*) FROM charactercreator_necromancer") print(c.fetchall()) """How many total Characters are there""" def total_items(): c.execute(" SELECT COUNT(*) FROM armory_item") print(c.fetchall()) """How many of the Items are weapons? How many are not?""" def total_weapons(): # merge armory_items and armory_weapons c.execute(" SELECT COUNT(*) FROM armory_weapon") print(c.fetchall()) """How many Items does each character have? (Return first 20 rows)""" def total_items_in_each_character(): c.execute("""SELECT character_id, COUNT(DISTINCT item_id) FROM (SELECT cc.character_id, cc.name, ai.item_id, ai.name FROM charactercreator_character AS cc, armory_item AS ai, charactercreator_character_inventory as cci WHERE cc.character_id = cci.character_id AND cci.item_id = ai.item_id) GROUP BY 1 ORDER BY 2 DESC LIMIT 20""") print(c.fetchall()) """How many Weapon does each character have? (Return first 20 rows)""" def total_weapons_in_each_character(): c.execute("""SELECT character_id, COUNT(DISTINCT item_ptr_id) FROM (SELECT cc.character_id, cc.name, aw.item_ptr_id FROM charactercreator_character AS cc, armory_weapon AS aw, charactercreator_character_inventory as cci WHERE cc.character_id = cci.character_id AND cci.item_id = aw.item_ptr_id) GROUP BY 1 ORDER BY 2 DESC LIMIT 20""") print(c.fetchall()) """On average, how many Items does each character have?""" def avg_number_of_items(): c.execute(""" SELECT round(AVG(unique_item),3) AS avg_number_of_items FROM (SELECT cc.character_id, COUNT(DISTINCT ai.item_id) AS unique_item FROM charactercreator_character AS cc, armory_item AS ai, charactercreator_character_inventory as cci WHERE cc.character_id = cci.character_id AND cci.item_id = ai.item_id GROUP BY 1) """) print(c.fetchall()) """On average, how many Weapons does each character have?""" def avg_number_of_weapons(): c.execute(""" SELECT round(AVG(unique_weapons),3) AS avg_number_of_weapons FROM (SELECT cc.character_id, COUNT(DISTINCT item_ptr_id) AS unique_weapons FROM charactercreator_character AS cc, armory_weapon AS aw, charactercreator_character_inventory as cci WHERE cc.character_id = cci.character_id AND cci.item_id = aw.item_ptr_id GROUP BY 1) """) print(c.fetchall()) avg_number_of_weapons()
a168b23632b7e338df53fd53c3c964edbbd5d5fb
kailash-manasarovar/A-Level-CS-code
/OCR_exam_questions/towers_of_hanoi.py
1,901
4.34375
4
# SAMPLE ASSESSMENT MATERIAL Paper 2 Q10 class Tower: # constructor new() def __init__(self): self.arraypole = [] self.counter = 0 # tells you if the stack is empty def isEmpty(self): return self.arraypole == [] # puts an element on the stack def push(self, diskValue): #if self.isEmpty(): if self.counter == 0: self.arraypole.append(diskValue) # this part does the validation of the diskValue making sure it is smaller than the one there elif diskValue < self.arraypole[self.counter]: self.arraypole.append(diskValue) self.counter = self.counter + 1 # this is what happens if the move is invalid else: print("Invalid move") # take an element off the stack def pop(self): return self.arraypole.pop() # looks at the top of the stack but doesn't remove any elements def peek(self): if self.isEmpty(): print(999) else: print(self.arraypole[len(self.arraypole) - 1]) # tells you how big the stack is def size(self): return len(self.arraypole) # prints the stack def __str__(self): result = "" for i in self.arraypole: result = result + " " + str(i) return result noOfDisks = 5 tower1 = Tower() tower2 = Tower() tower3 = Tower() i=noOfDisks while i>0: tower1.push(i) i=i-1 finished = False while finished != True: # set finished to False if noOfDisks = 999 # make the valid move between tower1 and tower3 if tower3.isEmpty(): tower3.push(tower1.pop()) elif tower3.peek() < tower1.peek(): pass else: tower3.peek() > tower1.peek() tower3.push(tower1.pop()) # make the valid move between tower1 and tower2 # make the valid move between tower3 and tower2
b8d125c6f7e8f2a8da0ce0bc841b486b88fc625d
BrittMcDanel/PythonToC
/example/math.py
248
3.828125
4
def add(a, b): return a + b def loop_func(size): for i in range(size): print("loop var", i) def main(): int_value = add(5, 10) double_value = add(5.0, 10.0) print("values", int_value, double_value) loop_func(20)
0ddc138c3bde9c021242c39fccc2ef63a1bc2665
sanjaydangwal/Python
/lambda.py
162
3.90625
4
add = lambda a,b:a+b print(add(2,5)) last_char = lambda l:l[-1] print(last_char("sanjay")) even_odd = lambda num:True if(num%2==0) else False print(even_odd(3))
42c44841f5850c9808865828054c93c97ff60857
ramoso5628/CTI110
/P3LAB_ Octavio Ramos.py
561
4.3125
4
# P3LAB Debugging # CTI-110 # 25 June 2019 # Octavio Ramos # This lab will be used to calculate students grades # User will enter a numeric grade. # The numeric grade is given in a letter grade. def main(): grade = int(input("Enter a numeric grade:")) if grade >=90: print("You made an A") elif grade > 79 and grade < 90: print("You made an B") elif grade > 69: print("You made a C") elif grade > 59: print("You made a D") else: print("You made an F") main()
eed588b7c7783ca655572aa042d2bb29d8b670f0
probaku1234/LeetCodeAlgorithmSolution
/Google/Design/LRU Cache.py
861
3.828125
4
""" URL : https://leetcode.com/explore/interview/card/google/65/design-4/3090/ """ from collections import OrderedDict class LRUCache(OrderedDict): def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity def get(self, key): """ :type key: int :rtype: int """ if key not in self: return - 1 self.move_to_end(key) return self[key] def put(self, key, value): """ :type key: int :type value: int :rtype: None """ if key in self: self.move_to_end(key) self[key] = value if len(self) > self.capacity: self.popitem(last=False) cache = LRUCache(2) cache.put(2, 1) cache.put(2,2) cache.get(2) cache.put(1,1) cache.put(4,1) cache.get(2)
ddc6a1890c8bb2f799d94e575ae7bac48a89222b
lpavezb/cc3101
/T1/p1/p1.py
3,256
3.625
4
#!/usr/bin/env python def p1(s): letters = "qwertyuiopasdfghjklzxcvbnm" const = "a" var = "b" par = "c" su = "d" mult = "e" res = "" if not arit(s): return "NO\n" pars = countBrackets(s) if pars == "NO\n": return pars res += par*pars # agrega parentesis res += const*countConsts(s) # agrega constantes res += su*s.count("+") # agrega sumas res += mult*s.count("*") # agrega multiplicaciones for a in s: # agrega variables, suponiendo que cada variable esta compuesta por una letra if a in letters: res += var res = ''.join(sorted(res)) # ordena respuesta final alfabeticamente return res def arit(s): letters = "qwertyuiopasdfghjklzxcvbnm" num = "1234567890" l = s.split("+") if '' in l: return False b = True for st in l: c = False if st[0] == '*' or st[len(st) - 1] == '*': return False for a in st: if a in letters or a in num: c = True b = b and c l = s.split("*") if '' in l: return False d = True for st in l: c = False if st[0] == '+' or st[len(st) - 1] == '+': return False for a in st: if a in letters or a in num: c = True d = d and c return b and d def countConsts(s): num = "1234567890" n = 0 i = 0 l = len(s) while i<l: if s[i] in num: n += 1 try: while s[i+1] in num: i += 1 except Exception as e: pass i += 1 return n def countBrackets(s): pars = 0 for a in s: if a == "(": pars += 1 if a == ")": pars -= 1 if pars < 0: return "NO\n" if pars == 0: return s.count("(") else: return "NO\n" def test(In, Out): file_in = open(In,"r") file_out = open(Out,"r") f = 0 for line in file_out: line_in = file_in.readline() if line == "NO\n": res = "NO\n" else: # ordena alfabeticamente res = line.replace(",","").replace("\n","") res = ''.join(sorted(res)) bol = p1(line_in) == res if not bol: print line_in f+=1 print "Errores: " + str(f) if __name__ == '__main__': print "-------------------------------------------------------------------------" b = input("probar con un string / probar con archivos con input-outputs [0/1]: ") print "-------------------------------------------------------------------------" if b==0: #s = "(90*r+b+(l*y)*95)*j*b*((g*51)+x)+29+g" s = raw_input("ingrese string: ") print "-------------------------------------------------------------------------" print p1(s) else: In = raw_input("ingrese nombre de archivo con inputs (ej: Arit_In.txt): ") Out = raw_input("ingrese nombre de archivo con outputs (ej: Arit_Out.txt): ") print "-------------------------------------------------------------------------" test(In, Out) print "-------------------------------------------------------------------------"
169a85b2227556f566a41c289a17a2f78db40b39
LeopoldACC/Algorithm
/周赛/week183/5377二进制变1.py
301
3.53125
4
class Solution: def numSteps(self, s: str) -> int: s = int(s,2) res = 0 while s !=1: if s%2==1: s+=1 res+=1 else: s//=2 res+=1 return res s =Solution() print(s.numSteps("1101"))
4b55a841cee8d6b37fb2b52c5943e688b167f7e9
MAK064/Python
/Python Challenge/1.py
278
3.71875
4
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] CypherIn = input("Input Cypher here:") count = 0 letter = 0 while True: letter = ord(CypherIn[count]) letter += 2 print(chr(letter)) count += 1
880b3b158b1f8e2b56d01ac8e6042cbd2d4b484a
Garrison-Shoemake/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
589
4.40625
4
#!/usr/bin/python3 """ This function will print a square equal to the size given """ def print_square(size): """ This function will raise errors if an integer is not given as well as if the value is equal or less than zero. """ if not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") if isinstance(size, float) and size < 0: raise TypeError("size must be an integer") for i in range(size): for j in range(size): print("#", end="") print("")
fd6911020e24d3803a1a2cb244068eff8a7d39d3
ssarangi/algorithms
/codeeval/hard/string_list.py
631
3.59375
4
import sys def string_list_helper(s, curr_str, N, results): if len(curr_str) == N: results.add(curr_str) return for i in range(0, len(s)): c = s[i] newstr = curr_str + c string_list_helper(s, newstr, N, results) def string_list(s, N): results = set() curr_str = "" string_list_helper(s, curr_str, N, results) results = sorted(results) return results with open(sys.argv[1], 'r') as test_cases: for test in test_cases: test = test.replace("\n", "") N, s = test.split(",") N = int(N) print(",".join(string_list(s, N)))
34e8d5c588eabf59060c347873016f0cb65191b3
sainingo/python-projects
/exercise.py
235
4.0625
4
#Create a program that asks the user to enter their name and their age name = input("Enter your Name: ") age = int(input("Enter your age: ")) in100 = age+100 print("Your name is "+ name +"" "and your will turn", in100,"in 100 years")
cd3783f42474e15fb46cbb93cf8f72924755b3d5
Meekol/BrainHackApp
/testing/testTkinter.py
689
3.578125
4
import tkinter as tk from tkinter import ttk window = tk.Tk() window.title("Brainhack Schedule App") window.minsize(600,400) def clickMe(): label.configure(text= 'Hello ' + name.get()) def clickSchedule(): print('do') label = ttk.Label(window, text = "Enter Input") label.grid(column = 0, row = 0) name = tk.StringVar() nameEntered = ttk.Entry(window, width = 15, textvariable = name) nameEntered.grid(column = 0, row = 1) button = ttk.Button(window, text = "Submit Info", command = clickMe) button.grid(column= 0, row = 2) button = ttk.Button(window, text = "Create Schedule", command = clickSchedule) button.grid(column= 0, row = 3) window.mainloop()
5118b53a4c5ea523dff54b06b296d90b45201497
sukhorukovmv/Python
/countWords.py
255
3.609375
4
#!/usr/bin/python3 string = str(input()).lower().split(' ') d = {} for word in string: d.setdefault(word, []).append(1) for i in d: #print(d[i]) #print(i.values()) print(i, sum(d[i])) ##a = list(d.values()) ##print(a) ##print(d)
49482c812b57c79ba52f0a8f243face216842817
technolingo/highpy
/singly_linked_list/tests/test_circular.py
786
3.765625
4
from unittest import TestCase from ..main import LinkedList, Node from ..circular import is_circular class IsCircularTestCast(TestCase): def test_circular(self): d = Node('d') c = Node('c', d) b = Node('b', c) a = Node('a', b) d.next = b llst = LinkedList(a) self.assertEqual(llst.get_first().data, 'a') self.assertEqual(llst.get_first().next, b) self.assertEqual(is_circular(llst), True) def test_non_circular(self): d = Node('d') c = Node('c', d) b = Node('b', c) a = Node('a', b) llst = LinkedList(a) self.assertEqual(llst.get_first().data, 'a') self.assertEqual(llst.get_first().next, b) self.assertEqual(is_circular(llst), False)
b477f1b76842f121324c9208b5e5762605b8121e
nchhaj189/deeplib
/test.py
605
3.546875
4
import neural from numpy import random from neural import Layers, NeuralNetwork if __name__ == "__main__": random.seed(1) layer1 = Layers(1,3) network = NeuralNetwork() network.addLayer(layer1) print (network.printweights) train_in = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) train_out = array([[0, 1, 1, 0]]).T network.train(train_in, train_out, 70000) print(network.printweights) print "Stage 3) Considering a new situation [1, 1, 0] -> ?: " output = network.calc(array([1, 1, 0])) print output