blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
89f526b54379ba7c5b430091097df8c7490da4e4 | Aasthaengg/IBMdataset | /Python_codes/p03779/s457418781.py | 118 | 3.53125 | 4 | x = int(input())
from itertools import accumulate
pos = 0
ans = 0
while pos < x:
ans+=1
pos+=ans
print(ans) |
964a588102133f7da7d083bf525d697195bb6716 | parthkhetarpal23/Searching-Algorithms | /main.py | 1,168 | 3.609375 | 4 | import eightpuzzle
import numpy as np
print("Enter Input array")
test = []
for i in range(9):
test.append(int(input("Element:")))
test = np.array(test).reshape(3,3)
#0,1,3,4,2,5,7,8,6
initial_state = test
goal_state = np.array([1,2,3,4,5,6,7,8,0]).reshape(3,3)
print("---------------------")
print(initial_state)
print("GOAL")
print(goal_state)
root_node = eightpuzzle.Node(state=initial_state,parent=None,action=None,depth=0,step_cost=0,path_cost=0,heuristic_cost=0)
print("Enter algorithm for solving 8 puzzle problem")
options = {1:'BFS',2:'IDS',3:'Astar with manhattan distance as heuristic',4:'Astar with misplaced tile as heuristic'}
print("1:'BFS',\n2:'IDS',\n3:'Astar with manhattan distance as heuristic',\n4:'Astar with misplaced tile as heuristic'")
ch=int(input())
def switch(ch):
if ch==1:
root_node.breadth_first_search(goal_state)
elif ch == 2:
root_node.iterative_deepening_DFS(goal_state)
elif ch==3:
root_node.a_star_search(goal_state,heuristic_function = 'manhattan')
elif ch==4:
root_node.a_star_search(goal_state,heuristic_function = 'num_misplaced')
switch(ch) |
bf2196dce7a61d980bab5903ee661555a0272b75 | brendentran/Udemy2.0 | /ranges.py | 247 | 4.28125 | 4 | # range produces a range of numbers = from the starting value, up to but not including the end value.
for i in range(2, 25):
print("i is now {}".format(i))
for i in range(0, 10, 2):
print("I is now {}".format(i))
|
ce847b1540f88aea5b53c2c7cfc712f5f55dd69a | ACNoonan/PythonMasterclass | /Lists/introtolists.py | 555 | 4.125 | 4 | # ip_address = input("Please enter an IP Address: ")
# print(ip_address.count("."))
parrot_list = ["non pinin", "no more", "a stiff", " bereft of life"]
parrot_list.append("A Norwegian Blue")
for state in parrot_list:
print("This parrot is " + state)
print("-" * 80)
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = even + odd
# numbers.sort()
print(numbers)
numbers_in_order = sorted(numbers)
print(numbers_in_order)
# Changing sorts
if numbers == numbers_in_order:
print("The lists are equal")
else:
print("The lists are not equal")
|
e107c4d4e53dbebe28fc64b30be900363b53723f | Sapan-Ravidas/Data-Stucture-And-Algorithms | /Queue/implementing queue using stack.py | 1,332 | 3.84375 | 4 | '''making deueue operation costly'''
class CostlyDequeue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, value):
self.stack1.append(value)
def dequeue(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
x = self.stack2.pop()
return x
'''making enqueue operation costly'''
class CostlyEnqueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, value):
while self.stack1:
self.stack2.append(self.stack1.pop())
self.stack1.append(value)
self.stack1.append(self.stack2.pop())
def dequeue(self):
x = self.stack1.pop()
'''using recurssion'''
class UsingRecurssion:
def __init__(self):
self.stack = []
def enqueue(self, value):
self.stack.append(value)
def dequeue(self):
if not self.stack:
return
x = self.stack.pop()
if not self.stack:
return x
item = self.dequeue()
self.stack.append(x)
return item
if __name__=="__main__":
q = UsingRecurssion()
q.enqueue(1)
print(q.dequeue())
q.enqueue(2)
q.enqueue(3)
print(q.dequeue())
print(q.dequeue())
|
2af06d87d163d520ee7c9faa1c7a0391c9033e23 | runzezhang/Code-NoteBook | /lintcode/1283-reverse-string.py | 619 | 4.21875 | 4 | # Description
# 中文
# English
# Write a function that takes a string as input and returns the string reversed.
# Have you met this question in a real interview?
# Example
# Example 1:
# Input:"hello"
# Output:"olleh"
# Example 2:
# Input:"hello world"
# Output:"dlrow olleh"
class Solution:
"""
@param s: a string
@return: return a string
"""
def reverseString(self, s):
# write your code here
# reverse_string = ''
# for i in range(len(s) - 1, -1, -1):
# reverse_string += s[i]
# return reverse_string
return s[::-1] |
975d6c640b3ca4356fa1299924fdaa9ed045549e | Reeftor/python-project-lvl1 | /brain_games/games/brain_calc.py | 637 | 3.984375 | 4 | # -*- coding:utf-8 -*-
"""Brain_calc game logic."""
import operator
from random import choice, randint
GAME_DESCR = 'What is the result of the expression?'
def make_question():
"""Brain_calc game function.
Returns:
question, correct_answer
"""
operations = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
}
num1 = randint(1, 100)
num2 = randint(1, 100)
ch_oper = choice(list(operations.keys()))
correct_answer = str(operations[ch_oper](num1, num2))
question = 'Question: {0} {1} {2}'.format(num1, ch_oper, num2)
return question, correct_answer
|
fd1aed361a6810e565968972082717ca28e5a1e2 | thananauto/python-test-frameworks | /python-selenium/oops/Innerclass.py | 464 | 3.5625 | 4 | class Innerclass(object):
def __init__(self):
self.head = Head()
self.foot = Foot()
def health(self):
print('My health is good')
class Head:
def activity(self):
print('Head start thinking')
class Foot:
def activity(self):
print("My foot have two legs")
if __name__ == '__main__':
innerclass = Innerclass()
innerclass.foot.activity()
innerclass.head.activity()
innerclass.health()
|
54effe6b0ed4134d2301b43a112e0004853a20eb | ZohanHo/PycharmProjectsZohan | /untitled3/Задача 30.py | 473 | 4.03125 | 4 | """По данному натуральному n ≤ 9 выведите лесенку из n ступенек,
i-я ступенька состоит из чисел от 1 до i без пробелов."""
n = int(input("введите число n: "))
if n > 10:
print("n > 10")
else:
y = []
for i in range (n):
i += 1
y.append(i)
print(y)
Сделал через список, думаю это не совсем верно
|
23832d81cbaf5a3040faa7496abd4d7a94975ce0 | JuDa-hku/ACM | /leetCode/92ReverseLinkedListII.py | 1,834 | 3.796875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} m
# @param {integer} n
# @return {ListNode}
def reverseBetween(self, head, m, n):
dummy = ListNode(0)
dummy.next = head
dummyStart = dummy
count = 0
if m == n:
return head
while True:
if count == m-1:
startRotate = dummyStart
if count == n:
endRotate = dummyStart
break
dummyStart = dummyStart.next
count += 1
if not endRotate.next:
tmphead, tmpend = self.reverseList(startRotate.next)
startRotate.next = tmphead
return dummy.next
if endRotate:
endRotateAfter = endRotate.next
endRotate.next = None
tmphead, tmpend = self.reverseList(startRotate.next)
startRotate.next = tmphead
tmpend.next = endRotateAfter
return dummy.next
def reverseList(self, head):
if not head:
return
tmphead, tmpend = self.reverseListHelp(head)
return tmphead, tmpend
def reverseListHelp(self, head):
if head.next == None:
return (head, head)
else:
tmpHead, tmpEnd = self.reverseListHelp(head.next)
tmpEnd.next = head
tmpEnd = tmpEnd.next
tmpEnd.next = None
return (tmpHead, tmpEnd)
a0, a1, a2,a3,a4 = ListNode(0), ListNode(1), ListNode(2),ListNode(3), ListNode(4)
#a0.next = a1
a1.next = a2
a2.next = a3
a3.next = a4
s = Solution()
head = s.reverseBetween(a0,1,1)
while head:
print head.val
head = head.next
|
7e84d79b636fecf30d5e2b5c41894dfe9118d5c4 | caovicto/CoursePlanner | /_site/assets/scripts/degreeScraper.py | 3,916 | 3.515625 | 4 |
##################################################
# \file Scraper.py
#
# \brief Class for scraping from website
##################################################
import json
import re
from termcolor import colored
from selenium import webdriver
# scraper object for scraping profile #
class Scraper:
def __init__(self):
self.driver = webdriver.Chrome(executable_path="/usr/lib/chromium-browser/chromedriver")
def CollectPrograms(self):
"""
:return:
:rtype:
"""
# entering driver information
self.driver.get("https://reg.msu.edu/AcademicPrograms/Programs.aspx?PType=MNUN")
contents = self.driver.find_element_by_xpath("//div[@id='MainContent_divData']")
links = [ele.get_attribute("href") for ele in contents.find_elements_by_xpath("//a")]
for link in links:
if link.find("Program=") != -1:
self.ScrapeProgram(link)
def ScrapeProgram(self, link):
"""
:param link:
:type link:
:return:
:rtype:
"""
self.driver.get(link)
# initializing json info
program = {}
program['requirement'] = []
# grab degree content
content = self.driver.find_element_by_xpath("//div[@id='MainContent_divDnData']")
rows = content.text.split("\n\n")
for i in range(0, len(rows)):
# get degree name and credits
if i == 0:
textBlock = rows[i].split('(')
program['name'] = textBlock[0]
textBlock = rows[i].split()
program['credits'] = textBlock[textBlock.index("Credits:")+1]
# get degree requirements
else:
requirement = self.ParseRequirement(rows[i])
if requirement.get('name') and (requirement['name'] != 'University Residency' or requirement['name'] != 'University Diversity Distribution'):
program['requirement'].append(requirement)
if len(program['requirement']):
# write program info to file
fileName = '_'.join(re.findall(r"(\w+)", program['name']))
file = open('../data/minors/'+fileName+'.json', 'w+')
json.dump(program, file)
print("Created ", colored(fileName, 'green'))
def ParseRequirement(self, textBlock):
"""
:param textBlock:
:type textBlock:
:return:
:rtype:
"""
# initialize requirement set
requirement = {}
requirement['requirement'] = []
rows = textBlock.split(': ')
# grab requirements options
for i in range(0, len(rows)):
# init requirement name
if i == 1:
requirement['name'] = rows[i].split('\n')[0]
# get requirement options
else:
possibleSet = []
for row in re.findall(r"(\d{1,2}\ \w+\ from.*)", rows[i]):
parsedRow = row.split(' from ')
reqSet = {}
reqSet['type'] = "credit" if parsedRow[0].find('credit') != -1 else "course"
reqSet['number'] = parsedRow[0].split(' ')[0]
reqSet['courses'] = (parsedRow[1].split(','))
possibleSet.append(reqSet)
if len(possibleSet):
requirement['requirement'].append(possibleSet)
# for ele in requirement['requirement']:
# print(ele)
return requirement
def Close(self):
self.driver.close()
################################################################
#
# RUNNING PROGRAM
#
#
################################################################
def main():
scraper = Scraper()
scraper.CollectPrograms()
scraper.Close()
if __name__ == "__main__":
main()
|
5a92ba9b35cb0b5e5100190897f3118844bc2a3f | Juliadaphiny/Lista-4 | /Questão_07.py | 447 | 3.984375 | 4 | # Disciplina: Probabilidade e Estatística
# Aluno: JÚLIA DAPHINY LINS BRANSÃO
# Lista_4
y = int(input("Digite um número entre 1 e 4: ")) #pega o número
while (y < 1 or y > 4): #Ve se e 1, 2 , 3 ou 4 se for sai direto caso não seja entra no while
print('Entrada inválida, digite o número novamente')
y = int(input("Digite um número entre 1 e 4: "))
continue;
else:
print('O número informado é:', y) #printa o número que digitou entre 1 e 4
|
62d73d26b46b21e5deebf080258ac53453a4a237 | krishnakesari/Python-Fund | /Sets.py | 1,377 | 4.125 | 4 |
def main():
a = set("I am fine")
b = set("I am ok")
print_set(sorted(a))
print_set(sorted(b))
def print_set(o):
print('{', end = ' ')
for x in o: print(x, end = ' ')
print('}')
if __name__ == '__main__': main()
# Members in set a but not b
def main():
a = set("I am fine")
b = set("I am ok")
print_set(a - b) # Members are in a but not b
def print_set(o):
print('Members with a but not b{', end = ' ')
for x in o: print(x, end = ' ')
print('}')
if __name__ == '__main__': main()
# Members in set a or b or both
def main():
a = set("I am fine")
b = set("I am ok")
print_set(a | b)
def print_set(o):
print('Members with a or b or both: {', end = ' ')
for x in o: print(x, end = ' ')
print('}')
if __name__ == '__main__': main()
# Members in set a or b not both
def main():
a = set("I am fine")
b = set("I am ok")
print_set(a ^ b)
def print_set(o):
print('Members with a or b but not both: {', end = ' ')
for x in o: print(x, end = ' ')
print('}')
if __name__ == '__main__': main()
# Members in both set a and b
def main():
a = set("I am fine")
b = set("I am ok")
print_set(a & b)
def print_set(o):
print('Members with both a and b are: {', end = ' ')
for x in o: print(x, end = ' ')
print('}')
if __name__ == '__main__': main()
|
e6bc44bec6e5126dc09ab5c95115f754ba700876 | LuizD13/Python | /AulasPython/PythonBasico/aula19.py | 180 | 3.734375 | 4 | """
Iterando strings com while em Python
"""
minha_string = 'o rato roeu a roupa do rei de roma.'
c = 0
while c < len(minha_string):
print(minha_string[c])
c += 1
|
16770a1855cc313d7ea35574e9f8d75ed6836ab1 | Srinjana/CC_practice | /MISC/ACCENTURE/circularprimesums.py | 1,194 | 4.0625 | 4 | # Problem statement
# You have to implement the following function: int CircularPrimesSum(int rangeMin, int rangeMax)
# A number is said to be a circular prime if all the rotations of the number are Prime. For the number 142, rotation set is defined as (142, 214, 421). Given a range, from 'rangeMin' to 'rangeMax', both inclusive, you have to return sum of all Circular prime numbers. Note: If there are no circular prime numbers within the given range then return -1
# Assumptions:
# • rangeMin > 1, rangeMax > 1
# • rangeMin <= rangeMax
import itertools
import math
min = int(input()) # Lower Limit
max = int(input()) # Upper Limit
t = [] # empty list to store numbers
def prime(max): # function to find prime no in the given Range
for x in range(2, int(math.sqrt(max)) + 1):
if (max % x) == 0:
break
else:
return max
def cirpirme(max): # Function to classify if the prime no is circular prime or not
no = str(max)
for x in range(0, len(no)):
r = no[x:len(no)] + no[0:x]
if not prime(int(r)):
return False
return True
for x in range(min, max+1): # To increase the efficiency of the code
if prime(x):
if cirpirme(x):
t.append(x)
print(sum(t))
|
52777d65748193e02f1cc14e0be6ba4fa04ca0ea | Aasthaengg/IBMdataset | /Python_codes/p02681/s677168514.py | 94 | 3.59375 | 4 | a = list(input())
b = list(input())
c = b
c.pop()
if(a == c):
print("Yes")
else:
print("No") |
cc1552b2cfab31a72a6da7722bbe1ddcfdca9d8a | nicolageorge/play | /amazon/reverse_array.py | 488 | 3.703125 | 4 | def reverse_list(the_list):
start = 0
end = len(the_list) - 1
while start <= end:
the_list[start], the_list[end] = the_list[end], the_list[start]
start += 1
end -= 1
return the_list
if __name__ == '__main__':
the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst = reverse_list(the_list)
print(', '.join([str(i) for i in lst]))
word = 'thiswillbereversed'
rev_word = reverse_list(list(word))
print(''.join([str(i) for i in rev_word]))
|
76d38a8c30a848daa874f32e492d713975a28ae4 | TusharDimri/Python | /(REGULAR EXPRESSIONS) 2 in Python.py | 4,839 | 3.765625 | 4 | import re
text = """farsatsdgbvhqefscbgvdxuhsIAdkbcwfuhvbcwuthnfskdnfhwirbgsdiunfaduognfivnfsjngdbklndgovnsflkvnfsljbnflkbsbnksflk
wjvnfjnvsfbnsfljbnfsljbnfsjlbnfsjbnsfkjbnfsljbntogndslbnsjlbtvjlsdnvosfdndljafnwoafncfsjvnsdljncealfnaiorgnrouanfoaaofns
AVDCWHDASDIAUVBEGIBFVIADNBVEIGBVIESVBPRUVBINIUPGIUPVGIUPRIPVUEGWUIVBGRVPIUGRBVGIRWNIHJBVFGWFVBUGDFBVUFBEFQUHVBEFVHBFBVLE
1234465836835
Ha HaHa
MetaCharacters (need to be escaped)
. ^ $ *+ ? {} [] \ | ()
https://www.google.com
http://coreyms.com
https://youtube.com
http://www.nasa.gov
231-555-4321
231.433.4231
321*312*2312
Mr. Schafer
Mr Smith
Ms Davis
Mrs. Robinson
Mr. T
Mr Ak47
tushar.dimri22@gmail.com
tushar.dimri@university@edu
tushar-321-dimri@my-work.net
"""
sentence = "Start a sentence and bring it to an end"
# What is a raw string
print("Tushar \t Dimri")
print(r"Tushar \t Dimri") # This is a raw string
# As we saw in the output, raw string ignores escape sequences and give preference to meta characters
pattern = re.compile(r'fsj') # This creates a variable which can be search in the string we want
matches = pattern.finditer(text)
for match in matches:
print(match)
# This returns a match object where match is the pattern and span is the index in which it was found(check output)
# Meta characters carry special meaning for pattern and are ery helpful while forming patterns
# To search for meta characters normally we need to escape the ]m using '\'. For example:-
fullstop = re.compile(r'\.')
matches1 = fullstop.finditer(text)
for fullstop in matches1:
print(fullstop)
# If we don't escape the '.' then we will get all characters except newline in the string as an object as '.' is a meta
# character
# Searching using word boundary (\b)
# Word Boundary means that we have a space(Space, Whitespace, Newline) before our pattern
pattern = re.compile(r'\b Ha')
matches3 = pattern.finditer(text)
for match in matches3:
print(match)
# ^ and $ are used to search something at the beginning or at the end of a string
pattern1 = re.compile(r'^Start')
matches4 = pattern1.finditer(sentence)
for match in matches4:
print(match)
pattern2 = re.compile(r'end$')
matches5 = pattern2.finditer(sentence)
for match in matches5:
print(match)
# Creating a pattern to match digits(phone number)
pattern3 = re.compile(r'\d\d\d[.-]\d\d\d[.-]\d\d\d\d')
matches6 = pattern3.finditer(text)
for match in matches6:
print(match)
# Create a pattern to check for digits in range 1 to 5
pattern4 = re.compile(r'[1-5a-z]')# It will check for numbers between 1 and 5 including 1 & 5.Also, a-z match lower case
matches7 = pattern4.finditer(text)
for match in matches7:
print(match)
pattern5 = re.compile(r'^[1-5a-z\n\.]a-z\n\.') # It will check for anything except specified values
matches7 = pattern5.finditer(text)
for match in matches7:
print(match)
# Alternative for 67-70
pattern6 = re.compile(r'\d{3}[.-]\d{3}[.-]\d{4}')
matches8 = pattern6.finditer(text)
for match in matches8:
print(match)
# Pattern to match name(20-24)
pattern7 = re.compile(r'M(r|s|rs)\.?\s[A-Za-z]\w*')
matches8 = pattern7.finditer(text)
for match in matches8:
print(match)
# Matching different types of e-mails
pattern8 = re.compile(r'[a-zA-Z0-9.-]+@[a-zA-Z-]+\.(com|edu|net)')
matches9 = pattern8.finditer(text)
for match in matches9:
print(match)
# Matching urls
pattern9 = re.compile(r'https?://(www\.)?(\w+)(\.\w+)')
matches10 = pattern9.finditer(text)
subbed_urls = pattern9.sub(r'\2\3', text)
print(subbed_urls)
for match in matches10:
print(match)
# Other Regular Expressions Functions
# findall() method
pat = re.compile(r'(Mr|Ms|Mrs)\.?\s[A-Z]\w*')
mat = pat.findall(text)
print(mat)
for match in mat:
print(match)
# As we can observe that findall method matched the groups i.e. pattern inside () which in this case is ((Mr|Ms|Mrs))
# Bur=t, if there are no groups in our pattern then this method will return a list containing the matches found
# For Example:-
pat2 = re.compile(r'\d{3}[.-]\d{3}[.-]\d{4}')
mat2 = pat2.findall(text)
print(mat2)
for match in mat2:
print(match)
# If there are multiple groups in our pattern the see for yourself what this returns
pat3 = re.compile(r'https?://(www\.)?(\w+)(\.\w+)')
mat3 = pat3.findall(text)
print(mat3)
for match in mat3:
print(match)
# As we can see in the output this returned a sting containing all the matching groups in a tuple as one element
# Another method of regular expressions module is match() method
patt = re.compile(r'Start')
match = patt.match(sentence)
print(match)
# Note that this method is used to match only the beginning of of the string
# Check this example
patt1 = re.compile(r'sentence')
match = patt1.match(sentence)
# Although there is a 'sentence' in the specified string yet no match us returned
# An alternative is to used ^ character of re.finditer method
# Another method of regular expressions is search()
patt3 = re.compile(r'\d{3}[.-]\d{3}[.-]\d{4}')
match = patt3.search(text)
print(match)
# As we can see in the output, this method returns the first match it found while traversing the string
# Concept of flags:-
patte = re.compile(r'start', re.IGNORECASE)
matc = patte.finditer(sentence)
for match in matc:
print(match) |
6f44382e2652fc3f822e22558a436f6d7ca8b4e1 | LinaSachuk/DU_HomeWork | /python-challenge/PyPoll/main.py | 1,604 | 3.640625 | 4 | import pandas as pd
import os
import csv
total_votes = 0
candidates_list = []
name_list = []
my_list = []
winner = ''
winner_votes = 0
csv_path = os.path.join("election_data.csv")
with open(csv_path, newline='') as csv_file:
csv_data = csv.reader(csv_file, delimiter = ',')
# print(csv_data)
csv_header = next(csv_data)
# print(f"csv_header: {csv_header}")
for row in csv_data:
total_votes += 1
name_list.append(row[2])
if row[2] not in candidates_list:
candidates_list.append(row[2])
for candidate in candidates_list:
my_list.append([candidate, name_list.count(candidate), round(name_list.count(candidate)/total_votes * 100 , 3)])
for i in my_list:
if i[1] > winner_votes:
winner_votes = i[1]
winner = i[0]
print("Election Results" '\n' '--------------------------------------')
print(f'Total Votes: {total_votes}' '\n' '--------------------------------------')
for i in my_list:
print(f"{i[0]} : {i[1]} ({i[2]}00%)")
print('--------------------------------------')
print(f"Winner : {winner}")
print('--------------------------------------')
output_file_path = ('Election Results.txt')
with open(output_file_path, 'w') as file:
file.write("Election Results" '\n' '--------------------------------------' '\n')
file.write(f'Total Votes: {total_votes}' '\n' '--------------------------------------''\n')
for i in my_list:
file.write(f"{i[0]} : {i[1]} ({i[2]}00%)"'\n')
file.write('--------------------------------------''\n')
file.write(f"Winner : {winner}"'\n')
file.write('--------------------------------------')
|
bd7ccf6312549b976b06bf662beb5889e8bd1a6d | gabsabreu/alura-python | /aula04ex1.py | 681 | 3.875 | 4 | print('***************************************')
print('Bem vinda(o) ao jogo de adivinhação!')
print('***************************************')
num_secreto = 63
qtd_tentativas = 3
rodada = 1
while(rodada <= qtd_tentativas):
print('Tentativa {} de {}'.format(rodada,qtd_tentativas))
chute = int(input('Digite o seu chute: '))
if (num_secreto == chute):
print('Você acertou!')
else:
if (chute > num_secreto):
print('Você errou! O seu chute foi maior que o número secreto.')
else:
print('Você errou! O seu chute foi menor que o número secreto.')
rodada = rodada + 1
print('Fim do jogo')
|
3f935f93f7dede935dd507a7272d925b09a29727 | koopa01/pythonlearning | /mooc_PKU_chen_bin.py | 12,331 | 3.765625 | 4 | # 输入某年某月某日,判断这一天是这一年的第几天
import datetime
dtstr = input('Enther the datatime: (20170228):')
dt = datetime.datetime.strptime(dtstr, '%Y%m%d')
another_dtstr = dtstr[:4] + '0101'
another_dt = datetime.datetime.strptime(another_dtstr, '%Y%m%d')
print(int((dt - another_dt).days) + 1)
# 输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
import string
s = input('input a string:')
letter = 0
space = 0
digit = 0
other = 0
for c in s:
if c.isalpha():
letter += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
other += 1
print('There are %d letters,%d spaces,%d digits and %d other\
characters in your string' %(letter, space, digit, other))
# 归并排序
import random
def merge_sort(data_list):
if len(data_list) <= 1:
return data_list
middle = int(len(data_list) / 2)
left = merge_sort(data_list[:middle])
right = merge_sort(data_list[middle:])
merged = []
while left and right:
merged.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
merged.extend(right if right else left)
return merged
data_list = [random.randint(1,100) for _ in range(50)]
print(merge_sort(data_list))
# 猜数字
# 第三章 作业
# 1.字符串循环左移
s=str(input())
n=int(input())
temp_list = list(s)
for _ in range(n):
temp_str = temp_list.pop(0)
temp_list.append(temp_str)
print(''.join(temp_list))
# 2.输入直角三角形两直角边a,b的值,输出斜边上的高
import math
a=int(input())
b=int(input())
print(math.sqrt(a**2 + b**2))
# 3.计算字符串最后一个单词的长度,单词以空格隔开。
s=str(input())
word_long = s.split(' ')[-1]
print(len(word_long))
# 4.接受一个由字母和数字组成的字符串,和一个字符,然后输出输入的字符串中含有该字符的个数。不区分大小写。
s=str(input())
s = s.split(' ')
target_strs = list(s[0])
target_str = s[1]
temp_add = 0
for _ in range(len(target_strs)):
if target_str == target_strs[_]:
temp_add += 1
print(temp_add)
# 5.给出两个整数,输出他们的和
n1=int(input())
n2=int(input())
print(n+n2)
# 6.给出一个圆的半径,求出圆的周长和面积
n=int(input())
print("%.4f,%.4f" % (2*n*3.14159, n**2*3.14159))
# 7.由三角形的三边长,求其面积。
a = int(input())
b = int(input())
c = int(input())
p = (a+b+c)/2
s = math.sqrt(p*(p-a)*(p-b)*(p-c))
print('%.2f'%s)
# 8.给出一个等差数列的前两项a1,a2,求第n项是多少
a=int(input())
b=int(input())
n=int(input())
c = b - a
print(a+c*(n-1))
# 第四章 作业
# 1.输入两个列表alist和blist,要求列表中的每个元素都为正整数且不超过10;
alist=list(map(int,input().split()))
blist=list(map(int,input().split()))
print(sorted(list(set(alist+blist))))
# 2.输入一个列表,要求列表中的每个元素都为正整数且列表包含的元素个数为偶数;
# 将列表中前一半元素保存至字典的第一个键值1中,后一半元素保存至第二个键值2中。
alist=list(map(int,input().split()))
# front = []
# for _ in range(len(alist)/2):
# front.append(alist.pop(0))
# d1 = {}
# d1[1] = front
# d1[2] = alist
# print(d1)
print({1:alist[:half_length:],2:alist[half_length::]})
# 3.输入一个列表,将其反转后输出新的列表。
alist=list(map(int,input().split()))
print(alist[::-1])
# 4.将列表中的所有元素按照它们的绝对值大小进行排序,绝对值相同的还保持原来的相对位置,
# 打印排序后的列表(绝对值大小仅作为排序依据,打印出的列表中元素仍为原列表中的元素)。
alist=list(map(int,input().split()))
# blist,clist = alist[::],[]
# for _ in range(len(alist)):
# blist.append(abs(blist.pop(0)))
# blist.sort()
# for _ in range(len(alist)):
# if blist[0] in alist:
# clist.append(blist.pop(0))
# else:
# clist.append(0-blist.pop(0))
# # print(alist,blist,clist)
# print(clist)
print(sorted(alist, key=abs))
# 第五章 作业
# 1.输入一个正整数max,输出100到max之间的所有水仙花数(包括max)。水仙花数是指一个n位数 (n≥3),它的每个位上的数字的n次幂之和等于它本身。
max_num = int(input())
for x in range(100,max_num+1):
s = 0
nums = list(str(x))
n = len(nums)
for _ in range(n):
nums[_] = int(nums[_])
for _ in range(n):
s += nums[_]**n
if s == x:
print(s)
# 2.输入两个字符串,输出两个字符串集合的并集。
s1 = input()
s2 = input()
print(sorted(set(list(s1)+list(s2))))
# 3.给定一个正整数n(n<1000),求所有小于等于n的与7无关的正整数的平方和。
# 如果一个正整数,它能被7整除或者它的十进制表示法中某个位数上的数字为7,则称之为与7相关的数。
def isseven(n):
m = str(n)
if '7' in m:
return 0
elif n % 7 == 0:
return 0
else:
return 1
n,s = int(input()),0
for _ in range(n + 1):
if isseven(_):
s += _**2
# print(_)
print(s)
# 4.输入一个正整数n(n<1000),输出1到n之间的所有完数(包括n)。
def perfectnum(n):
factor_sum = 0
for _ in range(1,n//2+1):
if n % _ == 0:
factor_sum += _
if factor_sum == n:
return 1
else:
return 0
n = int(input())
for x in range(1,n):
if perfectnum(x):
print(x)
# 5.打印一个n层(1<n<20)金字塔,金字塔由“+”构成,塔尖是1个“+”,下一层是3个“+”,居中排列,以此类推。
level = int(input())
for x in range(1,level+1):
print((level-x)*' ' + (2*x - 1)*'+' + (level-x)*' ')
# 6.给一个5位数,判断它是不是回文数,是则输出yes,不是则输出no。
n = int(input())
m = list(str(n))
if m[0] == m[4] and m[1] == m[3]:
print('yes')
else:
print('no')
# 7.将列表中的奇数变为它的平方,偶数除以2后打印新的列表(新的列表中所有元素仍都为整数)。
alist=list(map(int,input().split()))
for _ in range(len(alist)):
if alist[_] & 1 == 1:
alist[_] = alist[_] ** 2
else:
alist[_] = alist[_] // 2
print(sorted(alist))
# 8.给定一个大于2的正整数n,打印出小于n(不包括n且n不大于100)的所有素数。
n,result = int(input()),[]
def isprime(num):
for _ in range(2, num // 2 + 1):
if num % _ == 0:
return 0
return 1
for i in range(2, n):
if isprime(i):
result.append(i)
print(result)
# 9.猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
# 以后每天早上都吃了前一天剩下的一半零一个。到第n天(<1<n<11)早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
# def eat(num):
# for day in range(9,0,-1):
# num = (num + 1) * 2
# print(num,"第%d天\n" % day)
# return num
# print("第一天",eat(1))
n, r = int(input()), 1
for x in range(n - 1):
r = (r + 1) * 2
print(r)
# 第六章 作业
# 1.已知斐波拉契数列的前两项都是1,我们定义求斐波拉契数列的第n项(n<=50)的函数为fbnq
def fbnq(n):
l1 = [1,1]
for x in range(n-2):
l1.append(l1[x]+l1[x+1])
return l1.pop()
n=int(input(""))
print(fbnq(n))
# 2.输入两个正整数num1和num2(不超过1000),求它们的最大公约数并输出。
def hcf(n1,n2):
result = []
for x in range(1,(n1+n2)//2+1):
if n1%x==0 and n2%x==0:
result.append(x)
return sorted(result).pop()
num1=int(input(""))
num2=int(input(""))
print(hcf(num1,num2))
# 3.输入两个正整数num1和num2(不超过500),求它们的最小公倍数并输出。
def lcm(n1,n2):
if n2 > n1:
(n1,n2) = (n2,n1)
for x in range(n2,n2*n1+1):
if x%n2==0 and x%n1==0:
return x
num1,num2=int(input("")),int(input(""))
print(lcm(num1,num2))
# 4.求n(n为正整数且n<=20)的阶乘的函数为fact
def fact(n):
s = 1
for x in range(1,n+1):
s *= x
return s
n=int(input(""))
print(fact(n))
# 5.已知输入为一个列表,列表中的元素都为整数,我们定义冒泡排序函数为bubbleSort,将列表中的元素按从小到大进行排序后得到一个新的列表并输出
def bubbleSort(alist):
for x in range(len(alist)):
for y in range(len(alist)):
if alist[x] < alist[y]:
temp = alist[x]
alist[x] = alist[y]
alist[y] = temp
return alist
alist=list(map(int,input().split()))
print(bubbleSort(alist))
# 6.输入为一个列表,列表中的元素都为整数,我们定义元素筛选函数为foo,
# 功能是检查获取传入列表对象的所有奇数位索引(注意列表的索引是从0开始的)对应的元素,并将其作为新列表返回给调用者。
def foo(alist):
return alist[1::2]
alist=list(map(int,input().split()))
print(foo(alist))
# 第七章 作业
# 1.给定年月日,如2019/1/8,打印输出这一天是该年的第几天。
import time
day = input()
f = time.strptime(day, '%Y/%m/%d')
print(f.tm_yday)
# from datetime import *
# d=input()
# d1=datetime.strptime(d[:4]+'/1/1','%Y/%m/%d')
# print(d1)
# d2=datetime.strptime(d,'%Y/%m/%d')
# print(d2)
# print((d2-d1).days+1)
# 要将输入的格式转换成计算机能识别的格式,time.strptime()。tm_yday可以直接得出是今年的第几天。
# strptime和strftime傻傻分不清楚,strftime是 str-format-time, 时间字符串格式化,即我们看到的格式;
# strptime是str-parse-time,时间字符串语法化,即计算机理解的格式
# 2.接受一个正整数输入x,打印上述公式的输出值。
from math import *
x=int(input())
y=sin(15/180*pi)+(e**x-5*x)/sqrt(x**2+1)-log(3*x)
print(round(y,10))
# 3.一个特殊的正整数,它加上150后是一个完全平方数,再加上136又是一个完全平方数,求符合条件的最小的一个数。
n=1
while True:
if int((n+150)**0.5)**2 == (n+150) and int((n+150+136)**0.5)**2 == (n+150+136):
print(n)
break
n=n+1
# 4.打印出n阶的“叉”,这个叉图案由字符‘+’和‘X’构成,n越大,这个图案也就越大
n = int(input())
for x in range(2*n-1):
row = ['+']*(2*n-1)
row[x],row[-1-x] = 'X','X'
print(''.join(row))
# 5.约瑟夫环问题,已知n个人(以编号0,1,2,3...n-1分别表示)围坐在一张圆桌周围。
# 从编号为0的人开始报数1,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
n = int(input())
m = int(input())
ln,lout = [i for i in range(n)],[]
while len(ln) != 0:
while len(ln) < m:
m -= len(ln)
lout.append(ln.pop(m-1))
ln = ln[m-1:]+ln[:m-1]
print(lout)
# 第八章 作业
# 1.学生成绩排序
# 设计一个学生类(Student),其中的数据成员有:字符串类型sname表示录入的学生姓名,整型值mscore代表学生的数学成绩,整型值cscore代表学生的语文成绩,整型值escore代表学生的英语成绩。
# 然后要求根据录入的学生成绩(各不相同),输出总分最高的学生姓名和各科目成绩。
class Student:
def __init__(self,sname,mscore,cscore,escore):
self.sname = sname
self.mscore = mscore
self.cscore = cscore
self.escore = escore
self.total = mscore + cscore + escore
def show(self):
print('%s %d %d %d'%
(self.sname,self.msocre,self.cscore,self.escore))
def __lt__(self, other):
return self.res < other.res
# 然后要求根据录入的学生成绩(各不相同)
# ,输出总分最高的学生姓名和各科目成绩。
name = input().split(' ')
mscore =list(map(int,input().split(' ')))
cscore = list(map(int,input().split(' ')))
escore =list(map(int,input().split(' ')))
list1 = list()
for i in range(0,len(name)):
b = Student(name[i],mscore[i],cscore[i],escore[i])
list1.append(b)
list1.sort()
list1[-1].show()
|
e51f65f87bf881e7cd16a66ffcde3d30c1869ca6 | datormx/PythonExercises | /retos-platzi/Reto3_3_AjustaLasIniciales.py | 332 | 3.984375 | 4 | if __name__ == "__main__":
print('Hi, Use only minus to insert the texts ;)\n')
name = input('What\'s your name? ')
lastname = input('What\'s your lastname? ')
country = input('From which country are you from? ')
print(f'Hello, I am {name.capitalize()} {lastname.capitalize()} from {country.capitalize()}.') |
46e597206553c23680676f1bc84974eea6e430c3 | bingzhong-project/leetcode | /algorithms/valid-parentheses/src/Solution.py | 638 | 3.734375 | 4 | class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
parentheses = {"(": 1, "[": 2, "{": 3, ")": -1, "]": -2, "}": -3}
stack = []
for p in s:
if len(stack) == 0 and parentheses[p] < 0:
return False
if len(stack) > 0:
top = stack[-1]
if parentheses[top] + parentheses[p] == 0:
stack.pop()
continue
if parentheses[top] * parentheses[p] < 0:
return False
stack.append(p)
return len(stack) == 0
|
6d81f1a07ec89c92659592a17fad87d3420b0b68 | ShaoxiongYuan/PycharmProjects | /1. Python语言核心编程/1. Python核心/Day04/exercise08.py | 253 | 3.984375 | 4 | planet = ["金星", "地球", "火星", "木星", "土星", "天王星", ]
planet.insert(0, "水星")
planet.append("海王星")
print(planet[:2:])
for i in range(2, 8):
print(planet[i])
for i in range(len(planet) - 1, -1, -1):
print(planet[i]) |
02b89fbe65aaab700a58c06de94cd3f8f992fe9b | DmitryVlaznev/leetcode | /662-maximum-width-of-binary-tree.py | 3,357 | 4.1875 | 4 | # 662. Maximum Width of Binary Tree
# Given a binary tree, write a function to get the maximum width of the
# given tree. The width of a tree is the maximum width among all levels.
# The binary tree has the same structure as a full binary tree, but some
# nodes are null.
# The width of one level is defined as the length between the end-nodes
# (the leftmost and right most non-null nodes in the level, where the
# null nodes between the end-nodes are also counted into the length
# calculation.
# Example 1:
# Input:
# 1
# / \
# 3 2
# / \ \
# 5 3 9
# Output: 4
# Explanation: The maximum width existing in the third level with the
# length 4 (5,3,null,9).
# Example 2:
# Input:
# 1
# /
# 3
# / \
# 5 3
# Output: 2
# Explanation: The maximum width existing in the third level with the
# length 2 (5,3).
# Example 3:
# Input:
# 1
# / \
# 3 2
# /
# 5
# Output: 2
# Explanation: The maximum width existing in the second level with the
# length 2 (3,2).
# Example 4:
# Input:
# 1
# / \
# 3 2
# / \
# 5 9
# / \
# 6 7
# Output: 8
# Explanation:The maximum width existing in the fourth level with the
# length 8 (6,null,null,null,null,null,null,7).
# Note: Answer will in the range of 32-bit signed integer.
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
@staticmethod
def fromArray(nodes: List[int], i: int) -> TreeNode:
l = len(nodes)
if not l: return None
node = TreeNode(nodes[i])
ch_i = 2 * i + 1
node.left = Solution.fromArray(nodes, ch_i) if ch_i < l and nodes[ch_i] != None else None
ch_i += 1
node.right = Solution.fromArray(nodes, ch_i) if ch_i< l and nodes[ch_i] != None else None
return node
def widthOfBinaryTree(self, root: TreeNode) -> int:
if not root: return 0
from collections import deque
q = deque()
q.append([0, root])
res = 0
while q:
level_count = len(q)
l = r = None
for i in range(level_count):
idx, node = q.popleft()
if not l: l = r = idx
r = max(r, idx)
if node.left: q.append([idx * 2 + 1, node.left])
if node.right: q.append([idx * 2 + 2, node.right])
res = max(res, r - l + 1)
return res
def log(correct, res):
if correct == res:
print("[v]", res)
else:
print(">>> INCORRECT >>>", correct, " | ", res)
t = Solution()
tree = [1,3,2,5,3,None,9]
log(4, t.widthOfBinaryTree(t.fromArray(tree, 0)))
tree = [1,3,None,5,3]
log(2, t.widthOfBinaryTree(t.fromArray(tree, 0)))
tree = [1,3]
log(1, t.widthOfBinaryTree(t.fromArray(tree, 0)))
tree = [1]
log(1, t.widthOfBinaryTree(t.fromArray(tree, 0)))
tree = []
log(0, t.widthOfBinaryTree(t.fromArray(tree, 0)))
tree = [1,3,2,5]
log(2, t.widthOfBinaryTree(t.fromArray(tree, 0)))
tree = [1,3,2,5,None,None,9,6,None,None,None,None,None,None,7]
log(8, t.widthOfBinaryTree(t.fromArray(tree, 0))) |
11bd197ff88122f9f90a67682ae056bcc7762735 | sheelabhadra/LeetCode-Python | /853_Car_Fleet.py | 1,840 | 4.375 | 4 | #N cars are going to the same destination along a one lane road. The destination is target miles away.
#Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles
#towards the target along the road.
#A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed.
#The distance between these two cars is ignored - they are assumed to have the same position.
#A car fleet is some non-empty set of cars driving at the same position and same speed.
#Note that a single car is also a car fleet.
#If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.
#How many car fleets will arrive at the destination?
#Example 1:
#Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
#Output: 3
#Explanation:
#The cars starting at 10 and 8 become a fleet, meeting each other at 12.
#The car starting at 0 doesn't catch up to any other car, so it is a fleet by itself.
#The cars starting at 5 and 3 become a fleet, meeting each other at 6.
#Note that no other cars meet these fleets before the destination, so the answer is 3.
##SOLUTION: Sort the cars by their starting positions and calculate the time to reach target.
# update fleets if the current time > the last_time.
class Solution(object):
def carFleet(self, target, position, speed):
"""
:type target: int
:type position: List[int]
:type speed: List[int]
:rtype: int
"""
times = [float(target - p)/s for p,s in sorted(zip(position, speed))]
fleets, last_time = 0, 0
for time in times[::-1]:
if time > last_time:
fleets += 1
last_time = time
return fleets
|
9bb50043c7796a099cc0415571431064891e8fdc | qcl643062/leetcode | /141-Linked-List-Cycle.py | 890 | 3.890625 | 4 | """
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
"""
class ListNode(object):
def __init__(self, x, next = None):
self.val = x
self.next = next
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
if not head.next:
return False
twostep = head.next.next
while True:
if head.next == twostep:
return True
else:
head = head.next
if not twostep:
return False
elif not twostep.next:
return False
else:
twostep = twostep.next.next
s = Solution()
print s.hasCycle(ListNode(0, ListNode(1))) |
b552af96f20648be2c3e7827f2c042294fecac6c | Bapathuyamuna/My_First_programs-posting- | /list builting functions.py | 1,557 | 3.953125 | 4 | >>> l=[1,2,3,4]
>>> l.append('yamuna')
>>>
>>> l
[1, 2, 3, 4, 'yamuna']
>>> l.insert('yamuna')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
l.insert('yamuna')
TypeError: insert() takes exactly 2 arguments (1 given)
>>> l.insert(6,'yamuna')
>>> l
[1, 2, 3, 4, 'yamuna', 'yamuna']
>>> l.count('yamuna')
2
>>> l
[1, 2, 3, 4, 'yamuna', 'yamuna']
>>> l.count(4)
1
>>> l=[1,2,3]
>>> l1=[4,5,6]
>>> l.extend(l1)
>>> l1
[4, 5, 6]
>>> l+l1
[1, 2, 3, 4, 5, 6, 4, 5, 6]
>>> l1.extend(l)
>>> l1
[4, 5, 6, 1, 2, 3, 4, 5, 6]
>>> l=[1,2,3]
>>> l1=[4,5,6]l.extend(l1)
SyntaxError: invalid syntax
>>> l=[1,2,3,4]
>>> l.index(1)
0
>>> l.index(3)
2
>>> l.pop(2)
3
>>> l
[1, 2, 4]
>>> l=['yamuna']
>>> l.remove('m')
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
l.remove('m')
ValueError: list.remove(x): x not in list
>>> l=[1,2,3,4]
>>> l=[5,6,4,8,3]
>>> l.sort()
>>> l
[3, 4, 5, 6, 8]
>>> l.extend()
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
l.extend()
TypeError: extend() takes exactly one argument (0 given)
>>>
>>>
>>>
>>>
>>>
>>> t=(1,2,3,4)
>>> t.count(3)
1
>>> t.index(3)
2
>>> t1=(1,2,3,4)
>>> t2=(5,6,7,8)
>>> t1+t2
(1, 2, 3, 4, 5, 6, 7, 8)
>>> t=(1,2,3,4)
>>> for i in t
SyntaxError: invalid syntax
>>> t.apend()
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
t.apend()
AttributeError: 'tuple' object has no attribute 'apend'
|
d3e9789dedf1d4f95170372af235aac0f7778925 | daniel-reich/turbo-robot | /EWZqYT4QGMYotfQTu_13.py | 2,299 | 4.1875 | 4 | """
Tap code is a way to communicate messages via a series of taps (or knocks) for
each letter in the message. Letters are arranged in a 5x5 _polybius square_ ,
with the letter "K" being moved to the space with "C".
1 2 3 4 5
1 A B C\K D E
2 F G H I J
3 L M N O P
4 Q R S T U
5 V W X Y Z
Each letter is translated by tapping out the _row_ and _column_ number that
the letter appears in, leaving a short pause in-between. If we use "." for
each tap, and a single space to denote the pause:
text = "break"
"B" = (1, 2) = ". .."
"R" = (4, 2) = ".... .."
"E" = (1, 5) = ". ....."
"A" = (1, 1) = ". ."
"K" = (1, 3) = ". ..."
Another space is added between the groups of taps for each letter to give the
final code:
"break" = ". .. .... .. . ..... . . . ..."
Write a function that returns the tap code if given a word, or returns the
translated word (in lower case) if given the tap code.
### Examples
tap_code("break") ➞ ". .. .... .. . ..... . . . ..."
tap_code(".... ... ... ..... . ..... ... ... .... ....") ➞ "spent"
### Notes
For more information on tap code, please see the resources section. The code
was widely used in WW2 as a way for prisoners to communicate.
"""
def tap_code(word):
if not(isinstance(word,str)):
print("You need to input a string")
return FALSE
elif "." in word:
dots = word.split()
out = []
for letter in range(0,len(dots),2):
row = (len(dots[letter])-1+13)*5
col = len(dots[letter+1])-1
ascii_val = row+col
#if ascii_val == 67:
# out.append("C/K")
if ascii_val >= 75:
out.append(str(chr(ascii_val+1)))
else:
out.append(str(chr(ascii_val)))
separator = ''
out = separator.join(out)
out = out.lower()
else:
word = word.upper()
print(word)
out = []
for letter in word:
ascii_val = ord(letter)
if ascii_val == 75:
ascii_val = 67
elif ascii_val > 75:
ascii_val -= 1
row = int(ascii_val/5)-13
col = ascii_val % 5
out.append((row+1)*".")
out.append(" ")
out.append((col+1)*".")
out.append(" ")
out.pop()
separator = ''
out = separator.join(out)
return out
|
c2f9848cfb94143dba23eab573270c48a61d4e82 | omriz/coding_questions | /346.py | 1,445 | 4.375 | 4 | #!/usr/bin/env python3
"""
You are given a huge list of airline ticket prices between different cities around the world on a given day. These are all direct flights. Each element in the list has the format (source_city, destination, price).
Consider a user who is willing to take up to k connections from their origin city A to their destination B. Find the cheapest fare possible for this journey and print the itinerary for that journey.
For example, our traveler wants to go from JFK to LAX with up to 3 connections, and our input flights are as follows:
[
('JFK', 'ATL', 150),
('ATL', 'SFO', 400),
('ORD', 'LAX', 200),
('LAX', 'DFW', 80),
('JFK', 'HKG', 800),
('ATL', 'ORD', 90),
('JFK', 'LAX', 500),
]
Due to some improbably low flight prices, the cheapest itinerary would be JFK -> ATL -> ORD -> LAX, costing $440.
"""
def pre_process(costs_list):
to_ret = {}
for k in costs_list:
if k[0] not in to_ret:
to_ret[k[0]] = {}
to_ret[k[0]][k[1]] = k[2]
return to_ret
def find_cheapest(source,dest,k,costs):
options = []
if __name__ == "__main__":
costs_list = [
('JFK', 'ATL', 150),
('ATL', 'SFO', 400),
('ORD', 'LAX', 200),
('LAX', 'DFW', 80),
('JFK', 'HKG', 800),
('ATL', 'ORD', 90),
('JFK', 'LAX', 500),
]
costs = pre_process(costs_list)
path,cost = find_cheapest(source,dest,k,costs)
print(path)
print(cost)
|
ab3678938de30d32401f44444ae5381121e5dcac | EnoshTsur/Python-Course | /15-12-18/home_work.py | 2,999 | 3.875 | 4 | import re
"""
First Task
"""
# Initial Persons
persons_list = []
for index in range(1, 4):
print(f"Person number {index}:")
person = {
'name': input('Enter your name\n'),
'age': int(input('Enter your age\n'))
}
persons_list.append(person)
# 1)
for person in persons_list:
if person['age'] < 27:
person['name'] = 'Jimmy Hendrix'
print(persons_list)
# 2)
for person in persons_list:
if 't' in person['name'].lower():
person['age'] += 1
print(f"""Happy bday {person['name']}
Your are {person['age']} years old.""")
# 3)
counter = 0
while counter < persons_list[0]['age']:
if not counter % 2 == 0:
print(counter)
counter += 1
# 4)
e_letter = 'e'
for person in persons_list:
if e_letter in person['name'].lower():
lower_person = person['name'].lower()
if lower_person.startswith(e_letter):
print(f"{e_letter} in index 0")
elif lower_person[1] == e_letter:
print(f"{e_letter} in index 1")
else:
print(f"{e_letter} in index {person['name'].find(e_letter)}")
"""
Second Task
"""
# Initial Time
time = int(input('Enter time in minutes'))
# 1)
hours = int(time / 60)
minutes = time - (hours * 60)
print(f"hours: {hours}, minutes: {minutes}")
# 2)
if hours >= 1:
if hours < 2:
print("Ok...")
else:
print("Trilogy")
# 3)
if minutes > hours:
if minutes % 2 == 0:
hours *= 2
else:
minutes -= 1
else:
print(hours)
print(f"Hours: {hours}, Minutes: {minutes}")
"""
Third Task
"""
# Creating the file
file_content = """
My my candle candle burns at both ends;
It will not last the night;
But ah, my foes, and oh, my friends—
It gives a lovely light!
"""
file_path = "file.txt"
with open(file_path, mode='w') as my_file:
my_file.write(file_content)
# Reading the file
with open(file_path, mode='r') as my_file:
reading_content = my_file.read()
# 1)
all_words = reading_content.split()
# 2)
all_words_set = set({})
#
for word in all_words:
word = re.sub(r"[^A-Za-z]+", "", word)
all_words_set.add(word.lower())
# 3)
for word in all_words_set:
if word.startswith('t'):
print(f"Word ({word}) starts with 't'")
# 4)
for word in all_words_set:
if word.lower().startswith('a'):
print(f"Word: {word}")
print("Letters:")
for letter in word:
print(letter)
# 5) Short way
words_tuple = tuple(word for word in all_words if 'a' not in word.lower())
print(words_tuple)
# 5) Long way
to_be_tuple = []
for word in all_words:
if 'a' not in word.lower():
to_be_tuple.append(word)
to_be_tuple = tuple(to_be_tuple)
print(to_be_tuple)
# 6) Short way
new_e_words = [e_word.replace('e', '3') for e_word in all_words_set if 'e' in e_word]
print(new_e_words)
# 6) Long way
e_to_3 = []
for word in all_words_set:
if 'e' in word:
new_word = word.replace('e', '3')
e_to_3.append(new_word)
print(e_to_3)
|
f257014abf033c1e8eb5505fdd01a9eb6b95e4d8 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4272/codes/1668_2969.py | 206 | 3.5 | 4 | jogo = int(input("quatidade:"))
p1 = float(input("preco do primeiro jogo:"))
p2 = float(input("preco do segundo jogo:"))
if(jogo==1):
valor = p1
else:
valor = p1 + p2 *25/100
print(round(valor50.0,2))
|
b75527f8d017c20956e2eb929bb6cfa10aeba129 | Pratiknarola/PyTricks | /merge_dict.py | 73 | 3.546875 | 4 | """merge dict's"""
d1 = {'a': 1}
d2 = {'b': 2}
d1.update(d2)
print(d1)
|
f042a40535d51c0b5846e0bd46fd3c35bd6ceb36 | trolen/exercises | /06/bob_original.py | 268 | 3.53125 | 4 | #!/usr/bin/env python
def hey(input_string):
if input_string.strip() == '':
return 'Fine. Be that way!'
if input_string.isupper():
return 'Woah, chill out!'
if input_string[-1] == '?':
return 'Sure.'
return 'Whatever.'
|
268e355c3fd1bc4ff34b7a886955ddc435c772c3 | JAndresOrozco/CRUD-MongoDB | /produit.py | 1,581 | 3.8125 | 4 |
class produit():
def créer(self, collection):
option = input("Vous voulez entrer un produit?" "Oui/Non \n")
while not option == 'Non':
prenom = input("Entrez un produit: \n")
prix = float(input("Entrez un prix: \n"))
collection.insert_one({"prenom" : prenom , "prix" : prix })
option = input("Vous voulez entrer un nouveau produit?" "Oui/Non \n")
def mettreàjour(self, collection):
option = input("Vous voulez mettre à jour un produit?" "Oui/Non \n")
while not option == 'Non':
prenomChanger = input("Entrez le produit: \n")
prenom = input("Entrez un nouveau produit: \n")
prix = float(input("Entrez un nouveau prix: \n"))
collection.update_one({"prenom": prenomChanger},
{"$set":
{
"prenom": prenom,
"prix": prix
}
})
print('Enregistrement mis à jour')
option = input("Vous voulez mettre à jour un nouveau produit?" "Oui/Non \n")
def supprimer(self, collection):
option = input("Vous voulez supprimer un produit?" "Oui/Non \n")
while not option == 'Non':
prenomSupprimer = input("Entrez le produit: \n")
collection.delete_one({"prenom": prenomSupprimer})
print("Enregistrement supprimé")
option = input("Vous voulez supprimer un nouveau produit?" "Oui/Non \n")
|
3450ef66f8ce6ec445ec0e1f35567c80a8fd53e7 | UMDLARS/CYLGame | /game_db_editor.py | 7,751 | 3.765625 | 4 | #!/usr/bin/env python3
from typing import List, Optional, Tuple
import os
import sys
from builtins import input
from click import Choice, prompt
from CYLGame.Database import GameDB
gamedb: Optional[GameDB] = None
cur_school: Optional[str] = None
cur_comp: Optional[str] = None
def clear():
os.system("clear")
def pause(prompt="Enter any input: "):
get_input(prompt, lambda x: 1)
def get_input(prompt="", validator=lambda x: x, error_msg=""):
inp = input(prompt)
while not validator(inp):
print(error_msg)
inp = input(prompt)
return inp
def print_menu(options: List[Tuple], title: str, enable_no_selection=True) -> Optional:
"""
options should be in the form [(name, value)] example: [("School #1", "ABC")]
"""
clear()
print(title)
if enable_no_selection:
print("0: Return without selecting an option")
for index, (option, value) in enumerate(options):
print(str(index + 1) + ":", option)
start_index = 0 if enable_no_selection else 1
choices = Choice(list(map(str, range(start_index, len(options) + 1))))
choice = prompt("Select an item", type=choices)
if choice == "0":
print("Selecting None")
return None
print(options)
return options[int(choice) - 1][1]
def clear_selection():
global cur_comp, cur_school
cur_comp = None
cur_school = None
def add_competition():
global gamedb, cur_comp
clear()
comp_name = get_input("Enter New Competition Name: ")
# TODO(derpferd): add school selection
# TODO(derpferd): add token selection from school
clear_selection()
cur_comp = gamedb.add_new_competition(comp_name)
# # select the top scoring bots from each school
# for school in gamedb.get_school_tokens():
# top_bot = None
# top_score = -1
# for user in gamedb.get_tokens_for_school(school):
# score = gamedb.get_avg_score(user)
# if score is None:
# score = 0
# if score > top_score:
# top_score = score
# top_bot = user
# if top_bot is not None:
# gamedb.set_token_for_comp(token, top_bot, school)
print("Don't forget to run competition sim script with the following token:", cur_comp)
pause()
def select_competition():
global gamedb, cur_comp
options = []
for i, comp_tk in enumerate(gamedb.get_comp_tokens()):
options += [(gamedb.get_name(comp_tk), comp_tk)]
clear_selection()
cur_comp = print_menu(options, "Select Competition")
print("Current Competition Set to:", cur_comp)
def add_school_to_comp():
global gamedb, cur_comp
options = []
for i, school_tk in enumerate(gamedb.get_school_tokens()):
options += [(gamedb.get_name(school_tk), school_tk)]
selection = print_menu(options, "Select School")
if selection is None:
print("No School added")
else:
gamedb.add_school_to_comp(cur_comp, selection)
print("School added")
print("Don't forget to run competition sim script with the following token:", cur_comp)
pause()
def list_schools_in_comp():
global gamedb, cur_comp
clear()
print("Schools")
for token in gamedb.get_schools_in_comp(cur_comp):
print(gamedb.get_name(token))
pause()
# TODO(derpferd): add function to remove a school
def add_school():
global gamedb, cur_school
clear()
school_name = get_input("Enter New School Name: ")
clear_selection()
cur_school = gamedb.add_new_school(school_name)
print("Current School Set to:", cur_school)
def select_school():
global gamedb, cur_school
options = []
for i, school_tk in enumerate(gamedb.get_school_tokens()):
options += [(gamedb.get_name(school_tk), school_tk)]
clear_selection()
cur_school = print_menu(options, "Select School")
print("Current School Set to:", cur_school)
def get_new_tokens():
global gamedb, cur_school
clear()
count = int(get_input("How many tokens would you like: ", lambda x: x.isdigit(), "Please enter a number."))
clear()
print("New tokens")
for _ in range(count):
print(gamedb.get_new_token(cur_school))
pause()
def list_tokens():
global gamedb, cur_school
clear()
print("Tokens")
for token in gamedb.get_tokens_for_school(cur_school):
print(token)
pause()
def view_exceptions():
global gamedb
clear()
options = []
for token in gamedb.get_exception_tokens():
options.append((token, token))
selection = print_menu(options, "Select Exception")
clear()
if selection:
print(gamedb.get_exception(selection))
pause()
def view_code_from_hash():
global gamedb
clear()
code_hash = get_input("Enter Code hash: ")
code = gamedb.get_code_by_hash(code_hash)
if isinstance(code, list):
options = [(x, x) for x in code]
option = print_menu(options, "There were multiple matches, select one:")
if not option:
return
code = gamedb.get_code_by_hash(option)
clear()
print(code)
pause()
def get_main_menu_options():
global cur_school
options = ["Add New School", "Select School", "Add New Competition", "Select Competition"]
if cur_school is not None:
options += ["Get new Tokens", "List current Tokens"]
if cur_comp is not None:
# TODO(derpferd): implement
options += ["Add School to Competition", "List Schools in Competition"]
options.append("View Exceptions")
options.append("Code from Hash")
return options + ["Quit"]
def get_main_menu_title():
global gamedb, cur_school, cur_comp
title = "Main Menu"
if cur_school is not None:
title += "\n\nSelected School: " + gamedb.get_name(cur_school) + " (" + cur_school + ")"
if cur_comp is not None:
title += "\n\nSelected Competition: " + gamedb.get_name(cur_comp) + " (" + cur_comp + ")"
return title
def main():
global gamedb
print("Welcome to the GameDB Editor")
print("!!!!WARNING!!!!!!")
print("If you do NOT know what you are doing. Please exit now!!!")
if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
game_path = os.path.abspath(sys.argv[1])
print("You choose", game_path, "as a game path.")
else:
game_path = os.path.abspath(
get_input(
"Your current dir is '" + os.path.abspath(os.curdir) + "'\nEnter path to game dir: ",
lambda x: os.path.exists(x),
error_msg="Invalid Game Directory. Try Again.",
)
)
gamedb = GameDB(game_path)
option = ""
while option != "Quit":
options = get_main_menu_options()
options = [(x, x) for x in options]
option = print_menu(options, get_main_menu_title(), enable_no_selection=False)
print("You selected:", option)
if option == "Select School":
select_school()
elif option == "Select Competition":
select_competition()
elif option == "Add New Competition":
add_competition()
elif option == "Add School to Competition":
add_school_to_comp()
elif option == "List Schools in Competition":
list_schools_in_comp()
elif option == "Add New School":
add_school()
elif option == "Get new Tokens":
get_new_tokens()
elif option == "List current Tokens":
list_tokens()
elif option == "View Exceptions":
view_exceptions()
elif option == "Code from Hash":
view_code_from_hash()
if __name__ == "__main__":
main()
|
866a812707cdfdb9edf49d2a7e0a8cd3c5ba867f | AChen24562/Python-QCC | /Week-2-format-string/Exercise-6.py | 204 | 3.90625 | 4 | n = 2
print(f"{n} * 1 = {n * 1}")
print(f"{n} * 2 = {n * 2}")
print(f"{n} * 3 = {n * 3}")
x = 10
y = 8
print(x //y, x /y, x%y)
a = 10.5
b = 2
print (a % b, a/b, a//b)
_asd = "asd"
print(_asd)
|
7786699f416187517a90bb1b5e926bd785abb319 | zwt0204/python_ | /LeetCode/编辑距离.py | 1,277 | 3.65625 | 4 | # -*- encoding: utf-8 -*-
"""
@File : 编辑距离.py
@Time : 2020/7/13 16:29
@Author : zwt
@git :
@Software: PyCharm
"""
def edit_distence(str1, str2):
"""递归"""
if len(str1) == 0:
return len(str2)
elif len(str2) == 0:
return len(str1)
elif str1 == str2:
return 0
if str1[len(str1) - 1] == str2[len(str2) - 1]:
d = 0
else:
d = 1
return min(edit_distence(str1, str2[:-1]) + 1,
edit_distence(str1[:-1], str2) + 1,
edit_distence(str1[:-1], str2[:-1]) + d)
def edit_(str1, str2):
"""动态规划"""
matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]
for i in range(1, len(str1) + 1):
for j in range(1, len(str2) + 1):
if str1[i - 1] == str2[j - 1]:
d = 0
else:
d = 1
matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + d)
return matrix[len(str1)][len(str2)]
if __name__ == '__main__':
# print(edit_("xxc", "xyz"))
import numpy as np
temp = np.zeros((4, 4), dtype=np.int)
temp[0] = np.arange(4)
temp[:, 0] = np.arange(4)
print(temp) |
ff299534a548c0b506b123420de9f4d6507100f6 | akxl/adventofcode2018 | /day1/part2.py | 882 | 3.8125 | 4 | # which position occurs 2 times first?
# this is quite slow
def getPositionWithTwoOccurences(numbers):
history = [0]
currentPosition = 0
found = False
while (found == False):
for number in numbers:
currentPosition += number
if currentPosition in history:
print("The first position with 2 occurences is: %d" % (currentPosition))
found = True
return(currentPosition)
else:
history.append(currentPosition)
if __name__ == "__main__":
f = open("input.txt", "r")
numbers = list(map(int, f.read().split()))
print(sum(numbers)) # expect 576
print(getPositionWithTwoOccurences([1, -1])) # expect 0
print(getPositionWithTwoOccurences([3,3,4,-2,-4])) # expect 10
print(getPositionWithTwoOccurences([-6,3,8,5,-6])) # expect 5
print(getPositionWithTwoOccurences([7,7,-2,-7,-4])) # expect 14
print(getPositionWithTwoOccurences(numbers)) # 77674
|
a3bd04d3be2c4ccddbb4808a72f3e660320d0d8e | deepsjuneja/tathastu_week_of_code | /day5/program3.py | 438 | 3.921875 | 4 | def maxValue(List):
sum_even = 0
sum_odd = 0
for i in range(n):
if i%2 == 0:
sum_even += List[i]
else:
sum_odd += List[i]
print("Maximum Value that can be stolen by thief: ", max(sum_even, sum_odd))
n = int(input("Enter the no. of houses: "))
Li = []
print("Enter the value stored in each house: ")
for i in range(n):
value = int(input())
Li.append(value)
maxValue(Li)
|
5181ce027ea3524a9dccef96a3e27dbcf6d02c9a | Baratnannaka/Python_Training | /#break&continue.py | 82 | 3.59375 | 4 | #break&continue
for i in range(10):
if(i==3):
break
print (i); |
e0a3bc105f0df13d9ae8e8c5c031c2c766ad3226 | ma7salem/python-fundamentals | /#2 lists/demo.py | 152 | 3.734375 | 4 | info = ['mahmoud', 22, 3.2]
print(info[0])
print(info[-1])
info[0] = 'mohammed'
print(info[0])
info.append(3)
print(info)
info.pop(3)
print(info)
|
b2c0f547d7db610098a3bc1f4a0a92ba7d1f219e | hikyru/Python | /HW3_Obesity.2.py | 569 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 5:20 2020
@author: KatherineYu
"""
# User Input
gender = input("Gender: ")
gender = gender.lower()
waist = float(input("Waist Measurements: "))
# Determine whether user is fat or not
if gender == "male" and waist >= 90:
print('\n' "FAT.")
elif gender == "male" and waist < 90:
print('\n' "NOT FAT.")
elif gender == "female" and waist >= 85:
print('\n' "FAT.")
elif gender == "female" and waist < 85:
print('\n' "NOT FAT.")
else:
print('\n' "Input undefined. Please input 'female' or 'male'")
|
08da83a834a16347e34ad96d2b4baf2abae81a05 | wulinlw/leetcode_cn | /程序员面试金典/面试题16.05.阶乘尾数.py | 1,072 | 3.828125 | 4 | # #!/usr/bin/python
# #coding:utf-8
#
# 面试题16.05.阶乘尾数
#
# https://leetcode-cn.com/problems/factorial-zeros-lcci/
#
# 设计一个算法,算出 n 阶乘有多少个尾随零。
# 示例 1:
#
# 输入: 3
# 输出: 0
# 解释: 3! = 6, 尾数中没有零。
#
# 示例 2:
#
# 输入: 5
# 输出: 1
# 解释: 5! = 120, 尾数中有 1 个零.
#
# 说明: 你算法的时间复杂度应为 O(log n) 。
#
#
# Easy 46.2%
# Testcase Example: 3
#
# 提示:
# 0如何变成n!?这是什么意思?
# n!中的每个0表示n能被10整除一次。这是什么意思?
# n!中每一个因子10都意味着n!能被5和2整除。
# 你能计算出5和2的因数的个数吗?需要两者都计算吗?
# 你是否考虑过25实际上记录了两次因数5?
#
#
class Solution:
# 末尾的0都是2*5来的,统计有多少个5即可
def trailingZeroes(self, n: int) -> int:
m5 = 0
while n>0:
n //= 5
m5 += n
return m5
n = 5
o = Solution()
print(o.trailingZeroes(n)) |
c8c2dadfe14551e11f5374223acf50a6de0ac5ab | LaurenceYang/learn-python3 | /basic/tuple.py | 363 | 4.03125 | 4 | classmates = ('yang', 'wang', 'han')
print('classmates=', classmates)
print('classmates[0]=', classmates[0])
print('classmates[1]=', classmates[1])
print('classmates[2]=', classmates[2])
print('classmates[-1]=', classmates[-1]) # 用-1做索引,直接获取最后一个元素
# classmates[0] = "ma" #TypeError: 'tuple' object does not support item assignment
|
cc6628e29639bb5da86cdab0fad9da9c8e6dd08d | MrLW/algorithm | /04_list/easy_203_removeElements.py | 617 | 3.625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
res = ListNode(-1, head)
cur = res.next
pre = res
while cur != None:
if cur.val == val:
pre.next = cur.next
else:
pre = cur
cur = cur.next
return res.next
l4 = ListNode(1, None)
l3 = ListNode(2, l4)
l2 = ListNode(3, l3)
l1 = ListNode(4, l2)
s = Solution()
s.removeElements(l1, 2) |
d0aa7953b54048c3c27c04a5911961a01fd91814 | yesiknowjava/datastructure-and-algorithms-in-python | /datastructure/6.Heaps/max_heap_insert.py | 688 | 3.890625 | 4 | def heapify(value_list, child_val):
parent_index = (value_list.index(child_val) - 1)//2
parent_val = value_list[parent_index]
child_index = value_list.index(child_val)
if child_val > parent_val:
value_list[parent_index] = child_val
value_list[child_index] = parent_val
if parent_index != 0:
return heapify(value_list, parent_val)
return value_list
if __name__ == '__main__':
value_list = [10, 5, 6, 1, 2, 3, 4]#sample max heap
delete_value = 10
#to delete : we can only delete the root
value_list[0].append(value_list)
print(value_list)
value_list = heapify(value_list, value_list[-1])
print(value_list) |
849c1b35a3c1581b49569463bd2a951866e75aac | nasigh/assignment-3 | /array.py | 175 | 3.625 | 4 | import random
n = input ("please enter n:")
i=0
array=[]
while i< int(n):
x = random.randint(1,100)
if not (x in array):
array.append (x)
i=i+1
print(array)
|
b11113793f89bcd06541c1a00f46f5f719fb23ba | bradreardon/python-mcprofiles | /mcprofiles/api.py | 1,600 | 3.53125 | 4 | import requests
from json import JSONEncoder
from .exceptions import *
def get_session(uuid):
"""
Gets the session for a given UUID, containing all sorts of fun details.
If a UUID is invalid, an InvalidUsername exception will be raised.
:param uuid: The UUID to get session information for.
:return: Decoded JSON for the session of the given UUID.
"""
r = requests.get("https://sessionserver.mojang.com/session/minecraft/profile/%s" % uuid)
if r.text == "":
raise InvalidUsername
return r.json()
def to_uuid(users):
"""
Provides easy method for checking UUID of one or multiple users.
Will always return a dictionary with the keys representing usernames.
If a username is invalid, it will not be included in the response dictionary.
:param users: String or list of usernames to convert to UUIDs.
:return: A dictionary mapping all (valid) users to UUIDs.
"""
resp = {}
r = requests.post(
"https://api.mojang.com/profiles/minecraft",
headers={"Content-Type": "application/json"},
data=JSONEncoder().encode(users)
)
for pair in r.json():
resp[pair['name']] = pair['id']
return resp
def to_user(uuid):
"""
Provides method for checking username of a single UUID.
Will always return a string containing the username.
If a UUID is invalid, an InvalidUsername exception will be raised.
:param uuid: The UUID to look up through the API.
:return: The username associated with the given UUID.
"""
s = get_session(uuid)
return s['name'] |
657d8f64db74961f6ea5faa6ef8e02f4884a63e1 | theSkyHub/learning | /6.py | 113 | 3.703125 | 4 | for i in range (5,0,-1):
for j in range (1,i+1):
print(i,end="")
print()
for i in range (1,15,
##Aakash Verma
|
f8109cfc3c43a073181277cb4bdea407f662635a | muokicaleb/Hacker_rank_python | /math/polar_coordinates.py | 619 | 4.21875 | 4 | """
Task
You are given a complex Z. Your task is to convert it to polar coordinates.
Input Format
A single line containing the complex number Z. Note: complex() function can be used in python to convert the input as a complex number.
Given number is a valid complex number
Output Format
Output two lines:
The first line should contain the value of R.
The second line should contain the value of $.
Sample Input
1+2j
Sample Output
1.1071487177940904
"""
from cmath import sqrt, phase
cnum = complex(input())
print sqrt(pow(cnum.real, 2) + pow(cnum.imag, 2)).real
print phase(complex(cnum.real,cnum.imag)) |
5b409ec75d3ac9b4823bbffc6b043505855ea202 | narrasubbarao/practise | /Datatypes/Demo14.py | 284 | 4.15625 | 4 | l1 = [10,90,30,40,80,90,100]
print(l1)
val = l1.pop() # it will remove last value from list
print(val)
print(l1)
print("---------------------------")
l1 = [10,90,30,40,80,90,100]
print(l1)
val = l1.pop(3)
# Removes and returns an element at the given index
print(val)
print(l1)
|
b3d2652c69c7774e04ad446c72a66c3a19957a38 | CuongNguyen3110/NguyenManhCuong-Fundamental-C4E23 | /session2/pt_bac2.py | 389 | 3.6875 | 4 | a = int(input("Nhap a: "))
b = int(input("Nhap b: "))
c = int(input("Nhap c: "))
delta = b**2 - 4 * a * c
print(delta)
if delta < 0:
print("Phuong trinh vo nghiem")
elif delta == 0:
print("Phuong trinh co mot nghiem:", -b/(2*a))
else:
print("Phuong trinh co hai nghiem phan biet:")
print("x1 =", (-b + delta ** 1/2)/(2 * a))
print("x2 =", (-b - delta ** 1/2)/(2 * a)) |
0c07417af65ee1dac78b7a6434efbbd5ac0f2dfe | GhostDovahkiin/Introducao-a-Programacao | /03-Exercício-Aula-3/Slide-27/URI_1018.py | 508 | 3.609375 | 4 | Dinheiro = int(input("Digite o valor em R$: "))
Nota100 = Dinheiro//100
Dinheiro = Nota100 % 100
Nota50 = Dinheiro //50
Dinheiro = Nota50 % 50
Nota10 = Dinheiro//10
Dinheiro = Nota10 % 10
Nota5 = Dinheiro//5
Dinheiro = Nota5 % 5
Nota2 = Dinheiro//2
Dinheiro = Nota2 % 2
Nota1 = Dinheiro//1
print("Seu dinheiro decomposto é Notas de 100 = %4.4s. \nNotas de 50 = %0.4s. \nNotas de 10 = %4.4s. \nNotas de 5 = %4.4s. \nNotas de 2 = %4.4s. \nNotas de 1 = %4.4s" %(Nota100, Nota50, Nota10, Nota5, Nota2, Nota1))
|
2fbd6e37d359768b141ae3b5bcfa51d54c603cb3 | Lucakurotaki/ifpi-ads-algoritmos2020 | /Fabio02_A/f2_a_q23_data_recente.py | 1,144 | 3.921875 | 4 | def main():
print("\n~~~Primeira data~~~")
ano1 = int(input("Digite o ano: "))
mes1 = int(input("Digite o mês: "))
dia1 = int(input("Digite o dia: "))
print("\n~~~Segunda data~~~")
ano2 = int(input("Digite o ano: "))
mes2 = int(input("Digite o mês: "))
dia2 = int(input("Digite o dia: "))
print(data_recente(ano1,mes1,dia1,ano2,mes2,dia2))
def data_recente(a1,m1,d1,a2,m2,d2):
if verifica_data(a1,m1,d1,a2,m2,d2) == False:
return "Data inválida."
elif a1 > a2:
return "A primeira data é a mais recente."
elif a1 == a2 and m1 > m2:
return "A primeira data é a mais recente."
elif a1 == a2 and m1 == m2 and d1 > d2:
return "A primeira data é a mais recente."
elif a1 == a2 and m1 == m2 and d1 == d2:
return "As datas são iguais."
else:
return "A segunda data é a mais recente."
def verifica_data(a1,m1,d1,a2,m2,d2):
if a1>2020 or a2>2020:
return False
if m1>12 or m1<1 or m2>12 or m2<1:
return False
if d1>31 or d1<1 or d2>31 or d2<1:
return False
main()
|
dc3f459a8c82d1790ad1eed3558d2a5cefd19a90 | thoufiqzumma/tamim-shahriar-subeen-python-book-with-all-code | /all code/p.Centigrade to Farenhite formula is c/5=(f-32)/9=(k-273)/5.py | 183 | 3.59375 | 4 | """
Centigrade to Farenhite formula is c/5=(f-32)/9=(k-273)/5
"""
centigrade = float((input("enter a number: ")))
Farenhite = (1.8*centigrade)+32
print(f'Farenhite={Farenhite:.2f}')
|
51d65aa12eda72112df58d23be77aeaa3b6b99ec | SashaTsios/Beetroot | /lesson19_newer_testing.py | 1,157 | 3.515625 | 4 | import unittest
from lesson19_newergame2d_WO_test import Car
class GameTest(unittest.TestCase):
def setUp(self):
self.car_test = Car('SuperBrand', 'SuperModel', 'SuperColor', 1, [0, 0])
def test_move_left_2_steps_defaul_speed(self):
self.assertEqual(self.car_test.move_left(2, 1), [-2, 0])
def test_change_speed_from_1_to_5(self):
self.assertEqual(self.car_test.change_speed(5), 5)
def test_move_left_3_steps_changed_to_5_speed(self):
self.car_test.change_speed(5)
self.assertEqual(self.car_test.move_left(3), [-15, 0])
def test_move_left_3_steps_changed_to_10_speed(self):
self.assertEqual(self.car_test.move_left(3, 10), [-30, 0])
def test_combination(self):
self.assertEqual(self.car_test.move_left(10), [-10, 0])
self.car_test.change_speed(5)
self.assertEqual(self.car_test.move_left(1), [-15, 0])
self.assertEqual(self.car_test.move_left(2, 10), [-35, 0])
self.assertEqual(self.car_test.current_position(), [-35, 0])
self.assertEqual(self.car_test.move_right(1, 35), [0, 0])
if __name__ == '__main__':
unittest.main()
|
93270f86757226994f89e219d7f0aec7cf25529c | vukor/Introducing_Python | /4/10.py | 545 | 3.671875 | 4 | #!/usr/bin/env python3
'''
Определите декоратор test, который выводит строку 'start', когда вызывается функция, и строку 'end', когда функция завершает свою работу.
'''
def test(func):
def new_function(*args, **kwargs):
print('start')
result = func(*args, **kwargs)
print('Result:', result)
print('end')
return result
return new_function
@test
def hello():
return 'Hello!'
print(hello())
|
9b619419594677e60ae989bcdaa2b4fdb8081b56 | jdukosse/LOI_Python_course-SourceCode | /Chap5/printprimes.py | 715 | 4.375 | 4 | max_value = int(input('Display primes up to what value? '))
value = 2 # Smallest prime number
while value <= max_value:
# See if value is prime
is_prime = True # Provisionally, value is prime
# Try all possible factors from 2 to value - 1
trial_factor = 2
while trial_factor < value:
if value % trial_factor == 0:
is_prime = False # Found a factor
break # No need to continue; it is NOT prime
trial_factor += 1 # Try the next potential factor
if is_prime:
print(value, end= ' ') # Display the prime number
value += 1 # Try the next potential prime number
print() # Move cursor down to next line
|
6c2910a9278a571f95ca9c7237ce276b6ea27d15 | poojachilongia/python_training | /Assignment3.py | 781 | 4 | 4 | import random
firstname=str(input('enter first name'))
lastname=str(input('enter 2nd name'))
def generateOTP():
OTP=int(input("enter the number"))
if OTP>21:
print("the number entered is wrong try again")
OTP1=random.randint(1,21)
print("your one time password is")
print(OTP1)
if OTP==OTP1:
print("your OTP matched successfully")
else:
print("ERROR!!! enter the OTP again")
return OTP
generateOTP()
for x in range(3):
print("would you like to give another chance if yes(y) if no(n)")
try_again=input("enter the choice")
if try_again=="y":
generateOTP()
else:
print(" thanks for attempt")
break
print(" sorry program crashed")
|
3aa5c76b36fd722f62c0d96fda1c6c512bf8ed07 | zecookiez/AdventOfCode2019 | /day01_rocketEquation.py | 470 | 3.625 | 4 | # Problem description @ https://adventofcode.com/2019/day/1
"""
Input parsing
"""
lines = open("input.txt", "r").readlines()
input_arr = map(int, lines)
def solve(input_arr):
total = total2 = 0
for fuel in input_arr:
total += fuel // 3 - 2
while fuel // 3 > 2:
total2 += fuel // 3 - 2
fuel = fuel // 3 - 2
return total, total2
p1, p2 = solve(input_arr)
print "Answer: %d for part 1, %d for part 2" % (p1, p2)
|
ada16c3f50cffea2b25c38f58b2a9de73df46810 | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/arc076/A/4901176.py | 253 | 3.546875 | 4 | import math
N, M = map(int, input().split())
if N == M:
print((2 * math.factorial(N) * math.factorial(M)) % (10 ** 9 + 7))
elif N == M + 1 or N + 1 == M:
print((math.factorial(N) * math.factorial(M))% (10 ** 9 + 7))
else:
print(0) |
6b9ee983a29998dc3f5ff8267ebf130d10eff8b7 | ccc013/DataStructe-Algorithms_Study | /Python/Leetcodes/linked_list/jianzhi_offer_06_reversePrint.py | 1,429 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2020/12/3 8:00 上午
@Author : luocai
@file : jianzhi_offer_06_reversePrint.py
@concat : 429546420@qq.com
@site :
@software: PyCharm Community Edition
@desc :
https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
剑指 offer06 题--从尾到头打印链表
"""
from Linked_list.Linked_list import ListNode
from typing import List
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
res = []
# 先反转链表
prev, cur = None, head
while cur:
res.insert(0, cur.val)
prev, cur.next, cur = cur, prev, cur.next
# 遍历链表,并保存数值到数组
# while prev:
# res.append(prev.val)
# prev = prev.next
return res
def reversePrint2(self, head: ListNode) -> List[int]:
res = []
while head:
res.append(head.val)
head = head.next
return res[::-1]
def reversePrint3(self, head: ListNode) -> List[int]:
return self.reversePrint3(head.next) + [head.val] if head else []
if __name__ == '__main__':
# 建立一个链表
val_a = [1, 2, 3, 4, 5]
linked_list_a = ListNode.build_linked_list(val_a)
ListNode.print_linked_list(linked_list_a)
solution = Solution()
print("反转的链表:", solution.reversePrint3(linked_list_a))
|
a55c85b0482990b4b8da0f9edab314484a57b143 | canhetingsky/LeetCode | /Python3/405.convert-a-number-to-hexadecimal.py | 1,066 | 3.734375 | 4 | #
# @lc app=leetcode id=405 lang=python3
#
# [405] Convert a Number to Hexadecimal
#
# @lc code=start
class Solution:
# Solution 2
def toHex(self, num: int) -> str:
if num < 0:
num = 0xffffffff + 1 + num
return str(hex(num)).replace('0x','')
# Solution 1
# def toHex(self, num: int) -> str:
# ch = ['0', '1', '2', '3', '4', '5', '6',
# '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
# hex_str = ""
# if num == 0:
# return '0'
# if num < 0:
# num = 0xffffffff + 1 + num
# while num > 0:
# num, rem = divmod(num, 16)
# hex_str = ch[rem]+hex_str
# return hex_str
# Accepted
# 100/100 cases passed (28 ms)
# Your runtime beats 76.26 % of python3 submissions
# Your memory usage beats 100 % of python3 submissions (12.7 MB)
# @lc code=end
# Accepted
# 100/100 cases passed (24 ms)
# Your runtime beats 91.1 % of python3 submissions
# Your memory usage beats 100 % of python3 submissions (12.7 MB)
|
92e14955a411baab1349a2b4a85e2e263fb81f8d | seanpont/project-euler | /064.py | 2,598 | 3.546875 | 4 | """
Project Euler Problem #64
==========================
All square roots are periodic when written as continued fractions and can
be written in the form:
N = a[0] + 1
a[1] + 1
a[2] + 1
a[3] + ...
For example, let us consider 23:
23 = 4 + 23 -- 4 = 4 + 1 = 4 + 1 1 1 + 23 - 3
23--4 7
If we continue we would get the following expansion:
23 = 4 + 1
1 + 1
3 + 1
1 + 1
8 + ...
The process can be summarised as follows:
a[0] = 4, 1 = 23+4 = 1 + 23--3
23--4 7 7
a[1] = 1, 7 = 7(23+3) = 3 + 23--3
23--3 14 2
a[2] = 3, 2 = 2(23+3) = 1 + 23--4
23--3 14 7
a[3] = 1, 7 = 7(23+4) = 8 + 23--4
23--4 7
a[4] = 8, 1 = 23+4 = 1 + 23--3
23--4 7 7
a[5] = 1, 7 = 7(23+3) = 3 + 23--3
23--3 14 2
a[6] = 3, 2 = 2(23+3) = 1 + 23--4
23--3 14 7
a[7] = 1, 7 = 7(23+4) = 8 + 23--4
23--4 7
It can be seen that the sequence is repeating. For conciseness, we use the
notation 23 = [4;(1,3,1,8)], to indicate that the block (1,3,1,8) repeats
indefinitely.
The first ten continued fraction representations of (irrational) square
roots are:
2=[1;(2)], period=1
3=[1;(1,2)], period=2
5=[2;(4)], period=1
6=[2;(2,4)], period=2
7=[2;(1,1,1,4)], period=4
8=[2;(1,4)], period=2
10=[3;(6)], period=1
11=[3;(3,6)], period=2
12= [3;(2,6)], period=2
13=[3;(1,1,1,1,6)], period=5
Exactly four continued fractions, for N 13, have an odd period.
How many continued fractions for N 10000 have an odd period?
"""
def cycle_counter(gen):
a = []
while True:
n = gen.next()
if n in a:
return len(a) - a.index(n)
a.append(n)
assert cycle_counter([1, 3, 5, 6, 3].__iter__()) == 3
assert cycle_counter([1, 1].__iter__()) == 1
def doodle(n):
root = n ** .5 # root(23)
a = int(root) # a_0
nm, dr = 1, -a
for _ in xrange(1000):
d = (n - dr**2) / nm
a = int((root - dr) / d)
dr, nm = -dr - a * d, d
yield a, nm, dr
def solve():
count = 0
for n in xrange(1, 10000):
if n**.5 == int(n**.5): continue
if cycle_counter(doodle(n)) % 2 == 1:
count += 1
print count
solve() |
799c801667aa9374ce3bdb859b543f01e9cf8fcc | SandyUndefined/Nptel-Joy-of-Computing | /Week 6 Assignment3.py | 113 | 3.90625 | 4 | def printDict():
x=int(input())
d={}
for i in range(x):
d[i+1]=(i+1)**2
print(d,end='')
printDict()
|
16db97e691cc9a7c69ed626ae710a9c30bba6175 | Angela-de/lab | /advancedpython/map.py | 1,627 | 4.03125 | 4 | #listcomprehension
from functools import *
names = ["sam", "john", "james"]
print (map(len, names))
def too_old(x):
return x > 30
ages = [22, 25, 29, 34, 56, 24, 12]
print (list(filter(too_old, ages)))
#creating postive numbers from a list
print("\n")
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = [n for n in numbers if n > 0]
print (newlist)
#creating postive numbers from a list ...another way
print("\n")
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
for p in numbers:
if p>=0:
print(p)
#retun only even numbers
print("\n")
numbers = [1,56,234,87,4,76,24,69,90,135]
newlist = [n for n in numbers if n%2==0]
print (newlist)
# returning only even numbers..another way
print("\n")
def is_even(x):
return n % 2 == 0
enum =[1,56,234,87,4,76,24,69,90,135]
print(enum)
#creating a list containing tuples of uppercase version except "is"
print("\n")
words = ["hello", "my", "name", "is", "Sam"]
newlist = [(w.upper(),len(w)) for w in words if w != "is"]
print(newlist)
#creating a list containing tuples of uppercase version
print("\n")
words = ["hello", "my", "name", "is", "Sam"]
newlist = [(w.upper(),len(w)) for w in words]
print(newlist)
print("\n")
#fold
total = reduce(lambda item, running_total: item + running_total, [1, 2, 3, 4, 5])
print(total)
print("\n")
#fold
total2 = reduce(lambda item, running_total: item * running_total, [1, 2, 3, 4, 5])
print(total2)
print("\n")
#write a function to join strings
def join_strings():
words = ["hello", "world"]
helloworld =" " .join(words)
return helloworld
print(join_strings())
|
a6b964a883edbe7222ab0d10bc6e17f102eb7451 | Hubertius/Python | /Cows and Bulls/Cows_and_Bulls.py | 1,147 | 3.9375 | 4 | import random
def random_operations():
a = random.randint(1000,9999)
last = a % 10
third = (a % 100) // 10
second = (a % 1000) // 100
first = a // 1000
check = guess_the_number(first,second,third,last)
return check
def guess_the_number(first,second,third,last):
i = 0
correct = 0
while(True):
print("Guess the number on his correct position: ")
choice = int(input())
if( i == 0 and choice == first):
correct += 1
elif( i == 1 and choice == second):
correct += 1
elif( i == 2 and choice == third):
correct += 1
elif( i == 3 and choice == last):
correct += 1
if( i == 3 ):
break
i += 1
return correct
while(True):
check = random_operations()
if( check == 0):
print("0 cows, 4 bulls!")
elif( check == 1):
print("1 cows, 3 bulls!")
elif( check == 2 ):
print("2 cows, 2 bulls!")
elif( check == 3):
print("3 cows, 1 bulls!")
else:
print("You guessed correct!")
print("THE END")
break
exit(0)
|
ee4b3d6fbfda39f6fd7403adc7421c451a571cd7 | al-yakubovich/Image-Classification-Model | /cnn.py | 2,935 | 3.609375 | 4 | # Convolutional Neural Network
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# pip install tensorflow
# Installing Keras
# pip install --upgrade keras
# Part 1 - Building the CNN
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
# 32 - N of filters (N features maps)
# input_shape - shape of on input image, order in Tensorflow then in Theano. We use Tensorflow here
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
# image augmentation (privent overfitting): we have only 10k images. It is not enough. Augmentation create many batches. In each batch it will apply random transformations on a random selection of our images like rotating them, flipping them, shifting them, shearing them
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('dataset/training_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('dataset/test_set',
target_size = (64, 64),
batch_size = 32,
class_mode = 'binary')
# 8000 - N of images in test test
classifier.fit_generator(training_set,
steps_per_epoch = 8000,
epochs = 25,
validation_data = test_set,
validation_steps = 2000)
# without second convolutional layer
# train acc: 0.84
# test acc: 0.75
# diff: ~10%
# with second convolutional layer
# train acc: 0.85
# test acc: 0.82
# diff: ~3%
|
b0c8c3bcde4eee0fa11fc404eadfb4758e8323c6 | leticiaglass/projetos-educacionais-python | /praticaC_obstaculo.py | 2,029 | 4.375 | 4 | from math import radians, pi, cos, sin #Importa apenas as funções necessárias para o programa
titulo = "Projétil com Obstáculo 3" #Imprimindo o título e a descrição do programa
print(titulo)
print("Considere o movimento do projétil sem arraste do ar, supondo que trata-se de um jogo de bola dentro de um ginásio cujas paredes não são muito distantes da quadra de jogo. Para simplificar, supõe-se que o projétil é lançado de maneira que a sua direção de movimento horizontal seja perpendicular a uma das paredes.")
# Entrando com os valores
v0 = float(input("Digite um valor para a velocidade inicial do projétil (em m/s): "))
while (v0 < 0): # Impondo as condições
v0 = float(input("A velocidade deve ser positiva. Tente novamente: "))
th = radians(float(input("Digite um valor para o angulo de lançamento (em graus): ")))
while (th < 0 or th > pi / 2):
th = radians(float(input("O valor deve estar entre 0 e 90 graus. Tente novamente: ")))
l = float(input("Digite um valor para a distância até a parede: "))
while (l < 0):
l = float(input("O parede não pode estar atrás de você. Tente novamente: "))
dt = float(input("Digite o intervalo para a discretização do tempo (em segundos): "))
while (dt < 0):
dt = float(input("O intervalo não pode ser negativo. Tente novamente: "))
t = 0.
x0, y0 = (0., 0.) # coordenadas iniciais
print("t (s)\tx (m)\ty (m)") # Imprime os títulos das colunas
while True:
# Calcula as coordenadas no tempo t
x = x0 + v0 * cos(th) * t
y = y0 + v0 * sin(th) * t - 0.5 * 9.8 * t ** 2
# Verifica se não ultrapassou alguma das barreiras (chão ou parede)
if x > l:
print("O projétil atingiu a parede!")
break
if y < 0:
print("O projetil atingiu o chão!")
break
# imprime o tempo e as coordenadas uma vez que as condições (de quebra) não tenham sido satisfeitas
print("{:.3g}\t{:.3g}\t{:.3g}".format(t, x, y))
# incrementa o tempo
t = t + dt
print("end")
|
ea5c81d0b76371d1672e74fe61df35b71f09dff6 | monkeylyf/interviewjam | /sort/hackerrank_Counting_Sort_2.py | 307 | 3.609375 | 4 | """Counting Sort 2
https://www.hackerrank.com/challenges/countingsort2
"""
def main():
"""Calling sorted and that's it?!"""
N = int(raw_input())
arr = map(int, raw_input().split())
arr = sorted(arr)
for i in arr:
print i,
print ''
if __name__ == '__main__':
main()
|
6556200533560ea0afdda95c2f66002eca42db28 | jdavis/college-fall-2013 | /cs311/assignment05/reconstruct.py | 1,051 | 3.703125 | 4 | from collections import deque
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self, depth=0):
ret = ""
# Print right branch
if self.right is not None:
ret += self.right.__str__(depth + 1)
# Print own value
ret += "\n" + (" " * depth) + str(self.value)
# Print left branch
if self.left is not None:
ret += self.left.__str__(depth + 1)
return ret
def reconstruct(t):
s = [x for x in t[::-1]]
return reconstruct_rec(s, '')
def reconstruct_rec(s, p):
root = Node(s.pop())
if len(s) != 0:
if root.value >= s[-1]:
root.left = reconstruct_rec(s, root.value)
if len(s) != 0:
if p >= s[-1] or p == '':
root.right = reconstruct_rec(s, p)
return root
if __name__ == '__main__':
t = ['F', 'B', 'A', 'D', 'C', 'E', 'G', 'I', 'H']
print 'T =', t
print reconstruct(t)
|
f5454cc8f55c97fe56199ea9686e8aca87a58a94 | jzaia18/softdev05 | /utils/occupation.py | 837 | 3.640625 | 4 | import random as r
def takeFile():
data = {}
# File I/O
f = open('data/occupations.csv','r')
csv = f.read()
f.close()
# Fills the dictionary with the info from the csv
L = csv.split('\r\n')
for lines in L[1:]:
stuff = lines.split(',')
data[','.join(stuff[:-1])] = float(stuff[-1])
return data
# Gets a random element from a dictionary assuming values
# are floats that represent probability
def getRandWeighted(data):
# Picks a random number and subtracts probability from it
# until 0 is reached, signifying a pick
tot = r.random() * data['Total']
for each in data:
if each == 'Total':
continue
tot -= data[each]
if tot <= 0:
return each
if __name__ == '__main__':
takeFile()
print data
|
3a8ecffb56af14551332a385ab1a28b942e4e25c | syedarafia13/python | /02_program_01_twinkle_srfn.py | 319 | 3.78125 | 4 | # Author: SYEDA RAFIA FIZZA NAVEED
# Program to print Twinkle Twinkle little star poem in python.
'''
****************************************
'''
print('''Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.''')
'''
*****************************************
'''
|
4e3c9f79ddbfa1fd9ddc58c2d07978488280a859 | luisC62/Master_Python | /09_listas/predefinidas.py | 1,058 | 4.625 | 5 | """
Funciones predefinidas para listas
"""
cantantes = ['Frank Sinatra', 'Peter Gabriel', 'Sting', 'Bob Dylan']
numeros = [1, 2, 5, 8, 3, 4]
#Ordenar
print(numeros)
numeros.sort()
print(numeros)
#Añadir elementos
cantantes.append('Freddy Mercury')
print(cantantes)
#Insertar, en una posición dada
cantantes.insert(3, 'Joao Gilberto') #Inserta destrás de Sting
print(cantantes)
#Eliminar elementos de la lista
cantantes.pop(1)
print(cantantes) #Desaparece Peter Gabriel
cantantes.remove('Frank Sinatra') #El nombre ha de ser idéntico
print(cantantes)
#Dar la vuelta a una lista
numeros.reverse()
print(numeros)
#Buscar dentro de una lista
print('Bob Dylan' in cantantes) #Si se encuentra en la lista, devuelve true
#Contar elementos
print(len(cantantes)) #El mismo método para contar caracteres de un string
#Cuantas veces aparece un elemento en una lista
print(numeros.count(8))
numeros.append(8)
print(numeros.count(8))
print(numeros)
#Conseguir el índice
print(cantantes)
print(cantantes.index("Bob Dylan")) #El índice que tiene Bob Dylan
#Unir listas
cantantes.extend(numeros)
print(cantantes) |
7477e3a9f80ac5bce535e680f52c473f0b699677 | BrittanyClemmons/python-challenge | /PyBank/scipt.py/main.py | 2,347 | 3.9375 | 4 | #IMPORT CSV
import os
import csv
import statistics
csv_path = os.path.join('..','Resources','budget_data.csv')
#READ CSV
with open(csv_path, newline= '') as budget_csv:
csv_reader = csv.reader(budget_csv, delimiter= ',')
#print(csv_reader)
csv_header = next(csv_reader)
#print(f"CSV Header:{csv_header}")
#The total number of months included in the dataset
total_months = 0
date_list = []
profit_loss_list = []
for row in csv_reader:
total_months = total_months + 1
date_list.append(row[0])
profit_loss_list.append(row[1])
#The net total amount of "Profit/Losses" over the entire period
net_total = 0
for i in range(0,len(profit_loss_list)):
net_total = net_total + int(profit_loss_list[i])
#The average of the changes in "Profit/Losses" over the entire period)
difference = []
for i in range(1, len(profit_loss_list)):
y = int(profit_loss_list[i])
x = int(profit_loss_list[i - 1])
difference.append((y - x))
avg_change = round((sum(difference) / len(difference)), 2)
#The greatest increase in profits (date and amount) over the entire period
#The greatest decrease in losses (date and amount) over the entire period
max_change = max(difference)
min_change = min(difference)
#Not sure how to get the date into my list :(
#So I typed it in
#for row in csv_reader:
#if max_change == profit_loss_list[row]:
#print(date_list[row] and profit_loss_list[row])
def financial_analysis():
print(' ')
print("Financial Analysis")
print("---------------------------")
print(f"Total Months: {total_months}")
print(f"Total: ${net_total}")
print(f'Average Change: ${avg_change}')
print(f'Greatest Increase in Profits: Feb-2012 (${max_change})')
print(f'Greatest Decrease in Profits: Sep-2013 (${min_change})')
financial_analysis()
output_path = os.path.join('..', 'output', 'new.csv')
with open(output_path, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerow(['Financial Analysis','Total Months','Net Total','Average Change','Greatest Increase in Profits','Greatest Decrease in Profits'])
csvwriter.writerow(['------------------','86','$38382578','$-2315.12','Feb-2012 ($1926159)','Sep-2013 ($-2196167)'])
|
012f7794ac3e6944b6c521f6f0276fd69e6885b9 | magda-zielinska/python-level1 | /numbers.py | 410 | 3.984375 | 4 | max = -9999999
counter = 0
number = int(input("Enter value o -1 to stop: "))
while number != -1:
if number == -1:
continue
counter +=15
if number > max:
max = number
number = int(input("Enter value or -1 to stop: "))
if counter:
print("The largest number is" ,max)
else:
print("Are you kidding? You haven´t put any number!")
# or break in the place of continue |
2164fea7493c1c71b6f1d8ebab65b244fc19860c | 0x01DA/tenable | /short_n_sweet.py | 302 | 3.8125 | 4 | def AreNumbersEven(numbers):
bool_list = []
for n in numbers:
bool_list.append(((n % 2) == 0))
return bool_list
# numbers = raw_input()
numbers = "66 0 -47"
integer_list = [int(i) for i in numbers.split(' ')]
even_odd_boolean_list = AreNumbersEven(integer_list)
print(even_odd_boolean_list)
|
165138393890256df4a7399a3c99f7eebed98665 | tonydavidx/Python-Crash-Course | /chapter7/cities.py | 239 | 3.8125 | 4 | prompt =("Enter the name of the cities you have visited: ")
prompt += "\nEnter quite when you are done"
while True:
city =input(prompt)
if city == 'quit':
break
else:
print("i love to go to "+city.title()) |
72ac1597d8006e7d1f8f35762b3d13d08a2f4f50 | wejhhv/AI_webAPI | /request.py | 708 | 3.59375 | 4 | ###簡易チャットボットの作成
import requests
import json
print("チャットボットを開始します\nbyeと発言すれば終了します\nまた空白でサーバーとの通信を確認します")
# webAPIのURL
#url="http://127.0.0.1:5000/hello/"
url="https://ganosu.herokuapp.com/"
word=input("you>>>>>>")
# 終了までループ
while word!="bye":
#webAPIに入力した言葉を引き渡す
r=requests.get(url+word.encode("utf-8"))
# データはjson形式ではいる
data = r.json()
# 未学習かどうかの判定
print("bot>>>>>"+data)
# ユーザの表示
word=input("you>>>>>>")
print("チャットボットを終了しました")
|
f7267beec24db16b01e176be0c0e657ab63b96a5 | architsangal/Python_Assignments | /a4/Q4a.py | 806 | 3.90625 | 4 | def diamond():
n=5 # we know that 5 is odd
# dividing pattern in 6 parts(take " " as "_") ==>
#
# 1) _ _ _ 2) 1 3)
# _ _ 12 1
# _ 123 12
#
# 4) _ 5) 12 6) 1
# _ _ 1
#
# for first (n+1)/2 rows
i=0
while(i<(n+1)/2):
# for pattern 1)
j=i
while(j<=(n-1)/2):
print " \b",
j+=1
# for pattern 2)
j=1
while(j<=i+1):
print("\b"+str(j)),
j+=1
# for pattern 3)
j=i
while(j>=1):
print("\b"+str(j)),
j-=1
print
i+=1
# for last (n-1)/2 rows
i=0
while(i<(n-1)/2):
# for pattern 4)
j=0
while(j<(1+i)):
print("\b "),
j+=1
# for pattern 5)
j=(n-1)/2-i-1
c=0
while(j>=0):
c+=1
print("\b"+str(c)),
j-=1
# for pattern 6)
j=(n-1)/2-i-1
while(j>0):
c-=1
print("\b"+str(c)),
j-=1
print
i+=1
|
e9898112906ae48429d62eec924e6c25c016c6cc | xmig/i18nprocessor | /app/sysutils/timeutils.py | 881 | 3.828125 | 4 | """
Set of utils for time manipulation
"""
from datetime import datetime, timezone, timedelta
import time
_default_format_datetime = '%Y-%m-%d %H:%M:%S'
def time_as_string(time_val=None, time_fmt=None):
""" Returns time in form 'YYYY-MM-DD hh:mm:ss'
:param timeval: datetime
:param time_fmt: str @example '%Y-%m-%d %H:%M:%S'
"""
time_val = time_val or datetime.now()
time_fmt = time_fmt or _default_format_datetime
assert(issubclass(type(time_val), datetime))
return time_val.strftime(time_fmt)
def timestamp(future_seconds=0):
return time.time() + int(future_seconds)
def hour_subtract(same_date, hours):
return same_date - timedelta(hours=hours)
def date_time_now():
local_timezone = datetime.now(timezone.utc).astimezone(timezone.utc).tzinfo
date_time_now = datetime.now(local_timezone.utc)
return date_time_now
|
a6394543839ec157d8f6f9fc72e78d7db57fd736 | usman-tahir/rubyeuler | /trial_division.py | 237 | 3.890625 | 4 | #!/usr/bin/env python
# http://rosettacode.org/wiki/Primality_by_trial_division
def is_prime(n):
for i in xrange(3,n,2):
if n % i == 0:
return False
return True
print(is_prime(37))
print(is_prime(38))
print(is_prime(39))
|
18ec7e6c828008cf950e27c4176833f4ec0648b6 | nadvornix/python-fizzle | /fizzle.py | 6,418 | 3.515625 | 4 | #-*- encoding: utf-8 -*-
'''TODO:
'''
def dl_distance(s1,
s2,
substitutions=[],
symetric=True,
returnMatrix=False,
printMatrix=False,
nonMatchingEnds=False,
transposition=True,
secondHalfDiscount=False):
"""
Return DL distance between s1 and s2. Default cost of substitution, insertion, deletion and transposition is 1
substitutions is list of tuples of characters (what, substituted by what, cost),
maximal value of substitution is 2 (ie: cost deletion & insertion that would be otherwise used)
eg: substitutions=[('a','e',0.4),('i','y',0.3)]
symetric=True mean that cost of substituting A with B is same as B with A
returnMatrix=True: the matrix of distances will be returned, if returnMatrix==False, then only distance will be returned
printMatrix==True: matrix of distances will be printed
transposition=True (default): cost of transposition is 1. transposition=False: cost of transpositin is Infinity
"""
if not isinstance(s1, unicode):
s1 = unicode(s1, "utf8")
if not isinstance(s2, unicode):
s2 = unicode(s2, "utf8")
subs = defaultdict(lambda: 1) #default cost of substitution is 1
for a, b, v in substitutions:
subs[(a, b)] = v
if symetric:
subs[(b, a)] = v
if nonMatchingEnds:
matrix = [[j for j in range(len(s2) + 1)] for i in range(len(s1) + 1)]
else: #start and end are aligned
matrix = [[i + j for j in range(len(s2) + 1)]
for i in range(len(s1) + 1)]
#matrix |s1|+1 x |s2|+1 big. Only values at border matter
half1 = len(s1) / 2
half2 = len(s2) / 2
for i in range(len(s1)):
for j in range(len(s2)):
ch1, ch2 = s1[i], s2[j]
if ch1 == ch2:
cost = 0
else:
cost = subs[(ch1, ch2)]
if secondHalfDiscount and (s1 > half1 or s2 > half2):
deletionCost, insertionCost = 0.6, 0.6
else:
deletionCost, insertionCost = 1, 1
matrix[i + 1][j + 1] = min([
matrix[i][j + 1] + deletionCost, #deletion
matrix[i + 1][j] + insertionCost, #insertion
matrix[i][j] + cost #substitution or no change
])
if transposition and i >= 1 and j >= 1 and s1[i] == s2[j -
1] and s1[i
-
1] == s2[j]:
matrix[i + 1][j + 1] = min(
[matrix[i + 1][j + 1], matrix[i - 1][j - 1] + cost])
if printMatrix:
print " ",
for i in s2:
print i, "",
print
for i, r in enumerate(matrix):
if i == 0:
print " ", r
else:
print s1[i - 1], r
if returnMatrix:
return matrix
else:
return matrix[-1][-1]
def dl_ratio(s1, s2, **kw):
'returns distance between s1&s2 as number between [0..1] where 1 is total match and 0 is no match'
try:
return 1 - (dl_distance(s1, s2, **kw)) / (2.0 * max(len(s1), len(s2)))
except ZeroDivisionError:
return 0.0
def match_list(s, l, **kw):
'''
returns list of elements of l with each element having assigned distance from s
'''
return map(lambda x: (dl_distance(s, x, **kw), x), l)
def pick_N(s, l, num=3, **kw):
''' picks top N strings from options best matching with s
- if num is set then returns top num results instead of default three
'''
return sorted(match_list(s, l, **kw))[:num]
def pick_one(s, l, **kw):
try:
return pick_N(s, l, 1, **kw)[0]
except IndexError:
return None
def substring_match(text, s, transposition=True,
**kw): #TODO: isn't backtracking too greedy?
"""
fuzzy substring searching for text in s
"""
for k in ("nonMatchingEnds", "returnMatrix"):
if kw.has_key(k):
del kw[k]
matrix = dl_distance(
s, text, returnMatrix=True, nonMatchingEnds=True, **kw)
minimum = float('inf')
minimumI = 0
for i, row in enumerate(matrix):
if row[-1] < minimum:
minimum = row[-1]
minimumI = i
x = len(matrix[0]) - 1
y = minimumI
#backtrack:
while x > 0:
locmin = min(matrix[y][x - 1], matrix[y - 1][x - 1], matrix[y - 1][x])
if matrix[y - 1][x - 1] == locmin:
y, x = y - 1, x - 1
elif matrix[y - 1][x] == locmin:
y = y - 1
elif matrix[y][x - 1] == locmin:
x = x - 1
return minimum, (y, minimumI)
def substring_score(s, text, **kw):
return substring_match(s, text, **kw)[0]
def substring_position(s, text, **kw):
return substring_match(s, text, **kw)[1]
def substring_search(s, text, **kw):
score, (start, end) = substring_match(s, text, **kw)
# print score, (start, end)
return text[start:end]
def match_substrings(s, l, score=False, **kw):
'returns list of elements of l with each element having assigned distance from s'
return map(lambda x: (substring_score(x, s, **kw), x), l)
def pick_N_substrings(s, l, num=3, **kw):
''' picks top N substrings from options best matching with s
- if num is set then returns top num results instead of default three
'''
return sorted(match_substrings(s, l, **kw))[:num]
def pick_one_substring(s, l, **kw):
try:
return pick_N_substrings(s, l, 1, **kw)[0]
except IndexError:
return None
if __name__ == "__main__":
#examples:
commonErrors = [('a', 'e', 0.4), ('i', 'y', 0.3), ('m', 'n', 0.5)]
misspellings = [
"Levenshtain", "Levenstein", "Levinstein", "Levistein", "Levemshtein"
]
print dl_distance('dayme', 'dayne', substitutions=commonErrors)
print dl_ratio("Levenshtein", "Levenshtein")
print match_list("Levenshtein", misspellings, substitutions=commonErrors)
print pick_N("Levenshtein", misspellings, 2, substitutions=commonErrors)
print pick_one("Levenshtein", misspellings, substitutions=commonErrors)
print substring_search(
"aaaabcegf", "qqqqq aaaaWWbcdefg qqqq", printMatrix=True)
|
cb1a10ae89d0148a1fc7b176a99ae972c8beb92f | pAkalpa/TkinterBasics | /Basic Widgets/12.Geometry.py | 630 | 3.734375 | 4 | from tkinter import *
root = Tk()
titl = Label(root,text='Place Geometry Manager',font=(('Verdana'),15))
un_txt = Label(root,text='Name :')
pw_txt = Label(root,text='Password :')
un_ent = Entry(root,width=30)
pw_ent = Entry(root,width=30)
btn1 = Button(root,text='Save')
btn2 = Button(root,text='Click Me',bg='red')
titl.place(x=100,y=20)
un_txt.place(x=20,y=80)
pw_txt.place(x=20,y=110)
un_ent.place(x=100,y=80)
pw_ent.place(x=100,y=110)
btn1.place(x=250,y=140)
btn2.place(relx=0.5,rely=0.5,anchor='center')
root.geometry('450x450+650+350')#650+350 means location of window in main screen
root.mainloop() |
ec97f830c3f2897bcbc4df4f05a20a7e32210882 | coocos/advent-of-code-2018 | /day5.py | 1,626 | 4 | 4 | import string
import re
import os
from typing import List, Tuple
def trigger_reactions(polymer: str) -> str:
"""
Triggers the polymer reactions and returns the polymer with all the
reactions applied.
The algorithm works by iterating through the polymer and comparing the
current unit against the next unit. If the next unit is the same as
the current one but differ in capitalization then they are removed from
the string and the algorithm starts again but this time one unit earlier
than the current position.
"""
i = 0
while i < len(polymer) - 1:
if polymer[i].lower() == polymer[i + 1].lower():
if ((polymer[i].isupper() and polymer[i + 1].islower()) or
(polymer[i].islower() and polymer[i + 1].isupper())):
polymer = polymer[:i] + polymer[i + 2:]
i -= 1
continue
i += 1
return polymer
if __name__ == '__main__':
with open(os.path.join('inputs', 'day5.in')) as f:
complex_polymer = f.read()
# Solve first half of the puzzle - the -1 is due to newline
assert len(trigger_reactions(complex_polymer)) - 1 == 11814
# Solve second half of the puzzle by removing units alphabetically
# and finding the smallest polymer after reactions have been applied
polymers: List[Tuple[str, int]] = []
for char in string.ascii_lowercase:
polymer = re.sub(f'[{char}{char.upper()}]', '', complex_polymer)
polymers.append((char, len(trigger_reactions(polymer)) - 1))
assert min(polymers, key=lambda x: x[1]) == ('g', 4282)
|
03c4c73deebe0f79b2f908f016752e1f58cf41d1 | Gaju27/session12 | /Calculator/scientific_funcs/relu_call.py | 710 | 3.625 | 4 | from Calculator.decorator import fstring_print
__all__ = ['relu_']
@fstring_print
def relu_(value):
"""
:param value: input list of value for the calculation for relu
:return: return relu value which is 0 to value
"""
if not isinstance(value, (int, float)):
raise (ValueError, 'Make sure value must be int,float')
return 1 if value > 0 else 0
@fstring_print
def relu_d(value):
"""
:param value: input value for the derivative calculation for relu
:return: return the derivative of relu
"""
if not isinstance(value, (int, float)):
raise (ValueError, 'Make sure value must be int,float')
return 0 if value > 0 else 0
|
595807340d0661e7f6576c768819ba85433bb1a8 | pmantica1/geoencoder | /geoencoder/location.py | 929 | 3.671875 | 4 | class Location():
def __init__(self, bottom, top, left, right):
# Range for latitude is [-90, 90 ) and [-180, 180 )
assert top >= bottom, "Expected no latitude wrap around (top<bottom)"
assert 90 >= bottom >= -90, "Bottom out of range"
assert 90 >= top >= -90, "Top out of range"
assert 180 >= left >= -180, "Left out of range"
assert 180 >= right >= -180, "Right out of range"
self.bottom = bottom;
self.left = left;
self.top = top;
self.right = right;
def __eq__(self, other):
matching_lat_boxes = self.bottom == other.bottom and self.top == other.top
matching_long_boxes = self.left == other.left and self.right == other.right
return matching_long_boxes and matching_lat_boxes
def __str__(self):
return "bottom: %s | top: | %s | left: %s | right: %s" % (self.bottom, self.top, self.left, self.right)
|
bfaaeae4291707eea20d9c34e25fe9b1efafef8f | fastnlp/fitlog | /fitlog/fastlog/utils.py | 575 | 3.5 | 4 |
def flatten_dict(prefix, _dict, connector='-'):
"""
给定一个dict, 将其展平,比如{"a":{"v": 1}} -> {"a-v":1}
:param prefix:
:param _dict:
:param connector:
:return:
"""
new_dict = {}
for key, value in _dict.items():
if prefix != '':
new_prefix = prefix + connector + str(key)
else:
new_prefix = str(key)
if isinstance(value, dict):
new_dict.update(flatten_dict(new_prefix, value, connector))
else:
new_dict[new_prefix] = value
return new_dict |
862b78ae28e4a9f6c3829595a20f26b63edced70 | themoah/exercism-python | /leap/leap.py | 163 | 3.828125 | 4 | def is_leap_year(year):
if (year % 4 == 0):
if(year % 400 == 0): return True
elif(year % 100 == 0): return False
else: return True
else: return False
|
1b444d44481f83626c745557a7a88a1f85d3a206 | pruthvirajg/Python-for-everybody | /2_Python Data Structures/Assignment 10.2 - Tuples/Answer_Assignment_10_2.py | 1,812 | 3.875 | 4 | """
#**********************************************************************************************************
# Name : Assignment_10_2
# Author : Pruthvi Raj G :: (www.prudhvy.com )
# Version : Version 1.0
# Description : Answer for Assignment_10_2.
# Input : mbox-short.txt
# Date : 23-May-2021
#************************************************************************************************************
Question below:
10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages.
You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
"""
# Answer
name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
dixnary = dict()
for gline in handle:
if gline.find('From') == -1: continue
Split_lines = gline.split()
if len(Split_lines)<3: continue # Removing the From: mailid@univ.edu
count_idx = 0
for Time in Split_lines:
if not(count_idx == 5): # Taking the Time index - ['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008']
count_idx = count_idx +1
continue
else:
count_idx = count_idx +1
# Add the Hours to the dictionary and bring out the count for each Hour
Hour = Time[0:2]
if Hour not in dixnary:
dixnary[Hour] = 1
else:
dixnary[Hour] += 1
Sorted_list = sorted((k,v) for (k,v) in dixnary.items())
for printz_k,printz_v in Sorted_list:
print(printz_k , printz_v) |
e0c20cf36f284915706aaa2576a0f00346eefc5f | uri-ai-lab/ai-lab-book | /_build/jupyter_execute/lessons/lesson4.py | 4,931 | 4.03125 | 4 | [](http://www.youtube.com/watch?v=lm7pT90TsxY "Lesson 4")
## Using APIs
In this lesson, we will use Yahoo Finance's API to download stock data and insert it into our investment tracking database, upon which we can do additional calculations.
The only table in the database that we are concerned with for this lesson is the _stock_ table. However, there are many more tables to play around with, allowing for more complex programs and queries. For a more detailed overview of the database, watch the video embedded below.
### Stock table: Schema
Below is an overview of the schema of the stock table.
Note: The database is updated often, so it is possible this schema is out of date. You can check the current schema by running the _.schema table_ command in sqlite3.
Stock:
* **ticker** varchar(5)
* The stock's ticker symbol, as listed on the stock exchange. Up to 5 characters.
* **mkt**\_**date** varchar(10)
* Date in YYYY-MM-DD format.
* **open** float(16)
* Price per share at market open.
* **high** float(16)
* Highest price during trading hours.
* **low** float(16)
* Lowest price during trading hours.
* **close** float(16)
* Price per share at market close.
* **adj**\_**close** float(16)
* The stock's adjusted closing price, factoring in other actions after close. Considered to be more accurate.
* **volume** int
* Number of shares traded during trading hours.
The primary key of this table is (mkt\_date, ticker).
### Importing libraries
First of all, we have to import all of the necessary libraries. We will be using pandas, pandas datareader, datetime, yfinance, and sqlite3.
Then, as usual, we connect to the database using sqlite3.
from pandas_datareader import data as pdr
from datetime import datetime, date, timedelta
import yfinance as yf
yf.pdr_override() # overrides yfinance to expect pandas datareader
import pandas as pd
import sqlite3
con = sqlite3.connect("../data/invest_tracker.db")
cur = con.cursor()
### Calling the API
Now, we will build a simple function to download today's stock market prices from the given ticker. Thankfully, YFinance does all of the hard work for us, so weonly need to make a single API call.
The get\_data\_yahoo call on pandas datareader automatically queries the API, downloads data on the given ticker and date range, and writes it to a dataframe. Since we are only querying a single day, the returned dataframe will only contain a single row.
today = date.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
def getData(ticker):
print("Fetching ", ticker)
data = pdr.get_data_yahoo(ticker, start=yesterday, end=tomorrow)
return data
### Read and write data
All that is left to do now is pick a list of stock tickers, and use the function we just built to download the data. Once we have done that, we can prepare the data to be inserted into the database via SQL queries.
Let's break down each line of the for loop below, to better understand exactly what is going on.
For each ticker in the ticker list:
* Call the API to download data into dataframe
* Reset the index of the dataframe, so it is not indexed by the date
* Set the dataframe's column names and in the correct order
* Insert a column for the ticker at index 1
* Prepare SQL insertion command
* Get the single row of data
* Convert the date into proper format
* Execute the SQL command, making sure to give the proper datatype to each column
ticker_list = ['AAPL', 'GOOGL', 'FB', 'MSFT']
for tik in ticker_list:
tik_data = getData(tik)
tik_data.reset_index(inplace=True)
tik_data.columns = ['mkt_date', 'open', 'high', 'low', 'close', 'adj_close', 'volume']
tik_data.insert(1, 'ticker', tik)
tik_data.set_index('ticker')
sql = "INSERT or IGNORE INTO stock (mkt_date, ticker, open, high, low, close, adj_close, volume) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
row = tik_data.iloc[0]
print(row)
date_stripped = row.mkt_date.date()
cur.execute(sql, (str(date_stripped), str(row.ticker), float(row.open), float(row.high), float(row.low), float(row.close), float(row.adj_close), int(row.volume)))
con.commit()
con.close()
And with those few lines of code, we now have up-to-date stock market data on any ticker we want in our database. We could expand upon this code to download as many days, weeks, or months of data as we wish, and could perform all sorts of different plots, graphs, or calculations.
For a more comprehensive example on how this data can be used to track personal investments, see the advanced version of the stock API code found in the [extra content](https://github.com/uri-ai-lab/ai-lab-book) folder.
The YFinance module is also capable of a lot more. For full documentation on its uses, you can find the [code on GitHub](https://github.com/ranaroussi/yfinance). |
37afb981f033939f8d1302f0a3937de6e54b50a8 | Maus360/TiiT_reminder | /text_tiit.py | 3,187 | 3.8125 | 4 | import pickle
with open("number.pickle", "wb") as f:
pickle.dump(0, f)
with open("number.pickle", "rb") as f:
number = pickle.load(f)
print(number)
def text():
with open("number.pickle", "rb") as f:
number = pickle.load(f)
a = ("Беги, Форест, беги!!!",
"Случается, что бегство – оптимальная ответная реакция.",
"Бэнг, бэнг, бэнг, бэнг.",
"А ЯЯЯ лабы точно сдал???",
"Родина вам этого не забудет)",
"Дорогие первокурсники, вместо того, чтобы сидеть и пялиться в списки сдавших или не сдавших долги по ТИИТ, шли бы вы учиться!!",
"И если кто не понял ещё, что надо учить и разбираться, чтобы успешно допуститься к зачету, а затем его сдать, то я вам сочувствую.",
"Вам только осталось не буйствовать и учиться)",
"Так, господа, забираем документы, не задерживаем очередь!",
"Здравствуй, небо в облаках,\nЗдравствуй, юность в сапогах!\nПропади, моя тоска,\nВот он я, привет, войска!",
"А это точно не больно?",
"Это мой первый раз - поаккуратнее там.",
"Ща буит миасо))00",
"Ну вы держитесь там👊👊👊",
"Мы имеем дело с особой формой разума.",
"Я весь год готовился к зачету, но когда увидел вопросы, все знания тут же таинственным образом исчезли.",
"Тюрьма не хуй, сиди кайфуй.",
"Да ты успокойся!!",
"Да че ты очкуешь? Я так 100 раз делал…",
"Сложна, сложна не понимаю блять.",
"Кчауу",
"Слишком сложно - дасвидания…",
"Я головой то понимаю…",
"только ртом сказать не могу…",
"Мало кто поймет, но кто поймет, тот мало кто.",
"Цікай з городу, тобі пізда.",
"Щас бы в армию.",
"Когда снежок говорит, что он реальный ниггер.",
"Prepare your anus.",
"Если не читали конспект, то прочтите хоть это(http://www.piluli.ru/product/Vazelin)",
"Ваши знания должны быть так же глубоки, как и мой банан")
num = number
number += 1
with open("number.pickle", "wb") as file:
pickle.dump(number, file)
return a[num]
def text_final():
return "Давайте не будем забывать, что это не все, ведь впереди еще ФИЛОСОФИЯ❤❤❤"
|
b5f7eea126334db914c65616dab9a1f9eb07f29e | jacobhanshaw/ProjectEuler | /euler2.py | 810 | 3.765625 | 4 | import timeit
def method0(maxVal):
result = 0
term0 = 1
term1 = 1
while term1 <= maxVal:
if term1 % 2 == 0:
result += term1
term1 += term0
term0 = term1 - term0
return result
def method1(maxVal):
a = 2
b = 8
c = 34
result = a+b
while c <= maxVal:
result += c
a = b
b = c
c = 4 * b + a
return result
execs = 100000
maxVal = 4000000
tm0 = timeit.Timer("method0("+str(maxVal)+")",setup="from __main__ import method0")
tm1 = timeit.Timer("method1("+str(maxVal)+")",setup="from __main__ import method1")
print "Result:",method0(maxVal)
print "Method 0:",min(tm0.repeat(number=execs))/execs
print "Result:",method1(maxVal)
print "Method 1:",min(tm1.repeat(number=execs))/execs
|
cced843a71811bd2e2ec8dd84ba551e42db1e3cf | ShubhamVerma1/Deep-Learning-Course | /Generate Multidimension output/Regression.py | 1,092 | 3.609375 | 4 | import numpy as np
import pandas as pd
from sklearn import linear_model
x = np.random.normal(size = 50000) # generate 50000 numbers from normal distribution
Generated = x[x >= 0] # delete negatives
X_columns = list(range(0,10)) # X dimension to be 10
y_columns = list(range(0,100)) # y dimension to be 100
X = pd.DataFrame(columns = X_columns) # created X with 10 coulmns
y = pd.DataFrame(columns = y_columns) # created y with 100 coulumns
#In this part in feeding data
for i in range(1000):
X.loc[i] = np.random.choice(Generated, 10) #generating only 10 as our X columns are 10
y.loc[i] = np.random.choice(Generated, 100) #generating only 100 as our y columns are 100
#print(y.head(1))
#training part
clf = linear_model.LinearRegression()
clf.fit(X, y)
X_test = pd.DataFrame(columns = X_columns)
X_test.loc[0] = np.random.choice(Generated, 10)
#predicting
w = (clf.predict(X_test.iloc[[0]]))
w = w.reshape((10,10))
print(w)
"""
from matplotlib import pyplot as plt
plt.imshow(w, interpolation='nearest')
plt.show()
""" |
176413c77027d8e671c00344fa216e578829b7e1 | Arno98/Python-3-Basics | /Chapter 7 (Classes)/class_for_import_3.py | 441 | 3.890625 | 4 | class Restaurant():
def __init__(self, restaurant_name, restaurant_adress):
self.restaurant_name = restaurant_name
self.restaurant_adress = restaurant_adress
def show_information(self):
print("My restaurant is " + "'" + self.restaurant_name + "'.")
print("My restaurant is situated on this adress: " + self.restaurant_adress)
restaurant = Restaurant("Place", "Oliver Cromvell, st, 27-a")
restaurant.show_information()
|
df4486402b487e036a6ec5444a98a52721c5699f | grigor-stoyanov/PythonOOP | /design_pattern/abstract_factory.py | 1,699 | 3.9375 | 4 | from abc import ABC, abstractmethod
class Chair:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class Table:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class Sofa:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class AbstractFactory(ABC):
@abstractmethod
def create_chair(self):
pass
@abstractmethod
def create_table(self):
pass
@abstractmethod
def create_sofa(self):
pass
class VictorianFactory(AbstractFactory):
def create_chair(self):
return Chair('victorian Chair')
def create_table(self):
return Table('victorian Table')
def create_sofa(self):
return Sofa('victorian sofa')
class ArtFactory(AbstractFactory):
def create_chair(self):
return Chair('art Chair')
def create_table(self):
return Table('art Table')
def create_sofa(self):
return Sofa('art sofa')
class ModernFactory(AbstractFactory):
def create_chair(self):
return Chair('modern Chair')
def create_table(self):
return Table('modern Table')
def create_sofa(self):
return Sofa('modern sofa')
def get_factory(style):
if style == 'victorian':
return VictorianFactory()
elif style == 'Art':
return ArtFactory()
elif style == 'modern':
return ModernFactory()
# allows easier extensibility without changing client code
if __name__ == '__main__':
client_style = input()
factory = get_factory(client_style)
print(factory.create_chair())
|
4419329d44a49548e657ecb9e6eb9520103fca96 | UWPCE-PythonCert-ClassRepos/Wi2018-Online | /students/shayna_andersonhill/lesson02/series.py | 1,837 | 4.3125 | 4 | #!/usr/bin/python3
#Shayna Anderson-Hill
#Script to write compute the fibonacci and lucas series
#01-24-2018
#The Fibonacci Series starts with the integers 0 and 1.
#The next integer is determined by summing the previous two.
def fibonacci(n):
"""Return the nth value in the Fibonacci Series."""
n = n-2
fib_list = [0, 1]
for i in range(1,n+1):
fib_list.append(fib_list[(i-1)] + fib_list[i])
return fib_list[n+1]
#The Lucas Numbers are a related series that
#start with the integers 2 and 1.
def lucas(n):
"""Return the nth value in the Lucas Numbers."""
n = n-2
lucas_list = [2, 1]
for i in range(1,n+1):
lucas_list.append(lucas_list[(i-1)] + lucas_list[i])
return lucas_list[n+1]
def sum_series(n, first_value=0, second_value=1):
"""Return the nth value in the series."""
n = n-2
gen_list = [first_value, second_value]
for i in range(1,n+1):
gen_list.append(gen_list[(i-1)] + gen_list[i])
return gen_list[n+1]
#Test that the 8th value in the Fibonacci Series is 13
#[0, 1, 1, 2, 3, 5, 8, 13]
assert fibonacci(8) == 13
#Test that the 8th value in the Lucas Numbers is 29
#[2, 1, 3, 4, 7, 11, 18, 29]
assert lucas(8) == 29
#Test that calling the sum_series function with no optional parameters
#produces the Fibonacci Series
assert sum_series(7) == fibonacci(7)
#Test that calling the sum_series function with the optional arguments
#integers 2 and 1 will produce values from the Lucas Numbers
assert sum_series(6, first_value=2, second_value=1) == lucas(6)
#Test that the 8th value in the generalized series
#is generated by starting the series with the first and second value
#and that the next integer is determined by summing the previous two.
assert sum_series(8, first_value=-1, second_value=0) == -8
#[-1, 0, -1, -1, -2, -3, -5, -8]
|
bb98b5cb83d44e295e3f98532203899e9c3c034b | LuLStackCoder/My-Python-Library | /structures/Deque.py | 2,753 | 3.671875 | 4 | from .AbstractLinkedList import AbstractLinkedList
from .Node import DoubleNode
class Deque(AbstractLinkedList):
"""
Implementation of an Deque.
"""
def __init__(self, iterable=None) -> None:
super().__init__()
if iterable != None:
for i in iterable:
self.append(i)
def append(self, item) -> object:
"""
Add an element to the tail.
"""
new_node = DoubleNode(item, None, self._tail)
if (self.empty()):
self._head = new_node
self._tail = self._head
else:
self._tail.next = new_node
self._tail = new_node
self._size += 1
return self
def prepend(self, item) -> object:
"""
Add an element to the head.
"""
new_node = DoubleNode(item, self._head, None)
if (self.empty()):
self._head = new_node
self._tail = self._head
else:
self._head.prev = new_node
self._head = new_node
self._size += 1
return self
def shift(self):
"""
Remove an element from the head.
"""
if self.empty():
raise IndexError(f"{self.__class__.__name__} empty")
item = self._head.item
if self._head is self._tail:
del self._head
self._head = None
self._tail = None
else:
temp_node = self._head.next
del self._head
self._head = temp_node
self._head.prev = None
self._size -= 1
return item
def pop(self):
"""
Remove an element from the tail.
"""
if self.empty():
raise IndexError(f"{self.__class__.__name__} empty")
item = self._tail.item
if self._head is self._tail:
del self._tail
self._head = None
self._tail = None
else:
temp_node = self._tail.prev
del self._tail
self._tail = temp_node
self._tail.next = None
self._size -= 1
return item
def front(self):
"""
Get a head item.
"""
if not self.empty():
return self._head.item
else:
raise IndexError(f"{self.__class__.__name__} empty")
def back(self):
"""
Get a tail item.
"""
if not self.empty():
return self._tail.item
else:
raise IndexError(f"{self.__class__.__name__} empty")
def clear(self) -> None:
"""
Remove all elements from the list.
"""
while not self.empty():
self.pop()
|
fd97f9ebdf35548a79b810c704e9b179e01f5ea9 | jdanray/leetcode | /colorBorder.py | 566 | 3.796875 | 4 | # https://leetcode.com/problems/coloring-a-border/
class Solution(object):
def colorBorder(self, grid, r0, c0, color):
ogcolor = grid[r0][c0]
stack = [(r0, c0)]
seen = set()
border = set()
while stack:
r, c = stack.pop()
for dr, dc in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
if dr < 0 or dr >= len(grid) or dc < 0 or dc >= len(grid[0]) or grid[dr][dc] != ogcolor:
border.add((r, c))
elif (dr, dc) not in seen:
stack.append((dr, dc))
seen.add((dr, dc))
for (r, c) in border:
grid[r][c] = color
return grid
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.