blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
cff067e503263ad0da8c6260f658ea9a114a5fab | DocNow/twarc | /utils/tweetometer.py | 1,364 | 3.890625 | 4 | #!/usr/bin/env python3
"""
Reads tweet or Twitter user JSON and outputs a CSV of when the user account was
created, how many tweets they have sent to date, and their average tweets per
hour. The unit of measurement can be changed to second, minute, day and year
with the --unit option.
"""
import json
import optparse
import fileinput
import dateutil.parser
from datetime import datetime, timezone
op = optparse.OptionParser()
op.add_option(
"--unit", choices=["second", "minute", "hour", "day", "year"], default="hour"
)
opts, args = op.parse_args()
if opts.unit == "second":
div = 1
elif opts.unit == "minute":
div = 60
elif opts.unit == "hour":
div = 60 * 60
elif opts.unit == "day":
div = 60 * 60 * 24
elif opts.unit == "year":
div = 60 * 60 * 24 * 365
now = datetime.now(timezone.utc)
print("screen_name,tweets per %s" % opts.unit)
for line in fileinput.input(args):
t = json.loads(line)
if "user" in t:
u = t["user"]
elif "screen_name" in t:
u = t
else:
raise Exception("not a tweet or user JSON object")
created_at = dateutil.parser.parse(u["created_at"])
age = now - created_at
unit = age.total_seconds() / float(div)
total = u["statuses_count"]
tweets_per_unit = total / unit
print("%s,%s,%s,%0.2f" % (u["screen_name"], total, created_at, tweets_per_unit))
|
d9b5276ab1adfac25c28ac1718e05bd122aaf0b2 | TheolZacharopoulos/algorithms-playground | /data_structures/strings/reverse_words.py | 1,256 | 4.53125 | 5 | # Write a function that reverses the order of the words in a string.
# For example, your function should transform the string "Do or do not, there is no try." to
# "try. no is there not, do or Do". Assume that all words are space delimited and treat punctuation the same as letters.
def reverse_words(string):
start = 0
end = 0
length = len(string)
# Reverse the entire string
string_arr = list(string)
reverse_word(string_arr, start, length - 1)
while end < length:
# skip non-word characters
if string_arr[end] != ' ':
# save the position of beginning of word
start = end
# scan to the next non-word character
while end < length and string_arr[end] != ' ':
end += 1
# back to the end of the word
end -= 1
# reverse the word
reverse_word(string_arr, start, end)
end += 1
return ''.join(string_arr)
def reverse_word(word_arr, start, end):
while start < end:
temp = word_arr[start]
word_arr[start] = word_arr[end]
word_arr[end] = temp
start += 1
end -= 1
return word_arr
print(reverse_words("Do or do not, there is no try."))
|
ea5d0c7f1863207c982c5e57005af3ee71080e25 | anant100/python-basics | /Type of Methods in Class.py | 1,024 | 4.15625 | 4 | # Types of Methods:
# - Instance Methods - It's used for Instance variables.
# - Class Methods - It's used for Class variables
# - Static Methods - It's used when you don't want to use Class OR Instance variable & you want to use any other instance variables
class Student:
# Class Variable
school = 'MCIT'
# Instance Method
def __init__(self, m1, m2, m3):
# Instance Variables
self.m1 = m1
self.m2 = m2
self.m3 = m3
def avg(self):
return (self.m1+self.m2+self.m3)/3
# Class Method
@classmethod
def get_school(cls):
return cls.school
# Static Method
@staticmethod
def info():
print("This is static Method. You can use any operation without using Class OR Instance variables.")
s1 = Student(10,30,40)
s2 = Student(20,30,40)
print("School name is: ", Student.get_school())
print("Avg for Student 1: ", s1.avg())
print("Avg for Student 2: ", s2.avg())
print()
Student.info()
|
c1ba1f3323cf4c9856fd4b85214f9177d05cde38 | tvelden/sciencemaps | /DiversityForFull.py | 6,189 | 3.890625 | 4 | # Dijkstra's algorithm for shortest paths
# David Eppstein, UC Irvine, 4 April 2002
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117228
import pprint, pickle
from priodict import priorityDictionary
import csv
from xml.dom.minidom import parse
import sys
def Dijkstra(G,start,end=None):
D = {} # dictionary of final distances
P = {} # dictionary of predecessors
Q = priorityDictionary() # est.dist. of non-final vert.
Q[start] = 0
for v in Q:
D[v] = Q[v]
if v == end: break
for w in G[v]:
vwLength = D[v] + G[v][w]
if w in D:
if vwLength < D[w]:
raise ValueError, \
"Dijkstra: found better path to already-final vertex"
elif w not in Q or vwLength < Q[w]:
Q[w] = vwLength
P[w] = v
return (D,P)
def shortestPath(G,start,end):
"""
Find a single shortest path from the given start vertex
to the given end vertex.
The input has the same conventions as Dijkstra().
The output is a list of the vertices in order along
the shortest path.
"""
D,P = Dijkstra(G,start,end)
Path = []
while 1:
Path.append(end)
if end == start: break
end = P[end]
Path.reverse()
return Path
def getDistance(G, Path):
i = 0
a = Path
distance = 0
while (i < (len(a)-1)):
firstP = a[i]
#print 'firstP::',firstP
secondP = a[i+1]
#print 'second::', secondP
distance = distance + G[firstP][secondP]
#print '::::', distance
i += 1
return distance
basemappath = str(sys.argv[1])
edgepath = str(sys.argv[3])
orginaldatapath = str(sys.argv[2])
whichfield = str(sys.argv[4])
if whichfield != '1' and whichfield != '2':
print "put 1 for field 1or 2 for field 2"
sys.exit()
#### readfile to get the list of CA
doc = parse(basemappath)
sequenceCA = {}
CAsequence = {}
sequence = 1
listCA = {}
articleIDandCA = {}
ID_Year_dict = {}
nodes = doc.getElementsByTagName('node')
for item in nodes:
listName = item.getAttribute('label')
listName = listName.replace('and', '&')
sequenceCA[sequence] = str(listName).lower()
CAsequence[str(listName).lower()] = sequence
listCA[str(listName).lower()] = 0
sequence += 1
####### read in.txt to save ID-year pair and ID-CA pair dictionaries
f = open(orginaldatapath, 'r')
#totalarticle = 0
while True:
line = f.readline()
if len(line) == 0:
break
else:
if len(line.partition(" ")[0]) == 2:
CurrentIndex = line.partition(" ")[0]
if CurrentIndex == 'ID':
#totalarticle += 1
CurrentID = line.partition(" ")[2].strip()
#print CurrentIndex
if CurrentIndex == 'BI':
line = line.strip()
year = line[-4:]
ID_Year_dict[CurrentID] = year
if CurrentIndex == 'CA':
field = str(line.partition(" ")[2]).strip()
if field.lower() in listCA:
articleIDandCA[CurrentID] = field.lower()
f.close()
ArticleIDList = list()
Year_ArticleIDlist_dict = {}
### key = ID value = year
for key, value in ID_Year_dict.items():
if not Year_ArticleIDlist_dict.get(value):
ArticleIDList = list()
ArticleIDList.append(key)
Year_ArticleIDlist_dict[value] = ArticleIDList
else:
ArticleIDList = Year_ArticleIDlist_dict[value]
ArticleIDList.append(key)
Year_ArticleIDlist_dict[value] = ArticleIDList
yearsequence_dict={}
yearStart=1991
index=1
while True:
yearsequence_dict[index]=yearStart
yearStart +=1
index+=1
if yearStart>2010:
break;
###### building edge Graph#######
f = open(edgepath, 'r')
G = {}
while True:
line = f.readline()
if len(line)==0:
break
else:
FirstV =int(str(line[0:4]).strip())
SecondV = int(str(line[5:9]).strip())
Value = float(str(line[10:]).strip())
Value = 1 - Value
if not G.has_key(FirstV):
G[FirstV]={}
if not G.has_key(SecondV):
G[SecondV]={}
G[FirstV][SecondV]=Value;
G[SecondV][FirstV]=Value;
f.close()
#for key, value in CAsequence.items():
# print key, ':', value
############# for each year, calculate Rao-Stirling Diversity
Year_RaoStirling = {}
for yearSequence, year in yearsequence_dict.items():
IDlist = []
IDlist = Year_ArticleIDlist_dict[str(year)]
TemplistCA = {}
TemplistCA = listCA.copy()
for item in IDlist:
TemplistCA[articleIDandCA[item]] = TemplistCA[articleIDandCA[item]] + 1
print year, 'total::', len(IDlist)
currentNode = 1
endNode = 224
totalFreq = float(len(IDlist))
totalDiversity = 0
while(currentNode < endNode):
if TemplistCA[sequenceCA[currentNode]] != 0:
nextNode = currentNode + 1
while(nextNode < endNode):
if TemplistCA[sequenceCA[nextNode]] != 0:
totalDiversity = totalDiversity + ((float(TemplistCA[sequenceCA[currentNode]])/totalFreq) * (float(TemplistCA[sequenceCA[nextNode]])/totalFreq) * getDistance(G, shortestPath(G,currentNode, nextNode)))
nextNode = nextNode + 1
currentNode = currentNode + 1
#print totalDiversity
Year_RaoStirling[year] = totalDiversity
#csvfile = open('field1diversity.csv', 'wb')
CSVFile = 'field' + whichfield + 'diversity.csv'
with open(CSVFile, 'wb') as f:
csvWriter = csv.writer(f)
csvWriter.writerow(['year', 'value', 'total'])
for key, value in yearsequence_dict.items():
temp = list()
temp.append(value)
temp.append(Year_RaoStirling[value])
temp.append(float(len(Year_ArticleIDlist_dict[str(value)])))
csvWriter.writerow(temp)
print value, ':', Year_RaoStirling[value], ':', str(float(len(Year_ArticleIDlist_dict[str(value)])/1000.0))
#for key, value in sequenceCA.items():
# if TemplistCA[value] != 0:
############# with R.py
|
3448d145170d837ac710a911194bcd32258c4c92 | davidd1990/GeneradorPrimos | /GeneradorMultiProcess.py | 1,725 | 3.609375 | 4 | from multiprocessing import Pool
import time
n = 100
p = [2, 3, 5, 7]
r = 0
def encontrarprimos(n):
p = [2] + [x for x in range(3, n + 1, 2) if
not [y for y in range(3, int(x ** 0.5) + 1, 2) if (float(x) / y).is_integer()]]
print(p)
print("suma de la lista : ", sum(p))
def encontrar_primos_threads(n):
aux = n
global p
if not(dividir(aux)):
p.append(aux)
return aux
def dividir(x):
for y in range(3, int(x ** 0.5) + 1, 2):
if (float(x) / y).is_integer():
return True
if __name__ == "__main__":
v = "y"
while v == "y":
n = raw_input("Que numero deseas calcular")
try:
n = int(n)
print("Calculando.....")
t = time.time()
proc = Pool()
result = [2] + proc.map(encontrar_primos_threads, range(3, n + 1, 2))
proc.close()
proc.join()
result = filter(None, result)
print(result)
print("trabajo terminado con multiprocesamiento : ", time.time() - t)
# Aqui empieza el metodo normal sin ningun Thread
t = time.time()
encontrarprimos(n)
print("trabajo terminado sin multiprocesamiento en : ", time.time() - t)
v = raw_input("Deseas colocar otro numero y/n")
a = True
while a:
if v == "y" or v == "n":
a = False
else:
print("No entiendo lo que dices")
v = raw_input("Deseas colocar otro numero y/n")
except ValueError:
print("Debes colocar un numero =(")
print("Gracias por participar")
|
92d8d4df0de5a3d5aed9cb6f9fb81229ccaba202 | EGruenemeier984/CS126_Lab4 | /lab4.py | 3,830 | 3.9375 | 4 | # Ethan Gruenemeier- emg433@nau.edu
# Sam Hemmelgarn- sph227@nau.edu
# imports the random library from python
import random
# These are global variables for the squares that will appear to the user
X = "\u25A1"
Y = "\u25A0"
Z = [X, Y]
maps = {X: Y, Y: X}
# The main funct calls the game function with the
# creategrid function as the argument.
def main():
game(createGrid())
# This function creates a multi dimensional list of
# unicode squares randomly and formats them into a five by five grid.
def createGrid():
board = [[X, Y, X, Y, X], [X, Y, Y, X, X], [X, Y, Y, Y, X],
[Y, X, Y, X, X], [Y, Y, X, X, X]]
random.shuffle(board)
for rows in board:
game_board = " ".join(rows)
print(game_board)
return board
# The game funct starts the user interaction
# and counts the number of moves the user takes.
def game(board):
moves = 0
while not is_solved(board):
row = int(input("Please select a row (0-4): "))
col = int(input("Please select a column (0-4): "))
touch(board, row, col)
moves += 1
print(f"Total Moves: {moves}")
for rows in board:
print(" ".join(rows))
print("YOU WIN!!!")
# This funct takes in the game board and the
# rows and col of the board and uses a dictionary
# to map the unicode in the list.
# Uses conditionals to account for speacial cases (edges of board)
def touch(board, row, col):
if row == 0 and col == 0:
board[row][col] = maps[board[row][col]]
board[row][col + 1] = maps[board[row][col + 1]]
board[row + 1][col] = maps[board[row + 1][col]]
elif row == 0 and col == 4:
board[row][col] = maps[board[row][col]]
board[row][col - 1] = maps[board[row][col - 1]]
board[row + 1][col] = maps[board[row + 1][col]]
elif row == 4 and col == 0:
board[row][col] = maps[board[row][col]]
board[row][col + 1] = maps[board[row][col + 1]]
board[row - 1][col] = maps[board[row - 1][col]]
elif row == 4 and col == 4:
board[row][col] = maps[board[row][col]]
board[row][col - 1] = maps[board[row][col - 1]]
board[row - 1][col] = maps[board[row - 1][col]]
elif row == 4:
board[row][col] = maps[board[row][col]]
board[row - 1][col] = maps[board[row - 1][col]]
board[row][col - 1] = maps[board[row][col - 1]]
board[row][col + 1] = maps[board[row][col + 1]]
elif row == 0:
board[row][col] = maps[board[row][col]]
board[row + 1][col] = maps[board[row + 1][col]]
board[row][col - 1] = maps[board[row][col - 1]]
board[row][col + 1] = maps[board[row][col + 1]]
elif col == 4:
board[row][col] = maps[board[row][col]]
board[row][col - 1] = maps[board[row][col - 1]]
board[row + 1][col] = maps[board[row + 1][col]]
board[row - 1][col] = maps[board[row - 1][col]]
elif col == 0:
board[row][col] = maps[board[row][col]]
board[row][col + 1] = maps[board[row][col + 1]]
board[row + 1][col] = maps[board[row + 1][col]]
board[row - 1][col] = maps[board[row - 1][col]]
else:
board[row][col] = maps[board[row][col]]
board[row][col - 1] = maps[board[row][col - 1]]
board[row][col + 1] = maps[board[row][col + 1]]
board[row + 1][col] = maps[board[row + 1][col]]
board[row - 1][col] = maps[board[row - 1][col]]
# This function is to check the board to make sure it is not solved
def is_solved(array):
if array == [[Y, Y, Y, Y, Y], [Y, Y, Y, Y, Y], [Y, Y, Y, Y, Y],
[Y, Y, Y, Y, Y], [Y, Y, Y, Y, Y]]:
return True
elif array == [[X, X, X, X, X], [X, X, X, X, X], [X, X, X, X, X],
[X, X, X, X, X], [X, X, X, X, X]]:
return False
else:
return None
# calls the main funct
main()
|
673134b4d493a291dcd65be182a4287392e10d4f | zx-feishang/LearningPython3-begin- | /4 Function/7returnFunc.py | 3,113 | 4.03125 | 4 | # 函数作为返回值
# 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
def calc_sum(*args): # 可变参数的求和
ax = 0
for n in args:
ax = ax + n
return ax
print(calc_sum(1, 3, 5, 7, 9))
# 但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?
# 可以不返回求和的结果,而是返回求和的函数:
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1, 3, 5, 7, 9) # 当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数:
print(f)
# 调用函数f时,才真正计算求和的结果:
print(f())
# 此例在函数lazy_sum中又定义了函数sum,
# 并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量,
# 当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中,
# 这种称为“闭包(Closure)”的程序结构拥有极大的威力。
# 返回闭包时牢记:返回函数不要引用任何循环变量,或者后续会发生变化的变量。
# 在一些语言中,在函数中可以(嵌套)定义另一个函数时,如果内部的函数引用了外部的函数的变量,则可能产生闭包。
# 闭包可以用来在一个函数与一组“私有”变量之间创建关联关系。在给定函数被多次调用的过程中,这些私有变量能够保持其持久性。
# 根据这句话,其实我们自己就可以总结出在python语言中形成闭包的三个条件,缺一不可:
# 1)必须有一个内嵌函数(函数里定义的函数)——这对应函数之间的嵌套
# 2)内嵌函数必须引用一个定义在闭合范围内(外部函数里)的变量——内部函数引用外部变量
# 3)外部函数必须返回内嵌函数——必须返回那个内部函数
# 当我们调用lazy_sum()时,每次调用都会返回一个新的函数,即使传入相同的参数:
f1 = lazy_sum(1, 3, 5, 7, 9)
f2 = lazy_sum(1, 3, 5, 7, 9)
print(f1 == f2)
# 返回的函数在其定义内部引用了局部变量args,所以,当一个函数返回了一个函数后,其内部的局部变量还被新函数引用
# 返回的函数并没有立刻执行,而是直到调用了f()才执行
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1())
print(f2())
print(f3())
def count1(): # 一定要引用循环变量怎么办?方法是再创建一个函数,用该函数的参数绑定循环变量当前的值,无论该循环变量后续如何更改,已绑定到函数参数的值不变:
def f(j):
def g():
return j*j
return g
fs = []
for i in range(1, 4):
fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
return fs
f4, f5, f6 = count1()
print(f4())
print(f5())
print(f6())
|
c642e32e7c32cdc9a48b9a132f03983d55048306 | brechtPhilips/Python | /Python-Exercises/Beginner,Intermediate,Experienced/Ex59-CSV To Database.py | 342 | 3.640625 | 4 | import sqlite3
import pandas
data = pandas.read_csv("Files/ten-more-countries.txt")
conn = sqlite3.connect("Files/database.db")
cur = conn.cursor()
for index,row in data.iterrows():
print(row["Country"],row["Area"])
cur.execute("INSERT INTO countries VALUES (NULL,?,?,NULL )",(row["Country"],row["Area"]))
conn.commit()
conn.close() |
896e56634b75f3f27d13e5320ff7683fc1bc95fb | Nile-Weadick/Python | /randomRead.py | 1,020 | 4.15625 | 4 | """
The second program, randomread.py, is to read a set of
random numbers from a file,
counts how many were read, displays the random numbers,
and displays the total count of random numbers.
"""
def main():
# Open the file for reading.
try:
numFile = open('numFile.txt', 'r')
except IOError:
print("Could not open file")
return
# Initialize an accumulator to 0.0
total = 0
# Initialize a variable to keep count of the videos.
count = 0
print('Here are the random numbers generated')
# Get the numbers from the file and total them.
for line in numFile:
# Convert a line to a int
num = int(line)
# Add 1 to the count variable.
count += 1
# Display the time.
print(count, ":", num)
# Add the time to total.
total += num #logic error
# Close the file
numFile.close()
# Display the total
print('The total is', total)
main() |
40d90dfe6489fa8cbcb5f466b88b32bc56e0e7e6 | SergeyShurin/N-puzzle | /bfs_algo.py | 3,882 | 3.875 | 4 | from queue import *
import draw as draw
def breadth_first_search(graph, start):
print("\nbreadth_first_search:\n")
frontier = Queue()
frontier.put(start)
came_from = {}
came_from[start[0]] = None
while not frontier.empty():
current = frontier.get()
if (check_valid(current[0])):
break
for next in graph.neighbors(current):
if next[0] not in came_from:
frontier.put(next)
came_from[next[0]] = current[0]
draw.print_result(graph, frontier, came_from)
# return came_from
def dijkstra_search(graph, start):
print("\ndijkstra_search:\n")
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {}
came_from[start[0]] = None
# mask = create_mask(graph)
level = {}
level[start[0]] = 0
while not frontier.empty():
current = frontier.get()
current_level = level[current[0]] + 1
if (check_valid(current[0])):
# graph.draw(current[0])
break
for next in graph.neighbors(current):
if next[0] not in came_from:
# priority_match = match_priority(next[0], graph, mask)
# priority_dist = manhattan_distance(next[0], graph, mask)
frontier.put(next, current_level)
came_from[next[0]] = current[0]
level[next[0]] = current_level
draw.print_result(graph, frontier, came_from)
# return came_from
def gready_search(graph, start, heuristic):
print("\ngready_search:\n")
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {}
came_from[start[0]] = None
# mask = create_mask(graph)
while not frontier.empty():
current = frontier.get()
if (check_valid(current[0])):
break
for next in graph.neighbors(current):
if next[0] not in came_from:
priority = heuristic(next[0], graph)
# priority_match = match_priority(next[0], graph)
# priority_dist = manhattan_distance(next[0], graph)
# print(priority_match)
# print(priority_dist)
frontier.put(next, priority)
came_from[next[0]] = current[0]
draw.print_result(graph, frontier, came_from)
# return came_from
def a_star(graph, start, heuristic):
print("\nA*:\n")
frontier = PriorityQueue()
frontier.put(start, 0)
came_from = {}
came_from[start[0]] = None
# mask = create_mask(graph)
cost = {}
cost[start[0]] = 0
while not frontier.empty():
current = frontier.get()
current_cost = cost[current[0]] + 1
if (check_valid(current[0])):
break
for next in graph.neighbors(current):
# priority_match = match_priority(next[0], graph)
# priority_dist = heuristic(next[0], graph)
priority = heuristic(next[0], graph)
if (next[0] not in came_from or
priority + current_cost < cost[next[0]]):
# print(priority_match)
# print(priority_dist)
frontier.put(next, priority + current_cost)
came_from[next[0]] = current[0]
cost[next[0]] = current_cost + priority
draw.print_result(graph, frontier, came_from)
# return came_from
def check_valid(state):
new_list = list(state)
new_list.pop()
result = [i for i in range(1, len(new_list) + 1)]
return new_list == result
# def create_mask(graph):
# mask = {}
# state = graph.final_state
# mask[0] = state[0]
# counter = 1
# while (counter < graph.size):
# mask[graph.size * counter] = state[graph.size * counter]
# mask[counter] = state[counter]
# counter += 1
# return mask
|
4c9868103f99907a2921b14f4f909811d1e03683 | rpm1995/LeetCode | /545_Boundary_Of_Binary_Tree.py | 1,656 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]:
def isleafnode(node):
if not node:
return False
if not node.left and not node.right:
return True
return False
def addleafnodes(node):
if not node:
return
if isleafnode(node):
ans.append(node.val)
addleafnodes(node.left)
addleafnodes(node.right)
ans = []
if not root:
return ans
if not isleafnode(root):
ans.append(root.val)
leftsubtreenodes = root.left
while leftsubtreenodes:
if not isleafnode(leftsubtreenodes):
ans.append(leftsubtreenodes.val)
if leftsubtreenodes.left:
leftsubtreenodes = leftsubtreenodes.left
else:
leftsubtreenodes = leftsubtreenodes.right
leafnodes = root
addleafnodes(leafnodes)
rightsubtreenodes = root.right
rightplaceholder = []
while rightsubtreenodes:
if not isleafnode(rightsubtreenodes):
rightplaceholder.append(rightsubtreenodes.val)
if rightsubtreenodes.right:
rightsubtreenodes = rightsubtreenodes.right
else:
rightsubtreenodes = rightsubtreenodes.left
ans.extend(reversed(rightplaceholder))
return ans
|
e8fac57a90b52acf6ac4925087d1d5fcb9dd227f | anand1115/Data-Structures-2021 | /edyst_training/efficient_janitar.py | 502 | 3.625 | 4 | def getMinTrips(weights):
weights.sort()
trips = 0
left_index = 0
for i in range(n-1, -1, -1):
if(weights[i] > 1.99):
trips+=1
if(weights[i]<=1.99):
if(weights[i]+weights[left_index]<=3):
left_index+=1
trips+=1
if(left_index>=i):
break
return trips
n = int(input())
weights = list(map(float, input().split()))
trips = getMinTrips(weights)
print(trips)
#input
#5
#1.01 1.99 2.5 1.5 1.01 |
092643bcb689af43a3420d874d6978b13e3c1ec3 | LichAmnesia/LeetCode | /python/107.py | 1,172 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# @Author: Lich_Amnesia
# @Email: alwaysxiaop@gmail.com
# @Date: 2016-09-22 12:40:19
# @Last Modified time: 2016-09-22 12:57:42
# @FileName: 107.py
# 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 levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
dic = {}
# level = 0
if not root:
return [[]]
# dic[level].append(root.val)
def dfs(root, level):
if not root:
return
elif level in dic:
dic[level].append(root.val)
else:
dic[level] = [root.val]
if root.left:
dfs(root.left, level + 1)
# dic[level + 1].append(root.left.val)
if root.right:
dfs(root.right, level + 1)
# dic[level + 1].append(root.right.val)
dfs(root, 0)
ans_list = [dic[l] for l in sorted(dic, reverse=True)]
return ans_list
|
248dabec410fcdb5207acef5934f1536d209b497 | Dionisius18/basic-python-batch-4 | /Tugas-2/soal_1.py | 1,091 | 3.921875 | 4 | def daftar_menu() :
print("Selamat datang!")
print("---Menu---")
print("1. Daftar Kontak")
print("2. Tambah Kontak")
print("3. Keluar")
daftar_kontak = []
def print_daftar_kontak () :
for kontak in daftar_kontak :
print("nama : {}".format(kontak["nama"]))
print("nomor HP: {}".format(kontak["nomor"]))
def tambah_daftar_kontak (nama, nomor) :
kontak_baru = {"nama" : nama, "nomor": nomor}
daftar_kontak.append(kontak_baru)
daftar_menu()
pilihan = int(input("Pilih menu: "))
while True :
if pilihan == 1 :
print_daftar_kontak ()
daftar_menu()
pilihan = int(input("Pilih menu: "))
elif pilihan == 2 :
nama = input('nama :')
nomor = input('nomor :')
tambah_daftar_kontak(nama, nomor)
print("Kontak berhasil")
daftar_menu()
pilihan = int(input("Pilih menu: "))
elif pilihan == 3 :
print("program selesai, sampai jumpa!")
break
else :
print("menu tidak tersedia")
daftar_menu()
pilihan = int(input("Pilih menu: "))
|
840ccade0cc5a5c782f1ca641a255c064ea085a6 | AlenVeselic/PyTest | /Chapter 4/pCharGrid.py | 755 | 3.5625 | 4 |
grid=[]
for y in range(9):
row=[]
if y == 0 or y == 8:
for x in range(6):
row.append('.')
elif y == 1 or y == 7:
row. append('.')
for x in range(2):
row.append('0')
for x in range(3):
row.append('.')
elif y == 2 or y == 6:
for x in range(4):
row.append('0')
for x in range(2):
row.append('.')
elif y == 3 or y == 5:
for x in range(5):
row.append('0')
row.append('.')
elif y == 4 :
row.append('.')
for x in range(5):
row.append('0')
grid.append(row)
for y in range(len(grid[y])):
for x in range(len(grid)):
print(grid[x][y],end='')
print() |
be213db61868b3752bd2920c4ff731f7f511ba88 | prate91/kobo-books | /buildGraph.py | 1,485 | 3.765625 | 4 | import csv
import networkx as nx
def makeGraph(filename):
# initialize a new graph
G = nx.Graph()
# open a csv reader
f1 = csv.reader(open(filename,"r"))
# add edges and nodes for every row
for row in f1:
G.add_edge(row[0],row[1])
return G
# Barabasi-Albert
def makeBA(nodes, pattach):
ba = nx.barabasi_albert_graph(nodes, pattach)
return ba
# Erdos-Renyi
def makeER(nodes, prob):
er = nx.erdos_renyi_graph(nodes, prob)
return er
# Graph menu
def graph_menu():
print (10 * "-" , "MENU" , 10 * "-")
print ("1. Kobo-books")
print ("2. Authors")
print ("3. Barabasi-Albert")
print ("4. Erdos-Renyi")
print ("5. Exit")
print (27 * "-")
def chooseGraph():
loop=True
while loop:
graph_menu()
choice = input("Enter your choice [1-5]: ")
if choice=='1':
return makeGraph("deepNetworkClean.csv")
elif choice=='2':
return makeGraph("deepAuthors.csv")
elif choice=='3':
return makeBA(15598, 14)
elif choice=='4':
return makeER(15598,0.005)
elif choice=='5':
print ("Exit")
loop=False # This will make the while loop to end as not value of loop is set to False
else:
# Any integer inputs other than values 1-5 we print an error message
input("Wrong option selection. Enter any key to try again.. \n") |
e9dfa01cc48da36403563aaf33881763f184d545 | hariramarni/PCA-in-Python | /PCA-Supervisor code.py | 805 | 3.59375 | 4 | #Supervisors take on PCA Code
# -*- coding: utf-8 -*-
"""
# PCA from csv dataset
"""
# impor required libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# importing or loading the dataset - change the file path as needed
dataset = pd.read_csv(r'/Users/user/Desktop/Data.csv')
# (optional) print data to check that it has been correctly imported
print(dataset)
# PCA
from sklearn.decomposition import PCA
from sklearn import preprocessing
# Pre-process the data
sdata = preprocessing.scale(dataset)
pca = PCA(n_components=2)
pca.fit(sdata)
# show principal components
print(pca.components_)
# show the explained variance
print(pca.explained_variance_)
# scatter plot
# plot data
plt.scatter(sdata[:, 0], sdata[:, 1], alpha=0.2)
|
f4de18f41ecbca7fffb869e0aab6deecc52735f3 | outdatedtvreferences/Graphics | /graphics/Graphics_project.py | 1,638 | 3.59375 | 4 | import turtle
import math
screen = turtle.Screen()
screen.bgcolor("blue")
screen.title("Frosty the snowman!")
frosty = turtle.Turtle()
frosty.speed(0)
frosty.color("black")
frosty.fillcolor("white")
frosty.pensize(3)
frosty.hideturtle()
def face (x, y):
frosty.up()
frosty.goto(x + 10,y)
frosty.dot()
frosty.goto(x - 10,y)
frosty.dot()
frosty.goto(x,y -10)
frosty.dot()
frosty.goto(x -15,y -25)
frosty.down()
frosty.forward(30)
frosty.up()
def arm(x,y,length,heading):
frosty.up()
frosty.goto(x,y)
frosty.setheading(heading)
frosty.down()
frosty.forward(length)
frosty.setheading(heading + 20)
frosty.forward(20)
frosty.up()
frosty.back(20)
frosty.down()
frosty.setheading(heading - 20)
frosty.forward(20)
frosty.up()
frosty.home()
def circle(radius,y):
frosty.up()
frosty.sety(y)
arc_length = 1 * (math.pi/180) * radius
frosty.down()
frosty.begin_fill()
for i in range (360):
frosty.forward(arc_length)
frosty.up()
frosty.end_fill()
circle(40,20)
circle(70,-120)
circle(100,-320)
arm(70,-50,50,20)
arm(-70,-50,50,160)
face(0,70)
screen.exitonclick()
|
1a4be2d6d2ebf368d4614719c3fdf39662950a9f | chad-miller-official/cs-3251-prog-3 | /src/router.py | 3,602 | 3.9375 | 4 | import math
from copy import deepcopy
"""
Class to represent a router's routing table and other stored values.
Specifically, it contains a routing table, a table of number of hops for certain
paths, pinters to the least cost values in the table, itself's label, and the
next hops for the lowest cost paths.
"""
class RoutingTable:
def __init__( self, numRouters, router ):
self.table = [ [ None for i in range( numRouters ) ] for j in range( numRouters ) ]
self.numHops = [ [ 0 for i in range( numRouters ) ] for j in range( numRouters ) ]
self.coordinates = [ None for i in range( numRouters ) ]
self.router = router
self.hops = [ None for i in range( numRouters ) ]
#sets the number of hops it takes to get to a destination
def setNumHops( self, to, via, hops ):
self.numHops[to - 1][via - 1] = hops
#returns the number of hops to a destination
def getNumHops( self, to, via ):
return self.numHops[to - 1][via - 1]
#returns the cost of a certain path in the routing table
def getCost( self, to, via ):
return self.table[to - 1][via - 1]
#sets the cost in the routing table based on an event
def setCostFromEvent( self, to, via, cost ):
self.table[to - 1][via - 1] = cost
#sets cost in the routing table to given value
def setCost( self, to, via, cost ):
#print ('From vertex {} telling {} about path to vertex {} with cost: {}'.format(via, self.router, to, cost) )
if to == self.router or via == self.router:
return False
#set if non-existent, a lower cost, or it is an override from previous
#node of least cost
if self.table[to - 1][via - 1] is None \
or self.table[to - 1][via - 1] >= cost \
or self.coordinates[to - 1] == ( to, via ):
self.table[to - 1][via - 1] = cost
return True
return False
#sets the next hop for a given path
def setHop( self, to, via ):
if to == self.router or via == self.router:
self.hops[to-1] = via
elif to == via:
self.hops[to-1] = via
else:
self.hops[to-1] = via
#sets the coordinates of the least cost path in a row of the routing table
def setCoordinate(self, index1, index2):
self.coordinates[index1 - 1] = (index1, index2)
#updates all coordinates for least cost paths in each row of the routing table
def updateCoordinates( self ):
ret = False
for c in range( 0, len( self.table ) ):
if not any( self.table[c] ):
self.coordinates[c] = None
self.hops[c] = 0
continue
col = self.table[c].index( min( x for x in self.table[c] if x is not None ) )
self.setHop( c + 1, col + 1 )
if self.coordinates[c] != (c + 1, col + 1):
self.coordinates[c] = (c + 1, col + 1)
ret = True
return ret
#clones this router
def clone( self ):
return deepcopy( self )
def __str__( self ):
tableStr = ''
for i in range( 0, len( self.table ) ):
for j in range( 0, len( self.table[i] ) ):
if self.table[i][j] is None:
tableStr += 'X, '
else:
tableStr += str( self.table[i][j] ) + ', '
tableStr = tableStr.strip( ', ' )
tableStr += '\n'
tableStr = tableStr.strip( ', \n' )
tableStr += ''
return tableStr
|
360c65b253db67536ef6b75664f32972d43f30fd | cyy0127/Leet-Code-Solutions-Python | /X-of-A-Kind-of-Deck-of-Cards.py | 1,513 | 3.921875 | 4 | """
In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:
Each group has exactly X cards.
All the cards in each group have the same integer.
Example 1:
Input: [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]
Example 2:
Input: [1,1,1,2,2,2,3,3]
Output: false
Explanation: No possible partition.
Example 3:
Input: [1]
Output: false
Explanation: No possible partition.
Example 4:
Input: [1,1]
Output: true
Explanation: Possible partition [1,1]
Example 5:
Input: [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2]
Note:
1 <= deck.length <= 10000
0 <= deck[i] < 10000
"""
class Solution(object):
def hasGroupsSizeX(self, deck):
# if len(deck) <= 1: return false
if len(deck) <= 1:
return False
# get d = a list of unique cards in deck
d = list(set(deck))
# get c = the deck.count of each unique card
c = [deck.count(n) for n in d]
# if list(set(c)) == 1: return true
if list(set(c)) == 1:
return True
# return all(i%min(list(set(c))) == 0 for i in list(set(c)))
u = list(set(c))
m = min(u)
return all(math.gcd(i, m) != 1 for i in u)
"""
:type deck: List[int]
:rtype: bool
""" |
819d401ea1dbb5e9f8980ab0c8b2b8035fd48813 | sirspen/Dictionary-to-Array | /DicToArray.py | 449 | 3.609375 | 4 | import time
dic = open("Dictionary.txt", 'r') #opens our dictionary, you can change the filename
dicList = [] #this will be the list we export
for x in dic:
dicList.append(x[:-1])#adds the new word to the list and removes new line
dic.close()
newDic = open("NewDictionary.txt", 'w') #creates new .txt file to store strings
for y in dicList: #writes each new word into the .txt followed by a , and a space
newDic.write("\""+ y + "\", ")
|
30e3ef5cbc56d33d2290b6e2166030ccf3afbc54 | kyrajeep/Practice | /bst.py | 3,270 | 4.15625 | 4 | #implement a binary search tree
#approximate the square root of a number?
# x * x = x^2
# why would you use a binary search for that? -> this is brilliant.
# I think as I solve more problems it becomes more natural to think this way
# how would I write test cases
# with integers I already know the answer to
# input: number n
# output: the square root
# can I do a small example?
# what would be a suitable small example?
# if s * s = x then s is the output (solution)
# if s * s > x then solution < s
# if s * s < x then solution > s
# test cases : n = 4, sol = 2
# n = 8, sol = math.floor(math.sqrt(8))
# does the answer have to be an integer?
# If x is not a perfect square, then return floor(√x).
# 3 things to check. should I delegate it to a helper function
# there are three different responses depending on the output of this helper
# is n a global?
# how to respond to this helper
# should I create a class, a blueprint to print this out again and again?
import math
# n has to be a global variable. is the next line enough?
class squareroot:
# I decided to make this into a class because I am comfortable with it
# and also because I was having some issues passing around a global var
def __init__(self, n):
self.n = n
def squarert(self):
# now implement the binary search
# start at 0
# how am I going to store variables and pass them around
# do i have problem wiht scope?
m = self.n/2
prev_small = 0
prev_big = self.n
while (abs(m - prev_big) > 0.01 and abs(m - prev_small) > 0.01):
print("in while")
if self.squaretrue(m) == 0:
#if self.isinteger(m):
return m
#else:
# return math.floor(math.sqrt(m))
if self.squaretrue(m) == 1:
prev_big = m
m = (prev_small + prev_big)/2
if self.squaretrue(m) == 2:
prev_small = m
m = (prev_small + prev_big)/2
# the helper function to check if the current number is a sqrt
def squaretrue(self, m):
# have to save the previous iteration. i don't think it has to be a hash
# maybe an array
if (m**2 == self.n) or abs(self.n-m**2) < 0.01:
return 0
elif m**2 > self.n:
return 1
elif m**2 < self.n:
return 2
# how to pass this around
# smells like recursion
# I have to call the previous. but only the previous
def isinteger(self,k):
if abs(k - int(k)) == 0:
return True
else:
return False
#test cases
def testsquarert():
#I tried to test the function, but ended up making it into a class so
# could not use this test function
# I
pass
if squarert(4) == 2:
print("test for n = 4 passed")
elif squarert(4) != 2:
print("test for n = 4 failed")
if squarert(8) == math.floor(math.sqrt(8)):
print("test for n = 8 passed")
elif squarert(8) != math.floor(math.sqrt(8)):
print("test for n = 8 failed")
sqrtclass = squareroot(8)
print(sqrtclass.squarert())
|
583e2c07ab55b7e3758406be28fb81135ac2ac85 | henrylin2008/Coding_Problems | /LeetCode/Blind 75/Backtracking/Combinatorial Search/Letter Combinations of A Phone Number.py | 1,806 | 4.0625 | 4 | # Letter Combinations of A Phone Number
# Link: https://algo.monster/problems/letter_combinations_of_phone_number
# Given a phone number that contains digits 2-9, find all possible letter combinations the phone number could translate
# to.
# 1 2 3
# A B C D E F
# 4 5 6
# G H I J K L M N O
# 7 8 9
# P Q R S T U V W X Y Z
#
# Input:
# "56"
#
# Output:
# ["jm","jn","jo","km","kn","ko","lm","ln","lo"]
# This is essentially asking for all permutations with the constraint of a number to letter mapping.
#
# 1. Identify state(s)
# To construct a letter combination we need
# The letters we have selected so far
# To make a choice when we visit the current node's children, we don't need to maintain any additional state since
# the next possible letters are defined by the number to letter mapping.
# 2. Draw the tree
# 3. DFS on the tree
# Time Complexity: O(4^n)
# n is the length of the input string. Worst case we have 4 choices for every number, average case we have 3 choices so
# it should be closer to O(3^n).
from typing import List
KEYBOARD = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
}
def letter_combinations_of_phone_number(digits: str) -> List[str]:
def dfs(path, res):
if len(path) == len(digits):
res.append(''.join(path))
return
next_number = digits[len(path)]
for letter in KEYBOARD[next_number]:
path.append(letter)
dfs(path, res)
path.pop()
res = []
dfs([], res)
return res
if __name__ == '__main__':
digits = input()
res = letter_combinations_of_phone_number(digits)
print(' '.join(res))
|
b110e458a833a2b35912dd9d3cc2acfae329deb2 | faisalraza33/leetcode | /Python/0124. Binary Tree Maximum Path Sum.py | 1,550 | 4.0625 | 4 | # A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
# The path sum of a path is the sum of the node's values in the path.
# Given the root of a binary tree, return the maximum path sum of any non-empty path.
#
# Example 1:
#
# Input: root = [1,2,3]
# Output: 6
# Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
#
# Example 2:
#
# Input: root = [-10,9,20,null,null,15,7]
# Output: 42
# Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.
#
# Constraints:
#
# The number of nodes in the tree is in the range [1, 3 * 10^4].
# -1000 <= Node.val <= 1000
# 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
# Recursion
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
ma = float("-inf")
def get_max_gain(node):
if not node:
return 0
# left max gain. If < 0, returning 0 means ignoring this branch
l = max(get_max_gain(node.left), 0)
# right max gain
r = max(get_max_gain(node.right), 0)
nonlocal ma
ma = max(ma, l + r + node.val)
return max(l, r) + node.val
get_max_gain(root)
return ma
|
434730b1d74c95ef0237f421671853f600e96529 | AngeloDamiani/Cryptography-Mini-Project | /src/server/utility/cryptography/ICrypto.py | 385 | 3.59375 | 4 | import abc
class ICrypto(metaclass=abc.ABCMeta):
@abc.abstractmethod
def encrypt(self, msg : str) -> str:
"""
Encrypt a message
:return: an encrypted message
"""
pass
@abc.abstractmethod
def decrypt(self, msg : str) -> str:
"""
Decrypt a message
:return: a decrypted message
"""
pass
|
c356501963ebc184b40183a21c951cebcdb73c34 | ofarukgokdemir/kesfuzzunun | /kullanıcıdan3sayı.py | 400 | 4 | 4 | sayı1 = float(input("birinci sayıyı giriniz:"))
sayı2 = float(input("ikinci sayıyı giriniz:"))
sayı3 = float(input("üçüncü sayıyı giriniz:"))
if (sayı1>sayı2 and sayı1>sayı3):
print("en büyük sayı",sayı1)
elif (sayı2>sayı3 and sayı2>sayı1):
print("en büyük sayı", sayı2)
elif (sayı3>sayı1 and sayı3>sayı2):
print("en büyük sayı",sayı3)
|
4f39190954d3476c340b096097f250fdf90c655f | YatoCiks/Grafos | /Atividade4.py | 2,435 | 3.8125 | 4 | #-----------------------------------------------------
class Matriz():
"""Matriz de Adjacencia"""
def __init__(self, vertice):
self.vertice = vertice
self.grafo = []
for i in range(self.vertice):
nova_linha = []
for j in range(self.vertice):
nova_linha.append(0)
self.grafo.append(nova_linha)
def mostrar_grafo(self):
print("#--------------------- Matriz de Adjacencia ---------------------#")
for i in range(self.vertice):
print(self.grafo[i])
def adicionar_aresta(self, linha, coluna):
self.grafo[linha - 1][coluna - 1] += 1
self.grafo[coluna - 1][linha - 1] += 1
def converter_lista(self):
lista = Lista(self.vertice)
for i in range(self.vertice):
for j in range(self.vertice):
if self.grafo[i][j] != 0:
lista.grafo[i].append(j+1)
return lista
class Lista():
"""Lista de Adjacencia"""
def __init__(self, vertice):
self.vertice = vertice
self.grafo = []
for i in range(self.vertice):
self.grafo.append([])
def mostrar_grafo(self):
print("#--------------------- Lista de Adjacencia ----------------------#")
for i in range(self.vertice):
print(self.grafo[i])
#-----------------------------------------------------
print("Questao 1")
matriz_q1 = Matriz(6)
matriz_q1.adicionar_aresta(1, 4)
matriz_q1.adicionar_aresta(1, 5)
matriz_q1.adicionar_aresta(1, 6)
matriz_q1.adicionar_aresta(2, 3)
matriz_q1.adicionar_aresta(2, 4)
matriz_q1.adicionar_aresta(2, 5)
matriz_q1.adicionar_aresta(3, 4)
matriz_q1.adicionar_aresta(3, 5)
matriz_q1.adicionar_aresta(4, 6)
matriz_q1.adicionar_aresta(5, 6)
matriz_q1.mostrar_grafo()
lista_q1 = matriz_q1.converter_lista()
print("")
lista_q1.mostrar_grafo()
print("")
print("Questao 2")
matriz_q2 = Matriz(4)
matriz_q2.adicionar_aresta(1, 2)
matriz_q2.adicionar_aresta(1, 3)
matriz_q2.adicionar_aresta(1, 4)
matriz_q2.adicionar_aresta(2, 3)
matriz_q2.adicionar_aresta(2, 4)
matriz_q2.adicionar_aresta(4, 3)
matriz_q2.mostrar_grafo()
lista_q2 = matriz_q2.converter_lista()
print("")
lista_q2.mostrar_grafo()
|
338ac7ffac24a0ec3e82627db5db4ece75bb126b | tafiela/Learn_Python_the_hardway | /ex24.py | 1,061 | 3.890625 | 4 | print "Lets practice everything."
print 'You\'d need to know \'bout escape with \\ that do \n newlines and \t tabs'
poem = """
\t The lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print "__________"
print poem
print "__________"
five = 10-2 + 3-6 #equals to 5
print "\n\n\nThis should be five: %s " %five
def secret_formula(started):
jelly_beans = started * 5
jars = jelly_beans * 3
crates = jars * 10
return jars, crates, jelly_beans #is this working like the argv? order matters
start_point = 20
beans, jars, crates = secret_formula(start_point) #is this like argv?
print "\n\nWith a starting point of : %d " %start_point
print "\n\nWe'd have %d beans, %d jars, and %d crates." %(beans, jars,crates)
start_point = start_point / 10
print "\n\n******* "
print "\n\n\n\nWe can also do that this way."
print "\n\nWe'd have %d beans, %d jars, and %d crates." %secret_formula(start_point) |
afe925631c7d1019016262275876c371e849ed05 | aman1108/Python-Lab | /A4 List 2/A4_6.py | 88 | 3.734375 | 4 | mylist=input("Enter your list: ").split()
mylist.sort()
print(mylist[len(mylist)-1])
|
d23d5923f96eec283522f8e3440ccad7df002ae9 | krickesheet54/hello-world | /8_fahrenheit_to_c.py | 575 | 4.28125 | 4 | """
Author: Kricketune54
Date: 4/5/2020
File Description: Chapter 2 Challenge #8 of John Zelle book, does the reverse of convert.py
"""
def main():
print("This program will convert Fahrenheit temperatures to Celsius!")
fahrenheit = eval(input("What is the Fahrenheit temperature? " ))
#Note that having eval is what allows the numbers to caculate from the user's input
celsius = (fahrenheit - 32) / 9/5
print("The temperature is", celsius, "degrees Celsius.")
main()
#refer to pseudocode for a guide on the structure of this program!
|
9a9a5995966c209cef0bfb26607b15159bc77786 | guydols/ProjectEuler | /pe002.py | 602 | 3.9375 | 4 | # Each new term in the Fibonacci sequence
# is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence
# whose values do not exceed four million,
# find the sum of the even-valued terms.
import lib.formulas as fml
def main(limit):
terms = []
fibonacci = fml.getFibonacci(limit)
for num in fibonacci:
if num % 2 == 0:
terms.append(num)
return sum(terms)
if __name__ == '__main__':
limit = 4000000
print(main(limit))
|
25cd99ef2ba1f49a254057e95b85ce69b322a356 | onesMas46/BCS-2021 | /src/mid sem.py | 1,766 | 3.84375 | 4 | def desp():
print('=' * 50)
print('Customer code: ', code)
print('Beggening meter reading: ',ireading)
print('Ending meter reading: ',freading)
print('Gallons of water used: ',volwater)
print('Amount billed: $',round(amount, 2))
print('*' * 50)
while True:
code = input('Enter customer code: ')
code = code.upper()
if code == "C" or code == "R" or code == "I":
Beggening = input("Enter begenning meter reading: ")
ending = input("Enter ending meter reading: ")
if len(Beggening) <= 9 and len(ending) <= 9:
ireading = int(Beggening)
freading = int(ending)
volwater = (abs(freading - ireading)) * 0.1
if code == "R":
amount = ((5 + 0.0005) * volwater)
desp()
elif code == "C":
if volwater > 4_000_000:
amount = ((1_000 * 4_000_000) + (0.00025 * (volwater - 4_000_000)))
desp()
else:
amount = (1_000 * volwater)
desp()
else:
if volwater > 10_000_000:
amount = (2_000 * 10_000_000) + ((volwater - 10_000_000) * 0.00025)
desp()
elif 4_000_000 < volwater <= 10_000_000:
amount = volwater * 2_000
desp()
else:
amount = 1_000 * volwater
desp()
else:
print("invalid input of meter readings!!")
continue
else:
print("Invalid input of customer code") |
27922cdc3580ba6d9907ca46d2016f2720c0153f | arturolei/luftrobot | /luftrobot_simulator.py | 2,759 | 3.859375 | 4 | NORTH= 90
SOUTH= 270
EAST= 0
WEST= 180
class Robot:
def __init__ (self, bearing = NORTH ,x=0, y=0): #default direction, FYI, is North
self.bearing = bearing
self.x= x
self.y = y
@property
def coordinates(self):
return (self.x, self.y)
def turn_right(self):
self.bearing = (self.bearing-90) % 360 #Yay! Negative modulus!
def turn_left(self):
self.bearing = (self.bearing+90) % 360 #if we are going left we turn 90 degrees, unit circle
def advance(self):
if self.bearing == NORTH: #if we are going forward, facing north, y+1
self.y+=1
#self.coordinates = (self.x,self.y)
#NB: The previous line and 'self.coordinates' line could be combined.
if self.bearing == SOUTH: #if we are going forward, facing south, y-1
self.y-=1
#self.coordinates = (self.x,self.y)
if self.bearing == EAST: #if we are going forward, facing east, x+1
self.x+=1
#self.coordinates = (self.x,self.y)
if self.bearing == WEST: #if we are going forward, facing west, x-1
self.x-=1
#self.coordinates = (self.x,self.y)
def simulate(self, pathString):
listString = list(pathString) #turn string into list of letters
for step in listString: #'translate' list of strings into movements
if step =="R":
self.turn_right()
if step == "L":
self.turn_left()
if step =="A":
self.advance()
class Luftrobot(Robot):
def __init__ (self, bearing = NORTH ,x=0, y=0, altitude= 0): #default direction, FYI, is North
Robot.__init__(self,bearing, x, y)
self.altitude = altitude
@property
def coordinates(self):
return (self.x, self.y, self.altitude)
def warp(self, distance):
for i in range(distance):
self.advance()
def goback(self): #reverse of advance
if self.bearing == NORTH: #if we are going forward, facing north, y+1
self.y-=1
#self.coordinates = (self.x,self.y)
#NB: The previous line and 'self.coordinates' line could be combined.
if self.bearing == SOUTH: #if we are going forward, facing south, y-1
self.y+=1
#self.coordinates = (self.x,self.y)
if self.bearing == EAST: #if we are going forward, facing east, x+1
self.x-=1
#self.coordinates = (self.x,self.y)
if self.bearing == WEST: #if we are going forward, facing west, x-1
self.x+=1
#self.coordinates = (self.x,self.y)
def ascend(self):
self.altitude+=1
def descend(self):
self.altitude-=1
if self.altitude < 0:
self.altitude ==0
def simulate(self, pathString):
listString = list(pathString) #turn string into list of letters
for step in listString: #'translate' list of strings into movements
if step =="R":
self.turn_right()
if step == "L":
self.turn_left()
if step =="A":
self.advance()
if step == "U":
self.ascend()
if step =="D":
self.descend()
|
3170adeace536bb6fa327761fa3763f59e33f59e | eholowko/bootcamp-python-introduction | /Functions.py | 883 | 3.671875 | 4 | #! /home/kodolamacz/anaconda3/bin/python3.6
def Sortowanie_zliczanie(L,a,b):
max_index = 0
size = b - a
print(L, end=" ")
print()
hist = [0 for i in range(size + 1)]
for el in L:
hist[el - a] += 1
print(hist, end=" ")
print()
new_L = [0 for i in range(size)]
index = 0
for i,value in enumerate(hist):
for j in range(value):
new_L[index + j] = a + i
index += value
print(new_L, end=" ")
print()
for i,value in enumerate(hist):
if hist[max_index] < value:
max_index = i
return max_index
def main():
L = [2,3,5,6,3,6,7,1,8,-4,-4,-4,5,0,0]
a = -5
b = 10
index = Sortowanie_zliczanie(L,a,b)
print("Najwiekszy indeks = {}".format(index))
print("W liscie jest najwiecej {}".format(a + index))
if __name__ == "__main__":
main() |
fcbc4f3842409113f8d4a816fe0f96440a8304a7 | Erickddp/Tools_Cs_py | /passwcrack.py | 836 | 3.765625 | 4 | import hashlib
# Primeras dos instrucciones en que se solicita el HASH y el diccionario.
encontrada = 0
input_hash = input("Inserte la contraseña hasheada: ")
pass_doc = input("Inserte el diccionario: ")
# Operacion de busqueda.
try:
pass_file = open(pass_doc, 'r')
except:
print("Error: " + pass_doc + " no ha sido encontrada")
for palabra in pass_file:
palabra_cifrada = palabra.encode("utf-8")
palabra_hasheada = hashlib.md5(palabra_cifrada.strip())
digest = palabra_hasheada.hexdigest()
# En caso de ser encontrada la contraseña
if digest == input_hash:
print("Contraseña encontrada!!! \n \tLa contraseña es: " + palabra)
break
# En caso de no ser encontrada.
if not encontrada:
print("Contraseña no encontrada en el archivo " + pass_doc)
input() |
277351e4ca24d20393a7a7d546841165ca539fbc | NastyaZotkina/STP | /lab7.py | 1,745 | 4.09375 | 4 | import math
print("Нажмите 1 для нахождения площади треугольника через его стороны или нажмите 2 для нахождения площади через вершины:")
x=input("Сделайте Ваш выбор ")
x=int(x)
if x==1:
a=float(input("Введите сторону a "))
b = float(input("Введите сторону b "))
c = float(input("Введите сторону c "))
if(a>0 and b>0 and c>0):
p=(a+b+c)/2
if(a+b>c and a+c>b and b+c>a):
S=math.sqrt(p*(p-a)*(p-b)*(p-c))
if (math.fmod(S, S) == 0):
S = math.floor(S)
print("S =", S)
else:
print("Треугольник не существует")
else:
print("Были введены некорректные данные!")
elif x==2:
print("Введите координаты вершин треугольника:\n")
k1 = input("Координаты первой вершины ").split()
x1=float(k1[0])
y1=float(k1[1])
k2 = input("Координаты второй вершины ").split()
x2=float(k2[0])
y2=float(k2[1])
k3 = input("Координаты третьей вершины ").split()
x3=float(k3[0])
y3=float(k3[1])
S=math.fabs((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1))/2
if((x1==x2 and y1==y2)or(x2==x3 and y2==y3)or(x1==x3 and y1==y3)):
print("Треугольник не существует")
else:
if (math.fmod(S, S) == 0):
S = math.floor(S)
print("S =", S)
else:
print("Введены некорректные данные. Ошибка!")
|
b9ecde62734d4182795a42b7b7334c04cd2bb083 | kate711/day1 | /code/判断今天是今年的第几天.py | 309 | 3.765625 | 4 | import time
date = time.localtime()
year, month, day = date[:3]
day_month=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year % 400 ==0 or (year % 4==0 and year % 100 !=0 ): # 判断是否是闰年
day_month[1] = 29
if month == 1:
print(day)
else :
print(sum(day_month[:month-1]) + day)
|
d0c1f0015335d412b1543512b723d46cfb32bc2c | hinzed1127/aoc2019 | /01/01.py | 413 | 3.671875 | 4 | # import math
# fuel = 0
# file = open('masses.txt')
# for line in file:
# fuel += math.floor(int(line)/3) - 2
# print(fuel)
# part one
print(sum((int(line) // 3) - 2 for line in open('masses.txt')))
# part 2
def fuel(mass):
fuel_mass = (mass // 3) - 2
if fuel_mass <= 0:
return 0
else:
return fuel_mass + fuel(fuel_mass)
print(sum(fuel(line) for line in open('masses.txt')))
|
2b4a1393f62b54bf9961f3ebc956ce98faa7c2c0 | juliamcneill/intro-to-programming-class | /McNeillJulia_assign6/McNeillJulia_assign6_problem3.py | 2,821 | 4.1875 | 4 | """
McNeillJulia_assign6_problem3
Written by: Julia McNeill
Written for: Intro to Programming section 4, Mo-Wed 9:30am, Fall 2019
Date: 29 October, 2019
"""
#import num_stats document
from McNeillJulia_num_stats import is_odd, is_even, is_prime, is_perfect, is_abundant
while True:
#introduce program
print('Chart all even, odd, prime, perfect and abundant numbers within a given range.')
#ask user if they are ready to study
ready = input('Ready? (Enter Y or y to continue; any other value to quit.) ')
print()
#end program is user does not wish to continue
if ready != 'y' and ready != 'Y':
print("Goodbye!")
break
else:
while True:
#if user is ready to start, ask them for starting number
starting_number = int(input("Enter starting number (positive only): "))
#validate starting number, and reprompt if number is not valid
if(starting_number < 0):
print("Invalid, try again")
else:
break
while True:
#ask user for ending number
ending_number = int(input("Enter ending number (positive only): "))
#validate ending number, and reprompt if number is not valid
if(starting_number < ending_number):
break
else:
print("Invalid, try again")
#print the output
print()
print()
print()
#print column headers, creating a column of width 10 for each
print('{0:^10}'.format('Number'), end='')
print('{0:^10}'.format('Even'), end='')
print('{0:^10}'.format('Odd'), end='')
print('{0:^10}'.format('Prime'), end='')
print('{0:^10}'.format('Perfect'), end='')
print('{0:^10}'.format('Abundant'))
#iterate through each number in the range
#fill in x for each function that returns True
#fill in a blank space for each function that returns False
for number in range(starting_number, ending_number + 1):
print('{0:^10}'.format(number), end='')
if is_even(number):
print('{0:^10}'.format('x'), end='')
else:
print('{0:^10}'.format(' '), end='')
if is_odd(number):
print('{0:^10}'.format('x'), end='')
else:
print('{0:^10}'.format(' '), end='')
if is_prime(number):
print('{0:^10}'.format('x'), end='')
else:
print('{0:^10}'.format(' '), end='')
if is_perfect(number):
print('{0:^10}'.format('x'), end='')
else:
print('{0:^10}'.format(' '), end='')
if is_abundant(number):
print('{0:^10}'.format('x'))
else:
print('{0:^10}'.format(' '))
print()
print()
|
8260ae2c83782287779af7316de100138e506977 | JuanJoseSenit/subir_github | /bucles/ciclo_for_uso_range.py | 384 | 3.84375 | 4 | for i in range(5): #i desde 0 a 4
print(i, end=" ")
print(" ")
for i in range(5,10): #i desde 5 hasta el 9
print("i vale: " + str(i))
for i in range(5,10): #i desde 5 hasta el 9
print(f"valor de la variable {i}") #de esta forma podemos unir un texto a una variable sin tener que concatenar
for i in range(5,50,3): #desde el 5 al 49 de tres en tres
print (i, end="-") |
f66d6cdf7595d001fc5e2ee749888e0d23a6ea74 | yaoxuanw007/forfun | /leetcode/python/removeElement.py | 555 | 3.5625 | 4 | # https://oj.leetcode.com/problems/remove-element/
# 12:38 - 12:44
class Solution:
# @param A a list of integers
# @param elem an integer, value need to be removed
# @return an integer
def removeElement(self, A, elem):
aLen = len(A)
if aLen > 0:
i = 0
while i < aLen:
if A[i] == elem:
A[i] = A[aLen-1]
aLen -= 1
continue
i += 1
return aLen
s = Solution()
print s.removeElement([], 2)
print s.removeElement([2,2,2], 2)
print s.removeElement([1,2,3,2,4,2], 2)
|
6173fac74726f5495ebd2ec46a7544a7fc67d9e0 | allenlgy/Django-project | /高级数据类型/hm_17_字符串的查找和替换.py | 540 | 4.5625 | 5 | hello_str = "hello world"
# 1. 判断是否以指定字符开始
print(hello_str.startswith("H"))
# 2. 判断是否以指定字符串结束
print(hello_str.endswith("world"))
# 3. 查找指定字符
# index 同样能指定字符串位置
# find 方法如果找不到字符,不会报错,只会 -1
print(hello_str.find("llo"))
print(hello_str.find("abc"))
# 4. 替换字符串
# replace 方法执行完成之后形成一个新的字符串
# 不会修改原有的字符串
print(hello_str.replace("world","python"))
print(hello_str)
|
f0aabc87eba727f370dd66317c7084bbe718dbf2 | pradhumn14/makeabilitylabwebsite | /website/utils/ml_utils.py | 1,598 | 3.6875 | 4 | """
Hosts general utility functions for Makeability Lab Django website
"""
import re
# helper function to correctly capitalize a string, specify words to not capitalize in the articles list
# from: https://stackoverflow.com/a/3729957
# Note: this code written by J. Gilkeson and needs to be cleaned up (and/or removed if no longer needed)
def capitalize_title(s, exceptions):
word_list = re.split(' ', s) # re.split behaves as expected
final = [word_list[0].capitalize()]
for word in word_list[1:]:
final.append(word if word in exceptions else word.capitalize())
return " ".join(final)
#Standard list of words to not capitalize in a sentence
articles = ['a', 'an', 'and', 'as', 'at', 'but', 'by', 'for', 'from', 'is', 'of', 'on', 'or', 'nor', 'the', 'to', 'up', 'yet']
def get_video_embed(video_url):
"""Returns proper embed code for a video url"""
if 'youtu.be' in video_url or 'youtube.com' in video_url:
# https://youtu.be/i0IDbHGir-8 or https://www.youtube.com/watch?v=i0IDbHGir-8
base_url = "https://youtube.com/embed"
unique_url = video_url[video_url.find("/", 9):]
# See https://developers.google.com/youtube/youtube_player_demo for details on parameterizing YouTube video
return base_url + unique_url + "?showinfo=0&iv_load_policy=3"
elif 'vimeo' in video_url:
# https://player.vimeo.com/video/164630179
vimeo_video_id = video_url.rsplit('/', 1)[-1]
return "https://player.vimeo.com/video/" + vimeo_video_id
else:
return "unknown video service for '{}'".format(video_url) |
ed60c614abc38488de01571bfae3ea265887eb07 | INF1007-Gabarits/2021A_TP2 | /exercice4.py | 2,325 | 3.546875 | 4 | # Fontion fournie ne pas modifier
clearConsole = lambda: print('\n' * 10)
def print_table(table):
# Dimension 1 = ligne
# Dimension 2 = colonne
clearConsole()
for i, row in enumerate(table):
row_str = "{:>2}" * len(row)
row_str = row_str.format(*row)
print("{:^20}".format(row_str), '\n')
# ________________________________________________________________
# Partie 1
def init_maze(nb_row, nb_col, player_pos, end_pos, walls):
maze = ... # TODO Générer un labyrinthe vide -> rempli de "_"
# TODO Placer le joueur "O" la sortie "X" les murs "W"
return maze
# Partie 2
def validate_move(maze, new_player_pos):
result = False
# TODO Vérifier si la position est valide -> dans le labyrinthe et pas sur un mur
return result
#Partie 3
def move(key_pressed, maze, player_pos):
move_dic = ... # TODO Créer le dictionnaire d'équivalence entre la touche appuyée et la direction ("up", "left", "down", "right")
# TODO Vérifier si la touche appuyée est dans le dictionnaire
if (...) :
move = ... # TODO Récupérer la direction du mouvement
# TODO Générer la position potentielle du joueur en fonction de la direction
new_player_pos = ...
if validate_move(maze, new_player_pos):
# TODO Changer réellement la position du joueur
pass
return maze, player_pos
if __name__ == '__main__':
nb_row = 4
nb_col = 7
player_pos = ... # TODO Définir la position ligne, colonne sur en haut à gauche
end_pos = ... # TODO Définir la position ligne, colonne sur en bas à droite
# Coordoné sous la forme (ligne, colone)
walls = [[0, 1],[1, 1], [1, 2], [1, 3], [1, 5], [2, 1], [2, 5], [3, 3], [3, 5]]
maze = init_maze(nb_row, nb_col, player_pos, end_pos, walls)
print_table(maze)
# TODO Décommenter pour tester votre code en Partie 2
# test_pos = [-1,0] changez les valeurs pour tester tous les cas possibles
# valid = validate_move(maze, test_pos)
# print(valid)
# TODO Décommenter pour tester votre code en Partie 3
# while player_pos != end_pos:
# key_pressed = input("mouvement : ")
# maze, player_pos = move(key_pressed, maze, player_pos)
# print_table(maze)
#
# print("Vous avez gagnez !")
|
c915ec7f7d86d86125636ba552451db6dfda9976 | kmiiloberrio-dev/platzi-pensamiento-computacional | /factoriales.py | 282 | 4 | 4 | def factorial(n):
"""Calcula el factorialde n.
:param int n: cualquier entero
:type n: int
:return: factorial de n
:rtype: int
"""
if n == 1:
return 1
return n * factorial(n - 1)
n = int(input('Escribe un entero: '))
print(factorial(n))
|
04d4c82cae133609984fd5c7c3a8215298456413 | shanthanu9/Numerical-Methods | /Python-scripts/Numerical integration/num-int.py | 1,799 | 3.53125 | 4 | # <<<<<<<<<<< BASIC RULES
def trapezoidal_rule(x, y):
assert len(x) == len(y) == 2
h = x[1] - x[0]
return (h/2)*(y[0] + y[1])
def simpson_one_third_rule(x, y):
assert len(x) == len(y) == 3
h = x[1] - x[0]
return (h/3)*(y[0] + 4*y[1] + y[2])
def simpson_three_eighth_rule(x, y):
assert len(x) == len(y) == 4
h = x[1] - x[0]
return (3*h/8)*(y[0] + 3*y[1] + 3*y[2] + y[3])
def boole_rule(x, y):
assert len(x) == len(y) == 5
h = x[1] - x[0]
return (2*h/45)*(7*y[0] + 32*y[1] + 12*y[2] + 32*y[3] + 7*y[4])
# <<<<<<<<<<< COMPOSITE NEWTON COTE'S RULE
# <<<<<< Composite trapezoidal rule
def composite_trapezoidal_rule(x, y):
assert len(x) == len(y)
sum = 0
for i in range(0, len(x)-1):
sum += trapezoidal_rule(x[i:i+2], y[i:i+2])
return sum
x = [7.47, 7.48, 7.49, 7.50, 7.51, 7.52]
y = [1.93, 1.95, 1.98, 2.01, 2.03, 2.06]
# composite_trapezoidal_rule(x, y)
# <<<<<< Composite Simpson's one-third rule
def composite_simpson_one_third_rule(x, y):
assert len(x) == len(y)
sum = 0
for i in range(0, len(x)-2, 2):
sum += simpson_one_third_rule(x[i:i+3], y[i:i+3])
return sum
x = [0, 0.25, 0.5, 0.75, 1.00, 1.25, 1.50, 1.75, 2.00]
y = [0.5, 0.4923, 0.4706, 0.4384, 0.4, 0.3596, 0.32, 0.2832, 0.25]
# composite_simpson_one_third_rule(x, y)
# <<<<<< Composite Simpson's three-eighth rule
def composite_simpson_three_eighth_rule(x, y):
assert len(x) == len(y)
sum = 0
for i in range(0, len(x)-3, 3):
sum += simpson_three_eighth_rule(x[i:i+4], y[i:i+4])
return sum
# <<<<<< Composite Boole's rule
def composite_boole_rule(x, y):
assert len(x) == len(y)
sum = 0
for i in range(0, len(x)-4, 4):
sum += simpson_three_eighth_rule(x[i:i+5], y[i:i+5])
return sum |
e532b69cd8846c229d20fd619294ec6407c49d57 | RDinary/python_06_20 | /whiletrue.py | 2,202 | 3.75 | 4 | """
תרגיל:
כתבו פונקציה שתפקידה לקלוט מספר מהמשתמש ולוודא שהמספר בתחום בין 0 ל- 10000.V
V על הפונקציה לבקש קלט עד שהמשתמש יזין קלט נכון.
V על הפונקציה להחזיר את המספר בתור Integer.
תוודאו שהפונקציה לא תקרוס בשום שלב.
"""
#this is a git test
def get_num():
num = -3
while not (num <= 10000 and num >= 0):
try:
num = int(input("write a number 0-10000: "))
except ValueError:
print("this is not legal integer!")
except:
print("something went wrong")
return num
get_num()
'''
תרגיל:
כעת נממש את פונקציות Lower/Upper הקיימות ב- Python:
כתבו פונקציה המקבלת שני פרמטרים: מחרוזת ומספר.
אם המספר הוא 1 עליכם להחזיר מחרוזת באותיות קטנות, אם המספר הוא 2 עליכם להחזיר את המחרוזת באותיות גדולות.
בכל מקרה עליכם להדפיס את מספר המופעים של אותיות קטנות, אותיות גדולות, מספרים ואחר(סימנים וכו').
בצעו בדיקת קלט לפונקציה: לוודא שהמספר הוא 1 / 2 וגם שהמחרוזת היא אכן מחרוזת.
השתמשו בתכונות של טבלת ASCII
'''
a_ord = ord('a') # number
z_ord = ord('z') # number
A_ord = ord('A') # number
Z_ord = ord('Z') # number
ord_0 = ord('0')
delta = a_ord - A_ord # number
def Lower(somestring):
letters_list = []
for s in somestring: # s -> str with len ==1
if A_ord <= ord(s) <= Z_ord: # if s is capital letter
letters_list.append(chr(ord(s) + delta)) # ord(s) + delta -> num, chr() ->str
else:
letters_list.append(s)
lowerstring = "".join(letters_list)
return lowerstring
def Upper(somestring):
pass
def selector_function(some_string, some_number):
if some_number == 1:
print(Lower(some_string))
elif some_number == 2:
print(Upper(some_string))
selector_function("Have A wonderful day", 1)
|
e82277fdba921ba459741b8fedd0474d8719c47e | renanaquinno/python3 | /#ATIVIDADES_FABIO/#Atividade_Fabio_04_Repeticao_While/#Atividade_Fabio04_Repeticao_21_multiplicacao_sem_operador.py | 483 | 4 | 4 | #entrada
numero_a = int(input())
numero_b = int(input())
#processamento
def multiplicacao (numero_a, numero_b):
multiplicador = 0
resultado = 0
if numero_a > numero_b:
maior = numero_a
menor = numero_b
else:
maior = numero_b
menor = numero_a
while multiplicador < maior:
multiplicador += 1
resultado += menor
print(resultado)
#saida
multiplicacao(numero_a, numero_b)
|
8e2002464d191dc72f4fd1e5f19e7bc7f6ee20e3 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/11 Functions/return_value_from_function.py | 350 | 3.921875 | 4 | #!/usr/bin/python3
# Functions in Python
# Use of return keyword in Python
def main():
print(testfunc())
print(mytestfunc())
for i in mytestfunc(): print(i , end= ' ')
def testfunc():
return 'This is a test function'
# Return object from function
def mytestfunc():
return range(25)
if __name__ == "__main__": main()
|
9f9e7a87283f41fd95f7f50aa2fc0920721b0fb9 | SuperHong94/2020_1_ | /파이썬공부/python example/7week/ex.py | 379 | 4.03125 | 4 | SHIFT=1
def encrypt(raw):
ret=''
for ch in raw:
ret+=chr(ord(ch)+SHIFT)
return ret
def decrypt(raw):
ret=""
for ch in raw:
ret += chr(ord(ch)-SHIFT)
return ret
if __name__=="__main__":
raw=input("input: ")
encrypted=encrypt(raw)
print("encrypted:"+encrypted)
decrypted=decrypt(encrypted)
print("decrypted:"+decrypted) |
c2d8554c569126f252c2a7956b48e9775a79614a | gidoj/ore | /textstyler.py | 855 | 3.5 | 4 | # USAGE: styler.BOLD + 'some text' + styler.END
class Styler:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
COLOR_LENGTH = 9 # 5 + 4 = len(COLOR) + len(END)
STYLE_LENGTH = 8 # 4 + 4 = len(BOLD, UNDERLINE) + len(END)
@staticmethod
def style(text, mode):
'''Stylize text with desired mode.
Options are:
purple, cyan, darkcyan, blue, green, yellow,
red, bold, underline
'''
try:
stylized = mode + text + Styler.END
except TypeError:
print("Error: incorrect style mode specified.")
stylized = text
return stylized
|
8827491e380757a1c185e6f59034de784cc36ae5 | d1makov/py_sqlphones | /sqlcontacts.py | 1,628 | 3.890625 | 4 | """
sqlite database with contacts
"""
import sqlite3
class PhoneBook:
"""
PhoneBook class
"""
def __init__(self):
self.conn = sqlite3.connect("phone_book.db")
self.conn.execute("""CREATE TABLE IF NOT EXISTS first_phone_book(
id INTEGER PRIMARY KEY,
name VARCHAR(30) UNIQUE, phone VARCHAR(30))""")
def create(self, name, phone):
"""
Update database
:param name:
:param phone:
:return:
"""
sql = "INSERT OR IGNORE INTO " \
"first_phone_book (name, phone) VALUES(?, ?)"
try:
self.conn.execute(sql, (name, phone))
self.conn.commit()
except sqlite3.OperationalError:
raise KeyError
def read(self, name):
"""
search contact
:param name:
:return:
"""
sql = """SELECT phone FROM first_phone_book WHERE name=?"""
res = self.conn.execute(sql, (name,))
res = res.fetchone()
if not res:
raise KeyError
return int(res[0])
def update(self, name, phone):
"""
Change contact
:param name:
:param phone:
:return:
"""
sql = """UPDATE first_phone_book SET phone=? WHERE name=?"""
self.conn.execute(sql, (phone, name))
self.conn.commit()
def delete(self, name):
"""
Delete contact
:param name:
:return:
"""
sql = """DELETE FROM first_phone_book
WHERE name=?"""
self.conn.execute(sql, (name,))
self.conn.commit()
|
87dd4ce49665503c34f350fd26896b268f228128 | dudulima17/exercicios_python | /custo_fabrica(2).py | 524 | 3.90625 | 4 | #O custo ao consumidor de um carro novo é a soma do custo de fábrica com a percentagem do distribuidor e dos impostos (aplicados ao custo de fábrica). Supondo que a percentagem do distribuidor seja de 28% e os impostos de 45%, escrever um algoritmo que leia o custo de fábrica de um carro e escreva o custo ao consumidor.
#VARIÁVEIS DE ENTRADA
val_carro=int(input('Digite o valor do carro:'))
distri=0.28
impos=0.45
custo=0.27
custo_consu=(val_carro*custo)
print("O custo da fábrica é: ",custo_consu) #SAÍDA
|
bed8fabd1c1da687083e9625b3ccfd22f9482987 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/a81c0e0c53d14def8a393bd2566a810b.py | 995 | 3.671875 | 4 | import datetime
import calendar
def meetup_day(y, m, wd, d):
week_days = {
'monday': 0,
'tuesday': 1,
'wednesday': 2,
'thursday': 3,
'friday': 4,
'saturday': 5,
'sunday': 6
}
count = 0
if d == 'last':
for i in range(calendar.monthrange(y, m)[1], 1, -1):
if datetime.date(y, m, i).weekday() == week_days[wd.lower()]:
return datetime.date(y, m, i)
if d[0].isdigit():
for i in range(1, calendar.monthrange(y, m)[1]+1):
if datetime.date(y, m, i).weekday() == week_days[wd.lower()]:
count += 1
if count == int(d[0]):
return datetime.date(y, m, i)
else:
for i in range(13, 19):
if datetime.date(y, m, i).weekday() == week_days[wd.lower()]:
return datetime.date(y, m, i)
|
69521d165a9619d8269f60366554d13180ecddbb | MarceloBritoWD/URI-online-judge-responses | /Iniciante/1059.py | 108 | 3.78125 | 4 | # -*- coding: utf-8 -*-
x = 1
while (x <= 100):
if (x % 2) == 0:
print(x)
x = x + 1 |
d230ceacec7796c2354b50086f933739be083fb9 | amtfbky/git_py | /dg/base/review/67-抛出异常.py | 487 | 3.640625 | 4 | def input_passwd():
# 1.提示用户输入密码
pwd = input("请输入密码:")
# 2.判断密码长度>=8,返回用户输入密码
if len(pwd) >= 8:
return pwd
# 3.如果<8主动抛出异常
print("主动抛出异常")
# 1)创建异常对象,可以使用错误信息字符串作为参数
ex = Exception("密码长度不够")
# 2)主动抛出异常
raise ex
try:
print(input_passwd())
except Exception as res:
print(res)
|
beaa4cfea18f0617f0f98f1f9209532854bbca54 | setthecontrols/algos | /graphs/connected_components.py | 2,581 | 3.875 | 4 | # Reference: http://quiz.geeksforgeeks.org/connected-components-in-an-undirected-graph/
# In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two verties are connected to each other by paths, and which is connected to no additional vertices in the supergraph. - Wikipedia
# Given an undirected graph, we print all connected components line by line. For example, consider graph3.gif in this directory, represented in the following way by this dictionary:
graph3 = {
1: [0,2],
0: [1],
2: [1],
3: [4],
4: [3]
}
# Then the output should be:
"0 1 2"
"3 4"
2
# This is because "0 1 2" make up one component of the graph, and "3 4" the other, which means that there are 2 connected components.
# Pseudocode:
# Initialize a dictionary called "visited" whose keys are the vertices, and whose values are False or True depending on whether a vertex has been visited or not
# Initialize a "component_count" integer type which keeps track of the number of components
# Initialize a "component" string type which keeps track of which vertices are in each separate component
# For each vertex in the graph, do the following:
# If it is not visited, then run a depth first search on the graph (called with the graph, the vertex, the visited dict, and the component string)
# Within the depth first search:
# Mark the vertex as visited
# Push the vertex's value into the component string
# For each adjacent node,
# If the adjacent node is not visited, then run dfs on it with the graph, the adjacent node, the visited dict, and the component string
# Print the component string
# Reset the component string
# Add one to the component count
# At the very end, return the component count
def connected_components(graph):
visited = {vertex: False for vertex in graph}
component = ''
components_count = 0
def dfs(graph, vertex, visited):
nonlocal component
visited[vertex] = True
component += str(vertex) + ' '
for adjacent_vertex in graph[vertex]:
if not visited[adjacent_vertex]:
dfs(graph, adjacent_vertex, visited)
for vertex in graph:
if not visited[vertex]:
dfs(graph, vertex, visited)
print(component)
component = ''
components_count += 1
return components_count
print(connected_components(graph3))
|
6f0e86770a958af21963cff894abe8cbe3e5a87f | Brokenshire/codewars-projects | /Python/eight_kyu/multiply.py | 645 | 3.921875 | 4 | # Python solution for 'Multiply' codewars question.
# Level: 8 kyu
# Tags: Algorithms, Date/Time, Mathematics, and Numbers
# Author: Jack Brokenshire
# Date: 07/02/2020
import unittest
def multiply(a, b):
"""
The code does not execute properly. Try to figure out why.
:param a: a positive integer value
:param b: a positive integer value
:return: the result of multiplying the two integers together
"""
return a * b
class TestMultiply(unittest.TestCase):
"""Class to test 'multiply' function"""
def test_multiply(self):
self.assertEqual(multiply(1, 2), 2)
if __name__ == '__main__':
unittest.main()
|
67380bce023eedcd9347f93c58b041c2b3820dd4 | lehang123/COMP30024_ProjectFull | /2020-part-B-skeleton/teamProject/utils.py | 31,141 | 3.859375 | 4 | import math
def make_nodes(board, turn, include_boom=True):
"""
:param board: the current board
:param turn: who's turn to move
:param include_boom: include the boom action in nodes
:return: all the legal moves
"""
# all the white stacks are ours to move
opponent = 'white' if turn == 'black' else 'black'
stacks = board[turn]
oppo_stacks = board[opponent]
blocks = [stack[1:] for stack in oppo_stacks]
# according to stacks(current state), to generate next moves(nodes)
nodes = []
for j in range(len(stacks)):
stack = stacks[j]
n = stack[0]
for i in range(1, n + 1):
for k in range(1, n + 1):
moved_up_stacks = move_up(stack, i, k, blocks)
if moved_up_stacks:
update_nodes(oppo_stacks, moved_up_stacks, stacks, nodes, j, turn, opponent)
moved_down_stacks = move_down(stack, i, k, blocks)
if moved_down_stacks:
update_nodes(oppo_stacks, moved_down_stacks, stacks, nodes, j, turn, opponent)
moved_left_stacks = move_left(stack, i, k, blocks)
if moved_left_stacks:
update_nodes(oppo_stacks, moved_left_stacks, stacks, nodes, j, turn, opponent)
moved_right_stacks = move_right(stack, i, k, blocks)
if moved_right_stacks:
update_nodes(oppo_stacks, moved_right_stacks, stacks, nodes, j, turn, opponent)
if include_boom:
node = board.copy()
boom(stack, node)
nodes.append(node)
return nodes
def move_up(stack, ns, bs, blocks):
"""
move up a stack
:param stack: the stack that moves
:param ns: number of pieces in stack wants to move
:param bs: distance that wants to move
:param blocks: opponent pieces that can't be stepped on
:return: the result of moving
"""
n, x, y = stack[0], stack[1], stack[2]
yf = y + bs
if 0 <= x <= 7 and 0 <= y <= 6 and n >= ns > 0:
if n - ns != 0 and [x, yf] not in blocks and 0 <= yf <= 7:
return [[ns, x, yf], [n - ns, x, y]]
elif [x, yf] not in blocks and 0 <= yf <= 7:
return [[ns, x, yf]]
else:
return []
else:
return []
def move_down(stack, ns, bs, blocks):
"""
move down a stack
:param stack: the stack that moves
:param ns: number of pieces in stack wants to move
:param bs: distance that wants to move
:param blocks: opponent piece that can't be stepped on
:return: the result of moving
"""
n, x, y = stack[0], stack[1], stack[2]
yf = y - bs
if 0 <= x <= 7 and 1 <= y <= 7 and n >= ns > 0:
if n - ns != 0 and [x, yf] not in blocks and 0 <= yf <= 7:
return [[ns, x, yf]] + [[n - ns, x, y]]
elif [x, yf] not in blocks and 0 <= yf <= 7:
return [[ns, x, yf]]
else:
return []
else:
return []
def move_left(stack, ns, bs, blocks):
"""
move left a stack
:param stack: the stack that moves
:param ns: number of pieces in stack wants to move
:param bs: distance that wants to move
:param blocks: opponent piece that can't be stepped on
:return: the result of moving
"""
n, x, y = stack[0], stack[1], stack[2]
xf = x - bs
if 1 <= x <= 7 and 0 <= y <= 7 and n >= ns > 0:
if n - ns != 0 and [xf, y] not in blocks and 0 <= xf <= 7:
return [[ns, xf, y]] + [[n - ns, x, y]]
elif [xf, y] not in blocks and 0 <= xf <= 7:
return [[ns, xf, y]]
else:
return []
else:
return []
def move_right(stack, ns, bs, blocks):
"""
move right a stack
:param stack: the stack that moves
:param ns: number of pieces in stack wants to move
:param bs: distance that wants to move
:param blocks: opponent piece that can't be stepped on
:return: the result of moving
"""
n, x, y = stack[0], stack[1], stack[2]
xf = x + bs
if 0 <= x <= 6 and 0 <= y <= 7 and n >= ns > 0:
if n - ns != 0 and [xf, y] not in blocks and 0 <= xf <= 7:
return [[ns, xf, y]] + [[n - ns, x, y]]
elif [xf, y] not in blocks and 0 <= xf <= 7:
return [[ns, xf, y]]
else:
return []
else:
return []
def boom(origin, data):
"""
explode the piece
:param origin: the place that exploded
:param data: the board information
"""
white = data['white']
black = data['black']
affected_zone = boom_zone(origin[1::])
affected_pieces = []
unaffected_whites = []
unaffected_blacks = []
for stack in white:
if stack[1::] in affected_zone:
affected_pieces.append(stack)
else:
unaffected_whites.append(stack)
for stack in black:
if stack[1::] in affected_zone:
affected_pieces.append(stack)
else:
unaffected_blacks.append(stack)
data['white'] = unaffected_whites
data['black'] = unaffected_blacks
for piece in affected_pieces:
boom(piece, data)
def boom_zone(stack, exclude_self=False, check_valid=False):
"""
where is going to be affected after the stack exploded
:param stack: the stack that's going to exploded
:param exclude_self: return boom zone including current location ?
:param check_valid: check if it's valid
:return all the affected zone
"""
x, y = stack
if exclude_self:
zone = [[x - 1, y + 1], [x, y + 1], [x + 1, y + 1], [x - 1, y], [x + 1, y], [x - 1, y - 1], [x, y - 1],
[x + 1, y - 1]]
else:
zone = [[x - 1, y + 1], [x, y + 1], [x + 1, y + 1], [x - 1, y], [x, y], [x + 1, y], [x - 1, y - 1], [x, y - 1],
[x + 1, y - 1]]
if check_valid:
zone = [z for z in zone if (0 <= z[0] <= 7) and (0 <= z[1] <= 7)]
return zone
def update_nodes(oppo_nodes, action_stacks, stacks, nodes, index, me, oppo):
"""
Generate a board configuration after an action and add this node to nodes
@param oppo_nodes: the opponent tokens
@param action_stacks: new stack after the action
@param stacks: original stacks
@param nodes: the nodes that stored all possible board configuration after moves
@param index: the index of the stack that has been moved
@param me: the color of us
@param oppo: the color of opponent
"""
node = {}
my_nodes = action_stacks + stacks
my_nodes.pop(index + len(action_stacks)) # pop up original position
node_stack(my_nodes)
node[me] = my_nodes
node[oppo] = oppo_nodes
nodes.append(node)
def node_stack(my_node):
"""
something when pieces move, they stack on other my pieces, here is to stack
:param my_node: the node that create and haven't check for stacks
"""
for i in range(1, len(my_node)):
if my_node[i][-2::] == my_node[0][-2::]:
my_node[0][0] += my_node[i][0]
my_node.pop(i)
break
def count_pieces(_for, node):
"""
get the number pieces for an player
:param _for: opponent or player
:param node: the current board
:return: the number of pieces on board for that player
"""
return sum((map((lambda x: x[0]), node[_for])))
def lists_to_tuples(lists):
"""
as list is not hashable, sometime we need to cast it as a tuple.
We deal with list of list a lot, so we need to do a folding like cast for our multi-dimension list
:param lists: the lists that going to be casted
"""
if isinstance(lists, list):
# cast to tuple
return tuple([lists_to_tuples(l) for l in lists])
else:
return lists
def tuples_to_lists(tuples):
"""
work as the same as lists_to_tuples(lists), but this is backward
"""
if isinstance(tuples, tuple):
# cast to tuple
return [tuples_to_lists(t) for t in tuples]
else:
return tuples
def print_board(board_dict, message="", unicode=False, compact=True, **kwargs):
"""
For help with visualisation and debugging: output a board diagram with
any information you like (tokens, heuristic values, distances, etc.).
Arguments:
board_dict -- A dictionary with (x, y) tuples as keys (x, y in range(8))
and printable objects (e.g. strings, numbers) as values. This function
will arrange these printable values on the grid and output the result.
Note: At most the first 3 characters will be printed from the string
representation of each value.
message -- A printable object (e.g. string, number) that will be placed
above the board in the visualisation. Default is "" (no message).
unicode -- True if you want to use non-ASCII symbols in the board
visualisation (see below), False to use only ASCII symbols.
Default is False, since the unicode symbols may not agree with some
terminal emulators.
compact -- True if you want to use a compact board visualisation, with
coordinates along the edges of the board, False to use a bigger one
with coordinates alongside the printable information in each square.
Default True (small board).
Any other keyword arguments are passed through to the print function.
"""
if unicode:
if compact:
template = """# {}
# ┌───┬───┬───┬───┬───┬───┬───┬───┐
# 7 │{:}│{:}│{:}│{:}│{:}│{:}│{:}│{:}│
# ├───┼───┼───┼───┼───┼───┼───┼───┤
# 6 │{:}│{:}│{:}│{:}│{:}│{:}│{:}│{:}│
# ├───┼───┼───┼───┼───┼───┼───┼───┤
# 5 │{:}│{:}│{:}│{:}│{:}│{:}│{:}│{:}│
# ├───┼───┼───┼───┼───┼───┼───┼───┤
# 4 │{:}│{:}│{:}│{:}│{:}│{:}│{:}│{:}│
# ├───┼───┼───┼───┼───┼───┼───┼───┤
# 3 │{:}│{:}│{:}│{:}│{:}│{:}│{:}│{:}│
# ├───┼───┼───┼───┼───┼───┼───┼───┤
# 2 │{:}│{:}│{:}│{:}│{:}│{:}│{:}│{:}│
# ├───┼───┼───┼───┼───┼───┼───┼───┤
# 1 │{:}│{:}│{:}│{:}│{:}│{:}│{:}│{:}│
# ├───┼───┼───┼───┼───┼───┼───┼───┤
# 0 │{:}│{:}│{:}│{:}│{:}│{:}│{:}│{:}│
# └───┴───┴───┴───┴───┴───┴───┴───┘
# y/x 0 1 2 3 4 5 6 7"""
else:
template = """# {}
# ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
# │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │
# │ 0,7 │ 1,7 │ 2,7 │ 3,7 │ 4,7 │ 5,7 │ 6,7 │ 7,7 │
# ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
# │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │
# │ 0,6 │ 1,6 │ 2,6 │ 3,6 │ 4,6 │ 5,6 │ 6,6 │ 7,6 │
# ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
# │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │
# │ 0,5 │ 1,5 │ 2,5 │ 3,5 │ 4,5 │ 5,5 │ 6,5 │ 7,5 │
# ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
# │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │
# │ 0,4 │ 1,4 │ 2,4 │ 3,4 │ 4,4 │ 5,4 │ 6,4 │ 7,4 │
# ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
# │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │
# │ 0,3 │ 1,3 │ 2,3 │ 3,3 │ 4,3 │ 5,3 │ 6,3 │ 7,3 │
# ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
# │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │
# │ 0,2 │ 1,2 │ 2,2 │ 3,2 │ 4,2 │ 5,2 │ 6,2 │ 7,2 │
# ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
# │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │
# │ 0,1 │ 1,1 │ 2,1 │ 3,1 │ 4,1 │ 5,1 │ 6,1 │ 7,1 │
# ├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤
# │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │ {:} │
# │ 0,0 │ 1,0 │ 2,0 │ 3,0 │ 4,0 │ 5,0 │ 6,0 │ 7,0 │
# └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘"""
else:
if compact:
template = """# {}
# +---+---+---+---+---+---+---+---+
# 7 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|{:}|
# +---+---+---+---+---+---+---+---+
# 6 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|{:}|
# +---+---+---+---+---+---+---+---+
# 5 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|{:}|
# +---+---+---+---+---+---+---+---+
# 4 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|{:}|
# +---+---+---+---+---+---+---+---+
# 3 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|{:}|
# +---+---+---+---+---+---+---+---+
# 2 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|{:}|
# +---+---+---+---+---+---+---+---+
# 1 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|{:}|
# +---+---+---+---+---+---+---+---+
# 0 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|{:}|
# +---+---+---+---+---+---+---+---+
# y/x 0 1 2 3 4 5 6 7"""
else:
template = """# {}
# +-----+-----+-----+-----+-----+-----+-----+-----+
# | {:} | {:} | {:} | {:} | {:} | {:} | {:} | {:} |
# | 0,7 | 1,7 | 2,7 | 3,7 | 4,7 | 5,7 | 6,7 | 7,7 |
# +-----+-----+-----+-----+-----+-----+-----+-----+
# | {:} | {:} | {:} | {:} | {:} | {:} | {:} | {:} |
# | 0,6 | 1,6 | 2,6 | 3,6 | 4,6 | 5,6 | 6,6 | 7,6 |
# +-----+-----+-----+-----+-----+-----+-----+-----+
# | {:} | {:} | {:} | {:} | {:} | {:} | {:} | {:} |
# | 0,5 | 1,5 | 2,5 | 3,5 | 4,5 | 5,5 | 6,5 | 7,5 |
# +-----+-----+-----+-----+-----+-----+-----+-----+
# | {:} | {:} | {:} | {:} | {:} | {:} | {:} | {:} |
# | 0,4 | 1,4 | 2,4 | 3,4 | 4,4 | 5,4 | 6,4 | 7,4 |
# +-----+-----+-----+-----+-----+-----+-----+-----+
# | {:} | {:} | {:} | {:} | {:} | {:} | {:} | {:} |
# | 0,3 | 1,3 | 2,3 | 3,3 | 4,3 | 5,3 | 6,3 | 7,3 |
# +-----+-----+-----+-----+-----+-----+-----+-----+
# | {:} | {:} | {:} | {:} | {:} | {:} | {:} | {:} |
# | 0,2 | 1,2 | 2,2 | 3,2 | 4,2 | 5,2 | 6,2 | 7,2 |
# +-----+-----+-----+-----+-----+-----+-----+-----+
# | {:} | {:} | {:} | {:} | {:} | {:} | {:} | {:} |
# | 0,1 | 1,1 | 2,1 | 3,1 | 4,1 | 5,1 | 6,1 | 7,1 |
# +-----+-----+-----+-----+-----+-----+-----+-----+
# | {:} | {:} | {:} | {:} | {:} | {:} | {:} | {:} |
# | 0,0 | 1,0 | 2,0 | 3,0 | 4,0 | 5,0 | 6,0 | 7,0 |
# +-----+-----+-----+-----+-----+-----+-----+-----+"""
# convert to print format
if 'white' in board_dict:
board_dict = json_to_board(board_dict)
# board the board string
coords = [(x, 7 - y) for y in range(8) for x in range(8)]
cells = []
for xy in coords:
if xy not in board_dict:
cells.append(" ")
else:
cells.append(str(board_dict[xy])[:3].center(3))
# print it
print(template.format(message, *cells), **kwargs)
def json_to_board(data):
"""
:param data: the data in json format which easy to be used to run
:return: the data in the print_board required format to be used to print
"""
dict = {}
white = data['white']
for p in white:
position = (p[1], p[2])
stack = 'w' + str(p[0])
dict[position] = stack
black = data['black']
for p in black:
position = (p[1], p[2])
stack = 'b' + str(p[0])
dict[position] = stack
return dict
def board_dict_to_tuple(dic):
"""
:param dic: dictionary that convert to tuple
"""
white_pieces = dic['white']
black_pieces = dic['black']
return [lists_to_tuples(white_pieces), lists_to_tuples(black_pieces)]
def string_to_tuple(string):
x, y = string.split(",")
return int(x), int(y)
def nodes_to_move(before, after, color):
"""
to convert the change of two node (before and after) to the user input command
:param before: the node before (in dictionary form) {'white': xxx, 'black': xxx}
:param after: the node after (in dictionary form) {'white': xxx, 'black': xxx}
:param color: the color that moved
:return: the user input command
"""
cur_pieces = lists_to_tuples(before[color])
nex_pieces = lists_to_tuples(after[color])
cur_pieces_num = sum([w[0] for w in cur_pieces])
nex_pieces_num = sum([w[0] for w in nex_pieces])
if cur_pieces_num == nex_pieces_num:
# nothing boom, it's an move action
_before = set(cur_pieces).difference(nex_pieces)
_after = set(nex_pieces).difference(cur_pieces)
# the movement
n_m, x_1, y_1, x_2, y_2 = (0, -1, -1, -1, -1)
if len(_before) == len(_after):
# no difference in positions, means move from stack to stack
if len(_before) == 2:
[(b_n, b_x, b_y), (_, b_x1, b_y1)] = _before
for (n, x, y) in _after:
if x == b_x and y == b_y:
n_m = n - b_n
if n_m > 0:
x_1, y_1, x_2, y_2 = b_x1, b_y1, b_x, b_y
else:
x_1, y_1, x_2, y_2 = b_x, b_y, b_x1, b_y1
elif len(_before) == 1:
# this moved a full stacks
[(n_m, x_1, y_1)] = _before
[(_, x_2, y_2)] = list(_after)
else:
_before_positions = lists_to_tuples([[x, y] for (n, x, y) in _before])
_after_positions = lists_to_tuples([[x, y] for (n, x, y) in _after])
move_from = set(_before_positions).difference(_after_positions)
move_to = set(_after_positions).difference(_before_positions)
if move_to:
# move to some place new
[(x_2, y_2)] = move_to
for (n, x, y) in _after:
if x == x_2 and y == y_2:
n_m = n
else:
x_1, y_1 = x, y
elif move_from:
# move to an known place
[(x_1, y_1)] = move_from
for (n, x, y) in _before:
if x == x_1 and y == y_1:
n_m = n
else:
x_2, y_2 = x, y
return "MOVE", n_m, (x_1, y_1), (x_2, y_2)
# print_move(n_m, x_1, y_1, x_2, y_2)
elif nex_pieces_num < cur_pieces_num:
# white become less, boomed
(_, x, y) = list(set(cur_pieces).difference(nex_pieces))[0]
# print_boom(x, y)
return "BOOM", (x, y)
else:
# print("panic, growing number of whites")
return None
def make_goal(board, color):
"""
find the best(closest) goal state on the board to be used in the search algorithm, goal in this game is to destroy all the
black pieces, so we are going to find all the possible positions that we can place whites and explode to finish the
goal
we defining the best goal is the closest, and we are using manhattan distance to calculate between distance
:param board: the board
:param color: the color we check for number of goal needed
"""
stacks = board[color]
if stacks:
# get all the boom_zone for black
l = list(map(lambda x: x[1::], stacks))
boom_zones = boom_areas(stacks[0][1::], l.copy())
boom_keys = list(boom_zones.keys())
boom_dict = boom_zones_intersect(boom_zones, boom_keys[0], boom_keys[1::])
# find the minimum pieces required to destroy all blacks
goal_positions = []
find_positions(boom_zones, boom_dict, l, goal_positions)
return goal_positions
else:
return []
def boom_areas(stack, stacks):
"""
similar to boom_zone but now we check for chain reaction
@param stack: the stack that's going to explode
@param stacks: the rest of the stacks on the board
@return: all positions that are going to explode {stacks: position to explode them}
"""
bz = boom_zone(stack, True)
exploded = [stack]
p_bz = {}
for s in stacks:
if s in bz:
bz = merge_lists(bz, boom_zone(s, True)) # s exploded as well and expanded boom zone
exploded.append(s)
# remove those are already exploded
for e in exploded:
stacks.remove(e)
exploded += expand_bz(bz, stacks)
p_bz[lists_to_tuples(exploded)] = bz
if stacks:
p_bz.update(boom_areas(stacks[0], stacks.copy()))
return p_bz
else:
return p_bz
def clusters_count(stacks, num_clusters=0):
"""
count number of cluster for stacks
:param stacks: the rest of the stacks
:param num_clusters: the cluster that is counted already
:return: the number of cluster
"""
if not stacks:
return num_clusters
head = stacks[0]
ground_zero = boom_zone(head)
exploded = []
filter_list(stacks, (lambda x: x not in ground_zero), exploded)
for exp in exploded:
chain_explode(exp, stacks)
num_clusters += 1
return clusters_count(stacks, num_clusters)
def chain_explode(exp, stacks):
"""
simulate the chain explosion effect
:param exp: the one that exploded
:param stacks: the rest of the stack
"""
ground_zero = boom_zone(exp)
exploded = []
filter_list(stacks, (lambda x: x not in ground_zero), exploded)
if exploded:
for exp in exploded:
chain_explode(exp, stacks)
def get_clusters(stacks):
"""
get cluster for stacks
:param stacks: don't put in reference
:return: the cluster you have
"""
clusters = []
if not stacks:
return []
head = stacks[0][1::]
ground_zero = boom_zone(head)
exploded = []
filter_list(stacks, (lambda x: x[1::] not in ground_zero), exploded)
new_exploded = []
for exp in exploded:
new_exploded += chain_cluster(exp, stacks)
exploded += new_exploded
clusters.append(exploded)
return clusters + get_clusters(stacks)
def chain_cluster(exp, stacks):
"""
Chain different separate clusters together when boom zone intersect
:param exp: exploded token
:param stacks: other surrounding tokens
:return: tokens affected by explosion
"""
ground_zero = boom_zone(exp[1::])
exploded = []
filter_list(stacks, (lambda x: x[1::] not in ground_zero), exploded)
new_exploded = []
if exploded:
for exp in exploded:
new_exploded += chain_cluster(exp, stacks)
else:
return []
exploded += new_exploded
return exploded
def filter_list(remains, func, discards):
"""
to prevent delete strange behavior of deleting list while iterating,
this function is to help filter out list without breaking the rule to achieve that
:param remains: the remaining list
:param func: function to filter
:param discards: the discarded element
"""
temp = []
while remains:
x = remains.pop()
if func(x):
temp.append(x)
else:
# heapq.heappush(discards, x)
discards.append(x)
while temp:
remains.append(temp.pop())
def boom_affected_num(position, stacks):
"""
when one position goes off, how would one party get affected
:param position: that position that goes off
:param stacks: the current stacks that might be affected
:return: the number of affected for one party
"""
x, y = position
total = 0
bz = boom_zone([x, y], exclude_self=False, check_valid=True)
explodeds = []
filter_list(stacks, (lambda x: [x[1], x[2]] not in bz), explodeds)
for n, x, y in explodeds:
total += (boom_affected_num((x, y), stacks) + n)
return total
def cluster_boom_zone(position_cluster):
"""
to find a boom zone for a cluster
:param position_cluster: the cluster we looking for [[x1, y1], [x2, y2]]
:return: the boom zone of tnat cluster
"""
def valid_position(position):
return (0 <= position[0] <= 7) and (0 <= position[1] <= 7) and (position not in position_cluster)
cluster_bz = []
for position in position_cluster:
bz = boom_zone(position)
bz = [p for p in bz if valid_position(p)]
cluster_bz = merge_lists(cluster_bz, bz)
return cluster_bz
def merge_lists(l1, l2):
"""
merging of two list and remove duplicates
@param l1: list 1
@param l2: list 2
@return: merged list from l1 and l2 without duplicates
"""
return l1 + [i for i in l2 if i not in l1]
def expand_bz(bz, stacks):
"""
try expanding bz as far as possible, helper for boom_area
@param bz: boom zone
@param stacks: the rest of the stacks on the board
@return: resulted boom position after expanding
"""
keep_expand = False
exploded = []
for s in stacks:
if stacks in bz:
keep_expand = True # expanded, might be new elements will be coming in
bz = merge_lists(bz, boom_zone(s, True)) # s exploded as well and expanded boom zone
for e in exploded:
stacks.remove(e)
if keep_expand:
return exploded + expand_bz(bz, stacks)
else:
return exploded
def boom_zones_intersect(dic, keys_head, keys_rest):
"""
we are trying to find the intersection of boom_zones as this will help us to know if we put a white pieces there,
it's going to boom multiple boom zone.
:param dic: the dictionary that contains all (pieces - boom_zones) pairs
:param keys_head: we listed all the keys from the dict, and this is the first key
:param keys_rest: the rest of the keys from the dict
:return the intersect dictionary with intersect position as key and the pieces that affected as value
(always one position : (two to many) pieces)
"""
result = {}
if keys_rest:
hl1 = tuple(map(lambda x: tuple(x), dic[keys_head]))
for current_key in keys_rest:
hl2 = tuple(map(lambda x: tuple(x), dic[current_key]))
r = set(hl1).intersection(hl2)
if r:
# there is a intersection
for position in r:
result[position] = result.get(position, ()) + (keys_head + current_key)
# continue to check for intersection
result_rest = boom_zones_intersect(dic, keys_rest[0], keys_rest[1::])
for key in result_rest:
val = result.get(key, ()) + result_rest[key]
result[key] = tuple(set(tuple(i) for i in val))
for key in list(result):
if not (0 <= key[0] <= 7 and 0 <= key[1] <= 7):
result.pop(key, None)
return result
def find_positions(boom_zones, boom_dict, blocks, positions):
"""
finding the winning position
:param boom_zones: the boom zone that affect the pieces (pieces: boom_zones)
:param boom_dict: the intersection between the boom_zones (intersect: effected pieces)
:param blocks: the blocks that whites can't step on
:param positions: the positions that chosen
:return the position that will placed to destroy all the blacks
"""
boom_zones_queue = sorted([key for key in boom_zones], key=lambda t: len(t), reverse=True)
boom_dict_queue = sorted([(key, boom_dict[key]) for key in boom_dict], key=lambda t: len(t[1]), reverse=True)
max_boom_pieces = boom_zones_queue[0]
if boom_dict_queue: # always pop intersection first
# the max_intersection that
max_inter_zones = boom_dict_queue[0]
# max_inter_zones positions
mizpos = max_inter_zones[0]
# max_inter_zones pieces
mizpis = max_inter_zones[1]
pop_boom_zones(mizpis, boom_zones)
pop_boom_dict(mizpis, boom_dict)
positions.append(list(mizpos))
else:
# take out the boom_zones
boom_positions = boom_zones.pop(max_boom_pieces, None)
for bp in boom_positions:
if 0 <= bp[0] <= 7 \
and 0 <= bp[1] <= 7 \
and bp not in blocks \
and all(bp not in boom_zone(p) for p in positions):
positions.append(bp)
break
# take out the boom_dict
pop_boom_dict(max_boom_pieces, boom_dict)
if boom_zones:
find_positions(boom_zones, boom_dict, blocks, positions)
def pop_boom_zones(pop_pieces, boom_zones):
"""
to pop up the pieces from the boom_dict
:param pop_pieces: the pieces that need to be pop up
:param boom_zones: the boom_zones that pops
"""
for p in list(boom_zones):
if set(p).intersection(pop_pieces):
boom_zones.pop(p, None)
def boom_affected_count(position, board, dic):
"""
to see how many pieces is going to be affected if one position is exploded
:param position: position that blow off
:param board: the whole board, an array of stacks [('color', num, x, y)]
:param dic: that record the explosion {"s": 0, "b":0}
:return: the number of pieces that killed
"""
bz = boom_zone(position, exclude_self=False, check_valid=True)
explodeds = []
filter_list(board, (lambda x: [x[2], x[3]] not in bz), explodeds)
for c, n, x, y in explodeds:
dic[c] += n
boom_affected_count((x, y), board, dic)
def pop_boom_dict(pop_pieces, boom_dict):
"""
to pop up the pieces from the boom_dict
:param pop_pieces: the pieces that need to be pop up
:param boom_dict: the dict
"""
for p in list(boom_dict):
left = [piece for piece in boom_dict[p] if piece not in pop_pieces]
if left:
boom_dict[p] = tuple(left)
else:
boom_dict.pop(p, None)
def speedy_manhattan(position, stack):
"""
find the manhattan distance between 2 points
@param position: destination
@param stack: stack that moving
@return: the manhattan distance between the 2 points
"""
step = stack[0]
x = abs(position[0] - stack[1])
y = abs(position[1] - stack[2])
y_step = math.ceil(y / float(step))
x_step = math.ceil(x / float(step))
ans = x_step + y_step
return ans
|
52c4bd5b43dd2214cc8616e5db812d34ef795240 | YouthFlyingZy/python | /reverse.py | 386 | 4.09375 | 4 | # coding=utf-8
'''关于各种反转'''
#1.字符串反转
a='12345'
print(a[::-1]) #321
print(list(reversed(a))) #['5','4','3','2','1']
#2.列表反转
b=[1,2,3,4,5]
print(b[::-1]) #[5,4,3,2,1]
print(list(reversed(b))) #[5,4,3,2,1]
#3.元组反转
c=('R','u','n','o','o','b')
print(c[::-1]) #('b', 'o', 'o', 'n', 'u', 'R')
print(list(reversed(c))) #['b', 'o', 'o', 'n', 'u', 'R']
|
a12e2942c757be81d52c855115f6c0fa0236a10f | AlexandreChamard/CA320_Chat | /tests/client.py | 527 | 3.75 | 4 | #!/usr/bin/python3
# socket_echo_client.py
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 4242)
print('connecting to {} port {}'.format(*server_address))
sock.connect(server_address)
try:
# f = sock.makefile()
print('blabla')
l = sock.recv(42)
print(l)
sock.sendall(l)
# print('blabla')
finally:
print('closing socket')
sock.close()
|
bf11d37406a7b5d5ffc08a2f9a6109ef435a3d35 | cgallag/c-advent | /day11.py | 2,214 | 3.890625 | 4 |
def convert_to_num_list(password):
num_list = []
for letter in password:
num_list.append(ord(letter) - 97)
return num_list
def convert_from_num_list(num_list):
password = ''
for letter in num_list:
password += chr(letter + ord('a'))
return password
def meets_requirements(password):
letter_list = convert_to_num_list(password)
#1
has_three_letters = False
for num_letter, curr_letter in enumerate(letter_list[:-2]):
next_letter = letter_list[num_letter + 1]
second_next_letter = letter_list[num_letter + 2]
if ((curr_letter + 1) == next_letter) and ((curr_letter + 2) == second_next_letter):
has_three_letters = True
break
#2
not_has_i_o_l = True
if ('i' in password) or ('o' in password) or ('l' in password):
not_has_i_o_l = False
#3
letter_pairs = []
for num_letter, curr_letter in enumerate(letter_list[:-1]):
next_letter = letter_list[num_letter + 1]
if curr_letter == next_letter:
letter_pairs.append((curr_letter, next_letter))
has_letter_pairs = len(set(letter_pairs)) > 1
return (has_three_letters and not_has_i_o_l and has_letter_pairs)
def increment_password(password):
letter_list = convert_to_num_list(password)
for letter_num, letter in enumerate(reversed(letter_list)):
letter_loc = len(letter_list) - letter_num - 1
# continue incrementing
if letter + 1 > 25:
letter_list[letter_loc] = 0
# break loop
else:
letter_list[letter_loc] += 1
break
return convert_from_num_list(letter_list)
def find_next_password(password, ignore_initial=False):
count = 0
if ignore_initial:
password = increment_password(password)
while not meets_requirements(password):
if count%1000000 == 0:
print password
count += 1
password = increment_password(password)
return password
if __name__ == "__main__":
# print 'part 1 next password = {}'.format(find_next_password('vzbxkghb'))
print 'part 2 next password = {}'.format(find_next_password('vzbxxyzz', ignore_initial=True)) |
f2fc8347c3616d2a0c3c869183cd9a634c6b5832 | changetocoding/PyLoreKelly | /Week7/Library/kelly.py | 1,267 | 3.765625 | 4 | # DAVID: Nice fixed comments from last time
command = "Please enter an instruction "
phone_book = {"kelly": 4725692, "lore": 542652}
while True:
print(command)
user_prompt_text = input()
new_list = user_prompt_text.split()
# DAVID: Good spliting out into new better named variables (new_list[0] can be confusing later in the code)
user_prompt_text = new_list[0] # Don't understand why you reused user_prompt_text rather than a new name: Can be confusing later
name = new_list[1]
if user_prompt_text == "add":
# Good
name = new_list[1] # DAVID: lol and you didnt use name: Dont need this line as already done this
number = new_list[2]
phone_book[name] = number
print("This has been added \n")
elif user_prompt_text == "query":
name = "" # David Why set this and one below
number = 0
# David: just need below 3 lines but good
name = new_list[1]
new_number = phone_book.get(name)
print(name, new_number)
# David: What is wrong with this if statement
elif user_prompt_text == "query":
name = ""
number = 0
number = new_list[2]
phone_book[number] = name # this wont work
print(name, number) |
053de34e0ce077e7a772c99394ba0a0f55b06143 | betelgeuse-7/data-structures-and-algorithms | /Exercises/Stacks/s.py | 958 | 3.71875 | 4 | class StackIsEmptyException(Exception):
pass
"""
TOP
|
v
[ [w] [z] [y] [x] ]
"""
class Stack:
def __init__(self) -> None:
self.__items = []
self.__size = 0
def __str__(self) -> str:
return f"STACK ITEMS: {self.__items}"
def peek(self):
if self.__size == 0:
raise StackIsEmptyException
to_return = self.__items[-1]
return to_return
def push(self, value):
self.__items.append(value)
self.__size += 1
def pop(self):
if self.__size == 0:
raise StackIsEmptyException
to_pop = self.__items[-1]
self.__items.pop()
self.__size -= 1
return to_pop
def get_size(self):
return self.__size
def is_empty(self):
return self.__size == 0
def items(self):
return self.__items |
e70e162dc5a9afcc8da6c04066ffb8d87b0e4d31 | mirackara/CTAPredictionModels | /main.py | 8,655 | 4.15625 | 4 | import pandas
import datetime
import calendar
import numpy as np
import matplotlib.pyplot as plt
'''
Assignment 1.[15 Points] Write a Python function that takes a file name, as a string s, on input and, when called with s = ’CTA-Ridership-L-Station-Entries-Daily-Totals.csv’
reads in all data contained in the file. You are strongly #encouraged to use the Pandas module for this task (as #illustrated in lecture notes) but you are free to write #your own CSV file reader,
if you want. The function you #write to complete Assignment 1 will be used to complete #the subsequent assignments below.
'''
def Assignment1(s):
#Sorts the data from the csv file into a nicely formated data list
data = pandas.read_csv(s, names=['station_id','stationname','date','daytype','rides'], skiprows=[0])
return data
#Grabs the .csv file from PC location. NOTE: I had my csv named as cta.csv. Rename yours to corresponding file.
data = Assignment1('cta.csv')
'''Assignment 2.[15 Points] Write a function that prints to screen the average number of rides, for all months, for the UIC-Halsted (station id = 40350) train station.
Use the solution from Assignment 1 to access the data.
The output of your function must have the format
January : average number of rides as a float
February: average number of rides as a float
December: average number of rides as a float
'''
ridesList = data['rides'].tolist()
datesList = data['date'].tolist()
stationnameList = data['stationname'].tolist()
print("Assignment 2")
def Assignment2():
# Variable for the amount of times a month is counted
counterJan = 0
counterFeb = 0
counterMar = 0
counterApr= 0
counterMay = 0
counterJune = 0
counterJuly = 0
counterAug = 0
counterSept = 0
counterOct = 0
counterNov = 0
counterDec = 0
# Variable for the amount of rides
janRides = 0.0
febRides = 0.0
marRides = 0.0
aprRides = 0.0
mayRides = 0.0
juneRides = 0.0
julyRides = 0.0
augRides = 0.0
septRides = 0.0
octRides = 0.0
novRides = 0.0
decRides = 0.0
# In order to get our answer we have to divide rides/counter
for i in range(len(datesList)):
if stationnameList[i] == 'UIC-Halsted': #If the station is named 'UIC-Halsted'...
if datesList[i][0] == '0': #If the month is month < 10 ...
if datesList[i][1] == '1': #If the month is 'x' month...
janRides += ridesList[i] # Add the rides from the list
counterJan+=1 #Increase counter by 1
elif datesList[i][1] == '2':
febRides += ridesList[i]
counterFeb+=1
elif datesList[i][1] == '3':
marRides += ridesList[i]
counterMar+=1
elif datesList[i][1] == '4':
aprRides += ridesList[i]
counterApr+=1
elif datesList[i][1] == '5':
mayRides += ridesList[i]
counterMay+=1
elif datesList[i][1] == '6':
juneRides += ridesList[i]
counterJune+=1
elif datesList[i][1] == '7':
julyRides += ridesList[i]
counterJuly+=1
elif datesList[i][1] == '8':
augRides += ridesList[i]
counterAug+=1
elif datesList[i][1] == '9':
septRides += ridesList[i]
counterSept+=1
if datesList[i][0] == '1':
if datesList[i][1] == '0':
octRides += ridesList[i]
counterOct+=1
elif datesList[i][1] == '1':
novRides += ridesList[i]
counterNov+=1
elif datesList[i][1] == '2':
decRides += ridesList[i]
counterDec+=1
print('January: ' , janRides/counterJan)
print('February: ', febRides/counterFeb)
print('March: ', marRides/counterMar)
print('April: ', aprRides/counterApr)
print('May: ', mayRides/counterMay)
print('June: ', juneRides/counterJune )
print('July: ',julyRides/counterJuly )
print('August: ',augRides/counterAug)
print('September: ', septRides/counterSept )
print('October: ',octRides/counterOct)
print('November: ', novRides/counterNov )
print('December: ',decRides/counterDec )
Assignment2()
print('Assignment 3')
def getWeekday(year, month, day):
"""
input: integers year, month, day
output: name of the weekday on that date as a string
"""
date = datetime.date(year, month, day)
return calendar.day_name[date.weekday()]
def Assignment3():
'''
Assignment 3.[20 Points] Write a function that computes the average number of rides,
for all days of the week, for the UIC-Halsted (station id = 40350) train station.
Use the solution from Assignment 1 to access the data.
Assign the value of 1 for Monday, 2 for Tuesday, ... , and 7 for Sunday.
Using the polynomial curve fitting capabilities of NumPy, fit the data with a polynomial of degree 6.
predict the number of rides on a Wednesday for the UIC-Halsted train station
estimate which day of the week is the UIC-Halsted trains station most busy
estimate which day of the week is the UIC-Halsted trains station least busy
'''
# Days of the week
monday = 1
tuesday = 2
wednesday = 3
thursday = 4
friday = 5
saturday = 6
sunday = 7
# Variable for the day counter
counterMon = 0.0
counterTues = 0.0
counterWed = 0
counterThurs = 0.0
counterFriday = 0.0
counterSat = 0.0
counterSun = 0.0
# Variable for the amount of rides
monRides = 0.0
tuesRides = 0.0
wedRides = 0.0
thursRides = 0.0
friRides = 0.0
satRides = 0.0
sunRides = 0.0
datesSorted = [] #We have to sort the dates as well as convert to ints if we want to check it against the dates
for i in datesList: #Sorts the list
datesSorted.append(i.split('/'))
for i in range(len(datesSorted)): #Makes sure all values in the list are ints
for x in range(len(datesSorted[i])):
if type(datesSorted[i][x]) != int:
datesSorted[i][x] = int(datesSorted[i][x])
for i in range(len(ridesList)):
if stationnameList[i] == 'UIC-Halsted': #If the station name is UIC-Halsted...
if getWeekday(datesSorted[i][2], datesSorted[i][0], datesSorted[i][1]) == 'Monday':#If the day is Monday,,,
monRides += ridesList[i] # Add the rides from the list
counterMon+= 1 # Increase counter by 1
elif getWeekday(datesSorted[i][2], datesSorted[i][0], datesSorted[i][1]) == 'Tuesday':
tuesRides +=ridesList[i]
counterTues+=1
elif getWeekday(datesSorted[i][2], datesSorted[i][0], datesSorted[i][1]) == 'Wednesday':
wedRides +=ridesList[i]
counterWed+=1
elif getWeekday(datesSorted[i][2], datesSorted[i][0], datesSorted[i][1]) == 'Thursday':
thursRides +=ridesList[i]
counterThurs+=1
elif getWeekday(datesSorted[i][2], datesSorted[i][0], datesSorted[i][1]) == 'Friday':
friRides +=ridesList[i]
counterFriday+=1
elif getWeekday(datesSorted[i][2], datesSorted[i][0], datesSorted[i][1]) == 'Saturday':
satRides +=ridesList[i]
counterSat+=1
elif getWeekday(datesSorted[i][2], datesSorted[i][0], datesSorted[i][1]) == 'Sunday':
sunRides +=ridesList[i]
counterSun+=1
#Variables to add up the average number of rides per day
monTotal=monRides/counterMon
tuesTotal= tuesRides/counterTues
wedTotal = wedRides/counterWed
thursTotal= thursRides/counterThurs
friTotal = friRides/counterFriday
satTotal = satRides/counterSat
sunTotal = sunRides/counterSun
print('Mondays: ', monTotal)
print('Tuesday: ', tuesTotal)
print('Wednesday: ', wedTotal)
print('Thursday: ', thursTotal)
print('Friday: ', friTotal)
print('Saturday: ', satTotal)
print('Sunday: ', sunTotal)
#List of all weekdays
strWeekDays = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
weekdays = [monday,tuesday,wednesday,thursday,friday,saturday,sunday]
x = weekdays
y = [monTotal, tuesTotal, wedTotal, thursTotal, friTotal, satTotal, sunTotal]
ymax = str(max(y))
ymin = str(min(y))
for i in range(1,7):
if (str(y[i]) == ymax):
maxDay = strWeekDays[i]
if (str(y[i]) == ymin):
minDay = strWeekDays[i]
f = np.polyfit(x, y, 6)
F = np.poly1d(f)
#Plots the graph (X: Weekdays Y: Average Rides per days)
plt.plot(x, y, 'bo')
print("Prediction for the number of rides on a Wednesday for the UIC-Halsted train station: " + str(wedTotal))
print("Estimate for which day of the week is the UIC-Halsted trains station most busy: " + maxDay)
print("Estimate for which day of the week is the UIC-Halsted trains station least busy: " + minDay)
#Plots data on graph
plt.plot(x, F(x))
Assignment3()
|
954ef87632a5d7f12e05c91239b5f52b77c88605 | anlzou/python-test | /python-course/寒假练习/P367_python学习手册.py | 112 | 3.640625 | 4 | #lambda表达式
L = [lambda x:x**2,lambda x:x**3,lambda x:x**4]
for f in L:
print (f(2))
print (L[0](3))
|
eb54d8c069218190490faf117a3fe627e7ee76fc | gauravssnl/Data-Structures-and-Algorithms | /python/A First Course on Data Structures in Python/algo/recursion/recursivesumk.py | 142 | 3.5625 | 4 | def recursve_sum(k):
if k > 0:
return recursve_sum(k - 1) + k
return 0
if __name__ == "__main__":
print(recursve_sum(10)) |
e8e68196616cbe178899d1221cbaa6ba377354e6 | AlexisGfly/python_stack | /python/fundamentals/BankAccount.py | 871 | 3.5 | 4 | class BankAccount:
def __init__(self, int_rate, balance):
self.rate = int_rate
self.account_balance = balance
def deposit(self, amount):
self.account_balance += amount
return self
def withdraw(self, amount):
self.account_balance -= amount
return self
def display_account_info(self):
print('\tSaldo:',self.account_balance)
def yield_interest(self):
if self.account_balance > 0:
self.account_balance = self.account_balance * self.rate + self.account_balance
return self
guido = BankAccount(0.01, 500)
alexis = BankAccount(0.01, 600)
guido.deposit(100).deposit(200).deposit(300).withdraw(500).yield_interest().display_account_info()
alexis.deposit(250).deposit(250).withdraw(100).withdraw(200).withdraw(300).withdraw(400).yield_interest().display_account_info()
|
9781a85e2b1c00880e51fd390937486a41b7dbe9 | lambobr/Leetcode-Python | /climbStairs.py | 358 | 4.0625 | 4 | """This function is used to calculate the total number of combinations of 1 and 2 steps in climbing a ladder of n size"""
def climbStairs(n: int) -> int:
dp = [1]*(n+1)
print(dp)
dp[0] = 1
dp[1] = 2
for i in range(2,n+1):
dp[i] = dp[i-1] + dp[i-2]
print(dp[i])
return dp[n]
|
c8dc0c95d3e886dfdd295705008d6af7bf160cd6 | yangxiangtao/biji | /1-pbase/day15/exercise/1.py | 581 | 3.765625 | 4 | def myrange(*args):
if len(*args)==1:
step=1
start=0
end=args[0]
elif len(*args)==2:
step=1
start=args[0]
end=args[1]
elif len(*args)==3:
step=[2]
start=args[0]
end=args[1]
if step > 0:
while start < end:
yield start
start+=step
raise StopIteration
elif step <0:
while start > end:
yield start
start +=step
raise StopIteration
else:
raise('stop cannot be 0')
print(x**2 for x in myrange(1,18,3)) |
7ee023d05aa6fba4542ddedcc3fa312e352a2ca6 | JavaCodeMood/study_python_demo | /feibo.py | 332 | 3.75 | 4 | #!/usr/bin/python3
#斐波那契数列 1 1 2 3 5
#f(i) = f(i-1) + f(i-2)
a,b = 0, 1
while b < 20:
print(b)
a, b = b, a+b
print("----------------------")
x,y = 0,1
while y < 100:
#关键字end可以用于将结果输出到同一行,或者在输出的末尾添加不同的字符
print(y, end=',')
x,y = y, x+y |
3ea8b5acb599bb921dec03095a8df733af9577f6 | wtufhv/zj | /Days02/变量运算.py | 445 | 3.53125 | 4 | """
使用变量保存数据并进行算术运算
Version: 0.1
Author: 余超
"""
a = 321
#给a赋值为321
b = 123
#给b赋值为123
print(a + b)
#打印321+123的结果
print(a - b)
#打印321-123的结果
print(a * b)
#打印321*123的结果
print(a / b)
#打印321/123的结果
print(a // b)
#打印321整除123(舍去余数)(整除)
print(a % b)
#打印321/123的余数(模除)
print(a ** b)
#打印321的123次方(指数) |
fcf54cfc2bcca4435946fd844c00037f1c2a16c7 | paulinalc-lpsr/class-samples | /chooseHaikus.py | 549 | 3.90625 | 4 | # this will open the two haikus about a silly person or about how to write a haiku
fourthHaiku = open(“haiku4.txt” , “r”)
thirdHaiku = open(“haiku4.txt” , “r”)
# let them be able to choose their options
print(“Hi welcome to Haiku Reader!”)
print(“Choose..”)
print”(“(3) For a haiku about a silly person.”)
print(“(4) For a haiku about writing haikus.”)
option = int(raw_input)
if option == 3:
print(thirdHaiku.read())
if option == 4:
print(fourthHaiku.read())
fourthHaiku.close()
thirdHaiku.close()
|
eed74f1201e9ab63fcc125a875ac71179d171e1e | hckhilliam/programming | /LeetCode/30DayChallengeApril/20ConstructBSTPreorder.py | 1,204 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.i = 0
self.parents = {}
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
if not preorder:
return None
t = TreeNode(preorder[0])
if len(preorder) == 1:
return t
i = 1
while i < len(preorder) and preorder[i] <= t.val:
i += 1
i -= 1
t.left = self.bstFromPreorder(preorder[1:i + 1])
t.right = self.bstFromPreorder(preorder[i + 1:])
return t
# This assumes BST is balanced, which it isn't -_-
# def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
# if not preorder:
# return None
# t = TreeNode(preorder[0])
# if len(preorder) == 1:
# return t
# mid = ceil((len(preorder) - 1) / 2)
# if preorder[mid] > t.val:
# mid -= 1
# t.left = self.bstFromPreorder(preorder[1:mid + 1])
# t.right = self.bstFromPreorder(preorder[mid + 1:])
# return t
|
a3068ae6d4967a595d48cd01f5c9792668b73d93 | zzxzzg/python | /test1/function_test.py | 1,653 | 4.1875 | 4 | #! /usr/bin/env python3
# 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()。
# 任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
# 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
# 函数内容以冒号起始,并且缩进。
# return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。
#Python 定义函数使用 def 关键字,一般格式如下
# def 函数名(参数列表):
# 函数体
#在 Python 中,所有参数(变量)都是按引用传递。如果你在函数里修改了参数,那么在调用这个函数的函数里,原始的参数也被改变了
# 调用函数时可使用的正式参数类型:
# 必需参数
# 关键字参数
# 默认参数
# 不定长参数
def printinfo( name, age = 35):
"打印任何传入的字符串"
print ("名字: ", name);
print ("年龄: ", age);
return;
# 必需参数
printinfo("gaga",50)
# 关键字参数
# 关键字参数允许函数调用时参数的顺序与声明时不一致
printinfo(age=50,name="gaga")
# 默认参数
printinfo(name="gaga")
#不定长参数
# 放在函数最后,使用 *开头,var是一个元组
def printinfo2( name, age = 35,*var):
print("输出: ")
print("名字: ", name);
print("年龄: ", age);
print(var)
return;
printinfo2("gaga",50,1,2,3,4,5,6)
#lambda 来创建匿名函
#lambda [arg1 [,arg2,.....argn]]:expression
sum = lambda arg1, arg2: arg1 + arg2;
print ("相加后的值为 : ", sum( 10, 20 ))
|
90ddfc6691069743734a0b8894b39c27e9478409 | AyushKoul00/Desktop-Files | /Python/Learn.py | 1,987 | 3.609375 | 4 | # def fib(n):
# a,b = 0,1
# while n:
# print(a, end = ", ")
# a,b = b, a+b
# n=n-1
# fib(4)#send int(input("enter limit: "))
board = [[2, 0, 1],
[0, 0, 0],
[1, 1, 1]]
def show(r, c, display=True):
try:
board[r][c] = 1
if display:
for i, row in enumerate(board):
print(i, row)
except IndexError as e:
print("\nSomething went Wrong!", e)
except Exception as e:
print(e)
'''
var = "My", "Name", "is", "Ayush" # or put inside ()
for word in var[:-1]:
print(word, end = " ")
'''
def win(game):
#Horizontally
for row in game:
if row.count(row[0]) == len(row) and row[0] != 0:
print(f"Player {row[0]} is the winner!")
return
#Vertically
for col in range(len(game)):
check = []
for row in game:
check.append(row[col])
if check.count(check[0]) == len(check) and check[0] != 0:
print(f"Player {check[0]} is the winner!")
return
#Diagonally
check = [[], []]
for i in range(len(game)):
check[0].append(game[i][i])
check[1].append(game[i][len(game)-i-1])
if check[0].count(check[0][0]) == len(check[0]) and check[0][0] != 0:
print(f"Player {check[0][0]} is the winner!")
return
if check[1].count(check[1][0]) == len(check[1]) and check[1][0] != 0:
print(f"Player {check[1][0]} is the winner!")
return
# i = 0
# for row in board:
# print(i, row)
# i += 0
# print('\n')
# x = show
# x(0,0)
# win(board)
# #look at zip function (built-in)
# l = [1, 2, 3, 4, 5]
# print(l[1])
#Flip between 1 and 0:
choice = 0
for i in range(10):
print(choice+1)
choice ^= 1
#iterators vs iterable in python 13th video --> itertools (cycle), iter(), next()...
#list comprehension
print(" " + " ".join([str(i) for i in range(3)]))
size = 5
game = [[0 for i in range(size)] for i in range(size)]
print(game)
|
4e74af7609505bb05cfe68ac99968dca8e7406b3 | Moenupa/MINEWORLDY | /python_tools/others/2.py | 458 | 3.890625 | 4 | #this is a program to solve addition
print('Enter your number:')
#introduction to the subject
def PROC0(a,b):
sum = int(a) +int(b)
sum.zfill(2)
sum = str(sum)
x = int(sum[0])
y = sum[1]
#PROC2()
#PROC1()
#PROC0()
numbers = []
while True:
number = input('number:')
if number == 'q':
break
else:
numbers.append(number)
lenses = []
for number in numbers:
lens = len(number)
lenses.append(lens)
|
9d46521f7a9a5d194e2451e24a87edfbfae0eabd | HelloWorldSweden/Studio-X | /Algoritmer och Datastrukturer/U2 - Köer/LinkedQ.py | 550 | 3.59375 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedQ:
def __init__(self):
self.first = None
self.last = None
def enqueue(self, x):
new = Node(x)
if self.isEmpty():
self.last = new
self.first = new
else:
if self.first.next == None:
self.first.next = new
self.last.next = new
self.last = new
def dequeue(self):
if not self.isEmpty():
value = self.first.value
self.first = self.first.next
return value
return False
def isEmpty(self):
return self.first == None
|
9d1c9370b716d38d8ac844ad215ad62977a04def | arw2019/AlgorithmsDataStructures | /Equal Tree Partition/Leetcode_663.py | 1,031 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def checkEqualTree(self, root: TreeNode) -> bool:
self.cache = {}
def dfs(node: TreeNode) -> None:
if not node or node in self.cache:
return
tot = 0
if node.left:
if node.left not in self.cache:
dfs(node.left)
tot += self.cache[node.left]
tot += node.val
if node.right:
if node.right not in self.cache:
dfs(node.right)
tot += self.cache[node.right]
self.cache[node] = tot
dfs(root)
sum_of_all = self.cache[root]
for node, sum_subtree in self.cache.items():
if node != root and 2 * sum_subtree == sum_of_all:
return True
return False
|
cc06f8221ea3533918bfc37e2d637945895af013 | 2371406255/PythonLearn | /15_filter.py | 460 | 3.765625 | 4 | #!/usr/bin/env python3
#coding:utf-8
#filter:过滤序列,接收一个函数和一个序列,filter把传入的函数依次作用于每个元素,根据返回True还是False决定保留还是丢弃
#删除掉偶数
def is_odd(n):
return n%2==1
arr = list(filter(is_odd,[1,2,3,4,5,6]))
print(arr)#[1, 3, 5]
#删除掉空字符
def not_empty(s):
return s and s.strip()
arr = list(filter(not_empty,['a','','c',None,' ']))
print(arr)#['a', 'c']
|
c80c4f6a7c5f4b6de81563bc6bc214f4d856e4ee | SANDRAJG/sandryjg | /07_file-access_activity.py | 798 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 14 09:43:04 2019
@author: CEC
"""
file = open("devices.txt", "a")
while True:
newItem= input("Ingrese nuevo Item:")
if newItem == "exit":
print("All done!")
break
file.write(newItem+"\n")
file.close()
#otra forma
file=open("devices.txt","a")
while True:
newItem = input("Ingrese un nuevo item: ")
file.write(newItem + "\n")
if newItem == 'exit':
print("todo Listo!!")
break
file.close()
#corrección otra forma
file=open("devices.txt","a")
while True:
newItem = input("Ingrese un nuevo item: ")
if newItem == 'exit':
print("todo Listo!!")
break
else:
file.write(newItem + "\n")
file.close()
|
9024020c63d646e3a12b3e79ffe1c206cb23b46b | krnets/codewars-practice | /5kyu/Missing number in Unordered Arithmetic Progression/index.py | 1,084 | 4.03125 | 4 | # 5kyu - Missing number in Unordered Arithmetic Progression
""" An Arithmetic Progression is defined as one in which there is a constant difference
between the consecutive terms of a given series of numbers.
You are provided with consecutive elements of an Arithmetic Progression.
There is however one hitch: exactly one term from the original series is missing
from the set of numbers which have been given to you.
The rest of the given series is the same as the original AP.
Find the missing term in an unordered list.
Try if you can survive lists of MASSIVE numbers (which means time limit should be considered).
Note: Don't be afraid that the minimum or the maximum element in the list is missing,
e.g. [4, 6, 3, 5, 2] is missing 1 or 7, but this case is excluded from the kata.
find([3, 9, 1, 11, 13, 5]) # => 7 """
# def find(seq):
# return (len(seq)+1) * (min(seq) + max(seq)) // 2 - sum(seq)
def find(seq):
return (min(seq) + max(seq)) * (len(seq)+1) // 2 - sum(seq)
q = find([3, 9, 1, 11, 13, 5]) # 7
q
q = find([5, -1, 0, 3, 4, -3, 2, -2]) # 1
q
|
f010e9b2419d61be18301af29534ac595efa5d5e | jaruwitteng/6230401856-oop-labs | /jaruwit-6230401856-lab3/Problem 6.py | 683 | 4.09375 | 4 | def months_and_days():
correct = False
while not correct:
try:
months = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December")
days = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
dict = {}
for d, m in enumerate(months):
dict[m] = days[d]
print(dict.items())
month_input = input("Enter month:")
print("Number of days in", month_input, "is", dict[month_input])
correct = True
except KeyError:
print("Invalid")
months_and_days() |
aada8126fab4e2eafbd909c83b68ee2ab569559f | JohnyWilson/ChuckPython | /Chapter3.py | 800 | 4.0625 | 4 |
# Question 1
#Hours = int(raw_input('Enter Hours: '))
#Rate = float(raw_input('Enter Rate: '))
#if Hours > 40:
# Rate *=1.5
#print 'Gross Pay: ' + str(Hours*Rate)
# Question 2
try:
Hours = int(raw_input('Enter Hours: '))
except:
print('Error, please enter numeric input')
exit()
try:
Rate = float(raw_input('Enter Rate: '))
except:
print('Error, please enter numeric input')
exit()
if Hours > 40:
Rate *=1.5
print 'Gross Pay: ' + str(Hours*Rate)
# Question 3
# Question 4
width = 17
height = 12.0
print width/2, type(width/2)
print width/2.0, type(width/2.0)
print height/3, type(height/3)
print 1+2*5, type(1+2*5)
# Question 5: Code for C to F conversion
#print 'Temperature in Celcuis is: ' + str((5.0/9.0)*(float(raw_input('Enter Celcius Temerature: '))-32)) |
af6c1f8d7cf54db4209278f288eff4ca35e5b114 | Jasonluo666/LeetCode-Repository | /Python/Merge k Sorted Lists2.py | 896 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
import heapq
heads = []
for index in range(len(lists)):
if lists[index] is not None:
heapq.heappush(heads, (lists[index].val, index, lists[index]))
ans_head = ListNode(0)
pointer = ans_head
while len(heads) > 0:
_, index, next_node = heapq.heappop(heads)
temp = next_node
next_node = next_node.next
pointer.next = temp
pointer = pointer.next
if next_node is not None:
heapq.heappush(heads, (next_node.val, index, next_node))
return ans_head.next |
e29a5f0ff05d076b9122bb4f138c5c9e23ff5b6d | RobinVdBroeck/ucll_scripting | /topics/lambdas/selectWithAgeBetween.py | 177 | 3.78125 | 4 | def select_with_age_between(persons, min, max):
result = []
for p in persons:
if min <= p.age and p.age <= max:
result.append(p)
return result
|
03bd38935039dbb149b671b0811f4912e1ab2f01 | hayuzi/py-first | /base/io.py | 3,549 | 4.3125 | 4 | # python3输入和输出
import math
import pickle
import pprint
# 输出格式美化
# Python两种输出值的方式: 表达式语句和 print() 函数
# 第三种方式是使用文件对象的 write() 方法,标准输出文件可以用 sys.stdout 引用。
# 如果你希望输出的形式更加多样,可以使用 str.format() 函数来格式化输出值。
# 如果你希望将输出的值转成字符串,可以使用 repr() 或 str() 函数来实现。
# str(): 函数返回一个用户易读的表达形式。
# repr(): 产生一个解释器易读的表达形式。
# str.format() 的基本使用
print('{} 和 {}'.format('hello', 'world'))
print('{0} 和 {1}'.format('hello', 'world'))
print('{1} 和 {0}'.format('hello', 'world'))
print('{first}网址: {second}'.format(first='呵呵', second='哈哈哈'))
print('站点列表 {0}, {1}, 和 {other}。'.format('hello', 'world', other='哈哈哈哈'))
# '!a' (使用 ascii()), '!s' (使用 str()) 和 '!r' (使用 repr()) 可以用于在格式化某个值之前对其进行转化:
print('常量 PI 的值近似为: {!r}。'.format(math.pi))
# 可选项 ':' 和格式标识符可以跟着字段名。 这就允许对值进行更好的格式化。 下面的例子将 Pi 保留到小数点后三位:
print('常量 PI 的值近似为 {0:.3f}。'.format(math.pi))
# 在 : 后传入一个整数, 可以保证该域至少有这么多的宽度。 用于美化表格时很有用
print('{0:10} ==> {1:10d}'.format('test', 1))
# 如果你有一个很长的格式化字符串, 而你不想将它们分开, 那么在格式化时通过变量名而非位置会是很好的事情。
# 最简单的就是传入一个字典, 然后使用方括号 '[]' 来访问键值
table = {'one': 1, 'two': 2, 'three': 3}
print('one: {0[one]:d}; two: {0[two]:d}; three: {0[three]:d}'.format(table))
# 也可以通过在 table 变量前使用 '**' 来实现相同的功能
print('one: {one:d}; two: {two:d}; three: {three:d}'.format(**table))
# ----------
# 读取键盘输入
# Python提供了 input() 内置函数从标准输入读入一行文本,默认的标准输入是键盘。
# input 可以接收一个Python表达式作为输入,并将运算结果返回。
str = input("请输入:")
print("你输入的内容是: ", str)
# 读和写文件
# open() 将会返回一个 file 对象,基本语法格式如下:
f = open("./foo.txt", "w")
f.write("Python 是一个非常好的语言。\n是的,的确非常好!!\n")
# 关闭打开的文件
f.close()
f = open("./foo.txt", "r")
# 除了正常的 f.read(size) 以及 f.readline() 还有 f.readlines() 外,还可以循环迭代其中的内容
for line in f:
print(line, end='')
f.close()
# ----------
# pickle 模块
# python的pickle模块实现了基本的数据序列和反序列化。
# 通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。
# 通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。
# pickle.dump(obj, file, [,protocol])
# protocol的值可以是1和2(1和2表示以二进制的形式进行序列化。其中,1是老式的二进制协议;2是新二进制协议
# 使用pickle模块将数据对象保存到文件
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
output = open('data.pkl', 'wb')
pickle.dump(data1, output)
output.close()
pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
pkl_file.close()
|
2d665e244290caab03b33f9697dbb30c2877d6da | jccherry/Data-Structures-And-Algorithms | /06-Trees/John/binary_trees.py | 1,879 | 4.03125 | 4 | #binary tree implementation
#stores integers and compares against one another to see where they should be stored most efficiently
#some code from https://www.youtube.com/watch?v=jJO0MbwF5OI but modified to fit my needs
#simple node that stores an integer
class Node:
def __init__(self, value):
self.value = value
self.left_node = None
self.right_node = None
def is_full(self):
if self.left_node != None and self.right_node != None:
return True
else:
return False
def height(self):
if not is_full(self):
return 0
else:
return max(height(self.left_node),height(self.right_node)) + 1
class BinaryTree:
def __init__(self):
self.root = None
def add(self, val):
if(self.root == None):
self.root = Node(val)
else:
self._add(val, self.root)
def _add(self, val, node):
if(val < node.value):
if(node.left_node != None):
self._add(val, node.left_node)
else:
node.left_node = Node(val)
else:
if(node.right_node != None):
self._add(val, node.right_node)
else:
node.right_node = Node(val)
def PrintTree(self):
if(self.root != None):
self._PrintTree(self.root)
def _PrintTree(self, node):
if(node != None):
self._PrintTree(node.left_node)
print(str(node.value) + ' ')
self._PrintTree(node.right_node)
def DeleteTree(self):
self.root = None
#-----------------------------------------------------------------
tree = BinaryTree()
for i in range(0,20):
if i % 2 == 0:
tree.add(i*i)
else:
tree.add(i)
tree.PrintTree()
tree.DeleteTree()
print('deleted')
tree.PrintTree()
|
95c7fd8fc18fba84bc28e7b17413f2cb911e2dfc | kiranani/playground | /Python3/863.py | 1,686 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
def findAbove(root, target):
if not root:
return []
elif root.val == target.val:
return [(root, 'p')]
leftNodes = findAbove(root.left, target)
rightNodes = findAbove(root.right, target)
if len(rightNodes) > 0:
nodes = [(root, 'l')]
return rightNodes + nodes
elif len(leftNodes) > 0:
nodes = [(root, 'r')]
return leftNodes + nodes
else:
return []
def findK(root, k):
if not root or k < 0:
return []
elif k == 0:
return [root.val]
else:
return findK(root.left, k - 1) + findK(root.right, k - 1)
nodes = findAbove(root, target)
n = len(nodes)
vals = []
for i, (node, d) in enumerate(nodes):
if K - i == 0:
vals.append(node.val)
elif d == 'p':
vals.extend(findK(node.left, K - i - 1))
vals.extend(findK(node.right, K - i - 1))
elif d == 'r':
vals.extend(findK(node.right, K - i - 1))
elif d == 'l':
vals.extend(findK(node.left, K - i - 1))
return vals
|
c304005da3915e4c1376c92cbb1fc80037aa0d2d | JuliaMBa/hackademy | /start.py | 229 | 3.703125 | 4 | import code
print("Hello!")
a = input("What is your name? ")
code.hello(a)
z = code.circle_area(123)
print(z)
import datetime
# define fct today
day_number = code.today()
print("today is " + str(day_number) + " in the month")
|
fbecffc45a2b10f56161998e31407b8144e2cce6 | ElliotFriedman/OOP-Intro | /oop_part_1/ex04/first_class.py | 222 | 3.53125 | 4 | class FirstClass ():
def __init__ (self):
print("Hello World")
def say_hello(self, name, num):
print("Method say_hello in FirstClass is called")
print("Hello", name, "your number is", num)
|
cf38ec302ec7ba7c28ed5da0eb79ed7a2354c615 | zhaojiaxiaomei/guiSystem | /drink.py | 1,648 | 3.6875 | 4 | '''
2元1瓶饮料
2个空瓶可以换一瓶饮料
4个瓶盖可以换一瓶饮料
问带X(x>2)元可以喝几瓶
n # 记录饮料数
button # 记录瓶盖
bottle # 记录空瓶
money # 记录多少元钱
'''
n = 0
def drink(money, button=0, bottle=0):
global n
if button >= 4:
button -= 3
bottle += 1
n += 1
drink(money,button,bottle)
elif bottle >= 2:
button += 1
bottle -= 1
n += 1
drink(money,button,bottle)
else:
if money>1:
money -= 2
button += 1
bottle += 1
n += 1
drink(money,button,bottle)
else:
#当钱money不足2元,但瓶盖剩余3个,可以先和老板借一个瓶盖,喝了这瓶饮料将瓶盖还给老板,即botton=0,但空瓶多了一个
if button == 3:
button = 0
bottle += 1
n += 1
drink(money,button,bottle)
# 当钱money不足2元,但空瓶剩余1个,可以先和老板借一个空瓶,喝了这瓶饮料将空瓶还给老板,所以空瓶都不可能有剩余
elif bottle == 1:
bottle = 0
button += 1
n += 1
drink(money,button,bottle)
else:
print('总共喝了%d瓶' % n)
print('剩余%d个瓶盖' % button)
print('剩余%d个瓶子' % bottle)
print('剩余%d元钱' % money)
if __name__ == '__main__':
s=input('请输入你的钱')
|
523e06ae8081c5d006d0234b94e0b592c266da7f | Stevenzzz1996/MLLCV | /Leetcode/简单+剑指offer题/面试题53 - II. 0~n-1中缺失的数字.py | 413 | 3.9375 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: sfhong2020 time:2020/4/2 10:05
# 二分可以加快速度!
def misingNumber(nums):
l, r = 0, len(nums)-1
while l <= r:
mid = (l+r) // 2
if nums[mid] != mid:
r = mid-1
else: # 等于就说明前面没空!
l = mid+1
return l # 走到最后就行了!
print(misingNumber([0,1,2,3,5,6,7,8]))
|
13315ec0d2e033e73ef8e4d5d6d8cada3106dd5d | sergioescalera/Python-Getting-Started | /control-flow.py | 378 | 3.71875 | 4 | z = 1 + 1j
while abs(z) < 100:
z = z**2 + 1
print(z)
print(range(5))
r = range(4)
a = reversed(r)
print(type(r))
print(type(a))
print(a)
for i in a:
print(i)
for word in ('cool', 'powerful', 'readable'):
print('Python is %s' % word)
for j in [1, 1, 2, 2]:
print(j)
dict = {
"a": 1,
"b": 2,
"c": 3
}
for k in dict:
print(k)
print(type([]) is list)
|
7e7d8103722f3e189b130fdee0479a460fc77175 | wandsen/PythonNotes | /Unit_Testing/UnitTest_example.py | 225 | 4.03125 | 4 | def recursion_factorial(n):
if (n ==1):
return n
else:
return n * recursion_factorial(n-1)
def addition():
return 5 + 5
n = 7
print('Factorial of %s' %n, recursion_factorial(n))
print(addition()) |
498a0eb959596f474f35dd3a5839134f4c4de82c | zysymu/Metodos-Computacionais-da-Fisica | /Métodos B/19-caminhante_aleatorio.py | 1,282 | 3.6875 | 4 | import matplotlib.pyplot as plt
import numpy as np
plt.style.use("ggplot")
N = [10, 20, 100, 200] # diferentes numeros de passos
# um caminhante eh a soma de todos os N passos em x que ele da
# a distribuicao dos passos eh o gerador de nums aleatorios. precisamos normalizar pra que fique entre 0 e 1
def generator(r):
# vai nos dar o proximo x
# recebe um numero r entre 0 e 1
#return r*4 -2
return np.random.random_integers(-1,1)
def walker(N, x_in):
M = 100 # numero total de caminhantes
actual_std = []
theoretical_std = []
for step in range(M):
X = [x_in] # comeca com o passo inicial, depois vai dando append
T = [0] # array com os tempos pra poder plotar depois
x = x_in
for t in range(1, N): # loop temporal
x += generator(np.random.random())
X.append(x)
T.append(t)
plt.plot(T, X)
actual_std.append(np.std(X))
sqrd = [i**2 for i in X]
std_anal = (np.mean(sqrd))**(1/2)
theoretical_std.append(std_anal)
plt.xlabel("tempo")
plt.ylabel("x")
plt.show()
print("desvio quadratico: ", np.mean(actual_std))
print("desvio analitico: ", np.mean(theoretical_std))
for step in N:
walker(step, 0)
|
8295b9ebf818519b424dc34b69d98590a0bc91f2 | paragshah7/Python-CodingChallenges-LeetCode | /PythonBasics/basic3_if_for.py | 1,033 | 4.03125 | 4 | # coding=utf-8
name = "Liverpool"
if not name:
print("1 - Name is empty")
age = 22
if age >= 18:
print("2 - Eligible")
else:
print("2 - Not eligible")
condition = None
if condition:
print("3 - is True")
else:
print("3 - is False")
# one liner if condition
age2 = 12
message2 = "Eligible" if age2 >= 18 else "Not eligible"
print("4 - ", message2)
# Search in a list using for-else loop
def for_search():
names = ["Apple", "Banana"]
for name in names:
if name.startswith("A"):
print("5 - Found")
break
else:
print("5 - Not found")
nums = [1, 2, 3, 4, 5]
for num in nums:
if num == 4:
print("Break the loop", num)
break
if num == 3:
print("Found", num, "but continue")
continue
print(num)
for_search()
def for_print():
for x in "Python":
print(x)
for x in range(0, 10, 2): # Range is the function name, 2 is the interval
print(x)
# for_print()
|
788f0323a56da97fcbb0124a9f1542656c2e433a | elwyngalloway/NHLseasonML2 | /__practice_retrieval_from_database.py | 1,570 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 2 21:23:58 2018
@author: Galloway
"""
import sqlite3
import numpy as np
#import pandas as pd
db_name = "NHLseasonML_seasonstats.db"
# connect to our database that will hold everything, or create it if it doesn't exist
conn = sqlite3.connect(db_name)
#%%
# return all table names from db
with conn:
# get the cursor so we can do stuff
cur = conn.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table';") # finds all tables from db
#cols = [description[0] for description in cur.description] #records column names for all columns in table s_skater...
data = cur.fetchall()
#print("SQLite version: %s" % data)
print(data)
#%%
# return all column names within a table
with conn:
# get the cursor so we can do stuff
cur = conn.cursor()
cur.execute('SELECT * FROM s_skater_summary') #finds column names for all columns in table s_skater...
cols = [description[0] for description in cur.description] #records column names for all columns in table s_skater...
cols[:]
#%%
# retrieve data, including playerPositionCode, from s_skater_summary
with conn:
# get the cursor so we can do stuff
cur = conn.cursor()
# extract a number of columns from s_skater_summary
cur.execute("SELECT seasonId, playerPositionCode, assists, goals, gamesplayed, playerId FROM s_skater_summary")
data = cur.fetchall()
print(data[:5]) # print
#%%
|
619e7f4887f9eb68e14ea89c80004c1b440f3db1 | yindao50/python100 | /python24.py | 980 | 3.65625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
题目:有一分数序列:2/1,3/2,5/3,8/5,
13/8,21/13...求出这个数列的前20项之和。
程序分析:注意分子与分母的变化规律。把分数分为
两部分看,分子和分母分成两个单独的数来对待
"""
#方法一
def fractionRule(n):
denominator = 1.0
molecule = 2.0
sum = 0
for i in range(1,n+1):
sum += molecule / denominator
temp = molecule
molecule = molecule + denominator
denominator = temp
print u'这个数列的前%d项的和为:%f'.encode('gbk') % (n,sum)
#方法二 函数式lambda编程
def fractionRuleLambda(n):
denominator = 1.0
molecule = 2.0
l = []
for j in range(1,n+1):
denominator,molecule = molecule,molecule+denominator
l.append(molecule / denominator)
print u'这个数列的前%d项的和为:%f'.encode('gbk') % (n,reduce(lambda x,y:x + y,l))
def main():
fractionRule(20)
fractionRuleLambda(20)
if __name__ == '__main__':
main()
|
a8418455ef125025ade4ac7357d8ac25688e5e17 | liletoi/ICS2019_2020 | /Assignment 04/Program.py | 808 | 3.921875 | 4 | #F to C
#acres to barns
#polygon
import turtle
def temp(fahren):
celsius = round(((fahren - 32) * 5/9), 2)
print(str(fahren) + " degrees Fahrenheit is " + str(celsius) + " degrees Celsius.")
def area(acres):
barns = format((acres * (4.047 * (10**31))), '.3e')
print(str(acres) + " acres is approximately " + str(barns) + " barns.")
def polygon(shapes):
angle = 360 / shapes
for i in range(shapes):
turtle.forward(50)
turtle.left(angle)
fahren = int(input("What temperature in Fahrenheit would you like to convert to Celsius? "))
temp(fahren)
acres = int(input("How many acres do you want to convert to barns? "))
area(acres)
shapes = int(input("How many sides do you want your polygon to be(more than two but not too many)? "))
polygon(shapes)
screen = turtle.getscreen()
screen.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.