blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b99405d56570ccffea49b9f23782c97c040bda37
DrwIRC/NetworksProject1
/mailClient.py
798
3.640625
4
import smtplib """ Part 2 Project 1 Computer Networks Names: Brendan Malone and Sam Cesario The python scrpit below implements a simple STMP mail client. The code was tested on a cell phone's 4G connection """ serverName = raw_input('Name of SMTP SERVER to Connect to: ') sendFrom = raw_input('Send From: ') sendTo = raw_input('Send To (Can be multiple separate by a comma only): ') Mess = raw_input('Message (Only Text): ') sender = sendFrom receivers = sendTo.split(",") message = Mess #Connect to SMTP smtpO = smtplib.SMTP('smtp.gmail.com',25) print('Connected') smtpO.ehlo() smtpO.starttls() smtpO.ehlo() smtpO.login('SamDummy12@gmail.com','samgoogle') smtpO.sendmail(sender, receivers, message) smtpO.quit() print "From: " + sender + "\n" + "To: " + " , ".join(receivers) + "\n" + "Body: " + message + "\n"
9d11fb7098bfef403014f773edddba00a09d48e7
mengnan1994/Surrender-to-Reality
/py/0123_best_time_to_buy_and_sell_stock_iii.py
3,420
3.953125
4
""" Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). Example 1: Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. """ class Solution(object): def max_profit(self, prices): """ 有状态 闲置1,持有1,闲置2,持有2,闲置3 状态转换: 买入,卖出,等待 闲置1—等待-闲置1 闲置1-买入-持有1 持有1-等待-持有1 持有1-卖出-闲置2 闲置2-等待-闲置2 闲置2-买入-持有2 持有2-等待-持有2 持有2-卖出-闲置3 """ if len(prices) < 2: return 0 if len(prices) == 2: if prices[1] > prices[0]: return prices[1] - prices[0] else: return 0 days = len(prices) dp = {"idle1": [0 for _ in range(days)], "hold1": [0 for _ in range(days)], "idle2": [0 for _ in range(days)], "hold2": [0 for _ in range(days)], "idle3": [0 for _ in range(days)] } # 初始化: # 僵尸状态: dp["idle2"][0] = dp["hold2"][0] = dp["hold2"][1] = dp["idle3"][0] = dp["idle3"][1] = dp["idle3"][2] = - \ float("inf") # 第一天状态: dp["idle1"][0] = 0 dp["hold1"][0] = -prices[0] for day in range(1, days): dp["idle1"][day] = dp["idle1"][day - 1] dp["hold1"][day] = max( dp["idle1"][day - 1] - prices[day], dp["hold1"][day - 1]) dp["idle2"][day] = max( dp["hold1"][day - 1] + prices[day], dp["idle2"][day - 1]) dp["hold2"][day] = max( dp["idle2"][day - 1] - prices[day], dp["hold2"][day - 1]) dp["idle3"][day] = max( dp["hold2"][day - 1] + prices[day], dp["idle3"][day - 1]) print(max(dp["idle1"][-1], dp["hold1"][-1], dp["idle2"] [-1], dp["hold2"][-1], dp["idle3"][-1])) def max_profit_mem_opt(self, prices): idle1, hold1 = 0, -prices[0] idle2 = hold2 = idle3 = -float("inf") for day in range(1, len(prices)): idle1 = 0 hold1 = max(hold1, idle1 - prices[day]) idle2 = max(idle2, hold1 + prices[day]) hold2 = max(hold2, idle2 - prices[day]) idle3 = max(idle3, hold2 + prices[day]) return max(idle1, hold1, idle2, hold2, idle3) def test(self): prices = [1, 2, 3, 4, 5] self.max_profit(prices) Solution().test()
945643a1a3bb6d7790a84ddf8ffcb9c60efbd45e
PedroVitor1995/Algoritmo-ADS-2016.1
/testes/sorteio_questoes.py
282
3.65625
4
from random import shuffle def main(): sorteio(25, 10) def sorteio(qtd_itens, qtd_sorteio): lista = range(1, qtd_itens+1) shuffle(lista) print 'Questoes Sorteadas: ' for i in range(qtd_sorteio): print "\t %d >> %d" % (i+1, lista.pop()) if __name__ == '__main__': main()
ada8eb00516a8d56453159811370b323aee39581
AnoopKunju/code_eval
/moderate/city_blocks_flyover.py3
2,488
3.828125
4
#!/usr/bin/env python3 # encoding: utf-8 """ City Blocks Flyover Challenge Description: In our city we need to know how many blocks were impacted by a helicopter flying over our city. In our city, all of the blocks are rectangular. They are separated by N number of straight horizontal avenues that run East-West and M number of straight vertical streets which run North-South. A helicopter took off at the South-West corner of the city and flew directly to the farthest North-East corner. Your challenge is to determine how many city blocks it flew over? You will be given two lists, the first one is for streets and the second one is for avenues. Each avenue and each street is represented by a distance D to itself from the helicopter's starting point. E.g. manhattan_distance_1.jpg manhattan_distance_2.jpg On the first diagram the streets and the avenues are represented by the following lists: (0,1,3,4,6) for streets (0,1,2,4) for avenues The blocks the helicopter has flown over are colored dark grey. The inner region of each small rectangle is a city block. Rectangles' borders are not considered as a part of a block. Input Sample: Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Each test case will contain a list of distances for streets and a list of distances for avenues. Each list is in a brackets and the distances are separated by comma. The lists themselves are separated by a single whitespace. E.g. (0,2,4,8,10,13,14,18,22,23,24,33,40,42,44,47,49,53,55,63,66,81,87,91) (0,147,220) (0,1,2,4) (0,1,3,4,5) (0,1,3,4,6) (0,1,2,4) Output Sample: For each set of input print out the number of blocks the helicopter has flown over. E.g. 24 6 5 Constraints: N, M are in range [1, 100] D is in range [1, 1000] """ import sys with open(sys.argv[1], 'r') as input: test_cases = input.read().strip().splitlines() for test in test_cases: streets, avenues = test.split() streets_distances = [int(i) for i in streets.strip('())').split(',')] avenues_distances = [int(i) for i in avenues.strip('())').split(',')] intersections = [] x_step = avenues_distances[-1] / streets_distances[-1] y_step = streets_distances[-1] / avenues_distances[-1] for i in streets_distances[1:-1]: intersections.append((float(i), i * x_step)) for i in avenues_distances[1:-1]: intersections.append((i * y_step, float(i))) print(len(set(intersections)) + 1)
3de8e8c0178f2672eb5f90e2650330e469d545be
KimMooHyeon/Algorithm-Studying
/change_fah_cel.py
809
3.828125
4
# 화씨 온도에서 섭씨 온도로 바꿔주는 함수 def fahrenheit_to_celsius(fahrenheit): # 코드를 입력하세요. cel = (fahrenheit - 32) * 5 / 9 # 테스트용 온도 리스트 sample_temperature_list = [40, 15, 32, 64, -4, 11] # 화씨 온도 출력 print("화씨 온도 리스트: " + str(sample_temperature_list)) # 리스트의 값들을 화씨에서 섭씨로 변환 # 코드를 입력하세요. i = 0 while i < len(sample_temperature_list): sample_temperature_list[i] = (sample_temperature_list[i] - 32) * 5 / 9 sample_temperature_list[i]=round(sample_temperature_list[i],2) i = i + 1 # 섭씨 온도 출력 print("섭씨 온도 리스트: " + str(sample_temperature_list)) return cel fahrenheit_to_celsius(40)
efeb063f5a3e6487fd32ca00c145040188169425
JabirRahman/MITx-6.00.1x
/WeekTwo/SimpleAlgorithms/guessmynumber_solution.py
901
4.40625
4
#!/bin/bsh/ # Be careful about the 'input command'. It should be used only for later input # when user needs to answer with 'c', 'h' or 'l'. # No need to write a command to take input for the guessed number from the # user, just print a txt that will ask about the guessed number, like- # print('Please think of a number between 0 and 100!') low = 0 high = 100 print('Please think of a number between 0 and 100!') while True: guess = (high + low)//2 print('Is your secret number ' + str(guess) + ' ?') a = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if a == 'c': print('Game over. Your secret number was:', str(guess)) break elif a == 'l': low = guess elif a == 'h': high = guess else: print('Sorry, I did not understand your input.')
9f937d8e554a01b05444115f5b1240d290f1986b
VakinduPhilliam/Multiprocess_Parallelism
/Python_Multiprocessing_Queue.py
1,275
3.78125
4
# Python multiprocessing - Process-based parallelism # The following scripts are written to demonstrate multiprocessing (Process-based parallelism) # using Python. # Multiprocessing is a Python package that supports spawning processes using an API similar to # the threading module. The multiprocessing package offers both local and remote concurrency, # effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. # Due to this, the multiprocessing module allows the programmer to fully leverage multiple # processors on a given machine. It runs on both Unix and Windows. # The multiprocessing module also introduces APIs which do not have analogs in the threading module. # A prime example of this is the Pool object which offers a convenient means of parallelizing the # execution of a function across multiple input values, distributing the input data across processes # (data parallelism). # The Queue class is a near clone of 'queue.Queue'. from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) if __name__ == '__main__': q = Queue() p = Process(target=f, args=(q,)) p.start() print(q.get()) # prints "[42, None, 'hello']" p.join()
7d9e8980c15ab878cf8af5e88d69c6eda6796eb8
mikeyPower/python-programming-efficiently
/HackerRank/Finding The Percentage/finding_the_percentage.py
919
4.34375
4
''' You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer N followed by the names and marks for N students. You are required to save the record in a dictionary data type. The user then enters a student's name. Output the average percentage marks obtained by that student, correct to two decimal places. ''' if __name__ == '__main__': n = int(raw_input()) student_marks = {} for _ in range(n): line = raw_input().split() name, scores = line[0], line[1:] scores = map(float, scores) student_marks[name] = scores query_name = raw_input() total = 0; for i in student_marks[query_name]: total = total + i; average = total / len(student_marks[query_name]) print("%.2f" %average)
3296cedf812e1cf4be10e17f34284c5c6b4dc7ef
M1sterDonut/Exercises_Python-Crash-Course_Eric-Matthes
/motorcycles.py
1,714
4.28125
4
motorcycles = ['honda', 'yamaha', 'suzuki'] print (motorcycles) #replacing the first element motorcycles[0] = 'ducati' print (motorcycles) #adding elements - appending motorcycles.append('ducati') print (motorcycles) #adding to empty list motorcycles = [] motorcycles.append('honda') motorcycles.append('yamaha') motorcycles.append('suzuki') print(motorcycles) #inserting new element motorcycles = ['honda', 'yamaha', 'suzuki'] motorcycles.insert(0, 'ducati') print (motorcycles) #deleting list elements motorcycles = ['honda', 'yamaha', 'suzuki'] print (motorcycles) del motorcycles[0] print (motorcycles) motorcycles = ['honda', 'yamaha', 'suzuki'] print (motorcycles) del motorcycles[1] print (motorcycles) print (motorcycles[1]) #"popping" a motorcycle a.k.a. list item motorcycles = ['honda', 'yamaha', 'suzuki'] print (motorcycles) popped_motorcycle = motorcycles.pop() print (motorcycles) print (popped_motorcycle) motorcycles = ['honda', 'yamaha', 'suzuki'] last_owned = motorcycles.pop() print ('The last motorcycle I owned was a ' + last_owned.title() + '.') #Popping Items from any Position in a List motorcycles = ['honda', 'yamaha', 'suzuki'] first_owned = motorcycles.pop(0) print('The first motorcycle I owned was a ' + first_owned.title()+ '.') #Removing an Item by Value motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] print (motorcycles) motorcycles.remove('ducati') print (motorcycles) #use remove() method to work with a value removed from list motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] print (motorcycles) too_expensive = 'ducati' motorcycles.remove(too_expensive) print(motorcycles) print("\nA " + too_expensive.title() + " is too expensive for me.")
f01ffb2ddbc9ecbfd0ed0eae678f19052ffc4406
S4ND1X/365-Days-Of-Code
/Day 96/sortedByHeight.py
440
3.5
4
lista = [-1,150,190,170,-1,-1,160,180] listaNumeros = [] listaArboles = [] #?Guarda los numeros y si es -1 guarda su index for i in range(len(lista)): if lista[i] != -1: listaNumeros.append(lista[i]) else: listaArboles.append(i) listaNumeros.sort() #?Inserta un -1 en todos los indices guardados donde había un -1 for i in range (len(listaArboles)): listaNumeros.insert(listaArboles[i],-1) print(listaNumeros)
ee7508ac20324da8ad2691bb5ca84b1cbdf36abd
tjwhitaker/csu-oop
/python-library/library.py
4,781
3.625
4
import abc #Classes class Media: def __init__(self): return def compareCallNum(self, term): return term in self.callNum def compareTitle(self, term): return term in self.title def compareSubjects(self, term): return term in self.subjects @abc.abstractmethod def compareOther(self, term): pass @abc.abstractmethod def display(self): pass class Book(Media): def __init__(self, data): self.callNum = data[0] self.title = data[1] self.subjects = data[2] self.author = data[3] self.description = data[4] self.publisher = data[5] self.city = data[6] self.year = data[7] self.series = data[8] self.notes = data[9] def compareOther(self, term): return ((term in self.year) or (term in self.notes) or (term in self.description)) def display(self): print("---------------------------") print("Call Num: %s" % self.callNum) print("Title: %s" % self.title) print("Subjects: %s" % self.subjects) print("Author: %s" % self.author) print("Description: %s" % self.description) print("Publisher: %s" % self.publisher) print("City: %s" % self.city) print("Year: %s" % self.year) print("Series: %s" % self.series) print("Notes: %s" % self.notes) class Periodical(Media): def __init__(self, data): self.callNum = data[0] self.title = data[1] self.subjects = data[2] self.author = data[3] self.description = data[4] self.publisher = data[5] self.publishingHistory = data[6] self.series = data[7] self.notes = data[8] self.related = data[9] self.otherTitle = data[10] self.docNum = data[11] def compareOther(self, term): return ((term in self.series) or (term in self.notes) or (term in self.description) or (term in self.otherTitle)) def display(self): print("---------------------------") print("Call Num: %s" % self.callNum) print("Title: %s" % self.title) print("Subjects: %s" % self.subjects) print("Author: %s" % self.author) print("Description: %s" % self.description) print("Publisher: %s" % self.publisher) print("Publishing History: %s" % self.publishingHistory) print("Series: %s" % self.series) print("Notes: %s" % self.notes) print("Related: %s" % self.related) print("Other Title: %s" % self.otherTitle) print("Doc Num: %s" % self.docNum) class Film(Media): def __init__(self, data): self.callNum = data[0] self.title = data[1] self.subjects = data[2] self.director = data[3] self.notes = data[4] self.year = data[5] def compareOther(self, term): return ((term in self.year) or (term in self.notes) or (term in self.director)) def display(self): print("---------------------------") print("Call Num: %s" % self.callNum) print("Title: %s" % self.title) print("Subjects: %s" % self.subjects) print("Year: %s" % self.year) print("Notes: %s" % self.notes) print("Director: %s" % self.director) class Video(Media): def __init__(self, data): self.callNum = data[0] self.title = data[1] self.subjects = data[2] self.description = data[3] self.distributor = data[4] self.notes = data[5] self.series = data[6] self.label = data[7] def compareOther(self, term): return ((term in self.distributor) or (term in self.notes) or (term in self.description)) def display(self): print("---------------------------") print("Call Num: %s" % self.callNum) print("Title: %s" % self.title) print("Subjects: %s" % self.subjects) print("Description: %s" % self.description) print("Distributor: %s" % self.distributor) print("Series: %s" % self.series) print("Notes: %s" % self.notes) print("Label: %s" % self.label) class Engine: def __init__(self): self.catalog = [] self.results = [] def readFile(self, file, type): file = open(file, 'r') for line in file: data = line.split('|') if type == 'book': book = Book(data) self.catalog.append(book) elif type == 'film': film = Film(data) self.catalog.append(film) elif type == 'periodical': periodical = Periodical(data) self.catalog.append(periodical) elif type == 'video': video = Video(data) self.catalog.append(video) file.close() def search(self, option, term): #callNum if option == '1': for item in self.catalog: if item.compareCallNum(term): self.results.append(item) #title elif option == '2': for item in self.catalog: if item.compareTitle(term): self.results.append(item) #subject elif option == '3': for item in self.catalog: if item.compareSubjects(term): self.results.append(item) #other elif option == '4': for item in self.catalog: if item.compareOther(term): self.results.append(item) def displayResults(self): for item in self.results: item.display()
4d899a50832b312705dd9fdac934417e86d59dc0
oJacker/_python
/FullStack/02/formate_output.py
524
4
4
#!/usr/bin/env python # -*- coding:utf-8 -*- name = input("Please input Name: ") age = int(input("Please input Age: ")) job = input("Please input Job: ") salary = input("please input Salary: ") # Judge whether the salary is an integer if salary.isdigit(): salary = int(salary) else: exit("must input digit") msg = ''' ------------- about of %s -------- Name : %s Age : %d Job : %s Salary: %f You will be retired in %s years ---------------end ----------------- ''' % (name,name,age,job,salary,70-age) print(msg)
59f85aaa232ee44a8cea01169c042bb5993cea6d
mukeshdutt123/test-assessment
/nested- key-pair.py
240
3.578125
4
def returnobj(obj,key): obj1 = {} obj1 = obj keys = key.split('/') print(keys) i=0 for k in keys: for k[i] in obj1: for k[i] == obj1.items(i): continue Value = obj1[:- 1] return Value print(returnobj(obj,'x/y'))
3cdbde7f1435ef0fc65ab69b325fed08e1136216
cakmakok/pygorithms
/string_rotation.py
209
4.15625
4
def is_substring(word1, word2): return (word2 in word1) or (word1 in word2) def string_rotation(word1, word2): return is_substring(word2*2,word1) print(string_rotation("waterbottle","erbottlewat"))
1d6b70fbfa21da1a271394cd6c580e0669c688cc
AjaySoni3/python
/eaxm.py
539
3.59375
4
s = 'django' print(s[0]) print(s[-1]) print(s[0:-2]) print(s[1:-2]) print(s[-2:]) print(s[::-1]) l = [3,7,[1,4,'hello']] l[2][2] = 'goodbye' print(l) d1 = {'simple_key':'hello'} print(d1['simple_key']) d2 = {'k1':{'k2':'hello'}} print(d2['k1']['k2']) d3 = {'k1':[{'nest_key':['this is deep',['hello']]}]} print(d3['k1'][0]['nest_key'][1][0]) mylist = [1,1,1,1,1,2,2,2,2,3,3,3,3] x = set(mylist) print(x) age = 4 name = "Sammy" print(("hello my dog's name is {} and he is {} year old " .format(name,age)))
d42e10a34e85e1180089d26a88b8b607971b1f78
saitoasukakawaii/sort
/mergesort.py
560
3.90625
4
def merge(left,right): result = [] r,l = 0,0 while r<len(left) and l<len(right): if left[r] < right[l]: result.append(left[r]) r += 1 else: result.append(right[l]) l += 1 result += left[r:] result += right[l:] return result def merge_sort(lists): if len(lists) <= 1 : return lists else: num = len(lists)//2 left = merge_sort(lists[:num]) right = merge_sort(lists[num:]) return merge(left,right)
e97fe4da2b59f628a7736ebc40a4f2f79ff236e1
fatihkgm/mobileApplication-react-fench-id
/Desktop/Desktop/Semester5/AppliedScience/Python Programming/Week 05-Lecture/Lecture 05 Total Code/week_05_04.py
347
3.765625
4
def calc_tax(amount, tax_rate): tax = amount * tax_rate # tax is local variable return tax # return is necessary def main(): tax = calc_tax(85.0, .05) # tax is local variable print("Tax:", tax) # Tax 4.25 if __name__ == "__main__": # if main module main() # call main() function
25b22a561ec931bebaefb15fd487a45f0fb2adb1
siverka/codewars
/MultiplesOf3or5/multiples_of_3_or_5.py
475
4.40625
4
""" https://www.codewars.com/kata/multiples-of-3-or-5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Note: If the number is a multiple of both 3 and 5, only count it once. """ def multiples(number): var = [i for i in range(number) if i % 3 == 0 or i % 5 == 0] return sum(var)
10d874c19737e5b067485869dbdfeff24e39039d
BrunoCodeman/dojo_python
/callable/exercicio_callable.py
393
3.609375
4
#coding: UTF-8 ##Crie um script que obtenha todos os atributos da classe cachorro, ## separe métodos e atributos em listas diferentes e os exiba em sequência class Cachorro(object): def __init__(self, nome='Luke Skywalker', raca='Cocker Spaniel'): self.nome = nome self.raca = raca def latir(self): print('woof!') def lamber_a_cara_do_dono(self): print('Melhor limpar essa baba...')
68ce06953b5b98a430e0a24ffb049d5228ded6b8
Fleshner/NBA
/nba.py
1,448
3.515625
4
import json import re import statistics import requests print("-------------------------") x = input("Do you want to find the best player for your team? (Type Yes or No):") if (x == "Yes"): print("Great, let's do this. Here's the entire list of available players...") else: print("Alright, well good luck building a championship team without us! Have a good day :-)") exit() import json import requests import os from dotenv import dotenv_values from dotenv.main import load_dotenv load_dotenv() api = os.getenv("api") #url = 'https://api.sportradar.us/nba/{access_level}/{version}/{language_code}/league/free_agents.{format}?api_key={your_api_key}' #final_url = f'{url}' #url = "https://api.sportradar.us/nba/trial/v7/en/league/free_agents.json?" #final_url = f'{url}api_key={api}' import http.client conn = http.client.HTTPSConnection("api.sportradar.us") conn.request("GET", f"/nba/trial/v7/en/league/free_agents.json?api_key={api}") res = conn.getresponse() data = res.read() print(data) y = input("Now, what position are you looking for? (Input PG, SG, SF, PF, or C):") if (y == "PG"): print("Here's a list of available Point Guards:") if (y == "SG"): print("Here's a list of available Shooting Guards:") if (y == "SF"): print("Here's a list of available Small Forwards:") if (y == "SG"): print("Here's a list of available Power Forwards:") if (y == "C"): print("Here's a list of available Centers:")
1dcf1214fcefbc3ea1f80d273f1770c32e83a726
mumudexiaomuwu/Python24
/00Python/day02/basic01.py
1,101
4.125
4
# 查看关键字的模块 keyword import keyword print(keyword.kwlist) # 格式化输出print, %d代表占位符是一个整数 age = 12 print("我的年龄是%d岁" % age) age += 1 print("我的年龄是%d岁" % age) # 常用的格式符号 # %s -> string # %d -> int (digit) # %f -> float (%f占位符默认是显示小数点后6位的) # bool数值的格式化输出比较特殊(%s进行打印True/False, 或者%d打印1,非零即真) my_name = "小明" my_age = 25 is_man = True my_height = 180.88 print("我的姓名:%s" % my_name) print("我的年龄:%d" % my_age) print("我的身高:%f" % my_height) print("我的身高:%.2f" % my_height) print("我的性别为男:%s" % is_man) print("我的性别为男:%d" % is_man) # 在python百分号已经作为特殊符号,如果想表达一个%使用两个百分号替代一个百分号 purity = 86 print("纯度为:%d%%" % purity) # 换行输出只能使用\n print("Hello") print("Hello", end="\n") # 等同于上面的写法 print("Hello", end=" ") # 两个print同行 print("World") print("Hello\nWorld")
8e66c84344b7b7c8f53d536451dcf890bd5e7657
KittyKuttleFish/Python
/input_tests.py
127
3.71875
4
test = input("Please enter any string for input testing:") print("Testing String...") import time time.sleep(5) if(test)
21d6d0520b93f44f6d93c643fececc349149bbcc
phistrom/aws-region-proximity
/aws_region_proximity/command_line.py
2,194
3.578125
4
from . import regions from .__version__ import __version__ import argparse import json def get_closest_regions(*regions_available): """ Output a JSON dictionary where the key is an AWS region's code (i.e. us-east-1, eu-central-1, etc.), and the value is a list of all regions sorted by geographic proximity (for us-east-1, the list will be [us-east-1, us-east-2, ca-central-1, us-west-2, ...] You may optionally provide a list of regions. The return dictionary will always have one key for EVERY region, but the list of closest regions will be limited to those that you provide as arguments. :param regions_available: an optional list of regions to limit the output to :type regions_available: str :return: a dictionary where the keys are AWS region code names and the values are the list of all other regions in order of geographic proximity :rtype: dict[str, list[str]] """ closest_regions = {} for region in regions: key = region.code value = [r.code for r in region.closest_regions if (not regions_available) or r.code in regions_available] closest_regions[key] = value return closest_regions def cli(): """ Entrypoint for use in setup.py to make a console script named `aws-regions` :return: Prints the resulting dictionary from `get_closest_regions` to stdout """ parser = argparse.ArgumentParser("aws-regions", description="Generate a JSON map of regions with a list of all the other regions " "ordered by their geographic proximity.") parser.add_argument("regions", nargs="*", help="Optionally limit the list of closest regions to the ones specified on the command line.") parser.add_argument("-v", "--version", action="store_true", help="Prints the version (v%s) and exits." % __version__) args = parser.parse_args() if args.version: print("aws-region-proximity v%s" % __version__) exit(0) closest_regions = get_closest_regions(*args.regions) print(json.dumps(closest_regions, indent=4))
01f7dc2ee49e41dd10d3b0f2d7d2ed38b45f50f8
victormaiam/python_studies
/carro.py
696
3.984375
4
comando = "" carro_ligado = True while True: comando = input("> ").lower() if comando == "ligar": if carro_ligado: print ("Carro já está ligado") else: carro_ligado = True print("Carro ligou...") elif comando == "parar": if not carro_ligado: print("Carro já está parado.") else: carro_ligado = False print ("Carro parado") elif comando == "ajuda": print(""") ligar - para iniciar o carro parar - para parar o carro sair - para sair """) elif comando == "parar": break else: print("Desculpa não entendo o comando...")
1693e4d5f18d347c8ec5be538df5c5becd4ae866
Jigar710/Python_Programs
/ternary_op/map5.py
216
3.5625
4
lst1 = list(range(10,101,10)) print(lst1) lst2 = list(range(20,201,20)) print(lst2) def add1(a,b): return a+b lst3 = list(map(add1,lst1,lst2)) print(lst3) lst4 = list(map(lambda a,b:a+b,lst1,lst2)) print(lst4)
8b600cb7b0342ee83643acbfe35bc2421a5f9e0f
Erick2206/Data-Wrangling-using-MongoDB
/carriers.py
2,111
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Please note that the function 'make_request' is provided for your reference only. You will not be able to to actually use it from within the Udacity web UI. All your changes should be in the 'extract_carrier' function. Also note that the html file is a stripped down version of what is actually on the website. Your task in this exercise is to get a list of all airlines. Exclude all of the combination values like "All U.S. Carriers" from the data that you return. You should return a list of codes for the carriers. """ from bs4 import BeautifulSoup html_page = "options.html" def extract_carriers(page): data = [] skip=['All','AllUS','AllForeign','AllMajors','AllOthers'] with open(page, "r") as html: # do something here to find the necessary values soup = BeautifulSoup(html, "lxml") tags=soup.find('select',{'id':'CarrierList'}).children count=0 # print len(tags) for tag in tags: try: # print tag['value'] if tag['value'] in skip: # print '1' continue else: data.append(tag['value']) except: # print '2' continue print (data) return data def make_request(data): eventvalidation = data["eventvalidation"] viewstate = data["viewstate"] airport = data["airport"] carrier = data["carrier"] r = requests.post("http://www.transtats.bts.gov/Data_Elements.aspx?Data=2", data={'AirportList': airport, 'CarrierList': carrier, 'Submit': 'Submit', "__EVENTTARGET": "", "__EVENTARGUMENT": "", "__EVENTVALIDATION": eventvalidation, "__VIEWSTATE": viewstate }) return r.text def test(): data = extract_carriers(html_page) assert len(data) == 16 assert "FL" in data assert "NK" in data test()
f2b90a37b2b5f004098fb8d7d921e596d2da905d
jxa2009/spotify_buckets
/authorization.py
2,342
3.546875
4
import hashlib import base64 import random class auth: def __init__(self): self.code_verifier = '' self.hash_verifier = '' self.base64_verifier = '' self.code_challenge = '' # Generates a cryptographically random string between 43 adn 128 characters in length. Containing letters, digits, underscores, periods, hyphens, or tildes. # Returns the string generated def generate_code_verifier(self): crypto_random_string = 'abcdefghijklmnopqrstuvwxyz1234567890_.-~' lower_bound = 43 upper_bound = 128 code_verifier_len = random.randint(lower_bound, upper_bound) code_verifier = ''.join(random.choice(crypto_random_string) for _ in range(code_verifier_len)) return code_verifier # Hashes a given string using the SHA256 algorithm # Returns the hashed string def generate_hash_verifier(self,code_verifier_string): return hashlib.sha256(code_verifier_string.encode('utf-8')).hexdigest() # Base 64 encodes a given string # Returns encoded string as a string without byte object type def generate_base64_verifier(self, hash_verifier_string): enc = base64.standard_b64encode(hash_verifier_string) enc = enc.decode() return enc # Uses the classes functions to generate the code challenge all in one call # Returns the generated code challenge def generate_code_challenge(self): self.code_verifier = self.generate_code_verifier() self.hash_verifier = self.generate_hash_verifier(self.code_verifier) self.base64_verifier = self.generate_base64_verifier(self.hash_verifier.encode()) self.code_challenge = self.base64_verifier def getCodeChallenge(self): return self.code_challenge def getCodeVerifier(self): return self.code_verifier def main(): #print(read_client_credentials(client_credentials_file)) au = auth() au.code_verifier = au.generate_code_verifier() print("Code verifier: ", au.code_verifier) au.hash_verifier = au.generate_hash_verifier(au.code_verifier) print("Hash verifier: ", au.hash_verifier) au.base64_verifier = au.generate_base64_verifier(au.hash_verifier.encode()) print("Base64 Verifier: ", au.base64_verifier) if __name__ == '__main__': main()
3833fe93eafd7af25235afcd582c8fc8c95f19a9
wanglei007/dev-sprint2
/chap6.py
667
3.859375
4
# Enter your answrs for chapter 6 here # Name: Lei Wang # Ex. 6.6 def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] def is_palindrome(word): if len(word)==0 or len(word)==1: return True else: if first(word) == last(word): return is_palindrome(middle(word)) else: return False word = raw_input("give me a word: ") if is_palindrome(word): print "It is Palidrome!" else: print "Sorry, try another one" # Ex 6.8 GCD def GCD(a,b): if b==0: return a else: r = a % b return GCD(b, r) a = raw_input("give me a number: ") b = raw_input("give me another number: ") print GCD(int(a), int(b))
2018e507b1202403732ac9a9c206496b0ed07a01
ksj-123/pythonProject
/OO/ertek_visszaadas.py
349
3.84375
4
# saját típusból érték visszaadás class Point: def __init__(self, _x=0, _y=0): self.x = _x self.y = _y # origótól való távolság def distance_from_origin(self): return ((self.x ** 2) + (self.y ** 2)) ** 0.5 p = Point(5, 12) print(p.distance_from_origin()) q = Point() print(q.distance_from_origin())
812b677e4e432f3ee38134ea0d6e0570c1093db0
prashanthr11/Codevita-Practice
/Count the Factor.py
808
3.75
4
from math import factorial as ft def isprime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while(i * i <= n): if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True n = input() if n.isdigit() and int(n) > 0: n = int(n) n = ft(n) l = list() for i in range(2, 10000): if isprime(i): l.append(i) te = 0 ans = "" cnt = 0 while n != 1: if n % l[te] == 0: cnt += 1 n = n // l[te] else: ans += str(cnt) + " " cnt = 0 te += 1 print(ans + str(cnt)) else: print('Invalid Input')
5e30f782c2b2989bfb96cac1340ebbd0799d8298
fauzanardh/BINUS-Assignments
/Mr Jude/2019-09-30/e2_prices.py
223
3.890625
4
prices = { "banana": [4, 3], "apple": [2, 2], "orange": [1.5, 4], "pear": [3, 5] } total = 0 for x, y in prices.items(): print(f"{x}\nprice: {y[0]}\nstock: {y[1]}") total += y[0]*y[1] print(total)
c42869a5b6d2d2052c01b7305b35f59a03b2064a
YunJ1e/LearnPython
/DataStructure/Probability.py
1,457
4.21875
4
""" Updated: 2020/08/16 Author: Yunjie Wang """ # Use of certain library to achieve some probabilistic methods import random def shuffle(input_list): """ The function gives one of the permutations of the list randomly As we know, the perfect shuffle algorithm will give one specific permutation with the probability of 1/(# of element)! :param input_list: The list we need to shuffle :return: The shuffled list """ length = len(input_list) for i in range(length - 1, -1, -1): random_num = random.randint(0, i) input_list[random_num], input_list[i] = input_list[i], input_list[random_num] print(input_list) def reservoir_sample(sample, n, value): """ The function implements the reservoir sampling algorithm - reading part :param sample: The original sample :param n: Indicates the "value" is the n-th in the data stream :param value: Actual value in the data stream :return: tuple of the new sample and the "n" as a counter """ r = random.randint(0, n - 1) if r == 0: sample = value return sample, n + 1 def new_random(m, n): """ The function generate 0 ~ n-1 integers using randint(0, m-1) :param m: The random function m we have :param n: The random function n we need to build :return: randint(0,n-1) """ digit = 0 cur = n while cur > 0: cur = cur // m digit += 1 while True: sum = 0 for i in range(digit): sum = sum * m + random.randint(0, m - 1) if sum < n: return sum print(new_random(2, 1000))
ba9f1227c58e7468aea7bd269a63e08acc6f117b
IStoyanova/SmartCities_ParetOpt
/Tutorials/tutorial_uesgraph.py
8,647
3.953125
4
#!/usr/bin/env python # coding=utf-8 """ This is a tutorial script to learn about uesgraph.py usage and its main structure. Just run this script to start the tutorial. It is going to pause its execution at every user input function to go over every command step by step. Continue by pressing enter. You should follow the source code while executing the script to understand the Python networkx commands, which are not going to be printed in the output window. We recommend getting familiar with Python package networkx. networkx is a package to work with mathematical graphs. networkx.Graph inherites to uesgraph class. Thus, every attribute and method of networkx.graph can be used within uesgraph. See networkx stable docu at: https://networkx.readthedocs.org/en/stable/ """ import shapely.geometry.point as point # Import statement for networkx (as nx) import networkx as nx # Import statement to get uesgraph from updatedClassses import UESGraph_myVersion as uesgraph def run_part_1_nx_graph(): """ Executing tutorial code part 1 (networkx.Graph usage) """ print('1. Getting familiar with networkx.Graph:') print('#################################################') print('The class UESGraph is an inheritance from network.Graph.') print('Thus, UESGraph holds all methods and attributes of nx.Graph.') print('Please follow the lines within the source code!') # Here you are right :-) print('\nPress enter to continue:') input() print('Part 1.A') print('#---------------------------------------#') print('We are now going to create a graph object (with networkx.Graph) ') print('and add nodes and one edge.') # Generate an empty networkx.Graph graph = nx.Graph() # Adding node with id 1 to graph graph.add_node(1) print('\nPrint list of all nodes within graph: ', graph.nodes()) # Add further node with id 2 to graph graph.add_node(2) print('\nPrint list of all nodes within graph: ', graph.nodes()) # Add edge between node 1 and 2 graph.add_edge(1, 2) print('\nPrint list of edges of graph: ', graph.edges()) # We are now having a graph with two nodes, which are connected by an edge print('\nPress enter to continue:') input() print('Part 1.B') print('#---------------------------------------#\n') print('We are now going to add attributes to nodes and edges:') # Attributes are stored within dictionary (pairs of keys and values) # We assume that our graph represents a 'social network' (of two persons) # Adding an attribute "name" to node 1 graph.node[1]['name'] = 'Klaus' # In this case, 'name' is the dictionary key and 'Klaus' the value print('Print attribute "name" of node 1: ', graph.node[1]['name']) # Adding an attribute "name" to node 2 graph.node[2]['name'] = 'Claudia' print('Print attribute "name" of node 2: ', graph.node[2]['name']) # Adding an attribute "connection" to edge (1, 2) graph.edge[1][2]['connection'] = 'friendship' print('Print attribute "connection" of edge (1, 2): ' + graph.edge[1][2]['connection']) # Plot list of nodes with node data print('Show all nodes with attributes:', graph.nodes(data=True)) # Plot list of edges with edge data print('Show all edges with attributes: ', graph.edges(data=True)) print('\nFinished part 1') print('#################################################\n') def run_part_2_uesgraph(): """ Executes part 2 of uesgraph tutorial (general uesgraph usage) """ print('2. Getting familiar with uesgraph usage:') print('#################################################') print('Please follow the lines within the source code!') print('\nPress enter to continue:') input() print('Part 2.A') print('#---------------------------------------#') print('We are now going to generate a UESGraph and add building nodes, ' + 'street and heating network edges.') # Initialize uesgraph object ues_graph = uesgraph.UESGraph() # Plot description of uesgraph object print(ues_graph) # uesgraph has different attributes, which are initialized as empty lists # or dictionaries with emtpy lists print('Show uesgraph attribute nodelist_building (after init): ', ues_graph.nodelist_building) print('Show uesgraph attribute nodelist_heating (after init): ', ues_graph.nodelists_heating) # The attribue nodelist_building (list) holds every building node # The attribute nodelist_heating (dict) holds the network name as key # as well as a list of node ids as values print('\nPress enter to continue:') input() print('Part 2.B') print('#---------------------------------------#\n') print('Adding a building node to uesgraph object.') # Generate position as shapely Point object (coordinates 0 / 0) position_1 = point.Point(0, 0) # Add a building node with method add_building (with position as input) ues_graph.add_building(position=position_1) print('Nodelist_building', ues_graph.nodelist_building) # New node ids are automatically generated within uesgraph object, # starting with 1001 and counting up by 1 # Add two street nodes to uesgraph str_id_1 = ues_graph.add_street_node(position=point.Point(0, 5)) str_id_2 = ues_graph.add_street_node(position=point.Point(5, 5)) print('Nodelist_street', ues_graph.nodelist_street) print('Access data of street node 1: ', ues_graph.node[str_id_1]) # Add two heating network nodes ht_id_1 = ues_graph.add_network_node(network_type='heating', position=point.Point(5, 0)) ht_id_2 = ues_graph.add_network_node(network_type='heating', position=point.Point(10, 0)) print('Nodelists_heating:', ues_graph.nodelists_heating) print() """ print('Iteration control for heating network') for nodes in ues_graph.nodelists_heating['default']: print('Node number',nodes) input() """ # two street nodes and two heating network nodes. print('\nPress enter to continue:') input() print('Part 2.C') print('#---------------------------------------#\n') print('Now we are going to add street and heating network edges.') # Add street network edge (between node str_id_1 and str_id_2) ues_graph.add_edge(str_id_1, str_id_2, network_type='street') # We are adding an attribute 'network_type' as key with value 'street' print('Show all edges with data: ', ues_graph.edges(data=True)) # Add heating network edge (between node str_id_1 and str_id_2) ues_graph.add_edge(ht_id_1, ht_id_2, network_type='heating') # We are adding an attribute 'network_type' as key with value 'street' print('Show all edges with data: ', ues_graph.edges(data=True)) # Now the ues_graph holds a street and a heating network edge print('\nPress enter to continue:') input() print('Part 2.D') print('#---------------------------------------#\n') print('Now we are going add and remove a new building node') # Add a building node with method add_building b_id_new = ues_graph.add_building(position=point.Point(100, 100)) print('Nodelist_building (with new node): ', ues_graph.nodelist_building) # Remove new building node from uesgraph ues_graph.remove_building(node_number=b_id_new) print('Nodelist_building (after removal): ', ues_graph.nodelist_building) print('\nFinished part 2') print('#################################################\n') def run_tutorial_uesgraph(): """ Executes tutorial for uesgraph usage. """ print('Start of uesgraph tutorial') print('#################################################\n') print('General explanations:') print('uesgraphs is a Python package to describe and manage' + ' Urban Energy Systems in a Python graph structure.') print('Its main class is uesgraph.UESGraph. It manages structure and' + ' data of a district energy system') print('\nPress enter to continue:') input() # Executing part 1 of tutorial (networkx.graph usage) run_part_1_nx_graph() print('\nPress enter to continue:') input() # Execute part 2 of tutorial (uesgraph usage) run_part_2_uesgraph() print('End of tutorial') print('#################################################') if __name__ == '__main__': # Execute tutorial run_tutorial_uesgraph()
50e42ad88316d9de378e0515eb83afe808a2b452
kmantic/selfTaughtProgrammers
/fb.py
2,315
3.546875
4
#!/usr/bin/env python3 """ https://github.com/dev0ps221/wordgen/tree/dev?fbclid=IwAR1jRpl6r-9FJAoRhFzCm1NpDuNF0Dv0rS933q2HD_NwE3pzFxjSZ9vCZAs """ __author__ = "kharris" __version__ = "0.1.0" __license__ = "MIT" import sys #global list of lists lists = [] #################### ### def main(): print("main()") #init list of lists buildList() cnt = 0 while cnt < 5: cnt += 1 print("Running iteration #: ", cnt) cloneLastList() #send in the 2nd to last array (not the cloned array) flips = getFlipIndex(lists[ len(lists)-1 ]) #print("flips: ", flips[0], flips[1]) print("list now:", lists) flipAppropriateElem(flips) print("Final: ", lists ) #################### ### flip element value in last lists[list] (index to flip, letter to change to) def flipAppropriateElem(myTuple): lists[len(lists)-1][myTuple[0]] = myTuple[1] #################### ### def cloneLastList(): i = len(lists)-1 if len(lists) == 1: newList = lists[0].copy() else: newList = lists[i].copy() lists.append(newList) #################### ### build initial list def buildList(): if len(lists) == 0: lists.append([]) #modify range for desired list size (your problem has 8) for i in range(3): lists[0].append("a") #################### ### get next letter 'a' returns 'b', 'z' returns 'a', etc. def getNextLetter(s): return chr((ord(s.upper())+1 - 65) % 26 + 65).lower() #################### ### returns tuple (index, letter) in the last list in lists which is due to flip def getFlipIndex(myList): for idx, letter in enumerate(myList): if idx == 0: continue try: #print("idx: ", idx) #print("letter: ", letter) #print("last: ", myList[idx-1], "\n===========\n") if letter > myList[idx-1]: return (idx-1, getNextLetter(myList[idx-1])) except: print("exception") continue #list is done #modify to 7, 7 for list with size of 8 return (2, getNextLetter(myList[2])) if __name__ == "__main__": main()
b7686c8f7ea4268716724b05f6da1a4926a4eefd
ScytheSoftware/TulpeAndListConversion
/PythonApplication1.py
612
4.5
4
food_tuple = ("apple","Fries", "Pizza", "Chips", "Taco") new_list = list(food_tuple) new_item = input("Enter a new food item that you like!: ") new_list.append(new_item) new_food_tuple = tuple(new_list) #Checking if tuple try: check_tuple = input("List and Tuple switched!! Now try entering a new item: ") new_food_tuple[2] = check_tuple except TypeError: #I want this still to run to check if its back to a tuple, so I didn't use else. print("Checked, it's back to a Tuple") #printing tuple to screen print("\nHere's your list of Foods") for i in new_food_tuple: print("* " + i)
02fb888b42765dd84096807714ebdbb3466a0bcb
alasdairnicol/Project-Euler
/python/problem067.py
1,186
3.734375
4
""" Project Euler Problem 67 http://projecteuler.net/index.php?section=problems&id=67 By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o) """ from problem018 import process_input, get_max_total def solution(): """ Consider the following triange a b c the maximum total is a + max(b, c) """ # read triangle from text file and remove carriage returns triangle_as_string = open('triangle.txt', 'r').read().replace("\r", "") return get_max_total(process_input(triangle_as_string)) if __name__ == "__main__": print solution()
04478916f716c2ce5c822c160140168cb0857264
xiaolcqbug/aiai
/kubo/8月机试ll刘家昌/two线程.py
491
3.578125
4
# 线程两种写法 from threading import Thread import time # def task1(): # print('吃饭(第一种线程写法)') # # # def task2(): # print('喝水(第一种线程写法)') # # # if __name__ == '__main__': # p1 = Thread(target=task1) # p2 = Thread(target=task2) # p1.start() # p2.start() # 第二种线程写法 class mytheard(Thread): def run(self): print('第二种线程写法') if __name__ == '__main__': p = mytheard() p.start()
f5dbb4fb5d40471c4a4300d078c40a96f8ea768f
sachinsreedar92/essential-python-scripts
/WriteFile.py
787
3.625
4
import csv #Open file with "w"(write), the file will create automatically. file = open("/home/sachinsridhar/Desktop/staah.txt", "w") #Open CSV file to read CSV, note: reading and write file should be under "with" with open('/home/sachinsridhar/Desktop/NewStaah.csv') as csvFile: #Read CSV readCsv = csv.reader(csvFile) for row in readCsv: #Get Values and manupilate in the file.write Id = row[0] Id1 = row[1] #Write CSV you need format it to string if the value is an int file.write("Insert into product.chmm_hotel_merchant_map (ID,HOTEL_ID, MERCHANT_ID, STATUS, CREATED_BY, UPDATED_BY) values (product.CHMM_HOTEL_MERCHANT_MAP_SEQ.nextval,"+str(Id1)+", 6219839, 'A', 1,1);""\n") #You Must Close the FIle after writing it. file.close()
1442c1229a8c3c48f887a6eb955087cf8bedc3d2
Aravindan007/Python
/oops_circle.py
345
3.890625
4
class Circle: def __init__(self,r,r1): self.radius=r self.radius1=r1 def area(self): self.a=self.radius*2 print(self.a) def perimeter(self): self.p=self.radius1*2*3.14 print(self.p) s=Circle(2,3) s1=Circle(4,6) #s.display() s.area() s1.perimeter()
b42f23f4ebe9ae4af91255e2e2492f1cde1b018d
Peter-Varga08/LanguageTechnologyProject
/peregrine/gpu_test.py
1,250
3.625
4
import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout2d(0.25) self.dropout2 = nn.Dropout2d(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) # x represents our data def forward(self, x): # Pass data through conv1 x = self.conv1(x) # Use the rectified-linear activation function over x x = F.relu(x) x = self.conv2(x) x = F.relu(x) # Run max pooling over x x = F.max_pool2d(x, 2) # Pass data through dropout1 x = self.dropout1(x) # Flatten x with start_dim=1 x = torch.flatten(x, 1) # Pass data through fc1 x = self.fc1(x) x = F.relu(x) x = self.dropout2(x) x = self.fc2(x) # Apply softmax to x output = F.log_softmax(x, dim=1) return output network = Net() t = torch.ones(1,1,28,28) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") t = t.to(device) network.to(device) print(t.device) print(network) cpu_pred = network(t) print(cpu_pred.device)
7cdbea40b1c0370d7f5a56837c853a681c7518af
Gezort/MIPT-bioinformatics-2018
/10.py
436
3.515625
4
def distance(pattern, dna): k = len(pattern) n = len(dna) res = k for i in range(n - k + 1): dist = 0 for j in range(k): if pattern[j] != dna[i + j]: dist += 1 res = min(res, dist) return res def main(): pattern = input() dna_matrix = input().split() print(sum([distance(pattern, dna) for dna in dna_matrix])) if __name__ == '__main__': main()
1d2255908e878a8efd60632ed626031b727d0044
inzae1/pre-education
/quiz/pre_python_01.py
537
3.9375
4
"""1. 아래와 같이 숫자를 두번 물어보게 하고 ★을 출력해서 사각형을 만드시오 가로의 숫자를 입력하시오 : 세로의 숫자를 입력하시오 : 예시 <입력> 가로의 숫자를 입력하시오 : 5 세로의 숫자를 입력하시오 : 4 <출력> ★★★★★ ★★★★★ ★★★★★ ★★★★★ """ h = int(input('가로의 숫자를 입력하시오 :' )) v = int(input('세로의 숫자를 입력하시오 :' )) hs = '★' * h for i in range(v): print(hs)
dc5a7f84b32ee3fe21ef3ac7a6e00e05f4037181
2e0byo/OfficiumDivinum
/src/officiumdivinum/parsers/run_parser.py
4,231
3.75
4
""" Helper functions to run particular parsers on some or all files. These are provided since sometimes we read a single file and sometimes we must read many (with a glob). Parsers only handle single files, to aid standardisation. These functions print their output to stdout, for redirecting to a file. They also return it. """ from pathlib import Path from typing import List from typing import Union from jsonpickle import encode from ..objects import Feast from ..objects import Martyrology from . import K2obj from . import M2obj from . import P2obj from . import T2obj def sanctoral_to_json(fn: Path, calendar: str) -> str: """ Parameters ---------- fn : Path : File to parse. calendar : str : Calendar to use. Returns ------- str A Json str. """ days = [K2obj.parse_file(fn, calendar)] days = encode(days, indent=2) print(days) return days def martyrology_to_json(fn: Path) -> str: """ Parameters ---------- fn : Path : File to parse. Returns ------- str A Json str. """ day = M2obj.parse_file(fn) day = encode(day, indent=2) print(day) return day def temporal_to_json(fn: Path, calendar: str) -> str: """ Parameters ---------- fn : Path : The file to parse. calendar : str : The Calendar to use. Returns ------- str A Json str. """ day = T2obj.parse_file(fn, calendar) day = encode(day, indent=2) print(day) return day def pokemon( lang: str, calendar: str, root: str ) -> Union[List[Feast], List[Feast], List[Martyrology]]: """ Catch them all! Get all the relevant data for a particular calendar from a supplied root (which should be a cloned divinumofficium repository's web directory.) Parameters ---------- lang: str : The language, e.g. `Latin`. calendar: str : The calendar. root: str : The root, as a string. Returns ------- List Lists of Feast and Martyrology objects. """ root = Path(f"{root}/{lang}").expanduser() sanctoral = K2obj.parse_file( root / f"Tabulae/K{calendar}.txt", calendar, ) temporal = [] for f in (root / "Tempora").glob("*.txt"): temporal.append(T2obj.parse_file(f, calendar)) martyrology = [] for f in (root / "Martyrologium").glob("*.txt"): obj_or_objs = M2obj.parse_file(f) if isinstance(obj_or_objs, Martyrology): martyrology.append(obj_or_objs) else: martyrology += obj_or_objs psalms = {} for f in (root / "psalms1").glob("*.txt"): psalmno = f.stem psalm = P2obj.parse_file(f, lang) psalms[psalmno] = psalm return sanctoral, temporal, martyrology, psalms def pokemon_to_json(lang, calendar, root): """ Catch them all! (In json.) Like `pokemon`, but return encoded objects. Parameters ---------- lang: str : The language, e.g. `Latin`. calendar: str : The calendar. root: str : The root, as a string. Returns ------- str Json str. """ things = pokemon(lang, calendar, root) return (encode(i, indent=2) for i in things) if __name__ == "__main__": from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("INF", help="Input file.") parser.add_argument("--calendar", help="Select calendar.") actions = parser.add_argument_group("Actions") actions.add_argument("--martyrology", action="store_true") actions.add_argument("--sanctoral", action="store_true") actions.add_argument("--temporal", action="store_true") actions.add_argument("--pokemon", help="Get them all! Supply lang.") args = parser.parse_args() if any([args.sanctoral, args.temporal]) and not args.calendar: raise Exception("Calendar needed") inf = Path(args.INF).expanduser() if args.sanctoral: sanctoral_to_json(inf, args.calendar) if args.martyrology: martyrology_to_json(inf) if args.temporal: temporal_to_json(inf, args.calendar) if args.pokemon: pokemon_to_json(args.pokemon, args.calendar, args.INF)
7247f66bd60db09cc5196e9121d070f636bfba05
SamuelEngComp/RevisandoPython
/CAP-02/Numeros.py
587
3.953125
4
# Inteiros n1 = 10 n2 = 2 print(n1+n2) print(n1-n2) print(n1*n2) print(n1/n2) print(n1**n2) # Numeros de pontos flutuantes #Evitando erros de tipos idade = 26 # print("Samuel tem "+idade+"anos de idade") maneira errada, pois o python não conhece idade como STRING print("Samuel tem "+str(idade)+" anos de idade") #maneira certa é utilizando a função STR() print("Samuel tem "+str(2019-1992)+" anos de idade") #QUESTÃO DO NUMERO 8 print(5+3) print(10-2) print(4*2) print(16/2) print(2**3) numeroFavorito = 19 print("Meu numero favorito é: " + str(numeroFavorito) + " show !!! ")
5e0d88e4bcc3bacce6d9a82ba0e53f184dec6c00
YUNSERA/welcome
/9장 공부.py
643
3.5625
4
from tkinter import * class ProcessButtonEvent: def __init__(self): window = Tk() label = Label(window,text = "welcome to python.") button_OK = Button(window, fg ="red", bg = "white",text ="OK",command = self.processOK) button_Cancle = Button(window,text ="Cancle",command = self.processCancle) label.pack() button_OK.pack() button_Cancle.pack() window.mainloop() def processOK(self): print("OK버튼 눌림") def processCancle(self): print("Cancle버튼 눌림") ProcessButtonEvent()
c6be8a841e25ae3487c41f7d8f9b7aa5bca81acc
UnsupervisedDotey/Leetcode
/栈/844.py
786
3.65625
4
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: left_s = [] right_t = [] for _ in S: # print(_) if _ == "#" and len(left_s) != 0: left_s.pop() elif _ == "#" and len(left_s) == 0: pass else: left_s.append(_) for _ in T: # print(_) if _ == "#" and len(right_t) != 0: right_t.pop() elif _ == "#" and len(right_t) == 0: pass else: right_t.append(_) # print(left_s, right_t) return "".join(left_s) == "".join(right_t) if __name__ == "__main__": sol = Solution() print(sol.backspaceCompare(S = "ab#c", T = "ad#c"))
ff5a0ed68267800e9e64800ac5f489acbd1d8c9e
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4486/codes/1590_825.py
309
3.765625
4
# Teste seu codigo aos poucos. # Nao teste tudo no final, pois fica mais dificil de identificar erros. # Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo. import math R = float(input("Digite o raio:")) A = math.pi * R * R V = math.pi * R * R * R *4/3 print(round(A,3),round(V,3))
da3aead24ac7011cacd268b50bbf41e881e0ba93
ileaderx/pyClock
/flScreen.py
384
3.546875
4
from tkinter import * from tkinter import * import time root = Tk() clock = Label(root, font=('calibri', 150, 'bold'), background='black', foreground='white') clock.pack(fill=BOTH, expand=1) def tick(): s = time.strftime('%H:%M:%S %p') if s != clock["text"]: clock["text"] = s clock.after(200, tick) tick() root.mainloop()
0b6d054ffb45132d91d1715ea5d69d25d3d5ab03
ericgarig/daily-coding-problem
/092-course-prerequisites.py
1,875
3.828125
4
""" Daily Coding Problem - 2019-01-08. We're given a hashmap associating each courseId key with a list of courseIds values, which represents that the prerequisites of courseId are courseIds. Return a sorted ordering of courses such that we can finish all courses. Return null if there is no such ordering. For example, given {'CSC300': ['CSC100', 'CSC200'], 'CSC200': ['CSC100'], 'CSC100': []}, should return ['CSC100', 'CSC200', 'CSCS300']. """ import collections def solve(d): """ Given a list of prereqs, return the order courses must be taken in. NOTE: This assumes that courses are in only a single discipline ( and that courses prerequisites are a smaller course number ). """ od = collections.OrderedDict(sorted(d.items())) result = [] for id, prereq_list in od.items(): for one_course in prereq_list: if one_course not in result: break else: result.append(id) return result def solve_no_order_dict(d): """Return list of prereqs without using an ordered-dict.""" result = [] while True: for id, prereq_list in d.items(): for one_course in prereq_list: if one_course not in result: break else: result.append(id) del d[id] break else: if bool(d): return None return result print(solve({'CSC300': ['CSC100', 'CSC200'], 'CSC100': [], 'CSC200': ['CSC100'] })) # ['CSC100', 'CSC200', 'CSCS300'] print(solve_no_order_dict({'CSC300': ['CSC100', 'CSC200'], 'CSC100': [], 'CSC200': ['CSC100'] })) # ['CSC100', 'CSC200', 'CSCS300']
98358a5dd94f1a18198c4935c554420bc3ba10dc
ramya-creator/InnovationPython_Ramya
/Task7.py
3,794
4
4
"""1. Write a program that calculates and prints the value according to the given formula: Q= Square root of [(2*C*D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is a variable whose values should be input to your program in a comma-separated sequence. """ import math C = 50 H = 30 result = [] D = input("enter numbers seperated by ',': ") Ds = D.split(',') Ds = [int(a) for a in Ds] for i in Ds: Q=math.sqrt((2*C*i)/H) result.append(Q) print(result) """2. Define a class named Shape and its subclass Square. The Square class has an init function which takes length as argument. Both classes have an area function which can print the area of the shape where Shape’s area is 0 by default.""" class shape(): def __init__(self): pass def area(self): print(0) class square(): def __init__(self, length): self.length = length def area(self): a = (self.length * self.length) print("Area of square:", a) s = square(2) print(s.area()) print(shape().area()) #3. Create a class to find three elements that sum to zero from a set of n real numbers arr = [-25,-10,-7,-3,2,4,8,10] n = len(arr) def findTriplets(arr, n): f = True for i in range(0, n-2): for j in range(i+1, n-1): for k in range(j+1, n): if (arr[i] + arr[j] + arr[k] == 0): print(arr[i], arr[j], arr[k]) f = True if (f == False): print(" not exist ") findTriplets(arr, n) """4. Create a Time class and initialize it with hours and minutes. Create a method addTime which should take two Time objects and add them. Create another method displayTime which should print the time. Also create a method displayMinute which should display the total minutes in the Time. """ class Time: def __init__(self,hours,minutes): self.hours = hours self.minutes = minutes def addTime(t1,t2): t3 = Time(0,0) t3.hours = t1.hours + t2.hours t3.minutes = t1.minutes + t2.minutes while t3.minutes >= 60: t3.hours += 1 t3.minutes -= 60 return t3 def displayTime(self): print("Time is %d hours and %d minutes" %(self.hours, self.minutes)) def displayMinute(self): print((self.hours*60) + self.minutes, "minutes") a = Time(2,50) b = Time(1,20) c = Time.addTime(a,b) c.displayTime() c.displayMinute() """#5. Write a Person class with an instance variable “age” and a constructor that takes an integer as a parameter. The constructor must assign the integer value to the age variable after confirming the argument passed is not negative; if a negative argument is passed then the constructor should set age to 0 and print “Age is not valid, setting age to 0”. In addition, you must write the following instance methods: yearPasses() should increase age by the integer value that you are passing inside the function. amIOld() should perform the following conditional actions:I f age is between 0 and <13, print “You are young”. If age is >=13 and <=19 , print “You are a teenager”. Otherwise, print “You are old”.""" class Person: def __init__(self,age): if age<0: print("Age is not valid, setting age to 0") self.age=0 else: self.age=age def yearPasses(self,increase): self.age += increase return self.age def amIOld(self): if self.age>=0 and self.age<13: print("You are young") elif self.age>=13 and self.age<=19: print("You are a teenager") else: print("You are old") age=[-1,4,10,16,18,64,38] for i in age: a=Person(i) a.amIOld() a=Person(38) print(a.yearPasses(4))
4e42638ee793b6a803a4128df407d1046ea52ca1
AymenCharmi/Python-Class-2018
/Agenda.py
12,030
4.03125
4
#Faire un agenda où on peut ajouter ou supprimer un contact #structure: #Nom, prenom, telephone, adresse, email. #Ajouter - done #Modifier #search - done #Supprimer #Supprimer tous les contacts import getpass import csv # DISPLAY FUNCTION def displayContacts(): file = open("Agenda.csv", "r") for line in file: tab = line.split(";") print("{}; {}; {}; {}; {}".format(tab[0], tab[1], tab[2], tab[3], tab[4])) file.close() # --------------------------------------------------------------------------------------------------------------------- # ADDING FUNCTION def addContact(): # enter the elements needed, the sport, the team, the competition and the rank file = open("Agenda.csv", "a") familyName = input("Enter Name :\n") name = input("Enter firstname :\n") phoneNb = input("Enter phone number :\n") adresse = input("Enter adress :\n") email = input("Enter email adress :\n") file.write("{};{};{};{};{}\n".format(familyName,name,phoneNb,adresse,email)) file.close() # option to add another team print("\n\nDo you want to add annother contact? yes/no : ") choice = input("") if choice == "yes": addContact() else: print("\nalright here's the entire list") displayContacts() # --------------------------------------------------------------------------------------------------------------------- # MODIFY CONTACT def tab(): with open("Agenda.csv", 'r') as Fichier: n = [] p = [] t = [] a = [] m = [] for line in Fichier.readlines(): name, firstname, phone, address, mail = line.replace("\n", "").split(";") n.append(name) p.append(firstname) t.append(phone) a.append(address) m.append(mail) return n, p, t, a, m def renew_file(a, b, c, d, e): """ La fonction renouvelle le fichier csv en utilisant les elements présents en parametres. :param a: list :param b: list :param c: list :param d: list :param e: list :return: ecrire dans le fichier csv """ with open("Agenda.csv", "w") as fichier: for i in range(len(a)): fichier.write("{};{};{};{};{}\n".format(a[i], b[i], c[i], d[i], e[i])) def show(x): compt = [] mot = [] name, firstname, phone, address, mail = tab() for elem in name, firstname: for a, b in enumerate(elem): if x.lower() == b.lower(): print("Name: {}".format(name[a])) print("Firstname: {}".format(firstname[a])) print("phone: {}".format(phone[a])) print("Adress: {}".format(address[a])) print("Email Adress: {}\n".format(mail[a])) compt.append(a) mot.append(b) return compt, mot def modifyContact(): contact_modify = str Find = False g = True while g: name, firstname, phone, address, mail = tab() contact_modify = input("Which contact do you want to modify? ") for elem in name, firstname: for a, b in enumerate(elem): if contact_modify.lower() == b.lower(): print("\nhere's the contacts info {}".format(b)) ind_elem, element = show(b) Find = True if len(ind_elem) > 1: print("You have numerous {} in your contact list, Which one do you want to modify?".format(b)) for h, j in enumerate(element): print("\n{}- {} {}".format(h, name[ind_elem[h]], firstname[ind_elem[h]])) modification = int(input("\nWhich one do you want to modify? ---> ")) element_modifie = ind_elem[modification] else: element_modifie = ind_elem[0] choix_user = input("\nDo you still want to modify the contacts info? (yes/no) ---> ") if choix_user.lower() == "yes": elem_modify = int(input("What do you want to modify?" "\n1- Name" "\n2- Firstname" "\n3- Phone" "\n4- Adress" "\n5- Email adress" "\nVotre choix! ---> ")) if elem_modify == 1: new_name = input("enter new name: ") name[element_modifie] = new_name elif elem_modify == 2: new_prenom = input("Enter new firstname: ") firstname[element_modifie] = new_prenom elif elem_modify == 3: new_phone = input("Enter new phone number: ") phone[element_modifie] = new_phone elif elem_modify == 4: new_address = input("Enter new adress: ") address[element_modifie] = new_address elif elem_modify == 5: new_mail = input("Enter new email adress: ") mail[element_modifie] = new_mail renew_file(name, firstname, phone, address, mail) g = False elif choix_user.lower() == "no": break break g = False while Find is False: ajout = input("\n '{}' isn't in your contact list do you want to add him/her to your contact list? (yes/no)\n ---> ".format(contact_modify)) if ajout.lower() == "yes": addContact() Find = True elif ajout.lower() == "no": Find = True # --------------------------------------------------------------------------------------------------------------------- # SEARCH FUNCTIONS # search by Family Name def searchByFamilyName(): FamilyName = input("enter Family Name : ") file = csv.reader(open("Agenda.csv", "r"), delimiter=';') for row in file: if searchByFamilyName() == row[0]: print(row) # search by Name def searchByName(): name = input("enter name : ") file = csv.reader(open("Agenda.csv", "r"), delimiter=';') for row in file: if name == row[1]: print(row) # search by phone number def searchByPhoneNB(): phoneNb = input("enter phone number : ") file = csv.reader(open("Agenda.csv", "r"), delimiter=';') for row in file: if phoneNb == row[2]: print(row) # search by adress def searchByAdress(): adress = input("enter adress : ") file = csv.reader(open("Agenda.csv", "r"), delimiter=';') for row in file: if adress == row[3]: print(row) # search by email adress def searchByEmail(): email = input("enter email : ") file = csv.reader(open("Agenda.csv", "r"), delimiter=';') for row in file: if email == row[4]: print(row) # --------------------------------------------------------------------------------------------------------------------- # SEARCH MENU FUNCTION # gives you the choice for what you're looking for, a sport, a team, a competition or the ranking def search(): print("Enter 1 to search by Family Name") print("Enter 2 to search by Name") print("Enter 3 to search by phone Number") print("Enter 4 to search by adress") print("Enter 5 to search by email adress") src = int(input('Enter here : ')) if src == 1: searchByFamilyName() elif src == 2: searchByName() elif src == 3: searchByPhoneNB() elif src == 4: searchByAdress() elif src == 6: searchByEmail() else: print('sorry invalid input') # --------------------------------------------------------------------------------------------------------------------- # DELETE CONTACT def deleteContact(): element_modifie = int fini = False id_elem = [] element = [] name, firstname, phone, address, mail = tab() c_delete = input("Who do you want to delete? ") for elem in name, firstname: for a, b in enumerate(elem): if c_delete.lower() == b.lower(): id_elem.append(a) element.append(b) while fini is False: if len(id_elem) > 1: print("You have numerous {} in your contact list.\n".format(c_delete)) for h, j in enumerate(element): print("{} {} {}\n".format(h, name[id_elem[h]], firstname[id_elem[h]])) modification = int(input("\nWhich one do you want to delete? ---> ")) element_modifie = id_elem[modification] fini = True else: element_modifie = id_elem[0] break for i in name, firstname, phone, address, mail: i.remove(i[element_modifie]) renew_file(name, firstname, phone, address, mail) # --------------------------------------------------------------------------------------------------------------------- # DELETE ALL CONTACTS` def reEnterPassword(): pswd = '12345' password = input('re-enter password: ') if password == pswd: with open("Agenda.csv", "w") as f: f.write("Nom;Prenom;Telephone;Adresse;Email\n") return password def deleteAllContacts(): pswd = '12345' ch = False while ch is False: user_choice = input("Are you sure you want to delete all of your contacts? (yes/no)\n---> ") if user_choice.lower() == "yes": password = input('password:') while(password!=pswd): print("Wrong password") password = reEnterPassword() if password == pswd: with open("Agenda.csv", "w") as f: f.write("Nom;Prenom;Telephone;Adresse;Email\n") ch = True elif user_choice.lower() == "no": ch = True displayContacts() # --------------------------------------------------------------------------------------------------------------------- # MENU # gives you the choice to choose and when done calls the function loop to either quit or remake a choice def menu(): print("Enter 0 to quit") print("enter 1 to see contact list") print("Enter 2 to modify a contact") print("Enter 3 to search a contact") print("Enter 4 to add a contact") print("Enter 5 to delete a contact") print("Enter 6 to delete all contacts") choix = int(input("----> ")) if choix == 0: print("\nWe hope you had fun, see you next time!") quit() elif choix == 1: displayContacts() loop() elif choix == 2: modifyContact() loop() elif choix == 3: search() loop() elif choix == 4: addContact() loop() elif choix == 5: deleteContact() loop() elif choix == 6: deleteAllContacts() loop() # --------------------------------------------------------------------------------------------------------------------- # LOOPING MENU FUNCTION # gives you the choice to come back to the menu after an action def loop(): print("\n\nDo you want to go back to the menu? yes/no : ") choice = input("") if choice == "yes": menu() else: print("\nWe hope you had fun, see you next time!") quit() # --------------------------------------------------------------------------------------------------------------------- # MAIN def main(): print("\nWelcome to Sports Illustrated ") print("- we strive to bring the trends, news, and articles that are relevant to any sports fan.\n") menu() main()
9c10e783d4ee7090c9f2928c9bf140efc1ff6cdb
hector81/Aprendiendo_Python
/CursoPython/Unidad8/Ejemplos/funcion_modulo_os_access.py
974
3.78125
4
''' Saber si se puede acceder a un archivo o directorio. >>>os.access(path, modo_de_acceso) ''' import os path1 = os.access("/Users/user/Desktop/IV Curso AERTIC-UR. Tendencias en IT Iniciación a La Programación en Python 3/CursoPython", os.F_OK) print("Exists the path:", path1) # Checking access with os.R_OK path2 = os.access("/Users/user/Desktop/IV Curso AERTIC-UR. Tendencias en IT Iniciación a La Programación en Python 3/CursoPython", os.R_OK) print("Access to read the file:", path2) # Checking access with os.W_OK path3 = os.access("/Users/user/Desktop/IV Curso AERTIC-UR. Tendencias en IT Iniciación a La Programación en Python 3/CursoPython", os.W_OK) print("Access to write the file:", path3) # Checking access with os.X_OK path4 = os.access("/Users/user/Desktop/IV Curso AERTIC-UR. Tendencias en IT Iniciación a La Programación en Python 3/CursoPython", os.X_OK) print("Check if path can be executed:", path4)
8413b5eb2bfcd34d2dcb67f6499c0d9a6e9da2d1
timothymahajan/Project-Euler
/014/Longest_Collatz_Sequence.py
1,078
4
4
#Problem 14 ''' The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. ''' def Collatz(number): if (number==1): return 0 collatz = 1 while (number > 1): if(number%2 == 0): number = number/2 else: number = 3*number + 1 collatz = collatz + 1 return collatz collatz = 0 number = 0 for i in range(1, 1000000): col = Collatz(i) if (col >= collatz): collatz = col number = i print(number)
a5adee208d896de6de2a3c0c61e057d2deac0ddd
orlovskih/python_learning
/lesson_4/4_3.py
523
4.4375
4
'''Пользователь вводит любое целое положительное число (сделать проверку). Программа должна просуммировать все числа от 1 до введенного пользователем числа (не включая его). ''' a = int(input('Число:')) b = 0 if a <= 0: print('Число должно быть положительным') else: for i in range(a): b = b + i print('Сумма чисел =',b)
250510b82dd0f48cf7a3e44f646b12dd5270136a
clifflyon/fully-automatic-cross-associations
/cross_associations/plots.py
3,006
3.65625
4
""" plotting functions * plot shaded: show a summary of density for each cluster """ from collections import Counter import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np # from drawnow import drawnow, figure def get_density(matrix, q_col, q_row, col_cluster, row_cluster): """ Compute the density of a patch :param M: input matrix :param Q_col: column cluster memberships :param Q_row: row cluster memberships :param col_cluster: the row cluster :param row_cluster: the column cluster """ ones = 0 total = 0 for col in [_ for _, i in enumerate(q_col) if i == col_cluster]: for row in [_ for _, i in enumerate(q_row) if i == row_cluster]: ones += matrix[row, col] total += 1 assert total > 0 return ones * 1.0 / total def plot_spy(matrix_object, markersize=2, color="blue"): """ Plot sparse matrix like matlab :param matrix_object: matrix to plot :param markersize: how big is each data point :param color: what color is each point """ fig1 = plt.figure() ax1 = fig1.add_subplot(111, aspect='equal') ax1.spy(matrix_object.transformed_matrix, markersize=markersize, color=color) plt.show() def plot_spy_original(matrix_object, markersize=2, color="blue"): """ Plot sparse matrix like matlab :param matrix_object: matrix to plot :param markersize: how big is each data point :param color: what color is each point """ fig1 = plt.figure() ax1 = fig1.add_subplot(111, aspect='equal') ax1.spy(matrix_object.matrix, markersize=markersize, color=color) plt.show() def plot_shaded(matrix_object): """ plot greyscale density plot :param matrix_object: binary matrix with cluster attributes """ col_counter = Counter(matrix_object.col_clusters) row_counter = Counter(matrix_object.row_clusters) height, width = np.shape(matrix_object.matrix) fig1 = plt.figure() ax1 = fig1.add_subplot(111) ax1.set_xlim(right=width) ax1.set_ylim(top=height) # ax1.set_aspect("equal") col_offset = 0 for col, col_len in col_counter.most_common(): row_offset = 0 for row, row_len in row_counter.most_common(): density = get_density(matrix_object._dok_copy, matrix_object.col_clusters, matrix_object.row_clusters, col, row) ax1.add_patch( patches.Rectangle( (col_offset * 1.0, row_offset * 1.0), (col_offset + col_len) * 1.0, (row_offset + row_len) * 1.0, facecolor=str(1.0 - density), edgecolor="#0000FF", linewidth=1 ) ) row_offset += row_counter[row] col_offset += col_counter[col] ax1.invert_yaxis() plt.show()
5cafa82aa98cb0782ffe2b4f14d36bfabf2c681b
TheRealChrisM/CVGS-Computer-Science
/Python/fibRecursionTest.py
524
3.921875
4
#Christopher Marotta #15.7 Recursive #January 14, 2019 fibCount = 0 def fib(num): global fibCount fibCount = fibCount + 1 if num==1: result = 1 elif num == 0: result = 0 else: result = fib(num-1) + fib(num-2) return result playAgain = True while(playAgain): fibCount = 0 chosenNumber = int(input("Please input a number and it will calculate the Fibonacci value at that index: ")) print(fib(chosenNumber), " (Took " , fibCount, " calls to the fib function.)", sep = "")
36835f424d27e527676890b27b0496d96073492a
grogsy/python_exercises
/interview_question_examples/sort_by_bits.py
351
3.640625
4
# https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits from collections import defaultdict def sortByBits(arr): d = defaultdict(list) count = lambda num: bin(num).count('1') for num in arr: d[count(num)].append(num) output = [] for c in sorted(d.keys()): output += sorted(d[c]) return output
af4e14118ccc3c0e98fa52b16fcbcde9f0810724
Vluuks/Heuristieken
/manual_sorting.py
798
3.921875
4
swapcount = 0 def playSwap (alist, first, second): swapLength = len(alist[alist.index(first) : alist.index(second) +1 ]) alist[alist.index(first) : alist.index(second) +1 ] = reversed(alist[alist.index(first) : alist.index(second) +1 ]) print("\n", "swap length is:", swapLength) print(alist) melano = [23, 1, 2, 11, 24, 22, 19, 6, 10, 7, 25, 20, 5, 8, 18, 12, 13, 14, 15, 16, 17, 21, 3, 4, 9] miranda = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] print(miranda) print (melano) while melano != miranda: first = input("enter first number of swap: ") second = input("enter last number of swap swap: ") swapcount += 1 print(swapcount) playSwap(melano, first, second) print("Done! in", swapcount, "swaps!")
b38c298984b72c456cdda13761b6f76e53d7a361
duvallj/alpha-zero-general
/othello/tourney_files/my_core.py
3,623
3.671875
4
from .Othello_Core import * class MyCore(OthelloCore): def __init__(self): self.sq = self.squares() self.reset() self.players = BLACK + WHITE # self.scCount = 0 def reset(self): self.moves = {WHITE: None, BLACK: None} self.brackets = {WHITE: {}, BLACK: {}} def is_valid(self, move, board): """Is move a square on the board?""" return board[move] == EMPTY def opponent(self, player): """Get player's opponent piece.""" return self.players[player == BLACK] def find_bracket(self, square, player, board, direction): """ Find a square that forms a bracket with `square` for `player` in the given `direction`. Returns None if no such square exists. Returns the index of the bracketing square if found """ current = square + direction opponent = self.opponent(player) inbetween = False while board[current] == opponent: current += direction inbetween = True toreturn = None if board[current] == player and inbetween: toreturn = current return toreturn def is_legal(self, move, player, board): """Is this a legal move for the player?""" if not self.is_valid(move, board): return False for direction in DIRECTIONS: bracket = self.find_bracket(move, player, board, direction) if bracket is not None: return True return False ### Making moves # When the player makes a move, we need to update the board and flip all the # bracketed pieces. def make_move(self, move, player, board, real=True): """Update the board to reflect the move by the specified player.""" if not self.is_valid(move, board): return False toreturn = False for direction in DIRECTIONS: toreturn = self.make_flips(move, player, board, direction) or toreturn if toreturn: board[move] = player if real: self.reset() return toreturn def make_flips(self, move, player, board, direction): """Flip pieces in the given direction as a result of the move by player.""" oend = self.find_bracket(move, player, board, direction) if oend is None: return False spot = move while spot != oend: spot += direction board[spot] = player return True def legal_moves(self, player, board): """Get a list of all legal moves for player, as a list of integers""" if self.moves[player] is not None: return self.moves[player] else: moves = [spot for spot in self.sq if self.is_legal(spot, player, board)] self.moves[player] = moves return moves def any_legal_move(self, player, board): """Can player make any moves? Returns a boolean""" return bool(self.legal_moves(player, board)) def next_player(self, board, prev_player): """Which player should move next? Returns None if no legal moves exist.""" nplayer = self.opponent(prev_player) if self.any_legal_move(nplayer, board): return nplayer elif self.any_legal_move(prev_player, board): return prev_player else: return None def score(self, player, board): """Compute player's score (number of player's pieces minus opponent's).""" return board.count(player) - board.count(self.opponent(player))
ca24b56a383926f19ef37888caa487424ecd81a5
ramnathpatro/Python-Programs
/Functional_Programs/Flip_Coin.py
473
3.9375
4
import re import random inp = input("how many time you flip the coin") heads = 0 tails = 0 flip_coin = 0 check = re.search(r"^[\d]+$", inp) #print(check.group()) if check: inp = int(inp) while flip_coin < inp: flip_coin += 1 coin_tos = random.randrange(2) if coin_tos == 0: heads += 1 print("Head is", heads / inp * 100, "%") print("Tails", 100 - heads / inp * 100, "%") else: print("Enter the Number only")
96f2d35c3439bc739cdd912f4a7d92201f35d509
eg0rmeister/repo
/yield_test.py
356
3.8125
4
#!/usr/bin/python3 def foo(num): k = num while True: num += 1 print(str(k) + " is now " + str(num)) yield num val = [foo(0)] while True: for i in val: print(next(i)) a = input("input:") try: a = int(a) val.append(foo(a)) except ValueError: if a == "exit": exit()
9dcee4abf70892a7e4a725e01d78a72089cdf66d
macciocu/neuronbits
/breadth_first_vs_depth_first_search/bfs.py
2,517
3.96875
4
"""" Breadth First Search (BFS) """ import os import sys import queue import numpy as np import random from lib.node import Node class BFSNode(Node): def __init__(self, val, children=None): super().__init__(val, children) self._visited = False def visit(): self._visited = True def visited(): return self._visited def bfs_search(root: Node): if root is None: return queue = queue.Queue() # FIFO (First In First Out) queue.put(root) # add to end of queue while q.empty(): node = queue.get() # get first item for queue for child in node.children: if child.visited(): child.visit() queue.put(child) def create_random_weights_tree(tree_size): """ Creates a balanced tree structure of `tree_size` elements; inits each node with a random value between 0 and 1, and returns the root_node of the tree. """ root_node = BFSNode(random.random()) bottom_nodes = [ root_node, ] # holds nodes located at bottom of the tree nodes_count = 1 # counts total number of nodes in the tree while nodes_count < tree_size: next_bottom_nodes = [] # iterate through bottom tree nodes for node in bottom_nodes: if nodes_count + 2 > tree_size: # put in a last single node child = BFSNode(random.random()) node.children.append(child) next_bottom_nodes.append(child) nodes_count += 1 break else: # add 2 children nodes children = [BFSNode(random.random()), BFSNode(random.random())] node.children.extend(children) next_bottom_nodes.extend(children) nodes_count += 2 bottom_nodes = next_bottom_nodes return root_node def print_tree(root: Node, max_depth=10): iter_count = 0 bottom_nodes = [ root, ] while iter_count < max_depth: line = [] next_bottom_nodes = [] for node in bottom_nodes: line.append("{:.3f}".format(node.val)) next_bottom_nodes.extend(node.children) iter_count += 1 if len(next_bottom_nodes) == 0: break bottom_nodes = next_bottom_nodes print(" ".join(line)) if __name__ == "__main__": random.seed(1) root = create_random_weights_tree(100) print_tree(root, max_depth=10)
19f290884e9536f3cc313df2a78a385a9bf5ad09
tsupei/leetcode
/python/95.py
1,438
4
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def generateTreesOffset(self, n, offset): """ :type n: int :rtype: List[TreeNode] """ if n == 0: return [None] if n == 1: return [TreeNode(1+offset)] nodes = [] for root in range(1, n+1): left_nodes = self.generateTreesOffset(root-1, offset) right_nodes = self.generateTreesOffset(n-root, root+offset) for left_node in left_nodes: for right_node in right_nodes: root_node = TreeNode(root+offset) root_node.left = left_node root_node.right = right_node nodes.append(root_node) return nodes def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ return self.generateTreesOffset(n, 0) def vis(node, level): if not node: print("".join(["\t"] * level + ["null"])) return vis(node.left, level+1) print("".join(["\t"] * level + [str(node.val)])) vis(node.right, level+1) if __name__ == "__main__": sol = Solution() nodes = sol.generateTrees(3) print(nodes) for node in nodes: print("--") vis(node, 0)
6b230594f63919cae41f3f93e5a23af0a709923b
Akshatt/Leetcode-challenges
/July-leetcode/day9.py
1,249
4.125
4
''' Maximum Width of Binary Tree Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null. The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 q = [(root, 1)] ans = 1 while q: if len(q) >= 2: ans = max(q[-1][1] - q[0][1] + 1, ans) new_q = [] while q: node, pos = q.pop(0) if node.left: new_q.append((node.left, 2*pos)) if node.right: new_q.append((node.right, 2*pos + 1)) q = new_q return ans #Runtime: 40 ms #Memory Usage: 14.2 MB
3cdc3d54f6fb9b0b3acab04155ebf9307c885376
zby0902/algo
/linear/stack.py
1,548
3.84375
4
class Stack: """ A linear abstract data type that follow the rule of LIFO(last in first out) """ def __init__(self): self.items = [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def isEmpty(self): return self.items == [] def size(self): return len(self.items) def baseConverter(number,base): """ A base converter method based on the stack class """ if base > 16: raise ValueError('The limit of base is hex or 16') digits = '0123456789ABCDEF' rem_stack = Stack() while number > 0: rem = number % base rem_stack.push(rem) number = number//base num_string = '' while not rem_stack.isEmpty(): num_string += str(digits[rem_stack.pop()]) return num_string def parChecker(symbolString): """ A simple method checking the parentisises are balanced or not using stack """ s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol in '([{': s.push(symbol) else: top = s.pop() if not matches(top,symbol): balanced = False index += 1 if balanced and s.isEmpty(): return True else: return False def matches(openP,closeP): opens = '([{' closes = ')]}' return opens.index(openP) == closes.index(closeP)
044fdac9508f74c6cb5de0f6ab26926938baf40b
gschen/sctu-ds-2020
/1906101115-江汪霖/day0226/作业6.py
275
3.65625
4
def abc(n): s = 0 if n % 2 == 0: for i in range(2,n+1,2): a = 1/i s = s + a print(s) else: for i in range (1,n+1,2): a = 1/i s = s + a print(s) n = int(input('请输入n:')) abc(n)
67989cc7e7b1478e42feae45cc8823301afd0b57
the-eric-kwok/PyEditor
/library/demo_text_dnd.py
544
3.65625
4
import tkinter as tk import TkinterDnD2.TkinterDnD as tkdnd def drop(event): print("x: %d" % event.x_root, "y: %d" % event.y_root, "text:'%s'" % event.data) text.insert("@%d,%d" % (event.x_root, event.y_root), event.data) # You should be able to use "@60,306" as the first parameter # to .insert() to directly place the text at the drop location. root = tkdnd.Tk() text = tk.Text(root, width=50, height=10) text.pack() text.drop_target_register("DND_Text") text.dnd_bind('<<Drop:DND_Text>>', drop) root.mainloop()
0881521c9c51963287a0bc62aef4352472a999fa
kartik8460/python-with-dsa
/Data Structures/03CircularLinkedList/02PrintMethod.py
587
3.859375
4
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None def isEmpty(self): if self.head is None: print("Linked List is Empty") return True else: return False def printList(self): if self.isEmpty(): return temp = self.head while(temp.next != self.head): print(temp.data) if __name__ == "__main__": linkedList = CircularLinkedList() linkedList.printList()
3316ad34d2c6935146b7d7f38673d3300b5fbaf2
fangzhengo500/HelloPython
/chapter_5/chapter_5_7/chapter_5_7_1_pass.py
263
3.625
4
name = input('input a name:\n') if name in ['Ralph', 'Auldus', 'Melish']: print('Welcome!') elif name == 'Enid': # python 代码块不能为 pass,什么都不做 pass elif name in ['Bill', 'Gates']: print('Hello') else: print('Access Denied')
2ac070808731c89e041cf8d210bb0b71eae2a458
adamdrucker/raspberrypi-projects
/sitecrypt_bottle.py
4,808
3.96875
4
from random import randint from random import seed import random import time import os ALPHABET = "abcdefghijklmnopqrstuvwxyz" ALPHAUP = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" PUNC = ",.:;!?@#$%^&*-_`~/\[]{}()<>'\"" # 29 length # Seed to init random generator seed(random.randint(random.randint(0, 255), (random.randint(256, 511)))) # Generate two random numbers to be used in the OTP randomization r = random.randint(random.randint(0, 251), random.randint(257, 509)) s = random.randint(random.randint(521, 1021), random.randint(1031, 2039)) # Create one-time pad with randomized numbers def generate_otp(length): with open("otp.txt", "w") as f: for i in range(length): f.write(str(random.randint(r, s)) + "\n") # // File functions // # /////////////////// def load_sheet(filename): with open(filename, "r") as f: contents = f.read().splitlines() return contents def get_plaintext(): plain_text = input("Please type your message: ") return plain_text def load_file(filename): with open(filename, "r") as f: contents = f.read() return contents def save_file(filename, data): with open(filename, "w") as f: f.write(data) # // Encryption // # /////////////// ''' This function takes in a plaintext message and an OTP sheet from the ones generated in the first menu option. Any characters not in the ALPHABET/ALPHAUP/PUNC variables are added as is to the CIPHERTEXT variable. The ENCRYPTED value is derived from the index of each character in the ALPHABET plus the value in the 0-based corresponding position of the OTP text file. This is then modulus divided by the length of the string and the corresponding character at the index position is chosen as the ciphertext character. ''' def encrypt(plaintext, sheet): ciphertext = '' for position, character in enumerate(plaintext): if character in ALPHABET: encrypted = (ALPHABET.index(character) + int(sheet[position])) % 26 ciphertext += ALPHABET[encrypted] elif character in ALPHAUP: encrypted = (ALPHAUP.index(character) + int(sheet[position])) % 26 ciphertext += ALPHAUP[encrypted] elif character in PUNC: encrypted = (PUNC.index(character) + int(sheet[position])) % 29 ciphertext += PUNC[encrypted] else: ciphertext += character #print("Alphabet index char is: ", ALPHABET.index(character)) #print("Sheet pos is: ", int(sheet[position])) #print("Value of encrypted is: ", encrypted) return ciphertext # // Decryption // # /////////////// ''' Essentially the same operation as above, except characters in the CIPHERTEXT message are being applied to the PLAINTEXT variable, and index/sheet positions are subtracted from one another rather than added. ''' def decrypt(ciphertext, sheet): plaintext = '' for position, character in enumerate(ciphertext): if character in ALPHABET: decrypted = (ALPHABET.index(character) - int(sheet[position])) % 26 plaintext += ALPHABET[decrypted] elif character in ALPHAUP: decrypted = (ALPHAUP.index(character) - int(sheet[position])) % 26 plaintext += ALPHAUP[decrypted] elif character in PUNC: decrypted = (PUNC.index(character) - int(sheet[position])) % 29 plaintext += PUNC[decrypted] else: plaintext += character return plaintext # -------------------------------------------------------------------------------- #generate_otp(100) # Creates one 100-line text file called otp.txt #sheet = load_sheet("otp.txt") # Loads sheet for use in encryption #plaintext = get_plaintext() # Asks user for input #ciphertext = encrypt(plaintext, sheet) # Encrypts user input #save_file("encrypted.txt", ciphertext) # Saves encrypted message as encrypted.txt #print(load_file("encrypted.txt")) # Prints ciphertext #time.sleep(2) #print("Decrypting previous message...") #time.sleep(2) #ciphertext = load_file("encrypted.txt") # Loads encrypted contents into variable #plaintext = decrypt(ciphertext, sheet) # Decryption assigned to plaintext variable #print(plaintext) #time.sleep(1) #print("Removing One-Time Pad...") #os.remove("otp.txt") # Delete otp file from local directory #time.sleep(0.5) #print("Removing encrypted text file...") #os.remove("encrypted.txt") # Delete encrypted text file from local directory # -------------------------------------------------------------------------------- # How would both of those deletes work in the context of the website? Where would they # initially be stored? # Turn this stuff into functions
24856f5d3a2d0466e72d4d92e83e868fab9ff810
jflaboe/Project-Euler
/Euler50.py
1,255
3.6875
4
class Primes: def is_prime(self, num, update=True): if update is True: self._gen_primes_(num) for prime in self.primes: if prime >= num**(0.5)+1: return True if num % prime == 0: return False return True def _gen_primes_(self, max_val): if max_val > self.max_val: i = self.max_val while i < max_val: i += 1 if self.is_prime(i, update=False) is True: self.primes.append(i) self.max_val = max_val def __init__(self, max_val): self.primes = [2,3] self.max_val = 3 self._gen_primes_(max_val) primes = Primes(10000) total = 0 i = 0 while total < 1000000: total = total + primes.primes[i] i = i + 1 new_primes = primes.primes[0:i] max_chain = len(new_primes) chain = max_chain not_found = True while not_found is True: start = 0 while start <= max_chain - chain: total = sum(new_primes[start:start+chain]) if primes.is_prime(total): print(total) not_found = False break start = start + 1 chain = chain - 1
e12f3c00610569406645a9ae8bc41f759d6f78e7
ellaedmonds/CalcChap5Proj
/project.py
15,711
3.546875
4
''' project.py Katie Naughton and Ella Edmonds ''' from math import sin, cos, tan, acos, asin, atan from math import exp, expm1, e, pi from math import log, log10, sqrt, log2 from ggame import App, Color, LineStyle, Sprite from ggame import CircleAsset #inputs function=input("What function would you like to analyze? ") print("If you choose a log or sqrt function, make sure your interval is within the domain :)") x1=int(input("Where do you want your interval to start? ")) x2=int(input("Where do you want your interval to end? ")) print() print('f(x) graphed in blue') print("f'(x) graphed in purple") print('''f"(x) graphed in red''') print() #print(function) xcoordlist=[] #x values for i in range(x1,x2+1): if i == x2: xcoordlist.append(i+.0) else: for m in [.0,.1,.2,.3,.4,.5,.6,.7,.8,.9]: #print(i+m) xcoordlist.append(round((i+m),2)) #print(xcoordlist) a=False ycoordlist=[] #This prints a list of the y values. for r in xcoordlist: x=r Locfunction=function.lower() try: y=eval(Locfunction) ycoordlist.append(y) except: a=True asymptote=r print("There is a vertical asymptote at x=", asymptote, " in this function!") ycoordlist1=[] #this will find the a+.001 for the dq for r in xcoordlist: x=r+0.001 Locfunction=function.lower() y=eval(Locfunction) ycoordlist1.append(y) #print(ycoordlist1) ycoordlist2=[] #this will find the a+.001 for the sdq for r in xcoordlist: x=r-0.001 Locfunction=function.lower() y=eval(Locfunction) ycoordlist2.append(y) #print(ycoordlist2) intervalnum=len(ycoordlist1) #this tells us how long our cordinate lists are #print(intervalnum) #so we know how long to run the loop derivlist=[] #here we will make a list of the derivatives derivlist1=[] for s in range(intervalnum): deriv = ((ycoordlist1[s])-(ycoordlist2[s]))/(2*0.001) derivlist1.append(round(deriv,2)) derivlist.append(deriv) #print (derivlist) #deriv/x value/y value zip xyderivzip=list(zip(xcoordlist, ycoordlist, derivlist)) #print(xyderivzip) extremalist=[] #here we store the extrema points increasinglist=[] #here we store the interval where it inc/dec decreasinglist=[] zero = [] b = -1 c = 1 e=len(xyderivzip) for d in xyderivzip: B=xyderivzip[b] #here we got the values for the term before C=xyderivzip[c] #here we got the values for the term after if d[0] == xcoordlist[0]: #here the program check if we are dealing with the first term if d[2] >= 0: #if so this is automatically a max or min depending on if the deriv after it is - or + if d[1] < C[1]: print((d[0],round(d[1],2)),"is a local min") elif d[1] > C[1]: print((d[0],round(d[1],2)),"is a local max") zero.append((' ',d[0],'+',round(d[1],2))) if d[2] <= 0: if d[1] < C[1]: print((d[0],round(d[1],2)),"is a local min") elif d[1] > C[1]: print((d[0],round(d[1],2)),"is a local max") zero.append((' ',d[0],'-',round(d[1],2))) elif d[0] == xcoordlist[-1]: #here the program check if we are dealing with the last term if d[2] > 0: #if so this is automatically a max or min depending on if the deriv before it is - or + if d[1] < B[1]: print((d[0],round(d[1],2)),"is a local min") elif d[1] > B[1]: print((d[0],round(d[1],2)),"is a local max") zero.append(('+',d[0],' ',round(d[1],2))) if d[2] < 0: if d[1] < B[1]: print((d[0],round(d[1],2)),"is a local min") elif d[1] > B[1]: print((d[0],round(d[1],2)),"is a local max") zero.append(('-',d[0],' ',round(d[1],2))) else: #if the point is not an endpoint, the loop runs this if B[2]*d[2] > 0: #here it checks if the prior deriv and its teriv multiply to be more than 0 if d[2] > 0: #given the terms multipy to more than zero (indicating no sign change) increasinglist.append(d[0]) #if the deriv is greater than 0 then its inc at this point elif d[2] < 0: decreasinglist.append(d[0]) #if the deriv is less than 0 it is decreasing at the point elif B[2]*d[2] <= 0: #here we test for if the deriv is 0 the product is negative, insicating a sign change extremalist.append((d[0], d[1])) #we add the point to the extremalist if B[2] < 0 and C[2] < 0: #if deriv=0 and no sign change it goes here print('at',d[0],"the derviative DNE") elif B[2] < 0 and C[2] > 0: #if the deriv before is - and the deriv after is + we know it's a lacal min print((d[0],round(d[1],2)),"is a local min") increasinglist.append(d[0]) elif B[2] > 0 and C[2] < 0: #if the deriv before is + and the deriv after is - we know it's a lacal max print((d[0],round(d[1],2)),"is a local max") decreasinglist.append(d[0]) if B[2] < 0: #here we add + or - to our zero list indicating if the function is increasing or decreasing before our extrema before = '-' elif B[2] > 0: before = '+' if C[2] < 0: after = '-' elif C[2] > 0: after = '+' if d[2] == 0: zero.append((before,d[0],after,round(d[1],2))) elif B[2] != 0 and C[2] != 0: zero.append((before,(B[0]+d[0])/2,after,round(d[1],2))) #we make the zero list to work with later b+=1 c+=1 if c == e: c=0 #print(zero) maxlist = [] minlist = [] for d in zero: if d == zero[0]: themax = d[3] #sets "themax" as first y maxlist.append((d[1],d[3])) elif d[3] > themax: #if a value is greater than the max it maxlist = [] #resets the list of absmax points themax = d[3] #resets what "themax" is maxlist.append((d[1],d[3])) #added the (x,y) point elif d[3] == themax: maxlist.append((d[1],d[3])) #if the y is equal to the max it just adds the pount to the list if d == zero[0]: #here we do the same thing as we did for the max but with the min themin = d[3] minlist.append((d[1],d[3])) elif d[3] < themin: minlist = [] themin = d[3] minlist.append((d[1],d[3])) elif d[3] == themin: minlist.append((d[1],d[3])) print() for m in maxlist: print (m,"is an absolute max") for m in minlist: print(m,"is an absolute min") incstart = [] incend = [] decstart = [] decend = [] for d in zero: #here we use the zero list to determine the start values of inc and dec invervals if d[0] == '+': incend.append(d[1]) #if d[0] is + we know that d[1] will be the end of the increasing interval elif d[0] == '-': decend.append(d[1]) #if d[0] is - we know that d[1] will be the end of the decreasing interval if d[2] == '+': incstart.append(d[1]) #if d[2] is + we know that d[1] will be the begining of the increasing interval elif d[2] == '-': decstart.append(d[1]) #if d[2] is - we know that d[1] will be the begining of the decreasing interval print() #print(incstart) #print(incend) #print(decstart) #print(decend) if len(incstart) == 0: print("your function is never increasing.") else: print("Your function is increasing from:") for d in incstart: m = incstart.index(d) print(d,"to",incend[m]) print() if len(decstart) == 0: print("Your function is never decreasing.") else: print("Your function is decreasing from:") for d in decstart: m = decstart.index(d) print(d,"to",decend[m]) print() #second derivatives ycoordlista=[] for r in xcoordlist: x=r+0.002 Locfunction=function.lower() y=eval(Locfunction) ycoordlista.append(y) #print(ycoordlista) ycoordlistb=[] #This will find the y-.001 value for the symmetric differnce quotient. for r in xcoordlist: x=r-0.002 Locfunction=function.lower() y=eval(Locfunction) ycoordlistb.append(y) #print(ycoordlistb) intervalnum=len(ycoordlist1) #This tells us how long our cordinate lists are #print(intervalnum) #so we know how long to run the loop. derivlist=[] #This makes a list of the derivatives, and a rounded list derivlist1=[] #of the derivatives. for s in range(intervalnum): deriv = ((ycoordlist1[s])-(ycoordlist2[s]))/(2*0.001) derivlist1.append(round(deriv,2)) derivlist.append(deriv) #print (derivlist1) #print (derivlist) derivlista=[] #This makes a list of the derivatives, and a rounded list derivlista1=[] #of the derivatives. for s in range(intervalnum): deriva = ((ycoordlista[s])-(ycoordlist[s]))/(2*0.001) #derivlista1.append(round(deriva,2)) derivlista.append(deriva) #print (derivlista1) #print (derivlista) derivlistb=[] #This makes a list of the derivatives, and a rounded list derivlistb1=[] #of the derivatives. for s in range(intervalnum): derivb = ((ycoordlist[s])-(ycoordlistb[s]))/(2*0.001) #derivlistb1.append(round(derivb,2)) derivlistb.append(derivb) #print (derivlistb1) #print (derivlistb) deriv2list=[] deriv2list1=[] for s in range(intervalnum): deriv2 = ((derivlista[s])-(derivlistb[s]))/(2*0.001) #deriv2list1.append(round(deriv2,2)) deriv2list.append(deriv2) #print(deriv2list1) #print (deriv2list) xyderiv2zip=list(zip(xcoordlist, ycoordlist, derivlist, deriv2list)) #print(xyderiv2zip) poilist = [] #here we store the points of inflection cculist = [] #here we store the interval where it is ccu/ccd ccdlist = [] poi = [] b = -1 c = 1 e=len(xyderiv2zip) #THE TECHNIQUE HERE IS IDENTICLE TO THE MAX/MIN PART for d in xyderiv2zip: #just using the the second derivative instead of the first B=xyderiv2zip[b] C=xyderiv2zip[c] if d[0] == xcoordlist[0]: if C[3] > 0: poi.append((' ',d[0],'+')) if C[3] < 0: poi.append((' ',d[0],'-')) elif d[0] == xcoordlist[-1]: if B[3] > 0: poi.append(('+',d[0],' ')) if B[3] < 0: poi.append(('-',d[0],' ')) else: if B[3]*d[3] > 0: if d[3] > 0: cculist.append(d[0]) elif d[3] < 0: ccdlist.append(d[0]) else: poilist.append((d[0], d[1])) if B[3] < 0 and C[3] < 0: print((d[0],round(d[1],2)),"is just a 0") elif B[3] < 0 and C[2] > 0: print((d[0],round(d[1],2)),"is a poi from concave down to concave up") cculist.append(d[0]) elif B[3] > 0 and C[3] < 0: print((d[0],round(d[1],2)),"is a poi from concave up to concave down") ccdlist.append(d[0]) if B[3] < 0: before = '-' elif B[3] > 0: before = '+' if C[3] < 0: after = '-' elif C[3] > 0: after = '+' if B[3] != 0 and C[3] != 0: poi.append((before,d[0],after)) b+=1 c+=1 if c == e: c=0 #print(poi) if len(poi) == 2: print("There is no point of inflection") print() ccustart = [] ccuend = [] ccdstart = [] ccdend = [] for d in poi: if d[0] == '+': ccuend.append(d[1]) #if d[0] is + we know that d[1] will be the ending of the ccu interval elif d[0] == '-': ccdend.append(d[1]) #if d[0] is - we know that d[1] will be the ending of the ccd interval if d[2] == '+': ccustart.append(d[1]) #if d[2] is + we know that d[1] will be the begining of the ccu interval elif d[2] == '-': ccdstart.append(d[1]) #if d[2] is - we know that d[1] will be the begining of the ccd interval #print(ccustart) #print(ccuend) #print(ccdstart) #print(ccdend) if len(ccustart) == 0: print("your function is never concave up.") else: print("Your function is concave up from:") for d in ccustart: m = ccustart.index(d) print(d,"to",ccuend[m]) print() if len(ccdstart) == 0: print("Your function is never concave down.") else: print("Your function is concave down from:") for d in ccdstart: m = ccdstart.index(d) print(d,"to",ccdend[m]) #graphing code red = Color(0xff0000, 1.0) green = Color(0x00ff00, 1.0) blue = Color(0x0000ff, 1.0) black = Color(0x000000, 1.0) purple = Color(0x800080, 1.0) purple2 = Color(0x9932CC, 1.0) #This defines the points that will plot the function graph. thinline = LineStyle(1, blue) points = CircleAsset(2, thinline, blue) #This defines the coordinates to graph the original function. graphycoords=[y*-1 for y in ycoordlist] #print(graphycoords) xcoords = xcoordlist ycoords= graphycoords #print(xcoordlist) #print(ycoordlist) a = sqrt(x1**2) b = sqrt(x2**2) #This graphs the function. xycoords=list(zip(xcoords,ycoords)) for i in xycoords: Sprite(points, ((25*(i[0]+a+2),(25*(i[1]+10))))) #This defines the points that will plot the graph. thinline = LineStyle(1, purple) points = CircleAsset(2, thinline, purple) #This defines the coordinates to graph the derivative. graphy2coords=[y*-1 for y in derivlist] x2coords = xcoordlist y2coords = graphy2coords xy2coords=list(zip(x2coords,y2coords)) #This graphs the derivative. for i in xy2coords: Sprite(points, ((25*(i[0]+a+2),(25*(i[1]+10))))) thinline = LineStyle(1, red) points = CircleAsset(2, thinline, red) #This defines the coordinates to graph the derivative. graphy3coords=[y*-1 for y in deriv2list] x3coords = xcoordlist y3coords = graphy3coords xy3coords=list(zip(x3coords,y3coords)) #This graphs the second derivative. for i in xy3coords: Sprite(points, ((25*(i[0]+a+2),(25*(i[1]+10))))) myapp = App() myapp.run()
01697d5f5257710dd51213907e666e51876f05a5
InhwanJeong/TIL
/Algorithm/solve/backjoon/normal_1/5446_make_storage.py
2,379
3.609375
4
import sys class Trie: def __init__(self): self.root = {} self.locked_file = {} def show(self): print(self.root) print(self.locked_file) def insert(self, string): current_node = self.root for char in string: if char not in current_node: current_node[char] = {} current_node = current_node[char] def lock_file(self, string): current_node = self.locked_file for char in string: if char not in current_node: current_node[char] = {} current_node = current_node[char] def delete_all(self, delete_list): min_value = 0 for item in delete_list: if self.__search(item): min_value += 1 print(min_value) def __search(self, string): current_node = self.root for char in string: if char in current_node: current_node = current_node[char] else: return 0 self.__delete(string) return 1 def __delete(self, string): file_current_value = self.root lock_current_value = self.locked_file for i, char in enumerate(string): if char in lock_current_value: lock_current_value = lock_current_value[char] else: if i == 0: for j, key in enumerate(file_current_value.keys()): if key in list(lock_current_value.keys()): break if len(file_current_value.keys())-1 == j: self.root = {} del file_current_value[char] break file_current_value = file_current_value[char] if __name__ == '__main__': test_case = int(sys.stdin.readline()) for _ in range(test_case): trie = Trie() n = int(sys.stdin.readline()) delete_list = [] for _ in range(n): input_data = sys.stdin.readline().replace('\n', '') delete_list.append(input_data) trie.insert(input_data + '*') m = int(sys.stdin.readline()) for _ in range(m): input_data = sys.stdin.readline().replace('\n', '') trie.lock_file(input_data + '*') trie.delete_all(delete_list)
e157745f81eb22e2db7e7dc0ff4723436660a342
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 94 - Subsets.py
824
3.71875
4
# Subsets # Question: Given a set of distinct integers, nums, return all possible subsets. # Note: The solution set must not contain duplicate subsets. # For example: If nums = [1,2,3], a solution is: # [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]. # Solutions: class Solution: # @param {integer[]} nums # @return {integer[][]} def subsets(self, nums): if nums is None: return [] result = [] nums.sort() self.dfs(nums, 0, [], result) return result def dfs(self, nums, pos, list_temp, ret): # append new object with [] ret.append([] + list_temp) for i in range(pos, len(nums)): list_temp.append(nums[i]) self.dfs(nums, i + 1, list_temp, ret) list_temp.pop() Solution().subsets([1,2,3])
bf6ec7bc77607c70a8d8f8f3f17067dc4834693d
legioncode/WALaerospace
/code/classes/spacecraft.py
1,325
3.984375
4
class Spacecraft(object): """This object represents a spacecraft and its properties. It takes in 7 arguments: name, nation, payload-weight, payload-volume, mass, basecost and fuel-to-weight ratio. Furthermore this object can remember how many times it has been launched already, update its ratio, clear itself and compute its costs.""" def __init__(self, name, nation, payload, volume, mass, basecost, ftw): self.name = name self.nation = nation self.payload = payload self.firstpayload = payload self.volume = volume self.firstvolume = volume self.mass = mass self.basecost = basecost self.ftw = ftw self.assigned = [] self.ratio() self.clear() self.calculate() self.launches = 0 def ratio(self): # this is needed to make sure that if the space ship has an optimal # assignment (payload = 0) that `mw doesnt crash` if self.volume == 0: self.volume = 0.000000000000000000000000000000001 self.mv = self.payload / float(self.volume) def calculate(self): self.cost = (sum([i.mass for i in self.assigned]) + self.mass) * \ self.ftw / (1-self.ftw) * 1000 + self.basecost def clear(self): self.assigned = []
09b4c714095e3fa3860fe55e9966b9a1ad69729b
JoeKhoa/python_basic_
/Bài 31- Lệnh for else.mp4/for_else(same to while_else).py
195
3.765625
4
a = int(input('enter a number : ')) sum = 0 for n in range(5,10): if 4%a == 1: print('Exit the for_loop') break sum +=n else: print('the sum _ when a#3, a==2: ',sum)
70d06645ddebdf3a6cd892999b5f19ae323b9c65
sherwaldeepesh/Forsk-Python_Machine_Learning
/Day 7/Deepesh_Sherwal_26.py
511
3.5
4
# -*- coding: utf-8 -*- """ Created on Mon May 21 12:03:00 2018 @author: deepe """ from collections import OrderedDict dict1=OrderedDict() while True: string=raw_input() if not string: break tup=string.split(' ') key = " ".join(tup[:-1]).upper() value = int(tup[-1]) #list1.append((" ".join(tup[:-1]).upper(),int(tup[-1]))) if key in dict1: dict1[key] = dict1[key] + value else: dict1[key] = value for k,v in dict1.items(): print k,v
6e2261557ed43beb76614d2b5cc4a1b9d3da1938
chuymtz/python_scripts
/spyder_scripts/jan_workshop/so4.py
1,427
3.71875
4
# -*- coding: utf-8 -*- """ Python Workshop 1/30/2015 Exercise 4 1. Write a function that returns its GC-content when a sequence is given GC_Content = (#G + #C) / length(seq) 2. SeqForEX4.txt contains 5 different DNA sequences with its corresponding headers, find a way to read in the 5 sequences alone and print them out, respectively 3. Calculate the GC-content for all 5 sequences * Find the sequence with the highest GC-content, write its ID from header and its coresponding GC-content to a file named 'result.txt' @author: Yuan """ ################question 1############################# def GCCalculator(seq): return float((seq.count('C') + seq.count('G')))/len(seq) ################question 2############################## f = open('SeqForEX4.txt', 'r') allSeq = list() allID = list() for line in f: if line.startswith('>'): allID.append(line[1:5]) else: allSeq.append(line.strip()) for seq in allSeq: print seq #################question 3############################ GCContents = list() for seq in allSeq: GCContents.append(GCCalculator(seq)) print GCContents #################************############################ maxValue = max(GCContents) maxIndex = GCContents.index(maxValue) f = open('result.txt','w') f.write('%s %.2f' % (allID[maxIndex],maxValue)) f.close()
6b13da779299f107106c72067f7dec88111c24fb
expertbunny/expertbunny
/Hello World/Notes.py
2,951
4.125
4
#Basic of the python: print("@Bunny.io") print('o----') print(' ||||') print('*' * 10) # Variables of the python prgrams and that help to store data in the memory price = 10 price = 20 rating = 4.9 name_1 = 'Abhishek' is_published = True or False print(price) #Exicese no.1 name_2 = 'jhon smith' age = 20 is_new = True name_3 = input('What is your name? ') print('hi ' + name_3) #Exicese no.2 name_4 = input('what is your name?') color = input('what is your favourite color? ') print(name_4 + ' loves ' + color + ' colors') # Str and the Int Test birth_year = input('Birth year: ') print(type(birth_year)) age = 2020 - int(birth_year) print(type(age)) print(age) # Exicese no.2 weight_lbs = input('Weight (lbs): ') weight_kg = int(weight_lbs) * 0.45 print(weight_kg) # Strings Self_Intro = ''' Hi i am Expert Bunny ''' print(Self_Intro[0:9]) First = 'Smart' Last = 'bunny' message = First + '[' + Last + '] is a Expert' msg = f'{First} [{Last}] is a coder' print(msg) Time = 'The time is 12 right now' len(Time) Time.upper() Time.lower() Time.find(12) Time.title(Time) Time.replace() x = 10 x = x + 3 x += 3 print(x) x = 10 + 3 * 2 y = 11 + 2 * 3 print(y) All_is_well = True or False x = (2 + 3) * 10 - 3 print(x) import math print(math.floor(2.9)) is_hot = False is_cold = False if is_hot: print("It's a hot day") print("Drink plenty of water") elif is_cold: print("It is a cold day") print("Wear warm clothes") else: print("It is a lovely day") print("Enjoy your day") price = 1000000 has_good_credit = True if has_good_credit: down_payment = 0.1 * price else: down_payment = 0.2 * price print(f"Down_payment: ${down_payment}") has_high_income = True has_good_credits = True if has_high_income and has_good_credits: print("Eligiable for loan") has_good_credit = True has_criminal_record = True if has_good_credit and not has_criminal_record: print("Eligiable for loan") Temperature = 10 if Temperature < 10: print("It's a cold day") if Temperature > 30: print("It's a hot day") else: print("it's not a hot day") name = "smart" if len(name) < 3: print('name must be at the least 3 characters') elif len(name) > 50: print('name can be maximum of 50 characters') else: print('name looks good!') weigth = int(input("Weight: ")) unit = input('(L)bs or (k)g') if unit.upper() == "L": coverted = weigth * 0.45 print(f"You are {coverted} kilos abhishek") else: coverted = weigth / 0.45 print(f"You are {coverted} pounds abhishek") secret_number = 9 guess_count = 0 guess_limit = 3 while guess_count <guess_limit: guess = int(input('Guess: ')) guess_count += 1 if guess == secret_number: print("You Won!") break else: print("Sorry, you failed!")
708f74f96fd47c300d42a9a21697f641603fe170
lucasjurado/Curso-em-Video
/Mundo 3/ex114.py
258
3.609375
4
def quebra(): print('-'*20) def area(larg, comp): a = larg*comp print(f'A área do terreno {larg} x {comp} é de {a}m².') print('Controle de Terrenos') quebra() l = float(input('LARGURA (m): ')) c = float(input('COMPRIMENTO (m): ')) area(l,c)
e5b660256acefa34073903b956bb736c17ea3a70
Kajal2000/logical_question_python
/previouseven.py
327
4.0625
4
num = int(raw_input("enter a number")) i=1 var = num while i <= 3: var=var-1 if var%2==0: print "even h",var i = i + 1 a=1 while a <= 3: num=num+1 if num%2!=0: print "odd h",num a = a + 1 #user = int(raw_input("enter a number")) #i=1 #while i <= 3: # user=user-1 # if user%2==0: # print "even h",user # i = i + 1
de5acdb21a79a2fae7d23a4b9dc44b27cae46c0e
loss129/DiscreteHW8
/HW8.py
865
3.703125
4
import math import fractions import random import time import sys import numpy as np def findprimefactors(n): timer = time.time() factor = True # Start of the while loop to start the algorithm while (factor): #Get a random number within n for x x = random.randint(2,n-1) #Get a random number within n for r r = random.randint(2,n-1) # If the greatest common denomninator is greater than one then we have found a factor factor = fractions.gcd(np.absolute(x-r), n) if (factor > 1): # We only need one factor in order to find the other so we print the factors and break the while loop print(f'One factor: {factor}') print(f'Other factor: {n/factor}') print(f'For the number: {n}') print("%s Seconds Elapsed"%(time.time()-timer)) break # line to take the number from the command line findprimefactors(int(60477244035776630857))
ba47cbc62e34e7279da82b3a510a2363924c320f
yunyezl/algoitzman
/seongyong/Programmers/뉴스 클러스터링.py
1,233
3.734375
4
# Level 2 # 뉴스 클러스터링 # https://programmers.co.kr/learn/courses/30/lessons/17677 import copy def union(l1, l2): result = l1 for i in range(len(l2)): if l2[i] in result: if l2.count(l2[i]) > result.count(l2[i]): cnt = l2.count(l2[i]) - result.count(l2[i]) for _ in range(cnt): result.append(l2[i]) else: result.append(l2[i]) return len(result) def intersect(l1, l2): result = [] for i in range(len(l1)): if l1[i] in l2: result.append(l1[i]) del l2[l2.index(l1[i])] return len(result) def solution(str1, str2): str1 = str1.upper() str2 = str2.upper() list1 = [] list2 = [] for i in range(len(str1) - 1): if str1[i: i + 2].isalpha(): list1.append(str1[i:i + 2]) for i in range(len(str2) - 1): if str2[i: i + 2].isalpha(): list2.append(str2[i:i + 2]) if len(list1) == 0 and len(list2) == 0: return 1*65536 return int(intersect(copy.deepcopy(list1), copy.deepcopy(list2)) / union(list1, list2) * 65536) print(solution("aa1+aa2", "AAAA12"))
16e387e286c780b14cb656d4f6ee25325692b7b9
hjoel-code/Reliable-Autos-System
/system/model/Business/Customer.py
1,194
3.9375
4
from .Address import Address class Customer: #Constructor to initialise customer def __init__(self, fName='', lName='', email=''): self.fName = fName self.lName = lName self.email = email self.address = None #Setting customer's address def setAddress(self, addrLn1, addrLn2, addrLn3, parish): self.address = Address(addrLn1, addrLn2, addrLn3, parish) #Method to return the customer's full name as a string. def getFullName(self): return self.fName + " " + self.lName #Method to return customer's address as a string def getAddress(self): return self.address.toString() #Method to return customer's email as a string def getEmail(self): return self.email def toDict(self): if (self.address != None): self.address = self.address.__dict__ return self def toObject(self, obj): self.fName = obj['fName'] self.lName = obj['lName'] self.email = obj['email'] try: self.address = Address('','','','') self.address.toObject(obj['address']) except: self.address = None
7a514eb125b84961337919892b3646bfff2aea1b
yvinsam/PythonforML_UdemyCourse
/PCA_cheatsheet.py
1,526
4
4
#### Principal Component Analyis #####https://towardsdatascience.com/the-mathematics-behind-principal-component-analysis-fff2d7f4b643 ###The central idea of principal component analysis (PCA) is to reduce the dimensionality of a data set consisting of a large number ###of interrelated variables while retaining as much as possible of the variation present in the data set. This is achieved by transforming ### to a new set of variables, the principal components (PCs), which are uncorrelated, and which are ordered so that the first few retain most ## of the variation present in all of the original variables. ### Principal Component Analysis visualisation ## find what component are the most important ones in a classification ## use for high dimensional data from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(df) scaled_data = scaler.transform() #PCA from sklearn.decomposition import PCA pca = PCA(#spcifiy the number of components you want to keep n_components = 2) pca.fit(scaled_data) #transform the data into its first PC x_pca = pca.transform(scaled_data) scaled_data.shape() x_pca.shape() ### Plot PC plt.figure(#size of Plot ) ####### plot all the columsn plt.scatter(x_pca[:,0], x_pca[:,1]) plt.xlable('First Principal Component') #### array of com pca.components_ ## each row represents a principal component and each columns represent back to the data ### create a dataset with new PCP df_comp = pd.DataFrame(pca.components_, columns = cancer['feature_names'])
7efb1487717e1a9a78dadeb8f6c513e8ab7a447f
carlosjsaez/halite
/ian.py
2,047
3.53125
4
def change (elements) : elements [0] = 888 elements = [-3, -1, -2, -3, -4] print (elements[0]) numbers = [1, 4, 5] print (numbers [0]) change (numbers) print (numbers[0]) a = [1, 2, 3] b = a[-2: ] for i in b: i *=2 print(i) print ('a={}'.format(a)) print('b={}'.format(b)) a = [[1], [2], [3]] b = a[-2: ] for i in b: i *=2 print(i) print ('a={}'.format(a)) print('b={}'.format(b)) # 3.- 5-6 minutes, mostly to adjust the numbers N=10 def staircase(N): if N<1 or N>50: return print('N out of limits') for i in range(N): spaces = [' ' for x in range(N - i - 1)] hashes = ['#' for x in range(i+1)] line = ''.join( spaces + hashes) print(line) staircase(3) # 4.- 10 minutes test_str = 'abcd' def longestseq(test_str : str): chars = [x for x in test_str] max_seq = 1 cur_seq = 1 for i in range(len(chars)-1): if chars[i+1] == chars[i] : cur_seq += 1 if cur_seq > max_seq: max_seq = cur_seq else: cur_seq = 1 # print(max_seq) return max_seq longestseq(test_str) from unittest import TestCase def test_longestseq(): _ = None TestCase.assertTrue(_,longestseq('aabbfffc')==3) test_longestseq() class Node(): def __init__(self, value = 2, left = None, right = None): self.left = left self.right = right self.value = value def find(self, d): if self.data == d: return True elif d < self.data and self.left: return self.left.find(d) elif d > self.data and self.right: return self.right.find(d) return False def ispresent(d, node: Node): if node.value == d: return True elif d < node.value and node.left: return ispresent(d, node.left) elif d > node.value and node.right: return ispresent(d, node.right) else: return False def isPresent(value, node: Node): ispresent(2, d) c.r ight.value c= Node(5) b= Node(1) d = Node(3,b,c)
0d793cf72bea411038b8338fa2cd74b8660639f0
funaska/hse_homework_3
/first.py
783
4.15625
4
""" Напишите функцию calc_factorial, которая вычисляет факториал для любого неотрицательного целого числа """ import sys def calc_factorial(n): """ вычисляет факториал для любого неотрицательного целого числа вход: n - неотрицательное целое число выход: result - факториал от входного числа, int """ result = 1 if(n < 0): sys.exit('Входное число меньше ноля!') else: result = 1 for i in (range(1, n+1)): result *= i return result if __name__ == '__main__': print(calc_factorial(5))
08c905157904118e9d4680982805a205a1126117
renowator/Daily_Coding_Challenge
/util/util.py
1,206
3.515625
4
class Problem: def __init__(self): self.fn = lambda x: None def getSolution(self, solution): self.fn = solution def solve(self, args): return self.fn(args) class Test: def __init__(self, problem): self.test_result = [] self.grade = "" self.pr = problem def run_tests(self, i_o_dict): for in_val in i_o_dict: try: assert self.pr.solve(in_val) == i_o_dict[in_val], "Error" self.test_result.append(True) except AssertionError: self.test_result.append(False) return self.test_result def test_run(self, i_o_dict): self.test_result = self.run_tests(i_o_dict) if type(i_o_dict) is None: return None tests_passed = 0 for i in range(len(self.test_result)): if self.test_result[i]: tests_passed += 1 score = str(tests_passed*100/len(self.test_result)) self.grade += score + "%" return "Number of tests passed: {}\nNumber of tests failed: {}\nScore: {}".format(tests_passed, len(self.test_result) - tests_passed, self.grade)
7bd96d14baeddbc6aab0b9a52d5811e657751e12
markmrose/CS1101
/sort_fruits.py
1,369
4.1875
4
# sort_fruits.py # Written for Python 3.4.3 # Revision date: 3/15/15 # By: A. Programmer #--------------------------------------------------------------------------------------- # This program will sort the unsorted_fruits.txt file and write sorted_fruits.txt file back # # CAUTION: Make sure that the unsorted_fruits.txt file is in the same directory # that this program is run from. #--------------------------------------------------------------------------------------- # Lets open the file in the Python way and load the data into fruit infile=open("unsorted_fruits.txt", "r") outfile=open("sorted_fruits.txt", "w") # READ in the lines of the textfile into a LIST while eliminating the linefeeds fruit=infile.read().splitlines() # Get rid of the pesky blanks in the LIST and show the unsorted, cleaned list while '' in fruit: fruit.remove('') print("Unsorted text file with linefeeds and blanks removed:") print(fruit) print('\n') # SORT the fruits and show the list agin sorted this time fruit.sort() print("Sorted text to be written:") print(fruit) print('\n') # This is the header for the FOR LOOP which will write and print each line print("Show the records that are being written:") #FOR LOOP to write out the sorted fruits file for item in fruit: outfile.write("%s\n" % item) print("%s" % item) infile.close() outfile.close()
33373e26d1bd70e591ab1badaba5128611eea7d6
ChanR-Analytics/UCLA_M191
/src/myClass.py
433
3.9375
4
class myClass(): def __init__(self, myList): self.myList = myList def square(self): # Create a new list newList = [] # Loop through each number in the list for num in self.myList: # Square each number num = num**2 # Add the new numbers to the new list newList.append(num) # Save the new list as output return newList
0153573c91c17046dd61aacb9c1bc9861a240390
lan7012/homework
/体育竞技分析.py
1,313
3.6875
4
import random as r def printtip(): print("这个程序模拟两个选手A和B的某种竞技比赛") print("程序运行需要A和B的能力值(以0到1的小数表示)") def gameover(a, b): return a == 15 or b == 15 def ip(): a = eval(input("请输入A选手的能力值:")) b = eval(input("请输入B选手的能力值:")) n = eval(input("清输入场次数:")) return a, b, n def printend(vA, vB): n = vA + vB print("共模拟{}场比赛".format(n)) print("A获胜{}场比赛,占比{:0.1%}".format(vA, vA / n)) print("B获胜{}场比赛,占比{:0.1%}".format(vB, vB / n)) def OG(powerA, powerB): fsA, fsB = 0, 0 up = "A" while not gameover(fsA, fsB): if up == "A": if r.random() < powerA: fsA += 1 else: up = "B" else: if r.random() < powerB: fsB += 1 else: up = "A" return fsA, fsB def NG(n, powerA, powerB): vA, vB = 0, 0 for i in range(n): fsA, fsB = OG(powerA, powerB) if fsA > fsB: vA += 1 else: vB += 1 return vA, vB def main(): printtip() powerA, powerB, n = ip() vA, vB = NG(n, powerA, powerB) printend(vA, vB) main()
c06f88ed5d0d5b21c6672bb0b96d90c55249c2ba
Ak1zzi/python-stepik
/Ввод-вывод данных/Целочисленная арифметика. Часть 1/9.py
360
4.21875
4
# напишите программу, которая считывает целое положительное число x и выводит на экран последовательность # чисел x, 2x, 3x, 4x и 5x, разделенных тремя черточками. num = int(input()) print( num, num*2, num*3, num*4, num*5, sep='---' )
116ce23d270b00c2b96eca0a0613e8f717d45454
AbhinavNmdo/Python
/Learn_Lambda(Anonumous).py
111
3.640625
4
def sum(a, b): return a + b print(sum(5, 5)) # 0r addition = lambda a, b: a + b print(addition(10, 5))
e23dd0d3b7e1c63b81de94b73387d5496fd73d49
Juliemb15/GradesProject
/computeFinalGrades.py
957
3.78125
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 19 23:13:48 2020 @author: Peter """ import numpy as np def computeFinalGrades(grades): #sorting grades, so first value of array is the lowest value grades = np.sort(grades) #determining amount of graded assignments sizeofGrades = len(grades) #setting automatic failcheck fail = np.array([-3]) #Checking if student failed if fail in grades: gradesFinal = fail #Finding the final grade if two or more assignments have been graded #Dropping the first value which was sorted to be lowest grade elif sizeofGrades >= 2: gradesFinal = np.delete(grades, 0) ##replace np.mean with roundGrades function?## gradesFinal = np.mean(gradesFinal) #Setting final grade if one assignments have been grades elif sizeofGrades == 1: gradesFinal = grades return gradesFinal
8a846f6ebe2c094d8d4fe87ca036a1879d4b51fd
adalbertmwombeni/Ennos
/ennos2/avod/datasets/ennos/object_label.py
519
3.578125
4
class EnnosObjectLabel: """ Object label class for the ENNOS dataset """ def __init__(self, label: str): self.label = label # Object label (class) of the object, e.g. 'person' self.location = (0., 0., 0.) # location in 3D space (x, y, z) in meters self.sizes_3d = (0., 0., 0.) # object size in 3D (width (dx), length (dy), height (dz)) in meters self.rotation = (0., 0., 0.) # rotation around x, y and z axis self.truncation = 0. self.occlusion = 0.
33a0deb6523b1b2bf42456cafa0bcc8822da5243
Seungju182/Hackerrank
/algorithms/gem-stones.py
804
3.921875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'gemstones' function below. # # The function is expected to return an INTEGER. # The function accepts STRING_ARRAY arr as parameter. # def gemstones(arr): # Write your code here gem = 0 first = arr.pop() for letter in set(first): is_in = True for x in arr: if letter not in x: is_in = False break if is_in: gem += 1 return gem if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) arr = [] for _ in range(n): arr_item = input() arr.append(arr_item) result = gemstones(arr) fptr.write(str(result) + '\n') fptr.close()
2295d1b41b3d4f1d2a2e04794bc3e0097b7eeec7
subhambudhathoki007/projectclasswork
/practise/area_of_cir.py
151
4
4
#Program to find area of circle rad=float(input("enter radious of circle in m")) area=(22/7)*rad**2 print"enter area of circle",area,"meter squares")
f64f18f9ea0f14f457842c5310e8b16c87a56837
corganfuzz/opsoverloading
/chapter10/dickie.py
175
3.609375
4
class Person: def __init__(self, id): self.id = id sam = Person(100) sam.__dict__['age'] = 49 result = sam.age + len(sam.__dict__) print(result, sam.__dict__)
977d10f0a845050d840fddbd7331035a8f0a1ec4
ctac0h/jobeasy-algorithms-course
/Algorithms02/HW/Zeros Not For Heros.py
831
3.859375
4
# Numbers ending with zeros are boring. # They might be fun in your world, but not here. # Get rid of them. Only the ending ones. # # 1450 -> 145 # 960000 -> 96 # 1050 -> 105 # -1050 -> -105 # Zero alone is fine, don't worry about it. Poor guy anyway def get_rid_of_zeros(number): if number == 0: return 0 while number % 10 == 0: number = number // 10 return number def get_rid_of_zeros_str(number): if number == 0: return 0 return int(str(number).strip('0')) print(get_rid_of_zeros(1450)) print(get_rid_of_zeros(960000)) print(get_rid_of_zeros(1050)) print(get_rid_of_zeros(-1050)) print(get_rid_of_zeros(0)) print(get_rid_of_zeros_str(1450)) print(get_rid_of_zeros_str(960000)) print(get_rid_of_zeros_str(1050)) print(get_rid_of_zeros_str(-1050)) print(get_rid_of_zeros_str(0))
632a88edd30b7741f09211775ca7b77b70b35d92
wolfj95/mims-review
/parts.py
1,776
3.828125
4
from turtle import setheading, color, begin_fill, left, forward, right, end_fill, circle, fillcolor from helpers import restore_state_when_finished import math def ngon(num_sides, size): ''' This function draw a regular polygon with `num_sides` sides, each with length of `size`. ''' for i in range(num_sides): forward(size) right(360/num_sides) def draw_triangle(side_len, color_name): ''' This function draws an equilateral triangle with side lengths `side_len` and color `color_name`. ''' with restore_state_when_finished(): color(color_name) begin_fill() for i in range(3): forward(side_len) right(120) end_fill() def customized_circle(size, color_name): ''' This function draws a circle with radius `size` and color `color_name`. ''' color(color_name) begin_fill() circle(size) end_fill() def petal(size, color_name): ''' This function draws a single petal of a flower with size determined by `size` and of color `color_name`. ''' color("white") fillcolor(color_name) begin_fill() for i in range(int(size/2)): forward(i) right(360/size/2) right(90) for i in range(int(size/2)): forward(i) right(360/size/2) end_fill() def flower(size, num_petals, color_name, rotation): ''' This function draws a full flower with `num_petals` petals, each with size determined by `size` and color determined by `color_name`. `rotation` in a number of degrees that the flower should be rotated from 0 degrees (right). ''' for i in range(num_petals): setheading(rotation + (360/num_petals * i)) petal(size, color_name)