blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9e68c223a3b471d53635750fc17308ea1153b0b4 | skonienczwy/LearningPython | /ex0088.py | 1,250 | 3.703125 | 4 | from colorama import Fore, Back, Style
print('##Exercicio 88##')
def leiaInt(num):
while True:
try:
t = int(input(num))
return t
except ValueError as erro:
print(f'O Erro for causado por {erro.__class__}')
print(Fore.RED + 'ERRO! Digite um número Inteiro válido:')
print(Style.RESET_ALL)
except EOFError as erro:
print(Fore.RED + f'Não há dados inseridos pelo usuário, Erro foi identificado como: {erro.__class__}')
exit()
def leiaFloat(num):
while True:
try:
t = float(input(num))
return t
except ValueError as erro:
print(f'O Erro for causado por {erro.__class__}')
print(Fore.RED + 'ERRO! Digite um número Real válido:')
print(Style.RESET_ALL)
except EOFError as erro:
print(Fore.RED + f'Não há dados inseridos pelo usuário, Erro foi identificado como: {erro.__class__}')
print(Style.RESET_ALL)
exit()
n = leiaInt('Digite Um numero Inteiro: ')
n2 = leiaFloat('Digite Um numero Real: ')
print(f'Você digitou o número inteiro {n} e o número real {n2} ')
|
dcc72e7be254ac428bf959dc971d2779b142f458 | odoommk/PythonAcademy | /Unit5_Lists And Dictionaries/lesson3.py | 496 | 4.125 | 4 | zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked
#the poor tiger and ate it whole.
# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"
# What shall fill the void left by our dear departed tiger?
# Your code here!
zoo_animals[3] = "cheetah"
#Write an assignment statement that will replace the item that currently holds the value "tiger" with another animal (as a string). It can be any animal you like.
|
2097031a0f6124b66d23246f533411c8ce52704a | thisolivier/amazing_fish | /deck.py | 870 | 3.8125 | 4 | from random import shuffle
class Deck(object):
def __init__(self):
self.size=52
self.cards=[]
self.suits=["hearts","clubs","dimonds","spades"]
self.build()
self.shuffle()
def __repr__(self):
for card in self.cards:
print card
def build(self):
cards_in_suit=(self.size/len(self.suits))
for x in range(0,len(self.suits)):
for i in range(1,cards_in_suit+1):
self.cards.append(Card(i,self.suits[x]))
return self
def shuffle(self):
shuffle(self.cards)
print "shuffle is working!"
return self
class Card(object):
def __init__(self,value,suit):
self.suit=suit
self.value=value
def __repr__(self):
return "<Card val {} suit {}>".format(self.value, self.suit) |
dd6e8abd563d9b9165f264592da2e1006f694e6a | aidanrfoster/abe487 | /problems/hello-py/hello.py | 502 | 3.9375 | 4 | #!/usr/bin/env python3
import sys
import os
if len(sys.argv) <2:
print('Usage:', sys.argv[0], 'NAME [NAME2 ...]')
sys.exit(1)
elif len(sys.argv) ==2:
print('Hello to the', len(sys.argv[1:]),'of you:','{}!'.format(sys.argv[1]))
elif len(sys.argv) ==3:
print('Hello to the {} of you: {} and {}!' .format(len(sys.argv[1:]), sys.argv[1], sys.argv[2]))
elif len(sys.argv) >=3:
print('Hello to the {} of you: {}, and {}!' .format(len(sys.argv[1:]), ', '.join(sys.argv[1:-1]), sys.argv[-1]))
|
d4fe33eaaf22d707f284edf3b6808efd49cc740a | Exodus111/Infinite-Adventure | /Engine.py | 4,315 | 3.5625 | 4 | """
2.0
A Pygame Engine.
Can be used to run any Tile based 2d Pygame game.
"""
import os, sys
import pygame, vec2d
from pygame.locals import *
from vec2d import vec2d
class Engine(object):
"""The mainloop class for a Pygame"""
def __init__(self, name, size=(640,480), mouseset=True):
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
pygame.mouse.set_visible(mouseset)
self.screen = pygame.display.set_mode(size)
self.clock = pygame.time.Clock()
self.name = name
self.running = True
self.dt = 0.0
def main_loop(self, fps=0):
while self.running:
pygame.display.set_caption("{} FPS: {}".format(self.name, int(self.clock.get_fps())))
self.event_handler()
self.update()
self.draw()
pygame.display.flip()
self.clock.tick(fps)
timer = self.clock.get_rawtime()
self.dt += float(timer)/1000
def event_handler(self):
for event in pygame.event.get():
if event.type == QUIT:
self.running = False
elif event.type == KEYDOWN:
self.key_down(event.key)
elif event.type == KEYUP:
self.key_up(event.key)
elif event.type == MOUSEBUTTONDOWN:
self.mouse_down(event.button, event.pos)
elif event.type == MOUSEBUTTONUP:
self.mouse_up(event.button, event.pos)
elif event.type == MOUSEMOTION:
self.mouse_motion(event.buttons, event.pos, event.rel)
elif event.type == USEREVENT:
self.user_event(event)
def update(self):
pass
def draw(self):
pass
def user_event(self, event):
pass
def key_down(self, key):
pass
def key_up(self, key):
pass
def mouse_down(self, button, pos):
pass
def mouse_up(self, button, pos):
pass
def mouse_motion(self, buttons, pos, rel):
pass
class Tile(pygame.sprite.DirtySprite):
"""The class used to make the Tiles for walls and floors"""
def __init__(self, img, pos, number):
pygame.sprite.DirtySprite.__init__(self)
self.dirty = 2
self.image = pygame.image.load(img).convert()
self.rect = self.image.get_rect()
self.rect.center = pos
self.number = number
class Surfaces(object):
"""Surface Matrice class for Pygame Surfaces"""
def __init__(self, size, screen_size, amount=1):
self.size = size
self.screen_size = screen_size
self.screen_center = (screen_size[0]/2, screen_size[1]/2)
self.amount = amount
self._generate_surfaces()
self.var = 1
def _generate_surfaces(self):
if self.amount == 1:
self.surface = pygame.Surface(self.size)
self.rect = self.surface.get_rect()
elif self.amount == 4:
pass
elif self.amount == 8:
pass
def update_surface(self, pos, speed):
if self.amount == 1:
centerv = vec2d(self.screen_center[0] - self.rect.x,
self.screen_center[1] - self.rect.y)
playerv = vec2d(pos)
distance = centerv.get_distance(playerv)
if distance >= 50:
surfv = vec2d(self.rect.topleft)
move = playerv - centerv
move.length = speed *(distance/50)
surfv -= move
self.rect.topleft = surfv.inttup()
if self.rect.x > 0:
self.rect.x = 0
if self.rect.y > 0:
self.rect.y = 0
elif self.amount == 4:
pass
elif self.amount == 8:
pass
"""
This part isn't working right.
elif mousepos[0] > (self.screen_center[0] - 30):
print "Moving Left"
self.rect.x -= 15
elif mousepos[0] < 30:
print "Moving Right"
self.rect.x += 15
elif mousepos[1] > (self.screen_center[1] - 30):
print "Moving Down"
self.rect.y -= 15
elif mousepos[1] < 30:
print "Moving Up"
self.rect.y += 15
"""
|
ca9309e3114ca7699bf643dae70da316731abc94 | suizo12/hs17-bkuehnis | /source/game_data/plot/utils.py | 480 | 3.625 | 4 | def get_score(s, l):
"""
get the porcentage of value s in relation of the values of
:param s:
:param l:
:return:
"""
l = list(l)
l = sorted(l)
if s in l:
return round(l.index(s) * 100 / len(l) )
return None
def get_percent_score(s, l):
l = list(l)
l = sorted(l)
print(l)
median = sum(l) / len(l)
#median = 1000
#print(int(s * 100 / l[len(l)-1]))
r = int(s * 50 / median)
#print(r, s)
return r
|
f718efff286d6ac941ca527ab91a5b3a102dbd35 | kapil23vt/Python-Codes-for-Software-Engineering-Roles | /permutation string.py | 346 | 3.734375 | 4 | def permute(a, left, right):
if left==right:
print (''.join(a))
else:
for i in range(left,right+1):
a[left], a[i] = a[i], a[left]
permute(a, left+1, right)
a[left], a[i] = a[i], a[left] # backtrack
string = "ABC"
n = len(string)
a = list(string)
permute(a, 0, n-1)
|
b7682ff8aaa5d9dc9081385fea4b101150b6c6b1 | hongxchen/algorithm007-class01 | /Week_08/G20200343040277/LeetCode_0277_191.py | 393 | 3.71875 | 4 | #编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while n:
count += n&1
n >>= 1
print(count)
return count
|
33816ef35be76bb0b6c541269ec15b6528048156 | silviodaniel/Harvard-Project-Digital-Phenotyping | /week 1.py | 9,300 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
np.loadtxt("C:/Users/Silvio/Documents/Career/Harvard/best_text_ever.txt",dtype=int)
y = [x**2 for x in range(5)]
import math
math.pi
numbers=[2,4,6,8]#A LIST: can find how many objects in list using len
numbers[0:2]
numbers. (10)
numbers
x=[12,14,16]
x+numbers#adding lists
Out[6]: [12, 14, 16, 2, 4, 6, 8, 10]
numbers.reverse()#REVERSE
numbers
names=["B","A","C","D"]
names.sort()
names
sorted_names=sorted(names)
names
sorted_names#sorted, while other is not
len(names)
#Tuples are a type of sequence
T=(1,3,5,7)
len(T)
T+(9,11)
x=2
y=3
coordinate=(x,y)
type(coordinate)#UNPACKING TUPLES
coordinates=[(0,0),(1,1),(2,4),(3,9),(4,16)]
for (x,y) in coordinates:
print(x,y)
c=(2,)#SINGLE OBJECT TUPLE
type(c)
##
type((2,))
x=(1,2,3)
count(x)
x.count(3)##COUnts
##RANGES
list(range(5))
list(range(1,15,2))
list(range(7,32,5))
##Strings
S="Python"
S[-3:]#slice and take out hon
"Y" in S#FALSE
"hello"+" aliens"
3*S#PythonPythonPython
"eight equals " +str(8)
str.replace?
namewrong="Sulvuo Martunez"
name_correct=namewrong.replace("u","i")
name_correct
names=name_correct.split(" ")
names[0].upper()#ALL CAPS UPPERCASE
"0"+"1"+"2"+"3"+"4"+"5"+"6"+"7"+"8"+"9"
str(range(10))
dir(str)
x=str(125000)
str.isdigit("125,000")
#SETS
ids=set([1,2,4,6,7,8,9])
ids.add(10)
ids
#{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
ids.pop()#removes first number of set
ids=set(range(10))
males=set([1,2,6,9,10])
females=ids-males
females
everyone=males|females#Union
everyone & set([1,2,3])
word="antidisestablishmentarianism"
letters=set(word)
len(letters)
x={1,2,3}
y={2,3,4}
y-x#subtract sets, only take numbers from the set subtracting from
x.issubset(y)#check if all elements or objects in x are in y
x.symmetric_difference(y)#take all different elements between x and y
#Dictionaries
age=dict()
age={"Tim":29,"Jim":31,"Tyler":20,"David":23,"Jace":27,"Alicia":22}
age["Alicia"]=age["Alicia"]+1
age["Jace"]+=1
age["Jace"]
names=age.keys()
type(names)
#Add name to dictionary
age["Tom"]=37
names
ages=age.values()
#remove key from dictionary
age.pop('Tim',None)#returns value if it exists, and none if it doesn't
age.pop()
age["Tim"]
age[0]
ages
"Tom" in names
"Tom" in age#how to check if name in set, check membership
age
29 in ages
##TYPES
L=[1,2,3,4]
M=list(L)#Creates completely new object
M is L#false
M==L#True
#OR
M=L[:]
#Copies
import copy
x = [1,[2]]
y = copy.copy(x)
z = copy.deepcopy(x)
y is z
z is x
x is y
x==y
x==z
#IF statements
if x > y:
difference=x-y
print("x is greater than y")
else:
print("y is greater than x")
3%2==0
if n%2 == 0:
print("even")
else:
print("odd")
#For loops
names=["Tyler","Danielle","Ula","Alicia","David","Jovaniel","Alexandra"]
names[0]
names[0].upper()
for name in names:
print(name.upper())
#index to get names out
range(len(names))
#iterate over all key values pairs in dictionary
age.keys()#returns the keys of dictionary, which allow to access dictionary
for name in age.keys():
print(name,age[name])#prints out name specified by key, then value of object
for name in age:#shorthand, don't need parentheses or .keys
print(name,age[name])
for name in sorted(age):#alphabetical order
print(name,age[name])
for name in sorted(age, reverse=True):#reverse alphabetical order
print(name,age[name])
#for loop vs while loop: use while loop when don't know how many times running,
#and for loop when you know exactly how many times
bears = {"Grizzly":"angry", "Brown":"friendly", "Polar":"friendly"}
for bear in bears:
if bears[bear]=="friendly":#first call dictionary, then use for target to get value of object
print("Hello, "+bear+" bear!")
else:
print("odd")
#list(range(2,100))
is_prime = True
n=17
for i in range(2,n):
if n%i == 0:#if not prime
is_prime= False
print(is_prime)
N=20
for n in range(2,N):
is_prime = True
for i in range(2,n):
if n%i == 0:#if not prime
is_prime= False
if is_prime:
print(n)
print(is_prime)
for i in range(2,n):
if n%i == 0:#if not prime
is_prime= False
print(is_prime)
print(is_prime)
for i in range(5):
print(i)
8%2
9%2
21%3
137%7
137/7
19*7
3 /= 2
n=100
number_of_times = 0
while n >= 1:
n /= 2
number_of_times += 1
print(number_of_times)
sum=0
for i in range(10):
sum=sum+i
print(sum)
sum=0#For loop above is same as this while loop
i=0
while i<10:
sum=sum+i
print(sum)
i=i+1
color=["Blue","Silver","Orange"]
for i in color:
print(i,"is one of Silvio's favorite colors.")
#LIST COMPREHENSIONS
numbers=range(10)
squares2=[number**2 for number in numbers]
squares2
list(range(0,10,2))
list(range(1,10,2))
sum([num**2 for num in range(1,10,2)])
sum([i**2 for i in range(3)])
#1.3.6 remove line breaks
#turn a file into a list
#read file
for line in open(filename):
line=line.rstrip().split(" ")
print(line)
#output: ['first','line']
#can also add in text to a file by putting F.write("word\n") and F.close to complete.
#\n puts in line break
def addsub(a,b):
mysum=a+b
mysub=a-b
return(mysum,mysub)
addsub(2,3)#returns tuple
def modify(mylist):
mylist[0]*=10#Must use the = sign not just *
L=[1,2,3,4]
modify(L)
L
#Writing simple functions!
def intersect(s1,s2):
res=[]
for x in s1:
if x in s2:
res.append(x)
return(res)
intersect([1,2,3,4,5],[3,4,5,6,7])
import random
random.choice([1,2,4,5,6])
"a"+"b"
def password(length):
pw=str()
characters="abcdefghijklmnopqrstuvwxyz"+"0123456789"
for i in range(length):
pw=pw+random.choice(characters)
return(pw)
password(10)
def is_vowel(letter):
if type(letter)==int:
letter=str(letter)
if letter in "aeiouy":
return(True)
else:
return(False)
is_vowel(1)
def factorial(n):
if n==0:
return 1
else:
N=1
for i in range(1,n+1):
N*=i
return(N)
factorial(3)
"the answer is" +" 8"
#HW Week 1
import string
alphabet=string.ascii_letters
alphabet
sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters={}
for letter in sentence:
if letter in alphabet:
if letter in count_letters:#
count_letters[letter]+=1#adds 1 to existing letter
else:
count_letters[letter]=1#creates new letter with 1 value
print(count_letters)
for count_letters in sentence
if count_letters.key()
##########
count_letters={i:sentence.count(i) for i in sentence if i in alphabet}
print(count_letters)
#counts letters
big= 'TTtt'
big.lower().count('t')
##################
sentence = 'Jim quickly realized that the beautiful gowns are expensive'
count_letters={}
# Create your function here!
import string
alphabet=string.ascii_letters
alphabet
def counter(input_string):#counts unique letters & occurrences in inputted string
for letter in input_string:
if letter in alphabet:
if letter in count_letters:
count_letters[letter]+=1
else:
count_letters[letter]=1
return(count_letters)
counter(sentence)
#make a function that computes the golden ratio; two numbers, 0 and 1
#repeatedly, one for loop or one while loop
counter('Jim')
alphabet
def counter(input_string):
return{i: input_string.count(i) for i in input_string if i in alphabet}
print(counter(sentence))
address_count={}
address_count=counter(address)
print(address_count)
#count most frequent letter in address_count
address_count
def maxvalue(dic):
v=list(dic.values())
k=list(dic.keys())
return k[v.index(max(v))]
most_frequent_letter=(maxvalue(address_count))
print(most_frequent_letter)
vector(1,2,3)
v1
#TESTING
stats = {'a':1000, 'b':3000, 'c': 100}
def maxvalue(dic):
v=list(dic.values())
k=list(dic.keys())
return k[v.index(max(v))]
maxvalue(stats)
##############
import math
math.sqrt(4)
import numpy
x=(0,0)
y=(1,1)
print(math.sqrt(sum(numpy.square(numpy.subtract(y,x)))))
(numpy.square(y,x))
def distance(y,x):
math.sqrt(sum(numpy.square((numpy.subtract(y,x)))))
print(distance(1,1))
####
x=(0,0)
#type(x)
#??????
y=(1,1)
math.sqrt(2)
k=[0,0]
l=[1,1]
def distance(x,y):
return math.sqrt((x[0]-y[0])**2+(x[1]-y[1])**2)
distance(k,l)
print(distance(0,1))
print(distance(1,1))
math.sqrt(1**2+1**2)
math.sqrt(2)
c
x=[1,2,4,5]
mean(x)
import random
rand(0,2)
####
import random
random.seed(1) # This line fixes the value called by your function,
# and is used for answer-checking.
def rand(x,y):
# define `rand` here!
return float(random.randrange(-100,101)/100)
rand(-100,101)
?random.uniform()
(.363)/(.406/math.sqrt(14))
import random
import decimal
random.seed(1) # This line fixes the value called by your function,
# and is used for answer-checking.
def rand(x,y):
return random.uniform(x,y)
rand(-1,2)
random.uniform(1,2)
F = open("my_file.txt","w")
for i in range(10):
F.write("Hello World"+"\n")
F.close()
F = open("myfile.txt","w")
F
for i in range(10):
F.write(str(i)+"\n")
F.close()
import os
help(os)
os.getcwd()
def even(x):
|
3eb420ad18a30b0c57ff359a600ee9c4873cbd6f | diogolimalucasdev/Python-Exercicios | /19.05/converer em milimetros.py | 251 | 3.890625 | 4 | # elabboar um programa que leia um valor em metros e tranforme em milimetros
metros = float(input(" Digite um valor em metros: "))
milimetros = metros * 1000
print("o valor em metros(", metros, ") equivale a (", milimetros, ") em milimetros")
|
bc73faf7c494861611c27546fb9a880344a9cca2 | touhiduzzaman-tuhin/python-code-university-life | /Anisul/93.py | 88 | 3.703125 | 4 | import re
pattern = r"[A-Z]"
if re.match(pattern, "Aadjfdjkidd"):
print("Match")
|
95b798aac66542f624f91469e3d3548b18e119a9 | TakeshiJay/Apartement-Rental-System | /Term_Project/main.py | 34,375 | 3.796875 | 4 | # -*- coding: utf-8 -*-
import getpass
import json
import re
from tabulate import tabulate
import datetime
class ExpenseInputScreen: # Expense input screen
def __init__(self, expense_list):
self.__year = datetime.datetime.now().year
self.__month = datetime.datetime.now().month
self.__day = datetime.datetime.now().day
self.__category = None
self.__payee = None
self.__amount = 0.00
self.__expense_list = expense_list
def getExpense(self):
return(self.__year, self.__month, self.__day, self.__category,
self.__payee, self.__amount)
def inputExpense(self):
while True:
yearStr = input(f"Enter expense year (default {self.__year}): ")
if yearStr == "":
break
elif yearStr.isnumeric() is False:
print(f'Invalid year "{yearStr}", please try again')
continue
else:
self.__year = int(yearStr) # [0]
if (self.__year < 2021):
print(f'Invalid year {self.__year}, please '
'try again it must be 2021 or later')
self.__year = 2021
continue
break
while True:
monthStr = input(f"Enter expense month (default {self.__month}): ")
if monthStr == "":
break # accept default today's month
elif monthStr.isnumeric() is False:
print(f'Invalid month "{monthStr}", please try again (1-12)')
self.__month = datetime.datetime.now().month
continue
else:
self.__month = int(monthStr)
if (self.__month > 12) or (self.__month < 1):
print(f'Invalid month {self.__month}, please '
'try again (1-12)')
self.__month = datetime.datetime.now().month
continue
else:
break
hiddenMonth = self.__month
while (self.__day < 0) or (self.__day > 29):
if (hiddenMonth == 2):
dayStr = input("Enter expense day (1-28): ")
else:
dayStr = input('Enter expense day (1-31): ')
if dayStr == "":
return self.__expense_list
elif dayStr.isnumeric() is False:
print(f'Invalid day "{dayStr}", please try again (1-28)')
continue
elif self.__day > 27 and hiddenMonth == 2:
self.__day = -1
print(f'Invalid day "{dayStr}", please try again')
continue
else:
self.__day = int(dayStr)
break
self.__category = \
input('Enter expense category(e.g. repairs, utilities): ')
self.__payee = input('Enter payee (Bob\'s Hardware, Big Electric Co):')
while self.__amount == 0:
amountStr = input('Enter amount (39.95):')
if amountStr == "":
return self.__expense_list # empty
elif re.match(r'^-?\d+(?:\.?\d+)$', amountStr) is None:
print('Invalid input "{amountStr}", please do not use $')
self.__amount = 0.00
continue
else:
self.__amount = float(amountStr) #convert amount to float
expense = Expense(self.__year, self.__month, self.__day,
self.__category, self.__payee, self.__amount)
expenseRecord = ExpenseRecords(self.__expense_list)
expenseRecord.insertExp(expense)
return self.__expense_list
class ExpenseRecords:
# Initialize expenses with empty dictionary and updates as needed
def __init__(self, expenseRecord):
self.__expenses = {}
self.__updatedList = expenseRecord
self.__map = ['Year', 'Month', 'Day', 'Category', 'Payee', 'Amount']
def insertExp(self, expenseRecord):
year, month, day, category, payee, amount = expenseRecord.getExpense()
self.__expenses['Year'] = year
self.__expenses['Month'] = month
self.__expenses['Day'] = day
self.__expenses['Category'] = category
self.__expenses['Payee'] = payee
self.__expenses['Amount'] = amount
self.__updatedList.append(self.__expenses)
# If key is 'Amount' add the value of it to eTotal
def return_total_expenses(self):
sum = 0.0
for i in self.__updatedList:
sum += i['Amount']
return sum
# Print Expense Records
def displaySummary(self):
if len(self.__updatedList) < 1:
print("\nNo expense records to display.\n")
return
print("\n ==== Expense Summary ====\n")
# Tabulate
headers = self.__updatedList[0].keys()
rows = [x.values() for x in self.__updatedList]
print(tabulate.tabulate(rows, headers, tablefmt='rst'))
# Print Expense Total Last
print(f"Total Expenses: ${self.return_total_expenses():0.2f}")
# -*- coding: utf-8 -*-
"""
########## Term Project ############
# #
# owner: @author Larry Delgado #
# @author Jacob Sunia #
# #
# Due Jun 24, 2021 at 11:59 PM PDT #
# Finished: TBD at TBD #
#----------------------------------#
# CSULB CECS 343 Intro to S/W Engr #
# Professor Phuong Nguyen #
####################################
"""
# from ExpenseInputScreen import ExpenseInputScreen
class Expense:
def __init__(self, year, month, day, category, payee, amount):
self.__year = year
self.__month = month
self.__day = day
self.__category = category
self.__payee = payee
self.__amount = amount
def getExpense(self):
return(self.__year, self.__month, self.__day, self.__category,
self.__payee, self.__amount)
def validation(self):
pass
# Rent Input UI class
# @param rent_list rent records list of dictionaries for all users
# @param tenant_list tenant list of dictionaries for all users
#
# See "UsersApartmentsData.json" for the JSON file with key/value pairs
#
class RentInputScreen:
def __init__(self, rent_list, tenant_list):
self.__Name = None
self.__month = -1
self.__tenantIndex = -1
self.__amount = 0.00
self.__rent_list = rent_list
self.__tenant_list = tenant_list
def getRent(self):
return(self.__Name, self.__month, self.__amount)
def setTenantIndex(self, login_idx):
for i, dic in enumerate(self.__tenant_list[login_idx]):
if dic['name'] == self.__Name:
self.__tenantIndex = i
"""
def getIndex(self, login_idx):
for i, dic in enumerate(self.__tenant_list[login_idx]):
if dic['name'] == self.__Name:
self.__tenantIndex = i
"""
# inputRent inputs one tenant name, month(1-12) and rent payment
#
# @param login_idx user login index in the JSON file dictionary list
#
# Note: This method always returns self.__rent_list since it may add new
# values to give the caller the updated rent list
def inputRent(self, login_idx):
# robust tenant name collection reprompts user until either:
#
# 1. user enters [enter] returns to caller without doing anything.
# 2. searches for tenant name in the list.
# A. if not found, inform user, set tenant name to "", start over
# B. if found, set the tenant index
while self.__Name is None or self.__Name == "":
self.__Name = input("Enter rent payment tenant name: ")
if self.__Name == "":
return self.__rent_list
validTenant = False
for tl in self.__tenant_list[login_idx]:
if self.__Name in tl['name']:
validTenant = True
break
if validTenant is False:
print(f'Invalid tenant name "{self.__Name}"')
self.__Name = ""
continue
else:
self.setTenantIndex(login_idx)
# robust month digit collection
while (self.__month < 0) or (self.__month > 11):
monthStr = input("Enter payment month (1-12): ")
if monthStr == "":
return self.__rent_list
elif monthStr.isnumeric() is False:
print(f'Invalid month "{monthStr}", please try again (1-12)')
continue
else:
self.__month = int(monthStr) - 1 # index [0]
if (self.__month > 11) or (self.__month < 0):
print(f'Invalid month {self.__month}, please '
'try again (1-12)')
self.__month = -1
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"]
# robust amount ####.## collection
while self.__amount == 0:
amountStr = input(f"Enter {months[self.__month]}. payment "
f"for {self.__Name}: ")
if amountStr == "": # if amount string is empty return
return self.__rent_list
# TODO force 0-2 digits after decimal point using regular exp.
elif re.match(r'^-?\d+(?:\.?\d+)$', amountStr) is None:
print(f'Invalid amount "{amountStr}", please enter dollars '
"and cents (250.42) with no $")
self.__amount = 0.00
continue
else:
self.__amount = float(amountStr)
rentRow = RentRow(self.__Name, self.__month, self.__amount)
rentRecord = RentRecords(self.__rent_list, self.__tenant_list)
rentRecord.insertRent(rentRow, login_idx, self.__tenantIndex)
if self.__amount >= 0:
print(f'${self.__amount:0.2f} {months[self.__month]}. '
f'rent payment recorded for {self.__Name}')
else:
print(f'${self.__amount:0.2f} {months[self.__month]}. '
"security deposit return recorded "
f"for {self.__Name}")
return self.__rent_list
# -*- coding: utf-8 -*-
#rentRecords class will represent as our list class that holds all rent records from a specified user
# this classes main purpose will serve as an add new rent records and display feature for output
class RentRecords:
# The __init__ function is our overloaded constructor that will serve to initialize all of our
# used items needed in the class. This function runs in a complexity of T(n) = θ(1) based on
# initialization
# @param __rentRecord is the list of rent records from the year.
# @parm __tenantList is the list of tenants that will be used to identify a tenant
def __init__(self, __rentRecord, __tenantList):
self.__rows = __rentRecord # RentRecords dictionary
self.__tenantList = __tenantList
self.__months = \
['Ap.No', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# insertRent function serves to add onto the current value of the rent function. We would like
# to implement a new function that clears all values of a rental list but will try to implement
# if we do have time. The complexity of this algorithm is T(n) = θ(1) based on the use of getting
# a specified index which is passed in as a parameter
# @param rent_record will be the record that is passed into the class
# @param user_login_idx is the login index of the user which we would like to access
# @param ten_idx is the tenants index that we are set to access in our rent records
def insertRent(self, rent_record, user_login_idx, ten_idx):
name, month, amount = rent_record.getInfo()
self.__rows[user_login_idx][ten_idx][month] += amount
# printable dictionary is our function used to return a list by merging an apartment number to
# the first index of our rental lists to tabulate in classes further. This function runs in a
# runtime of T(n) = O(n) based off of the number of iterations we take into consideration in our
# function.
# @param user_login_idx is the login index of the user which we would like to access
# @return a list of apartment number and rental lists
def printable_Dictionary(self, user_login_idx):
aptNo = []
# print(self.__tenantList)
for i in self.__tenantList[user_login_idx]:
aptNo.append([i['aptNumber']])
for i in aptNo:
index = aptNo.index(i)
i.extend(self.__rows[user_login_idx][index])
return(aptNo)
# getSumOfRents is a function that iterates till we get the total of all months and all users in
# in our function. This function runs in a time complexity of T(n) = O(n^3) based on the number of
# iterations we are in our 3-Dimensional list
# @return a rounded number with set precision 2 of our rent total
def getSumOfRents(self):
rTotal = 0.00
# print(self.__rows)
"""
for key in self.__rows:
print(key, '->', self.__rows[key])
rTotal += self.__rows[key]
"""
for user in self.__rows:
for name in user:
for month in name:
rTotal += month
return round(rTotal,2)
# display is a function that tabulates our results from printable dictionary. This function is used
# to simply display all tenant apartment numbers and their respective rent records. The time complexity
# used to run this function is approximately T(n) = O(n) based on the time it taks for us to create a
# printable object
# @param user_login_idx is the login index of the user which we would like to access
def display(self, user_login_idx):
printable = self.printable_Dictionary(user_login_idx)
print("\n==== Rent Summary =====")
print(tabulate(printable, headers=self.__months))
print('Total Rent Collected: $', self.getSumOfRents())
# -*- coding: utf-8 -*-
class RentRow:
def __init__(self, name, month, amount):
#self.__rentRow = {}
self.__name = name
self.__month = month
self.__amount = amount
def get_name(self):
return(self.__name)
def get_month(self):
return(self.__month)
def get_amount(self):
return(self.__amount)
def getInfo(self):
return(self.__name, self.__month, self.__amount)
'''
def getRentSum(self):
sum = 0.0
for i in self.__rentRow:
sum+= i
return sum
'''
# -*- coding: utf-8 -*-
class TenantInputScreen: # Tenant input screen
def __init__(self, tenantList):
self.__tenants = tenantList
self.__aptNum = -1 # apartment number
self.__tenantName = None # tenant name
# get method returns tenant name and apartment number
def getTenant(self):
return(self.__tenantName, self.__aptNum)
def inputTenant(self):
aptStr = input("Apartment # (-# to remove): ")
if re.match("[-+]?\d+$", aptStr) is None:
return self.__tenants
self.__aptNum = int(aptStr)
if self.__aptNum == 0:
return self.__tenants
existing = self.__tenants.findTenant(abs(self.__aptNum))
if existing is not None:
if self.__aptNum < 0:
tenant = existing.getTenant()
if tenant == "":
tenant = "is vacant."
else:
tenant = "assigned to " + existing.getTenant()
delete = input(f"Apartment {abs(self.__aptNum)} {tenant}."
" Remove from building (y/n)? ").lower()
if delete != 'y':
return self.__tenants
else:
self.__tenantName = ""
elif existing.getTenant() != "":
replace = input(f"Apartment {self.__aptNum} already assigned "
f"to {existing.getTenant()}."
" Replace or vacate (y/n)? ").lower()
if replace != 'y':
return self.__tenants
else:
self.__tenantName = input("New tenant name "
"or [Enter] to vacate: ")
else:
self.__tenantName = input("Tenant name: ")
elif self.__aptNum > 0:
self.__tenantName = input("Tenant name: ")
newTenant = Tenant(self.__aptNum, self.__tenantName)
tenant = self.__tenants.insertTenant(newTenant)
if self.__aptNum > 0:
if self.__tenantName != "":
print(f"Apartment {tenant.getApt()} assigned "
f"to {tenant.getTenant()}.")
elif existing is None:
print(f"Apartment {tenant.getApt()} already vacant.")
else:
print(f"Apartment {tenant.getApt()} vacated.")
elif existing is not None:
print(f"Apartment {-self.__aptNum} removed from building.")
else:
print(f"Apartment {-self.__aptNum} not found -"
" not removed from building.")
return self.__tenants
# -*- coding: utf-8 -*-
# The TenantList class maintains a list of Tenant objects in private memory
# and provides public methods for list manipulation and output.
class TenantList:
# __init__(self) function is the overloaded class constructor
def __init__(self, tenantList):
if len(tenantList) > 0 and type(tenantList[0]) is dict:
self.__tenants = []
for entry in tenantList:
self.__tenants.append(Tenant(entry.get("aptNumber"),
entry.get("name")))
else:
self.__tenants = tenantList
# returns index position of apartment number and/or tenant name in list,
# else None.
def __getTenantPos(self, aptNum=None, tenantName=None):
for pos in range(self.countTenants()):
aNum, tName = self.__tenants[pos].getAptTenant()
if aptNum is not None and aptNum == aNum:
if tenantName is None or tenantName == tName:
return pos
elif tenantName is not None and tName == tenantName:
if aptNum is None or aptNum == aNum:
return pos
return None
# getTenantList returns the tenant list as a dictionary
def getTenantDict(self):
tenantDictList = []
for tenant in self.__tenants:
tenantDict = {}
tenantDict["aptNumber"] = tenant.getApt()
tenantDict["name"] = tenant.getTenant()
tenantDictList.append(tenantDict)
return tenantDictList
# insertTenant adds newTenant name to provided apartment number
# if the apartment number is negative, it deletes abs(apartment number) if
# it exists, else None is returned.
def insertTenant(self, newTenant):
aNum, tName = newTenant.getAptTenant()
if aNum == 0: # Apartment 0 invalid
return None
pos = self.__getTenantPos(abs(aNum)) # existing tenant in apt?
if pos is not None:
if aNum < 0:
self.__tenants.pop(pos) # delete apartment
else:
self.__tenants[pos] = newTenant # replace existing tenant
else:
if aNum < 0:
return None # tried to delete non-existent apartment number
else:
self.__tenants.append(newTenant) # add new tenant
self.__tenants.sort(key=lambda t: t.getApt()) # sort in place
return newTenant
# countTenants returns the number of Tenant objects in the tenants list
def countTenants(self):
return len(self.__tenants)
# countAptsTenants returns the number of apartments and tenants in list
def countAptsTenants(self):
occupied = filter(lambda t: t.aptOccupied(), self.__tenants)
# https://stackoverflow.com/questions/19182188/how-to-find-the-length-of-a-filter-object-in-python
return len(self.__tenants), sum(1 for _ in occupied)
def getTenant(self, pos):
if pos < self.countTenants() and pos > -1:
return self.__tenants[pos]
else:
return None
def findTenant(self, aptNum=None, tenantName=None):
pos = self.__getTenantPos(aptNum=aptNum, tenantName=tenantName)
if pos is not None:
return self.__tenants[pos]
else:
return None
def __str__(self):
str = ""
for i in range(self.countTenants()):
str += self.getTenant(i).__str__() + "\n"
return str
def display(self):
print()
print("Apt # Tenant Name")
print("----- -----------")
for i in range(len(self.__tenants)):
print(self.__tenants[i])
return
# -*- coding: utf-8 -*-
# Tenant provides an object type that stores an apartment number and tenant
# name in private memory, and public methods used with this object.
class Tenant:
# __init__ function is the overloaded class constructor
# @param aptNum is the integer apartment number
# @param tenantName is the name of our tenant
def __init__(self, aptNum, tenantName):
self.__aptNumber = aptNum
self.__name = tenantName
def __del__(self):
return
def getApt(self):
return self.__aptNumber
def getTenant(self):
return self.__name
def getAptTenant(self):
return self.__aptNumber, self.__name
def aptOccupied(self):
return self.__name != ""
def __lt__(self, other):
if self.__name < other.getTenant():
return True
else:
return False
def __eq__(self, other):
if self.__name == other.getTenant():
return True
else:
return False
def __str__(self):
return f"{self.getApt():5d} {self.getTenant()}"
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# import tabulate
# Initialize class records from previous into 1 Annual Report instance
class AnnualReport:
def __init__(self, __expenseRecords, __rentRecords, tenant_list):
self.__report1 = ExpenseRecords(__expenseRecords)
self.__report2 = RentRecords(__rentRecords, tenant_list)
def calc_netProfit(self):
netProfit = self.__report2.getSumOfRents() - self.__report1.return_total_expenses()
return netProfit
# The whole annual summary
def displayAnnualSummary(self):
print("Annual Summary\n")
rent_tot = self.__report2.getSumOfRents()
expe_tot = self.__report1.return_total_expenses()
print('Income')
print('Rent Total: $', rent_tot)
print(" ")
print('Expense Total: $', expe_tot)
# Net Profit
print("\nNet Profit: " + str(self.calc_netProfit()))
class LoginInputScreen:
def __init__(self, user_list):
self.__username = "" # prefixing with __ enforces private access
self.__password = ""
self.__confirmPassword = ""
self.__user_list = user_list
def getUserPassword(self):
return(self.__username, self.__password)
def inputUser(self):
self.__username = input('Enter your username: ')
if self.__username == "":
return None
self.__password = input('Enter your password: ')
if self.__password == "":
return None
else:
return(self.getUserPassword())
# inputNewUser prompts for a new username and password, verifying the
# password. If the username is taken, it re-prompts for a unique one.
# Return: self.getUserPassword() upon success, else None if user leaves
# a field blank by just pressing [enter].
def inputNewUser(self):
while True:
self.__username = input('Enter your new username: ')
if self.__username == "":
return None
if self.__username in self.__user_list:
print(f'Username "{self.__username}" is taken, '
'please try again...')
self.__username = ""
continue
while True:
self.__password = input('Enter your new password: ')
if self.__password == "":
return None
self.__confirmPassword = input("Please re-enter "
"your password: ")
if self.__confirmPassword == "":
return None
if self.__password != self.__confirmPassword:
print("Please re-enter the same password to confirm.")
else:
return(self.getUserPassword())
# -*- coding: utf-8 -*-
class UserList:
def __init__(self, user_list, passw_list, tenants_list, rent_records,
expenses_list):
self.__user_list = user_list
self.__passw_list = passw_list
self.__tenants_list = tenants_list
self.__rent_records = rent_records
self.__expenses_list = expenses_list
self.__loged_user_idx = -1
self.flag = False
def get_logged_idx(self):
return(self.__loged_user_idx)
def add_user(self, newU):
user, passw = newU
if user in self.__user_list:
print("Invalid: Username taken")
return None
else: # user cannot be in the list if the if condition is false
self.__user_list.append(user)
self.__passw_list.append(passw)
self.__tenants_list.append([])
self.__rent_records.append([])
self.__expenses_list.append([])
self.validate_user(user, passw)
def return_user(self, usrWB):
user, passw = usrWB
self.validate_user(user, passw)
if self.flag is True:
print('Welcome Back', user)
def validate_user(self, user, passw):
if user not in self.__user_list:
print("Invalid Username")
return 0
for i in self.__user_list:
if i == user:
idx = self.__user_list.index(i)
for j in self.__passw_list:
if self.__passw_list.index(j) == idx:
if j == passw:
self.flag = True
self.__loged_user_idx = idx
return True
else:
print("Invalid password")
return False
class UserInterface: # user interface
# __init__ default constructor that builds the User Interface. The
# constructor provides a space to print and prompt the Landlord
# @param flag boolean indicates if a user is logged in or not
# @param __expenses_List is an extended list of dictionary expense items
# @param __loged_user_idx is the current index of the logged in user;
# initially set to -1 because there are no current logged in users.
# @param __tenants_list is the list of tenants leasing one of the logged in
# users' apartments.
# @param __rent_records is a list of records throughout a yearly cycle
# that record all tenant payment transactions.
__OSUserName= getpass.getuser()
def __init__(self, dataFile='/Users/'+__OSUserName+'/Desktop/test/UsersApartmentData.json'):
self.__dataFile = dataFile
f = open(self.__dataFile, "r")
self.__dic = json.load(f)
f.close()
self.__UserList = self.__dic["Username"]
self.__password = self.__dic["Password"]
self.__expenses_List = self.__dic["Expenses"]
self.__loged_user_idx = -1
self.__tenants_list = self.__dic["TenantList"]
self.__rent_records = self.__dic["RentRecords"]
self.__tenantList = None # logged-in user TenantList
self.__expenseRecords = None # logged-in user ExpenseRecords
self.__rentRecords = None # logged-in user RentRecords
def loginMainMenu(self):
self.print_menus(1)
logonStatus = 0 # 0 means not logged in, 1 = logged in, 2 = quit
while logonStatus == 0:
logonStatus = self.logon_menu()
if logonStatus == 2:
return False # quit
# Save logged-in user TenantList, ExpenseRecords and RentRecords
# in self.__tenantList, self.__expenseRecords, and self.__rentRecords
self.__tenantList = \
TenantList(self.__tenants_list[self.__loged_user_idx])
self.__tenantScreen = TenantInputScreen(self.__tenantList)
# TODO
scanner = ''
while (scanner != 'l'):
scanner = input("Enter 'i' to Input data, 'd' to Display data, "
"or 'l' to Logout: ")
if scanner.lower() == 'i':
self.print_menus(3)
scanner_2 = input(" press [Enter] to return "
"to main menu: ")
self.inputScreen(scanner_2)
elif scanner.lower() == 'd':
self.print_menus(4)
scanner_2 = input(" press [Enter] to return "
"to main menu: ")
self.output_screen(scanner_2)
elif scanner.lower() == 'l':
print("Thank you for using the Apartment Rental System "
"by Team 6.")
print("See you again soon!\n")
return True
else:
print(f'"{scanner}" is an invalid option please try again.')
return True
def inputScreen(self, scanner_2):
if scanner_2 == 't':
self.__tenantList = self.__tenantScreen.inputTenant()
self.__tenants_list[self.__loged_user_idx] = \
self.__tenantList.getTenantDict()
self.__rent_records[self.__loged_user_idx].append([0]*12)
elif scanner_2 == 'r':
RIS = RentInputScreen(self.__rent_records, self.__tenants_list)
self.__rent_records = RIS.inputRent(self.__loged_user_idx)
elif scanner_2 == 'e':
EIS = ExpenseInputScreen(self.__expenses_List[self.__loged_user_idx])
EIS.inputExpense()
self.store_to_file()
# Output Screen
def output_screen(self, scanner_2):
if scanner_2 == 't':
tenantList = TenantList(self.__tenants_list[self.__loged_user_idx])
tenantList.display()
elif scanner_2 == 'r':
rentRecords = RentRecords(self.__rent_records, self.__tenants_list)
rentRecords.display(self.__loged_user_idx)
elif scanner_2 == 'e':
expenseRecords = ExpenseRecords(self.__expenses_List[self.__loged_user_idx])
expenseRecords.displaySummary()
elif scanner_2 == 'a':
annualReport = AnnualReport(self.__expenses_List[self.__loged_user_idx], self.__rent_records, self.__tenants_list[self.__loged_user_idx])
annualReport.calc_netProfit()
annualReport.displayAnnualSummary()
def logon_menu(self):
user = LoginInputScreen(self.__UserList)
userList = UserList(self.__UserList, self.__password,
self.__tenants_list, self.__rent_records,
self.__expenses_List)
while userList.flag is False:
login = input("Enter 1 to login, 2 to create new user, "
"or 'q' to Quit: ")
if login == '1': # user login
lis = LoginInputScreen(self.__UserList)
user = lis.inputUser()
if user is not None:
userList.return_user(user)
self.__loged_user_idx = userList.get_logged_idx()
elif login == '2': # create new user/password and login
lis = LoginInputScreen(self.__UserList)
user = lis.inputNewUser()
if user is not None:
if userList.add_user(user) is None:
print(f'There is already a username "{user[0]}".')
return 0 # not logged in
else:
print(f'New user "{user[0]}" logged in...\n')
self.store_to_file()
self.__loged_user_idx = userList.get_logged_idx()
return 1 # logged in
elif login.lower() == 'q': # quit program
return 2 # quit program
else:
print(f'"{login}" is an invalid entry, please try again.')
return 1 # logged-in
def print_menus(self, num):
if num == 1:
print("Welcome to the Apartment Rental System - "
"Multiuser Edition v0.4")
print("Please select one of the following login options:")
elif num == 3:
print("\nEnter 't' to add or replace a Tenant,")
print(" 'r' to record a Rent payment,")
print(" 'e' to record an Expense payment, or", end='')
# For output_screen
elif num == 4:
print("\nEnter 't' to display Tenant list,")
print(" 'r' to display Rent records,")
print(" 'e' to display Expense records,")
print(" 'a' to display Annual summary, or", end='')
else:
print(f"Menu number {num} not supported.")
def store_to_file(self):
js = json.dumps(self.__dic)
f = open(self.__dataFile, "w")
f.write(js)
f.close()
# main() instantiates a UserInterface object and calls its loginMainMenu()
# public method
def main():
ui = UserInterface()
loop = True
while loop is True:
loop = ui.loginMainMenu()
if __name__ == "__main__":
main()
|
8cfdad426ca270f0aadda0db5ff12be8a5274b05 | AiZhanghan/Leetcode | /秋招/京东/0827/quick_sort.py | 1,148 | 3.578125 | 4 | class Solution:
def quick_sort(self, items):
"""
Args
items: list[int]
"""
self._quick_sort(items, 0, len(items) - 1)
def _quick_sort(self, items, start, end):
"""
Args:
items: list[int]
start: int
end: int
"""
if start >= end:
return
pivot_index = self.partition(items, start, end)
self._quick_sort(items, start, pivot_index - 1)
self._quick_sort(items, pivot_index + 1, end)
def partition(self, items, start, end):
"""
Args:
items: list[int]
start: int
end: int
Return:
int
"""
# [0, i) >= pivot
i = start
pivot = items[end]
for j in range(start, end):
if items[j] >= pivot:
items[i], items[j] = items[j], items[i]
i += 1
items[i], items[end] = items[end], items[i]
return i
if __name__ == "__main__":
items = [2, 4, 10, 34, 1, 0]
Solution().quick_sort(items)
print(items) |
27f964af378fc9151b23767c5b824be981119291 | rileyshahar/csworkshops | /00-principles/100-fib-fix-one.py | 1,005 | 4.1875 | 4 | """Compute the first 8 fibonacci numbers."""
def fib_step(fibs):
"""Update fibs to add the next fibonacci number."""
# f(n) = f(n-1) + f(n-2)
fibs.append(fibs[-1] + fibs[-2])
def first_n_fib(n):
"""Return a list of the first n fibonacci numbers."""
# stores the computed values for later return
ret = [1, 1]
# repeat n-2 times; 2 iterations already done by intial conditions
for _ in range(n - 2):
fib_step(ret)
return ret
def print_list(to_print):
"""Print each value in to_print."""
for val in to_print:
print(val)
lst = first_n_fib(8)
print_list(lst)
def test_first_n_fib_0():
"""Test that `first_n_fib` is correct for n=0."""
assert first_n_fib(0) == []
def test_first_n_fib_2():
"""Test that `first_n_fib` is correct for n=2."""
assert first_n_fib(2) == [1, 1]
def test_first_n_fib_10():
"""Test that `first_n_fib` is correct for n=10."""
assert first_n_fib(10) == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
|
7f6b04ae5e797c6eb6261e6ec62dce29e3ea4d49 | meetashok/projecteuler | /20-30/problem-29.py | 343 | 3.609375 | 4 | ## Problem 29
lower_limit = 2
upper_limit = 100
def main():
powers = []
for a in range(lower_limit,upper_limit + 1):
for b in range(lower_limit, upper_limit + 1):
if a ** b not in powers:
powers.append(a**b)
return len(powers)
if __name__ == "__main__":
answer = main()
print(answer) |
f7eada261f0a0bf3dbdbedfddb89f2842e26f121 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2166/60688/317581.py | 264 | 4.03125 | 4 | inputstr=input();
if(inputstr=="1"):
print("7 1 4 9 2 11 10 8 3 6 5 12");
elif(inputstr=="2"):
print("2 1 4 3")
print("3 1 4 5 2")
elif(inputstr=="1/3-1/2"):
print("-1/6");
elif(inputstr=="-1/2+1/2+1/3"):
print("1/3");
else:
print(inputstr) |
130483f4f46c78c810da0eb3e30cf9829258179a | JesusGarcia143/progavanzada | /Ejercicio48.py | 1,169 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 8 02:06:24 2019
@author: Jesús García
"""
##Ejercicio: 48 "Signo Sodiacal Chino"
##Escriba un programa que lea un año del usuario y muestre el animal asociado
##con ese año Su programa debería funcionar correctamente durante cualquier año mayor o igual
##a cero, no solo los que figuran en la tabla.
##año = int ( input ( ' Ingrese su año de nacimiento: ' ))
if (año - 2000 ) % 12 == 0 :
signo = ' Dragón '
elif (año - 2000 ) % 12 == 1 :
signo = ' Serpiente '
elif (año - 2000 ) % 12 == 2 :
signo = ' Caballo '
elif (año - 2000 ) % 12 == 3 :
signo = ' oveja '
elif (año - 2000 ) % 12 == 4 :
signo = ' mono '
elif (año - 2000 ) % 12 == 5 :
signo = ' gallo '
elif (año - 2000 ) % 12 == 6 :
signo = ' Perro '
elif (año - 2000 ) % 12 == 7 :
sign = ' Pig '
elif (año - 2000 ) % 12 == 8 :
signo = ' Rata '
elif (año - 2000 ) % 12 == 9 :
signo = ' Buey '
elif (año - 2000 ) % 12 == 10 :
signo = ' tigre '
más :
signo = ' Liebre '
print ( ' Tu signo del zodiaco: ' , signo) |
38531023257cca81534f64ee1af1cb5bb1146781 | Tynnovators/Differentilly_private_productivity_analyzer | /logistic.py | 4,857 | 3.703125 | 4 |
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
#Steps
#STEP 1: DATA READING
df = pd.read_csv("images_analyzed_productivity1.csv")
print(df.head())
plt.figure(1)
plt.scatter(df.Age, df.Productivity, marker='+', color='red')
plt.ylabel("Productivity")
plt.xlabel("Age")
#plt.show()
plt.figure(2)
plt.scatter(df.Time, df.Productivity, marker='+', color='red')
plt.ylabel("Productivity")
plt.xlabel("Time")
#plt.show()
plt.figure(3)
plt.scatter(df.Coffee, df.Productivity, marker='+', color='red')
plt.ylabel("Productivity")
plt.xlabel("Coffee")
#plt.show()
#PLot productivity values to see the split between Good and Bad
sizes = df['Productivity'].value_counts(sort = 1)
plt.figure(4)
plt.pie(sizes, shadow=True, autopct='%1.1f%%')
#plt.show()
#Good to know so we know the proportion of each label
#STEP 2: DROP IRRELEVANT DATA
#In our example, Images_Analyzed reflects whether it is good analysis or bad
#so should not include it. ALso, User number is just a number and has no inflence
#on the productivity, so we can drop it.
df.drop(['Images_Analyzed'], axis=1, inplace=True)
df.drop(['User'], axis=1, inplace=True)
#STEP 3: Handle missing values, if needed
#df = df.dropna() #Drops all rows with at least one null value.
#STEP 4: Convert non-numeric to numeric, if needed.
#Sometimes we may have non-numeric data, for example batch name, user name, city name, etc.
#e.g. if data is in the form of YES and NO then convert to 1 and 2
df.Productivity[df.Productivity == 'Good'] = 1
df.Productivity[df.Productivity == 'Bad'] = 2
print(df.head())
#STEP 5: PREPARE THE DATA.
#Y is the data with dependent variable, this is the Productivity column
Y = df["Productivity"].values #At this point Y is an object not of type int
#Convert Y to int
Y=Y.astype('int')
#X is data with independent variables, everything except Productivity column
# Drop label column from X as you don't want that included as one of the features
X = df.drop(labels = ["Productivity"], axis=1)
#print(X.head())
#STEP 6: SPLIT THE DATA into TRAIN AND TEST data.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=20)
#random_state can be any integer and it is used as a seed to randomly split dataset.
#By doing this we work with same test dataset evry time, if this is important.
#random_state=None splits dataset randomly every time
#print(X_train)
from sklearn.linear_model import LogisticRegression #Import the relevant model
model = LogisticRegression() #Create an instance of the model.
model.fit(X_train, y_train) # Train the model using training data
prediction_test = model.predict(X_test)
from sklearn import metrics
#Print the prediction accuracy
print ("Accuracy = ", metrics.accuracy_score(y_test, prediction_test))
#Test accuracy for various test sizes and see how it gets better with more training data
'''
#UNDERSTAND WHICH VARIABLES HAVE MOST INFLUENCE ON THE OUTCOME
# To get the weights of all the variables
print(model.coef_) #Print the coefficients for each independent variable.
#But it is not clear which one corresponds to what.
#SO let us print both column values and coefficients.
#.Series is a 1-D labeled array capable of holding any data type.
#Default index would be 0,1,2,3... but let us overwrite them with column names for X (independent variables)
weights = pd.Series(model.coef_[0], index=X.columns.values)
print("Weights for each variables is a follows...")
print(weights)
#+VE VALUE INDICATES THAT THE VARIABLE HAS A POSITIVE IMPACT'''
baseline = model.score(X_test,y_test)
import diffprivlib.models as dp
dp_clf = dp.LogisticRegression()
dp_clf.fit(X_train, y_train)
print("Differentially private test accuracy (epsilon=%.2f): %.2f%%" %
(dp_clf.epsilon, dp_clf.score(X_test, y_test) * 100))
dp_clf = dp.LogisticRegression(epsilon=float("inf"), data_norm=1e5)
dp_clf.fit(X_train, y_train)
print("Agreement between non-private and differentially private (epsilon=inf) classifiers: %.2f%%" % (dp_clf.score(X_test, model.predict(X_test)) * 100))
accuracy = []
epsilons = np.logspace(-3, 1, 500)
for eps in epsilons:
dp_clf = dp.LogisticRegression(epsilon=eps, data_norm=100)
dp_clf.fit(X_train, y_train)
accuracy.append(dp_clf.score(X_test, y_test))
import pickle
pickle.dump((epsilons, baseline, accuracy), open("lr_accuracy_500.p", "wb" ) )
epsilons, baseline, accuracy = pickle.load(open("lr_accuracy_500.p", "rb"))
plt.figure(6)
plt.semilogx(epsilons, accuracy, label="Differentially private")
plt.plot(epsilons, np.ones_like(epsilons) * baseline, dashes=[2,2], label="Non-private")
plt.title("Differentially private logistic regression accuracy")
plt.xlabel("epsilon")
plt.ylabel("Accuracy")
plt.ylim(0, 1)
plt.xlim(epsilons[0], epsilons[-1])
plt.legend(loc=3)
plt.show()
|
649f3b5e1841109c873e5ba5617104b10accea52 | e1ijah1/LeetCode | /Array/easy/219_contains_duplicate_II.py | 779 | 3.859375 | 4 |
from typing import List
"""
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
"""
def contains_nearby_duplicate(nums: List[int], k: int) -> bool:
length = len(nums)
if length == len(set(nums)) and length <= 1:
return False
d = dict()
for i in range(len(length)):
# check key in dict
if nums[i] in d and i - d[nums[i]] <= k:
return True
else:
d[nums[i]] = i
return False
|
853492fbace7279cf211e9ec1cdd26a2de00cde6 | cadolphs/advent_of_code_2020 | /day08/computer.py | 1,697 | 3.546875 | 4 | from typing import Iterable
from day08.instruction import Instruction, parse_program_to_instructions
class Computer:
def __init__(self, instructions: Iterable[Instruction]):
self._accumulator = 0
self._instr_ptr = 0
self._instructions = list(instructions)
@property
def accumulator(self):
return self._accumulator
@property
def instruction_pointer(self):
return self._instr_ptr
def advance_instruction_pointer(self, offset: int):
self._instr_ptr += offset
def increase_accumulator(self, incr: int):
self._accumulator += incr
def run(self):
positions_visited = set()
try:
while self.instruction_pointer not in positions_visited:
positions_visited.add(self.instruction_pointer)
instr = self._load_instruction()
instr.execute(self)
# If we are here, we hit an infinite loop
raise InfiniteLoopException(
f"Instruction at position {self.instruction_pointer} has been executed already."
)
except StopExecution:
pass
self.stop()
def _load_instruction(self):
try:
return self._instructions[self.instruction_pointer]
except IndexError:
raise StopExecution()
def stop(self):
pass
@classmethod
def from_program_string(cls, program: str) -> "Computer":
instructions = parse_program_to_instructions(program)
return cls(instructions)
class BufferOverrunError(Exception):
pass
class StopExecution(Exception):
pass
class InfiniteLoopException(Exception):
pass |
24e664acd61efd6967f640698f23abd162d3f584 | moaazelsayed1/mit6.0001-psets | /ps1a.py | 627 | 4.21875 | 4 | def main():
annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(
input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
target = 0.25 * total_cost
monthly_savings = (annual_salary / 12) * portion_saved
currunt_savings = 0.0
number_of_months = 0
while (currunt_savings < target):
currunt_savings += monthly_savings + ((currunt_savings * 0.04) / 12)
number_of_months += 1
print(f"Number of months: {number_of_months} ")
if __name__ == "__main__":
main()
|
6906267b76c903ece911ceebdcf65fd661855130 | hanhanwu/Hanhan-Machine-Learning-Model-Implementation | /opt_hill_climbing.py | 1,227 | 3.90625 | 4 | '''
Created on May 7, 2016
@author: hanhanwu
Hill climbing starts from a random solution, looking for better neighbor solutions
In this process, it walks in the most steep slope till it reached a flat point
This method will find local optimum but may not be global optimum
Need to run the method several times, hoping one could get close to the global optimum
'''
import random
def hill_climbing(domain, costf, dest, people, flights):
rs = [random.randint(domain[i][0], domain[i][1]) for i in range(len(domain))]
best_solution = None
best_result = costf(rs, dest, people, flights)
while True:
neighbors = []
for j in range(len(domain)):
if rs[j]-1 > domain[j][0]:
neighbors.append(rs[0:j]+[rs[j]-1]+rs[j+1:])
if rs[j]+1 < domain[j][1]:
neighbors.append(rs[0:j]+[rs[j]+1]+rs[j+1:])
for k in range(len(neighbors)):
cost = costf(neighbors[k], dest, people, flights)
if cost < best_result:
best_result = cost
best_solution = neighbors[k]
if cost == best_result:
return best_solution, best_result
|
59a1ccd7edefec97bc3fd0623ef0c62c4f1d55d1 | karansthr/data-structures-and-algorithms | /tests/binary_search_tree.py | 744 | 3.78125 | 4 | import unittest
from data_structures.trees.binary_search_tree import Tree
class BinarySearchTreeTest(unittest.TestCase):
def test(self):
bst = Tree()
values = [5, 3, 1, 4, 8, 6, 10]
'''
5
/ \
3 8
/ \ / \
1 4 6 10
'''
for value in values:
bst.insert(value)
self.assertEqual(list(bst.preorder()), [5, 3, 1, 4, 8, 6, 10])
self.assertEqual(list(bst.postorder()), [1, 4, 3, 6, 10, 8, 5])
self.assertEqual(list(bst.inorder()), [1, 3, 4, 5, 6, 8, 10])
self.assertEqual(list(bst.levelorder()), [5, 3, 8, 1, 4, 6, 10])
self.assertEqual(list(bst.get_leafs()), [1, 4, 6, 10])
|
06a4bd8504e8b186a823883a590a4dd332f1b853 | Vitosh/Python_personal | /OOP/000_PreviousExam/problem001.py | 1,326 | 3.546875 | 4 | import math
my_input = input()
my_list = my_input.split()
my_queue = []
action = ['+', '-', '*', '/']
result = 0
is_first = True
for m in my_list:
if m not in action:
my_queue.append(m)
else:
if m == "+":
while len(my_queue):
if is_first:
is_first = False
result = int(my_queue.pop(0))
else:
result = math.floor(result + int(my_queue.pop(0)))
if m == "-":
while len(my_queue):
if is_first:
is_first = False
result = int(my_queue.pop(0))
else:
result = math.floor(result - math.floor(int(my_queue.pop())))
if m == "/":
while len(my_queue):
if is_first:
is_first = False
result = int(my_queue.pop(0))
else:
result = math.floor(result / int(my_queue.pop()))
if m == "*":
while len(my_queue):
if is_first:
is_first = False
result = int(my_queue.pop(0))
else:
result = math.floor(result*int(my_queue.pop()))
print(result) |
e14232bf87d76c1e1eb66f9509d2188e88896243 | hemiaoio/learn-python | /lesson-05/money_challenge_v1.0.py | 627 | 3.953125 | 4 | """
功能:52周存钱挑战
版本:V1.0
日期:2018/8/22
"""
def main():
# 每周存入的金额,初始第一周为10
money_per_week = 10
# 第N周
week_index = 1
# 递增的金额
increase_money = 10
# 总共周数
total_weeks = 52
# 账户累计
sum_moeny = 0
while(week_index <= total_weeks):
sum_moeny += money_per_week
print('第{}周:存入{}元,账户累计{}元'.format(
week_index, money_per_week, sum_moeny))
money_per_week += increase_money
week_index += 1
if __name__ == '__main__':
main()
|
811591598c46945521d4ccb13c4d9bbc16df8fc3 | adam-weiler/GA-Reinforcing-Exercises | /exercise.py | 1,039 | 4.125 | 4 | classroom_seating = [
[None, "Pumpkin", None, None],
["Socks", None, "Mimi", None],
["Gismo", "Shadow", None, None],
["Smokey","Toast","Pacha","Mau"]
]
def find_free_seats(classroom):
new_classroom = classroom
for row_index, row in enumerate(classroom):
for col_index, column in enumerate(row):
if not column:
# print(f'Row {row_index+1} seat {col_index+1} is free.') #Question 1.
print(f'Row {row_index+1} seat {col_index+1} is free. Do you want to sit there? (y/n)') #Question 2.
sit_here = input()
# sit_here = 'y'
if sit_here == 'y':
print('What is your name?')
your_name = input()
# your_name = 'Bobby'
new_classroom[row_index][col_index] = your_name
return new_classroom
print(f'Original seating: {classroom_seating}\n')
new_classroom_seating = find_free_seats(classroom_seating)
print(f'\nNew seating: {new_classroom_seating}') |
2ac14954b5f14e3dde929731fae738bcaa7cacde | shubhamoli/solutions | /leetcode/medium/144-Binary_tree_preorder.py | 1,231 | 3.859375 | 4 | """
Leetcode #144
"""
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:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def helper(node):
if not node:
return
res.append(node.val)
helper(node.left)
helper(node.right)
helper(root)
print(res)
return res
def preorderTraversal_ITER(self, root: TreeNode) -> List[int]:
if not root:
return []
q = []
res = []
q.append(root)
while q:
curr = q.pop(0)
res.append(curr.val)
tmp = []
if curr.left:
tmp.append(curr.left)
if curr.right:
tmp.append(curr.right)
# add item in front of queue
q = tmp + q
return res
if __name__ == "__main__":
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
assert Solution().preorderTraversal_ITER(root) == [1, 2, 3]
|
309420872569a68bb0227f91639a595bd2269ee4 | Kkkb/hello-world | /liaoxuefeng_python/my_class.py | 542 | 3.65625 | 4 | # -*- coding: utf-8 -*-
'''
请把下面的Student对象的gender字段对外隐藏起来,
用get_gender()和set_gender()代替,并检查参数有效性
'''
class Student(object):
def __init__(self, name, gender):
self.name = name
self.__gender = gender
def get_gender(self):
return self.__gender
def set_gender(self, gender):
if (gender == 'male') or (gender == 'female'):
self.__gender = gender
else:
raise ValueError('bad gender')
bart = Student('Bart', 'male')
print(bart.get_gender())
bart.set_gender('female') |
203e393cf70629be4bfe649735c0d0829e34660c | AniketArora/oefProgramming | /mauritsOefeningen/week1/oef4.py | 370 | 3.796875 | 4 | int1 = 45
int2 = 60
print('decimaal is: ' + str(int1) + ' en ' + str(int2))
print ('hex is: ' + hex(int1) + ' en ' + hex(int2)) #hex() wet het getal om naar een hexadecimaal
print('oct is: ' + oct(int1) + ' en ' + oct(int2)) #oct() zet het getal om naar een octadecimaal
print ('binair is: ' + bin(int1) + ' en ' + bin(int2)) #bin() zet het getal om naar binair
|
01e11c1f3052128a9b66ea709caf359d790d9288 | AnujRuhela7/Python-Tutorial | /PrintNumSquare.py | 111 | 4.15625 | 4 | n = int(input("Enter how many number you want to print : "))
for n in range(n):
print((n+1)**2,end = '\t')
|
ceb77357e8d5f2d8144860cf5d5254ae8202b575 | hjabbott1089/Pelican-tamer | /loops.py | 401 | 3.875 | 4 | for i in range(1, 21, 2):
print(i, end=' ')
print()
for t in range(0, 101, 10):
print(t, end=' ')
print()
for x in range(20, 0, -1):
print(x, end=' ')
print()
STARS = int(input('Enter the amount of stars you want: '))
for x in range(STARS):
print("*", end='')
print()
for z in range(STARS + 1):
for j in range(z):
print("*", end=' ')
print()
|
032b4c8e38b4c47cb246729167940f4d531e2ac4 | Systematiik/Python-The-Hard-Way | /ex20.py | 951 | 4.125 | 4 | from sys import argv
script, input_file = argv
#this function applies a variable f to print everything that f owns
def print_all(f):
print(f.read())
#the seek function sets the variable f to the very first byte
def rewind(f):
f.seek(0)
#this function prints out one line from variable f
def print_a_line(line_count, f):
print(line_count, f.readline())
current_file = open(input_file)
#this prints the file being opened
print("First let's print the whole file:\n"); print_all(current_file)
#this function points the file to the very first byte
#essentially setting it to the top of the file
print("Now let's rewind, kind of like a tape."); rewind(current_file)
print("\nLet's print three lines:\n")
current_line = 1; print_a_line(current_line, current_file)
current_line = current_line + 1; print_a_line(current_line, current_file)
current_line = current_line + 1; print_a_line(current_line, current_file) |
1dae34c514f4d9bc6ab58a490e924d83a290d859 | CorySpitzer/tron-engine | /engines/board.py | 4,905 | 3.6875 | 4 | """
Game logic for Tron game.
Robert Xiao, Feb 2 2010
minor edits by Jim Mahoney, Jan 2014
"""
import random
class Board:
def __init__(self, w, h, start=None, layout=None, outerwall=True):
''' w: width
h: height
start:
"symrand" for symmetrically random (default)
"random" for totally random
((x1,y1), (x2,y2)) to put p1 at (x1,y1) and p2 at (x2,y2)
layout:
None to have an empty board
a list of strings, one per row of the board, which show the initial
placement of walls and optionally players '''
self.w = w
self.h = h
if layout is not None and start is None:
p1loc = None
p2loc = None
for y,row in enumerate(layout):
for x,c in enumerate(row):
if c == '1':
p1loc = (x,y)
elif c == '2':
p2loc = (x,y)
if p1loc is None and p2loc is None:
self.start = "symrand"
elif p1loc is not None and p2loc is not None:
self.start = (p1loc, p2loc)
else:
raise ValueError("Board is missing a player position!")
elif start is None:
self.start = "symrand"
else:
self.start = start
if layout is None:
self.layout = [' '*w]*h
else:
self.layout = layout
if outerwall:
self.w += 2
self.h += 2
self.layout = ['#'*self.w] + ['#'+row+'#' for row in self.layout] + ['#'*self.w]
if isinstance(self.start, (tuple, list)):
p1, p2 = self.start
self.start = (p1[0]+1, p1[1]+1), (p2[0]+1, p2[1]+1)
def BoardFile(fn):
f = open(fn, "rU")
line = f.readline().split()
w,h = int(line[0]), int(line[1])
layout = []
for i in xrange(h):
layout.append(f.readline().strip('\n'))
return Board(w, h, layout=layout, outerwall=False)
class GameBoard:
MOVES = [None, (0, -1), (1, 0), (0, 1), (-1, 0)]
def __init__(self, template):
w = self.width = template.w
h = self.height = template.h
self.board = map(list, template.layout)
self.board_trail = [list('-')*w for i in xrange(h)]
if template.start in ("symrand", "random"):
free_squares = [(x,y) for x in xrange(w) for y in xrange(h) if self.board[y][x]==' ']
for i in xrange(10):
x,y = random.choice(free_squares)
self.p1loc = x,y
if template.start == "symrand":
self.p2loc = w-1-x, h-1-y
else:
self.p2loc = random.choice(free_squares)
if self.p1loc != self.p2loc and self.board[self.p1loc[1]][self.p1loc[0]] == ' '\
and self.board[self.p2loc[1]][self.p2loc[0]] == ' ':
break
else:
raise Exception("Couldn't place players randomly.")
else:
self.p1loc, self.p2loc = template.start
self.start = self.p1loc, self.p2loc
self.board[self.p1loc[1]][self.p1loc[0]] = '1'
self.board[self.p2loc[1]][self.p2loc[0]] = '2'
self.diff = None
def project(self, pos, delta):
return pos[0]+delta[0], pos[1]+delta[1]
def isfree(self, pos):
return (0 <= pos[0] < self.width and 0 <= pos[1] < self.height) and self.board[pos[1]][pos[0]] == ' '
def move(self, p1move, p2move):
p1loc = self.project(self.p1loc, self.MOVES[p1move])
p2loc = self.project(self.p2loc, self.MOVES[p2move])
self.board_trail[self.p1loc[1]][self.p1loc[0]] = ' NESW'[p1move]
self.board_trail[self.p2loc[1]][self.p2loc[0]] = ' NESW'[p2move]
p1lost = False
p2lost = False
if not self.isfree(p1loc):
p1lost = True
if not self.isfree(p2loc):
p2lost = True
outcome = None
if (p1lost and p2lost) or p1loc == p2loc:
outcome = 'D'
p1move = p2move = 10 # draw
elif p1lost:
outcome = '2'
p1move = 9 # lose
p2move = 8 # win
elif p2lost:
outcome = '1'
p1move = 8
p2move = 9
self.board[self.p1loc[1]][self.p1loc[0]] = '.'
self.board[self.p2loc[1]][self.p2loc[0]] = '*'
self.board[p1loc[1]][p1loc[0]] = chr(128+p1move)
self.board[p2loc[1]][p2loc[0]] = chr(160+p2move)
self.diff = self.p1loc, self.p2loc, p1loc, p2loc
self.p1loc = p1loc
self.p2loc = p2loc
return outcome
def getdims(self):
return '%s %s'%(self.width, self.height)
def getboard(self):
return [''.join(row) for row in self.board]
|
8794bb053a781e1747b737cb7336286ba00ec5e5 | InfiniteWing/Solves | /zerojudge.tw/c087.py | 849 | 3.703125 | 4 | import math
prime=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181]
def Prime(a,b):
global prime
if(min(a,b)==1):
return False
for p in prime:
if(a%p==0 and b%p==0):
return False
for p in prime:
if(a%p==0):
while(a%p==0):
a=a/p
if(b%p==0):
while(b%p==0):
b=b/p
if(min(a,b)==1):
return True
if(max(a,b)%min(a,b)==0):
return False
return True
def C(n):
sum=0
for i in range(n):
sum+=i
return sum
while 1:
n=int(input())
if(n==0):
break
data=[]
for i in range(n):
data.append(int(input()))
count=0
for i in range(n):
for j in range(i+1,n):
if(Prime(data[i],data[j])):
count+=1
if(count>0):
pi2=((C(n)*6))/(count)
print("%.6f"%(math.sqrt(pi2)))
else:
print("No estimate for this data set.")
|
7fe3611e3d9980a6ebd472db6ab887b9b4a076cd | verdatestudo/Algorithms_Khan | /selection_sort.py | 1,130 | 4.46875 | 4 | '''
Algorithms from Khan Academy - selection sort
https://www.khanacademy.org/computing/computer-science/algorithms
Last Updated: 2016-May-11
First Created: 2016-May-11
Python 2.7
Chris
'''
def selection_sort(my_list):
'''
There are many different ways to sort the cards.
Here's a simple one, called selection sort, possibly similar to how you sorted the cards above:
Find the smallest card. Swap it with the first card.
Find the second-smallest card. Swap it with the second card.
Find the third-smallest card. Swap it with the third card.
Repeat finding the next-smallest card, and swapping it into the correct position until the array is sorted.
'''
if len(my_list) == 1:
return my_list
small = float('inf')
for idx, item in enumerate(my_list):
if item < small:
small = item
small_idx = idx
my_list[small_idx] = my_list[0]
my_list[0] = small
return [my_list[0]] + selection_sort(my_list[1:])
print selection_sort([1, 4, 21, 3, 8, 12, 99, 2, 2, -1]), [-1, 1, 2, 2, 3, 4, 8, 12, 21, 99]
|
79b0510c6eb2f97779887d14408712fd7020b9f6 | Pavithra612/DAY-3_Assignment-3-4 | /assignment4.py | 540 | 4.21875 | 4 | # Write a program to implement insertion sort
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
n = int(input('enter numbeer of element : '))
arr = []
for i in range(0,n):
element = int(input())
arr.append(element)
print(f'list you entered is {arr}')
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print (arr[i]) |
2dbd3c06503ee05ca630704bf94c7b61abb1a6de | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4380/codes/1734_2495.py | 185 | 4.0625 | 4 | n=int(input("Digite um numero: "))
while (n!=-1):
if (n%2==0):
mensagem = "PAR"
print(mensagem)
else:
mensagem = "IMPAR"
print(mensagem)
n=int(input("Digite um numero: "))
|
690f43ebae6f4957d2a439f127d512cbd3f49cc1 | mwaskom/seaborn | /examples/timeseries_facets.py | 1,023 | 3.5625 | 4 | """
Small multiple time series
--------------------------
_thumb: .42, .58
"""
import seaborn as sns
sns.set_theme(style="dark")
flights = sns.load_dataset("flights")
# Plot each year's time series in its own facet
g = sns.relplot(
data=flights,
x="month", y="passengers", col="year", hue="year",
kind="line", palette="crest", linewidth=4, zorder=5,
col_wrap=3, height=2, aspect=1.5, legend=False,
)
# Iterate over each subplot to customize further
for year, ax in g.axes_dict.items():
# Add the title as an annotation within the plot
ax.text(.8, .85, year, transform=ax.transAxes, fontweight="bold")
# Plot every year's time series in the background
sns.lineplot(
data=flights, x="month", y="passengers", units="year",
estimator=None, color=".7", linewidth=1, ax=ax,
)
# Reduce the frequency of the x axis ticks
ax.set_xticks(ax.get_xticks()[::2])
# Tweak the supporting aspects of the plot
g.set_titles("")
g.set_axis_labels("", "Passengers")
g.tight_layout()
|
d755be3a8232b04e6a2c799a1dbcb11effb98236 | lofues/LeetCode-Excerise | /515_在每个树行中找最大值.py | 934 | 3.8125 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def largestValues(self, root: TreeNode) -> List[int]:
if root and not isinstance(root,TreeNode):
return None
if not root:
return None
queue = [(root,1)]
ret_list = []
while queue:
cur_node,cur_level = queue.pop(0)
if cur_node:
left,right = cur_node.left,cur_node.right
if len(ret_list) < cur_level:
ret_list.append([cur_node.val])
else:
ret_list[-1].append(cur_node.val)
if left:
queue.append((left,cur_level + 1))
if right:
queue.append((right,cur_level + 1))
return [max(x) for x in ret_list] |
19d5087f1844a42ac097f21e2d86c9322847b3ef | Kunwar-Yuvraj/CBSE-Class-12-Project-Programs | /project 5.py | 514 | 3.578125 | 4 | '''
Project question - Removes all the line that contains character 'a' in a file
and write it to another file.
'''
# solution:-
file1=open("inputfile.txt",'r+')
data1=file1.readlines()
file1.close()
file1=open("inputfile.txt",'w')
data2=[]
file2=open("outputfile.txt",'w')
data3=[]
for i in data1:
if "a"in i:
data3=data3+[i]
else:
data2=data2+[i]
file1.writelines(data2)
file2.writelines(data3)
file1.close()
file2.close() |
1295bf144eaff793f584678eb37052ed37f85139 | chenxu0602/LeetCode | /1460.make-two-arrays-equal-by-reversing-sub-arrays.py | 1,836 | 3.84375 | 4 | #
# @lc app=leetcode id=1460 lang=python3
#
# [1460] Make Two Arrays Equal by Reversing Sub-arrays
#
# https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/description/
#
# algorithms
# Easy (72.52%)
# Likes: 261
# Dislikes: 63
# Total Accepted: 34.6K
# Total Submissions: 47.8K
# Testcase Example: '[1,2,3,4]\n[2,4,1,3]'
#
# Given two integer arrays of equal length target and arr.
#
# In one step, you can select any non-empty sub-array of arr and reverse it.
# You are allowed to make any number of steps.
#
# Return True if you can make arr equal to target, or False otherwise.
#
#
# Example 1:
#
#
# Input: target = [1,2,3,4], arr = [2,4,1,3]
# Output: true
# Explanation: You can follow the next steps to convert arr to target:
# 1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3]
# 2- Reverse sub-array [4,2], arr becomes [1,2,4,3]
# 3- Reverse sub-array [4,3], arr becomes [1,2,3,4]
# There are multiple ways to convert arr to target, this is not the only way to
# do so.
#
#
# Example 2:
#
#
# Input: target = [7], arr = [7]
# Output: true
# Explanation: arr is equal to target without any reverses.
#
#
# Example 3:
#
#
# Input: target = [1,12], arr = [12,1]
# Output: true
#
#
# Example 4:
#
#
# Input: target = [3,7,9], arr = [3,7,11]
# Output: false
# Explanation: arr doesn't have value 9 and it can never be converted to
# target.
#
#
# Example 5:
#
#
# Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]
# Output: true
#
#
#
# Constraints:
#
#
# target.length == arr.length
# 1 <= target.length <= 1000
# 1 <= target[i] <= 1000
# 1 <= arr[i] <= 1000
#
#
#
# @lc code=start
from collections import Counter
class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
return Counter(target) == Counter(arr)
# @lc code=end
|
d93854bd8843fa616dedc7eb468595000e4c50ec | stevegcarpenter/hackerrank-problems-python | /nested-lists.py | 315 | 3.9375 | 4 | #!/usr/bin/env python3
# https://www.hackerrank.com/challenges/nested-list/problem
n = int(input())
students = [[input(), float(input())] for _ in range(n)]
nextlowest = sorted(list(set([score for name, score in students])))[1]
print('\n'.join([name for name, score in sorted(students) if score == nextlowest]))
|
408ca45ecbf84e4f894307966e073611f2106499 | Derfies/pglib | /pglib/generators/recursivemaze.py | 3,547 | 3.984375 | 4 | import random
import numpy as np
from regionbase import RegionBase
TILE_EMPTY = 0
TILE_CRATE = 1
class RecursiveMaze(RegionBase):
"""
Taken from: https://arcade.academy/examples/maze_recursive.html
"""
def create_empty_grid(self, width, height, default_value=TILE_EMPTY):
""" Create an empty grid. """
return np.full((width, height), default_value)
def create_outside_walls(self, maze):
""" Create outside border walls."""
# Create left and right walls
for row in range(len(maze)):
maze[row][0] = TILE_CRATE
maze[row][len(maze[row]) - 1] = TILE_CRATE
# Create top and bottom walls
for column in range(1, len(maze[0]) - 1):
maze[0][column] = TILE_CRATE
maze[len(maze) - 1][column] = TILE_CRATE
def make_maze_recursive_call(self, maze, top, bottom, left, right):
"""
Recursive function to divide up the maze in four sections
and create three gaps.
Walls can only go on even numbered rows/columns.
Gaps can only go on odd numbered rows/columns.
Maze must have an ODD number of rows and columns.
"""
# Figure out where to divide horizontally
start_range = bottom + 2
end_range = top - 1
y = random.randrange(start_range, end_range, 2)
# Do the division
for column in range(left + 1, right):
maze[column][y] = TILE_CRATE
# Figure out where to divide vertically
start_range = left + 2
end_range = right - 1
x = random.randrange(start_range, end_range, 2)
# Do the division
for row in range(bottom + 1, top):
maze[x][row] = TILE_CRATE
# Now we'll make a gap on 3 of the 4 walls.
# Figure out which wall does NOT get a gap.
wall = random.randrange(4)
if wall != 0:
gap = random.randrange(left + 1, x, 2)
maze[gap][y] = TILE_EMPTY
if wall != 1:
gap = random.randrange(x + 1, right, 2)
maze[gap][y] = TILE_EMPTY
if wall != 2:
gap = random.randrange(bottom + 1, y, 2)
maze[x][gap] = TILE_EMPTY
if wall != 3:
gap = random.randrange(y + 1, top, 2)
maze[x][gap] = TILE_EMPTY
# If there's enough space, to a recursive call.
if top > y + 3 and x > left + 3:
self.make_maze_recursive_call(maze, top, y, left, x)
if top > y + 3 and x + 3 < right:
self.make_maze_recursive_call(maze, top, y, x, right)
if bottom + 3 < y and x + 3 < right:
self.make_maze_recursive_call(maze, y, bottom, x, right)
if bottom + 3 < y and x > left + 3:
self.make_maze_recursive_call(maze, y, bottom, left, x)
def make_maze_recursion(self, maze_width, maze_height):
""" Make the maze by recursively splitting it into four rooms. """
maze = self.create_empty_grid(maze_width, maze_height)
# Fill in the outside walls
self.create_outside_walls(maze)
# Start the recursive process
self.make_maze_recursive_call(maze, maze_height - 1, 0, 0, maze_width - 1)
return maze
def _run(self, region):
# TODO: Want to embed this a little so run automatically gets called
# with the padding region.
#region = self.get_padding_region(region)
region.matrix = self.make_maze_recursion(region.width, region.height)
return [region] |
66c5feb7b71b3bf0338dfd558ce704777d5c7679 | knee-rel/CSCI-Lab-3 | /lab3c.py | 1,423 | 4.125 | 4 | # Nirel Marie M. Ibarra
# 192468
# March 15, 2021
# I have not discussed the Python language code in my program
# with anyone other than my instructor or the teaching assistants
# assigned to this course
# I have not used Python language code obatained from another student
# or any other unauthorized source, either modified or unmodified
# If any Python language code or documentation used in my program
# was obtained from another source, such as a textbook or website,
# that has clearly noted with a proper ciration in the comments
# of my program
#closest answer
#infinitely asks prompt unless number is outside the range
def negate(a):
neg = -a
return neg
def add(a, b):
total = a + b
return total
def maximum(a, b, c):
if a > b and a > c:
big = a
elif b > a and b > c:
big = b
elif c > a and c > b:
big = c
return big
while True:
prompt = input()
if prompt == "negate":
number = int(input())
print(negate(number))
continue
elif prompt == "add":
number_a = int(input())
number_b = int(input())
print(add(number_a, number_b))
continue
elif prompt == "maximum":
number_a = int(input())
number_b = int(input())
number_c = int(input())
print(maximum(number_a, number_b, number_c))
continue
elif prompt == "stop":
break
|
b16dbc5d0a85a90e5d4d34a97f7996cddf9505e9 | kjh03160/Tech_Course_1st_Test | /4.py | 1,955 | 3.703125 | 4 | def solution(infos, actions):
answer = []
LOGIN = False
ADD = []
for i in actions:
# if 'LOGIN' in i:
# if LOGIN == True or not i[6:] in infos:
# answer.append(False)
# elif i[6:] in infos:
# LOGIN = True
# answer.append(True)
if LOGIN == False:
if 'LOGIN' in i:
if i[6:] in infos:
LOGIN = True
answer.append(True)
continue
answer.append(False)
elif LOGIN == True:
if 'LOGIN' in i:
answer.append(False)
continue
elif 'ADD' in i:
a = i.split()
ADD.append(int(a[-1]))
answer.append(True)
continue
elif 'ORDER' in i:
if len(ADD) != 0:
ADD = []
answer.append(True)
continue
answer.append(False)
# if 'ADD' in i:
# a = i.split()
# if a[-1].isdigit():
# ADD.append(a[-1])
# answer.append(True)
# else:
# answer.append(False)
# elif 'ORDER' in i:
# if len(ADD) > 0:
# answer.append(True)
# ADD = []
# else:
# answer.append(False)
# else:
# answer.append(False)
return answer
infos = ["kim password", "lee abc"]
actions = [
"ADD 30",
"LOGIN kim abc",
"LOGIN lee password",
"LOGIN kim password",
"LOGIN kim password",
"ADD 30",
"ORDER",
"ORDER",
"ADD 40",
"ADD 50"
]
print(solution(infos, actions))
print("[false, false, false, true, false, true, true, false, true, true]") |
92dba5b21f96b4c4fb316380dc8d1aae532a87b1 | Bharathi-raja-pbr/Python-if-else-exercises- | /2b3.py | 206 | 4.3125 | 4 | # to find the largest of two numbers
n1=int(input("enter number 1"))
n2=int(input("enter number2"))
if n1 > n2 :
print(f"{n1} is the greatest integer")
else:
print(f"{n2} is the greatest number")
|
6e026dbd2736d40281a9223d5a784c35e54496b8 | luozhiping/leetcode | /middle/longest_palindromic_subsequence.py | 972 | 3.640625 | 4 | # 516. 最长回文子序列
# https://leetcode-cn.com/problems/longest-palindromic-subsequence/
class Solution(object):
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
length = len(s)
# bp = [[0 for _ in range(length)] for _ in range(length)]
last = [0 for _ in range(length)]
current = [0 for _ in range(length)]
# result = 1
for i in range(length-1, -1, -1):
current[i] = 1
for j in range(i+1, length):
if s[j] == s[i]:
current[j] = last[j-1] + 2
# result = max(result, bp[i][j])
else:
current[j] = max(last[j], current[j-1])
current, last = last, current
return last[length-1]
s = Solution()
assert s.longestPalindromeSubseq("bbbab") == 4
assert s.longestPalindromeSubseq("cbbd") == 2 |
29734f813540db85db28e2598f3e5bb2873797d8 | 666sempron999/Abramyan-tasks- | /If(30)/6.py | 228 | 3.578125 | 4 | '''
If6 . Даны два числа. Вывести большее из них.
'''
A = int(input("Введите A: "))
B = int(input("Введите B: "))
if A > B:
print(1)
elif B > A:
print(2)
else:
pass
|
300467ba8be04f63d0259f23cd578d3ad2934364 | mrtuanphong/learning-python | /sqlite3/customers/select.py | 416 | 3.734375 | 4 | import sqlite3
# Connect to database:
conn = sqlite3.connect("customer.db")
# Create a cursor
c = conn.cursor()
# Query the database
c.execute("SELECT rowid, * FROM customers")
#c.fetchone()
#c.fetchmany(3)
#c.fetchall()
items = c.fetchall()
#print(items)
for item in items:
print(item)
#print(item[0], '\t', item[1], '\t', item[2])
# Commit our command
conn.commit()
# Close our connection
conn.close() |
8da8f8c65adf5fdc5ae1fd2727711dc91f6c02d8 | shinespark/algorithm-with-python | /01_recursive_difinition/fibonacci.py | 736 | 3.890625 | 4 | # coding: utf-8
import time
# 二重再帰
def fib(n):
if n == 0 or n == 1:
return 1
return fib(n - 1) + fib(n - 2)
# 末尾再帰
def fib2(n, a1=1, a2=0):
if n < 1:
return a1
return fib2(n - 1, a1 + a2, a1)
# 繰り返し
def fib3(n):
a1, a2 = 1, 0
while n > 0:
a1, a2 = a1 + a2, a1
n -= 1
return a1
if __name__ == "__main__":
start = time.clock()
print(fib(10))
end = time.clock()
print("{0:f}".format(end - start) + 's')
start = time.clock()
print(fib2(10))
end = time.clock()
print("{0:f}".format(end - start) + 's')
start = time.clock()
print(fib3(10))
end = time.clock()
print("{0:f}".format(end - start) + 's')
|
d079e376da7e2002ea2b71cd7477df9d72688413 | AlexandrZhytenko/solve_tasks | /popular_words.py | 822 | 3.90625 | 4 | def popular_words(text, words):
dict_words = dict((key, value) for (key, value) in zip(words, len(words) * [0]))
for i in text.split():
if i.lower() in dict_words:
dict_words[i.lower()] += 1
return dict_words
# def popular_words(text, words):
# lower_count = text.lower().split().count
# return {word: lower_count(word) for word in words}
# def popular_words(text, words):
# from collections import Counter
# import re
# count = Counter(re.split("[^a-z']+", text.lower()))
# return {word: count[word] for word in words}
if __name__ == "__main__":
text = '''When I was One
I had just begun
When I was Two
I was nearly new
'''
words = ['i', 'was', 'three', 'near']
print popular_words(text, words) |
417f1134df2cd2f9c03567d5cf93776ce82c9bc9 | pravsp/problem_solving | /Python/LinkedList/solution/deletenode.py | 868 | 3.609375 | 4 | """Delete node solution except tail."""
import __init__
from singlyLinkedList import SinglyLinkedList
from utils.ll_util import LinkedListUtil
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead
"""
nextnode = node.getNextNode()
if not nextnode:
del node
return
node.data = nextnode.data
node.setNextNode(nextnode.getNextNode())
if __name__ == '__main__':
print('Deleting a node form linked list')
llist = SinglyLinkedList()
LinkedListUtil().constructList(llist)
llist.printList()
dataToDelete = input("Enter Node data to delete:")
node = llist.getNode(int(dataToDelete))
# llist.delNode(int(dataToDelete))
Solution().deleteNode(node)
llist.printList()
|
bf7dc609bee8abcb297665e991d1e7191f349040 | vladcipariu91/DSA-Problems | /chapter_3/heap/heap.py | 2,417 | 3.796875 | 4 | # min heap
class Heap:
def __init__(self, initial_size):
self.cbt = [None for _ in range(initial_size)]
self.next_index = 0
def insert(self, data):
self.cbt[self.next_index] = data
self.up_heapify()
self.next_index += 1
def up_heapify(self):
child_index = self.next_index
while child_index >= 1:
parent_index = (child_index - 1) // 2
parent = self.cbt[parent_index]
child = self.cbt[child_index]
if parent > child:
self.cbt[parent_index] = child
self.cbt[child_index] = parent
child_index = parent_index
def remove(self):
if self.size() == 0:
return None
else:
to_remove = self.cbt[0]
self.swap()
self.next_index -= 1
self.down_heapify()
return to_remove
def swap(self):
aux = self.cbt[0]
self.cbt[0] = self.cbt[self.next_index - 1]
self.cbt[self.next_index - 1] = aux
def down_heapify(self):
current_index = 0
while current_index < self.next_index:
current = self.cbt[current_index]
left = None
right = None
left_index = 2 * current_index + 1
if left_index < self.next_index:
left = self.cbt[left_index]
right_index = 2 * current_index + 2
if right_index < self.next_index:
right = self.cbt[right_index]
min_element = current
if right is not None:
min_element = min(current, right)
if left is not None:
min_element = min(min_element, left)
if min_element == current:
return
if min_element == left:
self.cbt[current_index] = left
self.cbt[left_index] = current
current_index = left_index
elif min_element == right:
self.cbt[current_index] = right
self.cbt[right_index] = current
current_index = right_index
def size(self):
return self.next_index
heap = Heap(10)
heap.insert(10)
print(heap.cbt)
heap.insert(7)
print(heap.cbt)
heap.insert(11)
print(heap.cbt)
heap.insert(5)
print(heap.cbt)
heap.remove()
print(heap.cbt)
heap.remove()
print(heap.cbt)
|
7c7e139997884bbb71eb5edb1ea09b6fa5e48ba6 | silastsui/advent-of-code-2017 | /8.py | 2,392 | 3.578125 | 4 | class Instruction(object):
def __init__(self, var, change, c_var, condition):
self.var = var
self.change = change
self.c_var = c_var
self.condition = condition
def clean_instr(filename):
"""
Args:
filename (str): filename
"""
with open(filename) as f:
lines = []
for line in f.readlines():
line = line.split()
if line[1] == 'inc':
change = int(line[2])
else:
change = -int(line[2])
c_var = line[4]
condition = line[5:]
lines.append(Instruction(line[0], change, c_var, condition))
return lines
def eval_condition(c_var, condition):
"""
Helper function to evaluate instruction conditions
"""
condition[1] = int(condition[1])
if condition[0] == '>':
return registers[c_var] > condition[1]
elif condition[0] == '<':
return registers[c_var] < condition[1]
elif condition[0] == '>=':
return registers[c_var] >= condition[1]
elif condition[0] == '<=':
return registers[c_var] <= condition[1]
elif condition[0] == '==':
return registers[c_var] == condition[1]
elif condition[0] == '!=':
return registers[c_var] != condition[1]
def dec8a(instr):
"""
Args:
instr (list): list of instruction objects
"""
registers = {}
for instr in data:
if instr.var not in registers.keys():
registers[instr.var] = 0
if instr.c_var not in registers.keys():
registers[instr.c_var] = 0
if eval_condition(instr.c_var, instr.condition):
registers[instr.var] += instr.change
if max(registers.values()) > max_value:
max_value = max(registers.values())
return max(registers.values())
def dec8b(instr):
"""
Args:
instr (list): list of instruction objects
"""
registers = {}
max_value = 0
for instr in data:
if instr.var not in registers.keys():
registers[instr.var] = 0
if instr.c_var not in registers.keys():
registers[instr.c_var] = 0
if eval_condition(instr.c_var, instr.condition):
registers[instr.var] += instr.change
if max(registers.values()) > max_value:
max_value = max(registers.values())
return max_value
|
779bb7fb038868b508f80d35a4b9d39c120f0ebc | jnucanwin/LeetCode | /LeetCode/树/257. 二叉树的所有路径.py | 1,275 | 3.71875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def binaryTreePaths(self, root):
s = []
result = []
r = None
if not root:
return []
p = root
while p or s:
if p:
s.append(p)
p = p.left
else:
p = s[-1]
if p.right and p.right != r:
p = p.right
s.append(p)
p = p.left
else:
p = s[-1]
if not p.left and not p.right:
result.append([node.val for node in s])
p = s.pop()
r = p
p = None
res = []
for r in result:
temp = ""
for p in r:
temp = temp + str(p) + "->"
res.append(temp[:-2])
return res
a = TreeNode(1)
b = TreeNode(2)
c= TreeNode(3)
d= TreeNode(5)
# e = TreeNode(4)
# f= TreeNode(7)
# g = TreeNode(9)
# h = TreeNode(3)
# i = TreeNode(5)
a.left = b
a.right = c
b.right = d
s = Solution()
s.binaryTreePaths(a) |
d517ea380f21af405ea276c1510c6e2c0a2d8407 | hyejun18/daily-rosalind | /prepare/template_scripts/algorithmic-heights/MER.py | 735 | 3.9375 | 4 | ##################################################
# Merge Two Sorted Arrays
#
# http://rosalind.info/problems/MER/
#
# Given: A positive integer n <= 10^5 and a sorted
# array A[1..n] of integers from -10^5 to 10^5,
# a positive integer m <= 10^5 and a sorted array
# B[1..m] of integers from -10^5 to 10^5.
#
# Return: A sorted array C[1..n+m] containing all
# the elements of A and B.
#
# AUTHOR : dohlee
##################################################
# Your imports here
# Your codes here
if __name__ == '__main__':
# Load the data.
with open('../../datasets/rosalind_MER.txt') as inFile:
pass
# Print output
with open('../../answers/rosalind_MER_out.txt', 'w') as outFile:
pass
|
024d199bc065a6a86d3e21d890e996f4348eea18 | adelgar/python-for-everybody-book | /Chapter 10 (Tuples)/timeofday.py | 653 | 3.546875 | 4 | while True:
fname = input('Enter a file name: ')
try:
if fname == 'done':
break
else:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
counts = dict()
for line in fhand:
line = line.rstrip()
if line.startswith('From'):
words = line.split()
if not words[0] == 'From:':
hour = words[5].split(':')
if hour[0] not in counts:
counts[hour[0]] = 1
else:
counts[hour[0]] += 1
#counts[words[1]] = counts.get(words[1], 0) + 1
lst = list()
for key, val in list(counts.items()):
lst.append((key, val))
lst.sort(reverse=False)
for key, val in lst:
print(key, val)
print('\n')
|
62e92bb62b32e80aae2925e3af09e76f1b93ba44 | zhangwang0537/LeetCode-Notebook | /source/Clarification/Array/896.单调数列.py | 632 | 3.734375 | 4 | # 如果数组是单调递增或单调递减的,那么它是单调的。
#
# 如果对于所有 i <= j,A[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= j,A[i]> = A[j],那么数组 A 是单调递减的。
#
# 当给定的数组 A 是单调数组时返回 true,否则返回 false。
# 使用all()函数
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
return (all(A[i] <= A[i+1] for i in range(len(A) - 1)) or
all(A[i] >= A[i+1] for i in range(len(A) - 1)))
# 时间复杂度:O(N)N是A的长度。遍历了两次。
# 空间复杂度:O(1)。 |
78354023e9e6585af1c01a4d2ddcf6174e0af737 | hridayjham/A2 | /A2/src/BodyT.py | 2,132 | 4.03125 | 4 | ## @file BodyT.py
# @author Hriday Jham
# @brief Contains the BodyT type to represent the object body
# @date 02/16/2021
from Shape import Shape
from math import pow
## @brief BodyT is used to represent the Body of an object.
class BodyT(Shape):
## @brief constructor for class BodyT. BodyT is a set of shapes
# @param three sequences of real numbers
def __init__(self, x, y, m):
if not (len(x) == len(y) and len(y) == len(m)):
raise ValueError("Lengths of inputs are invalid")
else:
for i in m:
if i <= 0:
raise ValueError("m values cannot be 0 or negative")
self.cmx = self.__cm(x, m)
self.cmy = self.__cm(y, m)
self.m = sum(m)
self.moment = self.__mmom(x, y, m)
self.moment -= sum(m) * (pow(self.__cm(x, m), 2) + pow(self.__cm(y, m), 2))
## @brief used to calculate centre of mass
# @param two sequences of real numbers
# @return Real number denoting centre of mass
def __cm(self, z, m):
temp = 0
for i in range(len(m)):
temp += z[i] * m[i]
return temp / sum(m)
## @brief used to calculate moment of inertia
# @param three sequences of real numbers
# @return Real number used to calculate moment of inertia
def __mmom(self, x, y, m):
temp = 0
for i in range(len(m)):
temp += m[i] * (pow(x[i], 2) + pow(y[i], 2))
return temp
## @brief return the centre of mass along x axis
# @return Real number denoting centre of mass along x axis
def cm_x(self):
return self.cmx
## @brief return the centre of mass along y axis
# @return Real number denoting centre of mass along y axis
def cm_y(self):
return self.cmy
## @brief return the mass of the Body
# @return real number denoting the mass of the body
def mass(self):
return self.m
## @brief return the moment of inertia of the Body
# @return real number denoting the moment of inertia of the body
def m_inert(self):
return self.moment
|
619b22898c8b4c21682eba0b95c86f67e456c99f | Software05/Github | /Modulo-for/app1.py | 456 | 4.3125 | 4 | # break - ejemplo
print("La instrucción de ruptura:")
for i in range(1,6):
if i == 3:
break
print("Dentro del ciclo.", i)
print("Fuera del ciclo.")
# continua - ejemplo
print("\nLa instrucción continue:")
for i in range(1,6):
if i == 3:
continue
print("Dentro del ciclo.", i)
print("Fuera del ciclo.")
#https://edube.org/learn/programming-essentials-in-python-part-1-spanish/control-de-ciclo-en-python-break-y-continue |
dbfada8c8a029e27495c98d2dd3692f03f79b618 | anaswara-97/python_project | /exam2/lmb_fun.py | 96 | 3.5 | 4 | num = [16]
if(list(filter(lambda x: x % 2 == 0,num))):
print("even")
else:
print("odd")
|
26e7a5f0ebdd5157c53a8e3b86231b646696ea70 | singhchaman/MIT600x | /MITx 6.00.1x/week 2/ps1.py | 503 | 3.78125 | 4 | c=0
for i in s:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
c=c+1
print "Number of vowels:", c
c=0
for i in range(1,len(s)-1):
if s[i-1:i+2]=='bob':
c=c+1
print "Number of vowels:", c
curString = s[0]
longest = s[0]
for i in range(1, len(s)):
if s[i] >= curString[-1]:
curString += s[i]
if len(curString) > len(longest):
longest = curString
else:
curString = s[i]
print 'Longest substring in alphabetical order is:', longest |
43e7a79efb891b703ed01d5e0fe0c6773e4b4d53 | sepulenie/codewars | /codewars_5.py | 140 | 3.5 | 4 | def solution(string, ending):
print( ending in string and string[len(string)-1]==ending[len(ending)-1])
pass
solution('lol', 'oy') |
a8cd09dc58e4dd1a2e8f39da1e07d8cf0d289377 | glonek47/gitarasiema | /5.1.py | 212 | 3.890625 | 4 | while True:
a = float(input("Podaj pierwszą liczbę: "))
b = float(input("Podaj drugą liczbę liczbę: "))
if a < 0 or b < 0:
continue
else:
print("Średnia to: ", (a+b)/2) |
d4491d836d9336a1baaca1fd9e2eccae4811198a | TCReaper/Computing | /Computing Revision/2015 DHS Prelim/ISBN Fun.py | 8,331 | 3.96875 | 4 |
################################### Task 3.1 #############
def ISBN_Check_Digit(isbn):
isbnstring = isbn.replace('-','')
if check_type(isbnstring) == 13:
isbn = isbnstring[:-1]
switch = 0
total = 0
for i in isbn:
if switch == 0:
total += int(i)
switch += 1
if switch == 1:
total += int(i) * 3
switch -= 1
output = total % 10
elif check_type(isbnstring) == 10:
isbn = isbnstring[:-1]
count = 1
total = 0
for i in isbn:
total += int(i) * count
count += 1
output = total % 11
elif check_type(isbnstring) == 9 or check_type(isbnstring) == 12:
isbnstring += '0'
return ISBN_Check_Digit(isbnstring)
else:
return 'Not a valid ISBN-10 or ISBN-13 number!'
return output
def check_type(isbn):
isbn = isbn.replace('-','')
if len(isbn) == 13:
return 13
if len(isbn) == 10:
return 10
if len(isbn) == 12:
return 12
if len(isbn) == 9:
#print(isbn,'check')
return 9
################################### Task 3.2 #############
def Valid_ISBN(isbn):
if ISBN_Check_Digit(isbn) != 'Not a valid ISBN-10 or ISBN-13 number!':
return True
return False
################################### Task 3.3 #############
def ISBN10_To_ISBN13(isbn):
isbnstring = isbn.replace('-','')
if check_type(isbnstring) == 13:
return 'This is already a ISBN-13 number.'
elif check_type(isbnstring) == 10:
return '978-'+isbnstring
else:
return 'Not a valid ISBN-10 or ISBN-13 number!'
################################### Task 3.4 #############
def ISBN13_To_ISBN10(isbn):
isbnstring = isbn.replace('-','')
if check_type(isbnstring) == 13:
return isbn[3:]
elif check_type(isbnstring) == 10:
return 'This is already a ISBN-10 number.'
else:
return 'Not a valid ISBN-10 or ISBN-13 number!'
################################### Task 3.5 #############
## czezcompu
## tingdarenlerfuncz
## ezcomputingdarenlerfuncz
## ezcomputingdare nlerfunc
## zezcomputingd arenler
## funczezcomputin gdaren
## lerfunczezcomput ingda
## renlerfuncz ezcomp utingdarenl erfun
## czezcomputingdarenl erfunczezcomput ingd
## arenlerfunczezcom putingdarenlerfunczez
## compu tingdarenle rfunczezcomputingdare
## nlerfunczezcomputing darenlerfun czezcompu
## tingdarenlerfunczez computingdarenlerfunc
## zezcomputingdarenlerfunczezcomputing daren
## lerfu nczezcomputingdare nlerfu
## nczez computi ngdare
## nlerfu nczezc
## omputi ngdare
## nlerfu nczezc
## omput ingd arenle
## rfun czezc omp utingd
## aren lerfunczez compu tin
## lerfu nczezcomp uting daren
## zezco mputingdar enler funcze
## putin gdarenler funcz ezcompu
## arenl erfunczez comput ingdare
## uncze zcomputi ngdarenlerfunczezcom putingd a
## erfu nczezcom putingdarenlerfunczezcomputi ng
## enle rfuncze zcomp uting darenlerfu ncze
## ompu tingdare nle rfunczezcomputing darenl
## erfun czezc omput ingdarenlerfunczez computi
## ngda renle rfuncze zcomputingdarenlerf unczezc
## mputi ngdarenlerfunc zezcompu tingda
## lerfu nczezcomputi ngda renler func ze
## mputin gdar enle rfuncz ezcomp
## ingdar enl erfun czez
## computin gdar enler fun
## zezcomp utin gdarenlerfunc
## ingdare nlerfunczezcomput ing darenle r
## funczezcomputi ngdarenlerfunczezcomp utin gdarenl
## erfu nczezcomputing darenlerfunczez computingdarenlerfunc
## zezc omputingda renlerfuncz ezcomputingdarenler
## func zezcom putingdarenl erfun czezcomputi
## ngdarenler funczezcomp utin
## gdarenl erfuncze zcom
## put ingdar enle
## rfuncz ezco
## mputingdar
## enlerfu
## ncz
# assume array is of 267 books
# next prime is 269
global lib_array
lib_array = [0 for i in range(269)]
def Hash_Key(isbn):
global lib_array
isbn = isbn.replace('-','')
isbnint = 0
for i in isbn:
isbnint += int(i)
index = isbnint % 269
if lib_array[index] == 0:
return index
else:
step = isbnint % 17
found_space = False
while not found_space:
if lib_array[step] == 0:
found_space = True
else:
step = isbnint % 11
return step
################################### Task 3.6 #############
def generate_library():
libraryfile = open('LIBRARY.txt','w')
libraryfile.close()
libraryfile = open('LIBRARY.txt','a')
for i in range(267):
libraryfile.write(str(Hash_Key(generate_isbn()))+'\n')
def generate_isbn():
import random
if random.randint(0,1) == 0: #generate isbn10
isbn = ''
for i in range(9):
isbn += str(random.randint(0,9))
return isbn + str(ISBN_Check_Digit(isbn))
else: #generate isbn13
isbn = ''
for i in range(9):
isbn += str(random.randint(0,9))
isbn = isbn + str(ISBN_Check_Digit(isbn))
isbn = ISBN10_To_ISBN13(isbn)
return isbn
def Insert_Book(isbn):
libraryfile = open('LIBRARY.txt','r')
global lib_array
lib_array = []
for i in libraryfile:
i = i.strip()
lib_array.append(i)
libraryfile.close()
index = Hash_Key(isbn)
lib_array[index] = isbn
libraryfile = open('LIBRARY.txt','w')
for i in lib_array:
libraryfile.write(i+'\n')
|
f7a128d6f865414ac0601e5d2cc3124a40f35cad | likhitha5101/DAA | /Assignment-7/dijkstra.py | 4,198 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## CS1403 — Design and Analysis of Algorithms
# ### 1. Given a weighted graph G = (V, E), and a distinguished vertex s ∈ V (source vertex), find the shortest weighted path from s from every other vertex in G.
# In[29]:
from collections import defaultdict
import sys
class Heap():
def __init__(self):
self.array = []
self.size = 0
self.pos = []
def newMinHeapNode(self, v, dist):
minHeapNode = [v, dist]
return minHeapNode
def swapMinHeapNode(self,a, b):
t = self.array[a]
self.array[a] = self.array[b]
self.array[b] = t
def minHeapify(self, idx):
smallest = idx
left = 2*idx + 1
right = 2*idx + 2
if left < self.size and self.array[left][1] < self.array[smallest][1]:
smallest = left
if right < self.size and self.array[right][1] < self.array[smallest][1]:
smallest = right
if smallest != idx:
self.pos[ self.array[smallest][0] ] = idx
self.pos[ self.array[idx][0] ] = smallest
self.swapMinHeapNode(smallest, idx)
self.minHeapify(smallest)
def extractMin(self):
if self.isEmpty() == True:
return
root = self.array[0]
lastNode = self.array[self.size - 1]
self.array[0] = lastNode
self.pos[lastNode[0]] = 0
self.pos[root[0]] = self.size - 1
self.size -= 1
self.minHeapify(0)
return root
def isEmpty(self):
return True if self.size == 0 else False
def decreaseKey(self, v, dist):
i = self.pos[v]
self.array[i][1] = dist
while i > 0 and self.array[i][1] < self.array[int((i - 1) // 2)][1]:
self.pos[ self.array[i][0] ] = (i-1)//2
self.pos[ self.array[(i-1)//2][0] ] = i
self.swapMinHeapNode(i, (i - 1)//2 )
i = (i - 1) // 2;
def isInMinHeap(self, v):
if self.pos[v] < self.size:
return True
return False
# In[30]:
def printArr(dist, n):
print ("Vertex\tDistance from source")
for i in Dict:
print ("%c\t\t%d" % (i,dist[Dict[i]]))
# In[31]:
class Graph():
def __init__(self, V):
self.V = V
self.graph = defaultdict(list)
def addEdge(self, src, dest, weight):
newNode = [Dict[dest], weight]
self.graph[Dict[src]].insert(0, newNode)
newNode = [Dict[src], weight]
self.graph[Dict[dest]].insert(0, newNode)
def dijkstra(self, src):
V = self.V
dist = []
minHeap = Heap()
for v in range(V):
dist.append(sys.maxsize)
minHeap.array.append( minHeap.newMinHeapNode(v, dist[v]) )
minHeap.pos.append(v)
minHeap.pos[Dict[src]] = Dict[src]
dist[Dict[src]] = 0
minHeap.decreaseKey(Dict[src], dist[Dict[src]])
minHeap.size = V;
while minHeap.isEmpty() == False:
newHeapNode = minHeap.extractMin()
u = newHeapNode[0]
for pCrawl in self.graph[u]:
v = pCrawl[0]
if minHeap.isInMinHeap(v) and dist[u] != sys.maxsize and pCrawl[1] + dist[u] < dist[v]:
dist[v] = pCrawl[1] + dist[u]
minHeap.decreaseKey(v, dist[v])
printArr(dist,V)
# In[33]:
graph = Graph(12)
Dict={'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11}
graph.addEdge('a', 'b', 3)
graph.addEdge('a', 'd', 4)
graph.addEdge('a', 'c', 5)
graph.addEdge('b', 'e', 3)
graph.addEdge('b', 'f', 6)
graph.addEdge('c', 'd', 2)
graph.addEdge('c', 'g', 4)
graph.addEdge('d', 'e', 1)
graph.addEdge('d', 'h', 5)
graph.addEdge('e', 'f', 2)
graph.addEdge('e', 'i', 4)
graph.addEdge('f', 'j', 5)
graph.addEdge('g', 'h', 3)
graph.addEdge('g', 'k', 6)
graph.addEdge('h', 'i', 6)
graph.addEdge('h', 'k', 7)
graph.addEdge('i', 'l', 5)
graph.addEdge('i', 'j', 3)
graph.addEdge('k', 'l', 8)
graph.addEdge('j', 'l', 9)
graph.dijkstra('a')
# In[ ]:
|
7dd33202d9970365080240a19646694a5dc9d176 | SherMM/rosalind-python | /rna.py | 119 | 3.59375 | 4 | def dnaToRNA(dna):
rna = ""
for letter in dna:
if letter == "T":
rna += "U"
else:
rna += letter
return rna |
e5d27134c990fabe70bdcf84bc4b0d21686f0c88 | Arktiica/edhesivePython | /Unit 7 Functions/7_4CodePractice-calcGPAWeighted.py | 472 | 4 | 4 | def GPAcalc(g, w):
if g.lower() == 'a':
return 4 + w
elif g.lower() == 'b':
return 3 + w
elif g.lower() == 'c':
return 2 + w
elif g.lower() == 'd':
return 1 + w
elif g.lower() == 'f':
return 0 + w
else:
return "Invalid"
msg = input("Enter your letter grade:")
msg2 = int(input("Is it weighted? (0 = no, 1 = yes) "))
gpa = GPAcalc(msg, msg2)
print("Your GPA score is: " + str(gpa))
|
40f1e9408b95e121c3c42090720ae7c0e72f8945 | dmikii/pcc2e-work | /Chapter7/dinner_seating.py | 187 | 4.21875 | 4 | table = input("How many people will be dining this evening? ")
table = int(table)
if table > 8:
print("Sorry, but you'll have to wait for a table.")
else:
print("Your table is ready.") |
07a9a14b86570c3e48aede73674f3085849eb2bd | Nagendra17423/Movie-Recommendation-System | /options/tage.py | 433 | 3.625 | 4 | import pandas as pd
from math import pow, sqrt
movies=pd.read_csv("movies.csv")
tags=pd.read_csv("tags.csv")
tags=pd.merge(movies,tags).drop(['timestamp','movieId','title','genres'],axis=1).sort_values(by=['userId'])
# tags
i=int(input("Enter the user id"))
x=tags.loc[tags['userId'] == i]
# x
t_count = x['tag'].value_counts()
y=t_count[:10]
z=y.index
print("The top 3 tags from the user are")
print(z[0])
print(z[1])
print(z[2])
|
bcc767f1e513482a6f27b4cdb15fd0a298c4b999 | bangerterdallas/portfolio | /List_Comprehension_Bubble_Sort/assn15-task2.py | 1,103 | 4.1875 | 4 | def bubbleSort(inputList):
loop = True
while loop:
loop = False
for j in range(len(inputList) - 1):
if inputList[j] > inputList[j + 1]:
inputList[j], inputList[j + 1] = inputList[j + 1], inputList[j]
loop = True
def main():
numberList = []
loop = True
count = 0
sum = 0
max = None
while loop:
number = input("Enter a number to add to the list or enter nothing to review the list: ")
if number.isdigit() == True:
numberList.append(int(number))
print("added number: " + number)
count += 1
sum += int(number)
elif number == "":
break
else:
print("Enter correct input >:(")
print("Number of values entered: " + str(count))
bubbleSort(numberList)
print("Maximum value: " + str(numberList[-1]))
print("Minimum value: " + str(min(numberList)))
print("Sum of all values: " + str(sum))
average = (sum / count)
print("Average value: " + str(average))
main() |
70166884f504a8224d1f9d5e14b95a3a49b8726a | pravinpande/Python | /ReverseString.py | 429 | 4.125 | 4 | #reverse string
def reverse_join(s):
return " ".join(reversed(s.split()))
print(reverse_join('This is a string'))
def reverse_while(s):
length = len(s)
spaces = [' ']
word = []
i = 0
while i < length:
if s[i] not in spaces:
word_start = i
while i < length and s[i] not in spaces:
i += 1
word.append(s[word_start:i])
i += 1
return " ".join(reversed(word))
print(reverse_while('This is a string'))
|
915878cafa68b9932fb96250e3bd1a866c3661bd | gachikuku/simple_programming_python | /LS12.py | 328 | 4.375 | 4 | #!/usr/bin/env python
"""
12. Write a function that merges two sorted lists into a new sorted list. [1,4,6],[2,3,5] → [1,2,3,4,5,6]. You can do this quicker than concatenating them followed by a sort.
"""
def rotate(x,k):
return x[k:] + x[:k]
example = [1,2,3,4,5]
k = 2
print(rotate(example,k))
|
e286fb181dffaa32a552e6fa55c8c905228781fc | tuomas56/random-python-stuff | /fraction.py | 7,419 | 4.0625 | 4 | import numbers
#module Fractions
#contains classes and functions for dealing with fractions
#@author Tuomas Laakkonen
#@date 1418054074 8/12/14
#@copyright Tuomas Laakkonen (c) 2014
#@license GPLv3
#contains fields for numerator and denominator and methods to simplify
class Fraction(numbers.Rational):
def __init__(self,numerator,denominator):
self._numerator = numerator
self._denominator = denominator
self.simplify()
def simplify(self):
numerator = self._numerator
denominator = self._denominator
while gcd(numerator,denominator) > 1: #while the numbers are not coprime
a = gcd(numerator,denominator)
numerator //= a #divide both sides by the hcf
self._numerator = numerator
self._denominator = denominator
@property
def numerator(self):
return self._numerator
@numerator.setter
def numerator(self, value): #automatically simplify when setting
self._numerator = value
self.simplify()
@property
def denominator(self):
return self._denominator
@denominator.setter
def denominator(self, value): #automatically simplify when setting
self._denominator = value
self.simplify()
def sign(self):
return sign(self.denominator) * sign(self.numerator)
#Fraction(1,4).flip() == Fraction(4,1)
def flip(self):
return Fraction(self.denominator,self.numerator)
def __str__(self):
return {1:"",0:"",-1:"-"}[self.sign()] + str(abs(self.numerator)) + "/" + str(abs(self.denominator))
def __repr__(self):
return str(self)
def __float__(self):
return self.numerator / self.denominator
def __int__(self):
return self.__trunc__()
def __mul__(self,other): #self * other
if isinstance(other,int):
return self * from_int(other)
elif isinstance(other,float):
return self * from_float(other)
elif isinstance(other,Fraction):
return Fraction(self.numerator * other.numerator,self.denominator * other.denominator)
else:
raise ValueError("Can't multiply Fraction and "+str(type(other)))
def __rmul__(self,other): #other * self
return self * other #because multiplication is commutative
def __div__(self,other):
return self.__truediv__(other)
def __rdiv__(self,other):
return self.__rtruediv__(other)
def __truediv__(self,other): #self / other
if isinstance(other,int):
return self / from_int(other)
elif isinstance(other,float):
return self / from_float(other)
elif isinstance(other,Fraction):
return self * other.flip() # a / b == a * 1/b therefore if a == c/d and b == e/f then c/d / e/f == c/d * 1/(e/f) == c/d * f/e
else:
raise ValueError("Can't divide Fraction by "+str(type(other)))
def __rtruediv__(self,other): #other / self
if isinstance(other,int):
return from_int(other) / self
elif isinstance(other,float):
return from_float(other) / self
elif isinstance(other,Fraction):
return other * self.flip() # a / b == a * 1/b therefore if a == c/d and b == e/f then c/d / e/f == c/d * 1/(e/f) == c/d * f/e
else:
raise ValueError("Can't divide "+str(type(other))+" by Fraction")
def __floordiv__(self,other): #self // other
return int(self / other)
def __rfloordiv__(self,other): #other // self
return int(other / self)
def __add__(self,other): #self + other
if isinstance(other,int):
return self + from_int(other)
elif isinstance(other,float):
return self + from_float(other)
elif isinstance(other,Fraction):
return Fraction(self.numerator * other.denominator + other.numerator * self.denominator,self.denominator * other.denominator)
else:
raise ValueError("Can't add Fraction and "+str(type(other)))
def __radd__(self,other): #other + self
return self + other #because adding is commutative
def __sub__(self,other): #self - other
if isinstance(other,int):
return self - from_int(other)
elif isinstance(other,float):
return self - from_float(other)
elif isinstance(other,Fraction):
return Fraction(self.numerator * other.denominator - other.numerator * self.denominator,self.denominator * other.denominator)
else:
raise ValueError("Can't subtract Fraction from "+str(type(other)))
def __rsub__(self,other): #other - self
if isinstance(other,int):
return from_int(other) - self
elif isinstance(other,float):
return from_float(other) - self
elif isinstance(other,Fraction):
return Fraction(other.numerator * self.denominator - self.numerator * other.denominator,self.denominator * other.denominator)
else:
raise ValueError("Can't subtract "+str(type(other))+" from Fraction")
def __pow__(self,other): #self ** other
return float(self) ** other
def __rpow__(self,other): #other ** self
return other ** float(self)
def __abs__(self): #abs(self)
return +self
def __ceil__(self):
return self.__trunc__() + 1 if self - self.__trunc__() >= 0.5 else self.__trunc__()
def __eq__(self,other): #self == other
if isinstance(other,int):
return self == from_int(other)
elif isinstance(other,float):
return self == from_float(other)
elif isinstance(other,Fraction):
return self.numerator == other.numerator and self.denominator == other.numerator
def __lt__(self,other): #self < other
if isinstance(other,int):
return self < from_int(other)
elif isinstance(other,float):
return self < from_float(other)
elif isinstance(other,Fraction):
return self.numerator < other.numerator and self.denominator < other.numerator
def __le__(self,other): #self <= other
if isinstance(other,int):
return self <= from_int(other)
elif isinstance(other,float):
return self <= from_float(other)
elif isinstance(other,Fraction):
return self.numerator <= other.numerator and self.denominator <= other.numerator
def __gt__(self,other): #self > other
if isinstance(other,int):
return self > from_int(other)
elif isinstance(other,float):
return self > from_float(other)
elif isinstance(other,Fraction):
return self.numerator > other.numerator and self.denominator > other.numerator
def __ge__(self,other): #self >= other
if isinstance(other,int):
return self >= from_int(other)
elif isinstance(other,float):
return self >= from_float(other)
elif isinstance(other,Fraction):
return self.numerator >= other.numerator and self.denominator >= other.numerator
def __floor__(self):
return self.__trunc__()
def __mod__(self,other): #self % other
raise ValueError("Cannot modulo a Fraction")
def __neg__(self): #-self
return Fraction(self.numerator * -1,self.denominator) if self.sign() == 1 else self
def __pos__(self): #+self
return Fraction(self.numerator * -1,self.denominator) if self.sign() == -1 else self
def __rmod__(self,other): #other % self
raise ValueError("Cannot modulo by a Fraction")
def __round__(self,p):
x = str(float(self))
return float(x[:x.index(".")+p])
def __trunc__(self):
return int(str(float(self)).split(".")[0])
#gcd(int a, int b) -> int
#greatest common factor of a and b
def gcd(a,b):
while b != 0:
b,a = a % b, b
return a
#sign(number a) -> int
#returns the sign of a number: -1 (negative), 0 (zero) or 1 (positive)
def sign(a):
return 1 if a > 0 else -1 if a < 0 else 0
#from_float(float a) -> fraction
#returns a fraction representing the exact value of a
def from_float(a):
return Fraction(int(a*10**len(str(a).split(".")[1])),10**len(str(a).split(".")[1]))
#from_int(int a) -> fraction
#returns a fraction representing the exact value of a
def from_int(a):
return Fraction(a,1)
|
d2f251040a789bb6bc0dfd34f191a37963774236 | HBalija/data-structures-and-algorithms | /04-sorting-algorithms/03-insertion-sort/03-insertion-sort.py | 505 | 4.1875 | 4 | #!/usr/bin/env python3
def insertion_sort(lst):
# start from second element
for i in range(1, len(lst)):
current_value = lst[i]
# work backwards
j = i - 1
while j >= 0 and lst[j] > current_value:
# while in loop, copy values to lst[j + 1] position
lst[j + 1] = lst[j]
j -= 1
# set the current value
lst[j + 1] = current_value
return lst
print(insertion_sort([6, 4, 15, 10, 2])) # [ 2, 4, 6, 10, 15 ]
|
05f3604967ab4e0d0ebc2fb7162395a76ba84d56 | bamfdonahoo/ProjectEuler | /pe002.py | 806 | 3.984375 | 4 | ### Project Euler Problem 002
##
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
def fibonacci():
list = []
e_list = []
o_list = []
a=1
b=2
for i in range(300):
if b < 4000000:
#print("b = ",b)
list.append(b)
#print("list = ",list)
a,b= b,a+b
for i in list:
if (i%2==0):
e_list.append(i)
else:
o_list.append(i)
e_list.sort()
#print("e_list = ",e_list)
even_list = dict.fromkeys(e_list)
print( sum(even_list.keys()) )
o_list.sort()
obj = fibonacci() |
045addfb678e8a4c3606cdc31a028d1e8a27a3e6 | ANTsX/ANTsPyNet | /antspynet/utilities/cropping_and_padding_utilities.py | 3,104 | 3.59375 | 4 | import ants
import numpy as np
import math
def crop_image_center(image,
crop_size):
"""
Crop the center of an image.
Arguments
---------
image : ANTsImage
Input image
crop_size: n-D tuple
Width, height, depth (if 3-D), and time (if 4-D) of crop region.
Returns
-------
ANTs image.
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> cropped_image = crop_image_center(image, crop_size=(64, 64))
"""
image_size = np.array(image.shape)
if len(image_size) != len(crop_size):
raise ValueError("crop_size does not match image size.")
if (np.asarray(crop_size) > np.asarray(image_size)).any():
raise ValueError("A crop_size dimension is larger than image_size.")
start_index = (np.floor(0.5 * (np.asarray(image_size) - np.asarray(crop_size)))).astype(int)
end_index = start_index + np.asarray(crop_size).astype(int)
cropped_image = ants.crop_indices(ants.image_clone(image) * 1, start_index, end_index)
return(cropped_image)
def pad_image_by_factor(image,
factor):
"""
Pad an image based on a factor.
Pad image of size (x, y, z) to (x', y', z') where (x', y', z')
is a divisible by a user-specified factor.
Arguments
---------
image : ANTsImage
Input image
factor: scalar or n-D tuple
Padding factor
Returns
-------
ANTs image.
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> padded_image = pad_image_by_factor(image, factor=4)
"""
factor_vector = factor
if isinstance(factor, int):
factor_vector = np.repeat(factor, image.dimension)
if len(factor_vector) != image.dimension:
raise ValueError("factor must be scalar or the length of the image dimension.")
image_size = np.array(image.shape)
delta_size = image_size % factor_vector
padded_size = image_size
for i in range(len(padded_size)):
if delta_size[i] > 0:
padded_size[i] = image_size[i] - delta_size[i] + factor_vector[i]
padded_image = pad_or_crop_image_to_size(image, padded_size)
return(padded_image)
def pad_or_crop_image_to_size(image,
size):
"""
Pad or crop an image to a specified size
Arguments
---------
image : ANTsImage
Input image
size : tuple
size of output image
Returns
-------
A cropped or padded image
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> padded_image = pad_or_crop_image_to_size(image, (333, 333))
"""
image_size = np.array(image.shape)
delta = image_size - np.array(size)
if np.any(delta < 0):
pad_size = 2 * math.ceil(0.5 * abs(delta.min()))
pad_shape = image_size + pad_size
image = ants.pad_image(image, shape=pad_shape)
cropped_image = crop_image_center(image, size)
return(cropped_image)
|
734f158b54c8d856de0a2e81e59397b69399ddbf | TeoBlock/cti110 | /M5T2_McIntireTheodore.py | 1,073 | 4.34375 | 4 | # CTI-110
# Module 5 Tutorial 2
# Theodore McIntire
# 12 October 2017
# This program totals the number of bugs collected in a week
#def main() uses a for loop
def main():
# This program uses these variables
# ? ? ? I DO NOT UNDERSTAND WHY THIS PROGRAM DOES NOT RUN
# IF THESE VARIABLES ARE DEFINED OUTSIDE OF/ABOVE MAIN ? ? ?
quantityPerDay = 0
runningTotal = 0
week = range(1, 8)
for count in week:
print('Day', count)
quantityPerDay = int(input('Enter the number of bugs collected: '))
runningTotal = runningTotal + quantityPerDay
print ('On day', count, 'the number of bugs collected is', quantityPerDay, 'and subtotal is', runningTotal)
print(' ')
print("At the end of the week the total number of bugs collected is:", runningTotal)
# This finishes the code for this method
'''
#def alt() outline if needed
def alt():
# This finishes the code for this method
'''
# program start - multiple methods are run to test the code
main()
#end of program
|
e99c494aa951ec405b8cfa9e7b8164ecc7d4d443 | akshirapov/automate-the-boring-stuff | /Projects/identifying-photo-folders/identifying_photo_folders.py | 912 | 3.828125 | 4 | #! python3
# identifying_photo_folders.py - Scans the entire hard drive and finds
# photo folders.Photo folders is that it's any folder, where more than
# half of the files are photos.
import os
from PIL import Image
for root, dirs, files in os.walk('/home'):
num_photo_files = 0
num_non_photo_files = 0
for filename in files:
# Check file extension
if not (filename.endswith('.jpg') or filename.endswith('.png')):
num_non_photo_files += 1
continue # skip to next filename
# Open image file
image = Image.open(os.path.join(root, filename))
width, height = image.size
# Check size
if width > 500 and height > 500:
num_photo_files += 1
else:
num_non_photo_files += 1
# Check for "photo" folder.
if num_photo_files > num_non_photo_files:
print(os.path.abspath(root))
|
ee036f4ff4f0dfea359b35f0584174e384628f79 | vmteja/Aihw3 | /model_helper_funcs.py | 2,992 | 3.796875 | 4 |
import random
from random import shuffle
import math
import gc #garbage collector
def randomize_data(data):
"""
randomly re-arrange the data in the list
"""
# shuffle(data)
l = len(data)
for i, card in enumerate(data):
swapi = random.randrange(i, l)
data[i], data[swapi] = data[swapi], card
def convert_to_numeric(data):
"""
converts the 40 length strings of the input data to numeric
input is a list of tuples. Each tuple has a string of length 40 and label to which it belongs to.
"""
#-- should labels also be changed numeric or are they already provided in numeric format ?
for element in data:
insert_number(element[0])
def insert_number(arr):
"""
replaces each alphabet with a number
"""
char_dict = {'A':1, 'B':2, 'C':3, 'D':4} # not used now
for index,char in enumerate(arr):
#arr[index] = char_dict[char]
if char == 'A':
arr[index] = 1
elif char == 'B':
arr[index] = 2
elif char == 'C':
arr[index] = 3
elif char == 'D':
arr[index] = 4
return arr
def create_train_valid(data, split_fraction):
"""
splits the data into train and validation sets
"""
l = len(data)
split_size = int(l*split_fraction)
train_data = data[:split_size]
valid_data = data[split_size:]
return train_data, valid_data
def seperate_data_lables(data):
"""
seperates data and their respective labels
returns two lists; one a list of data elements (40-leng numeric arrays),
second list is the labels at their their corresponding indexes
"""
features = []
labels = []
for element in data:
#print(element)
features.append(element[0])
labels.append(element[1][0])
return features, labels
def batches(batch_size, features, labels):
"""
creates batches of features and labels
returns: Batches of (Features, Labels)
"""
assert len(features) == len(labels)
output_batches = []
sample_size = len(features)
for start_i in range(0, sample_size, batch_size):
end_i = start_i + batch_size
batch = [features[start_i:end_i], labels[start_i:end_i]]
output_batches.append(batch)
return output_batches
"""
# for debugging
if __name__ == "__main__":
s1 = 'AB'
s2 = 'CD'
s3 = 'AA'
s4 = 'BD'
l1 = list(s1)
l2 = list(s2)
l3 = list(s3)
l4 = list(s4)
a1 = (l1,1)
a2 = (l2,2)
a4 = (l2,3)
a5 = (l2,4)
a3 = []
a3.append(a1)
a3.append(a2)
a3.append(a4)
a3.append(a5)
print ("--",a3)
randomize_data(a3)
print ("--",a3)
convert_to_numeric(a3)
print ("--",a3)
x,y = seperate_data_lables(a3)
print ("***",x)
print ("***",y)
for batch_features, batch_labels in batches(1,x,y):
#print (batch_features)
print('!! : {},{}'.format(batch_features,batch_labels))
"""
|
9479a7c0d1a18507c0a1392654f4c34f7ad12d54 | unspoken666/Code | /python/PythonDraw.py | 2,156 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
#method one
#PythonDraw.py
import turtle
turtle.setup(650,350,200,200)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)
for i in range(4):
turtle.circle(40,80)
turtle.circle(-40,80)
turtle.circle(40,80/2)
turtle.fd(40)
turtle.circle(16,180)
turtle.fd(40 * 2/3)
turtle.done()
#method two
#PythonDraw.py
from turtle import *
setup(650,350,200,200)
penup()
fd(-250)
pendown()
pensize(25)
pencolor("purple")
seth(-40)
for i in range(4):
circle(40,80)
circle(-40,80)
circle(40,80/2)
fd(40)
circle(16,180)
fd(40 * 2/3)
done()
#method three
#PythonDraw.py
import turtle as t
t.setup(650,350,200,200)
t.penup()
t.fd(-250)
t.pendown()
t.pensize(25)
t.pencolor("purple")
t.seth(-40)
for i in range(4):
t.circle(40,80)
t.circle(-40,80)
t.circle(40,80/2)
t.fd(40)
t.circle(16,180)
t.fd(40 * 2/3)
t.done()
#PythonDraw.py 绘制蟒蛇
import turtle as t #引入了一个库 绘图库 海龟图
def Snake1(rader,angle,leng):
for i in range(leng):
t.circle(rader,angle)
t.circle(-rader,angle)
def Snake2(rader,angle,neck):
t.circle(rader,angle/2)
t.fd(rader)
t.circle(neck+1,180)
t.fd(rader * 2/3)
def main():
t.setup(1500,200,0,0)
'''turtle.seth(180)
turtle.up()
fd(400)
t.seth(0)
t.pd()'''
size = 30
t.pensize(size)
t.seth(-40)
t.pencolor("red")
Snake1(40,80,1)
t.pencolor("orange")
Snake1(40,80,1)
t.pencolor("yellow")
Snake1(40,80,1)
t.pencolor("green")
Snake1(40,80,1)
t.pencolor("blue")
Snake1(40,80,1)
t.pencolor("purple")
Snake2(40,80,size/2)
main()
#自定义蟒蛇绘制
#PythonDraw.py 绘制蟒蛇
import turtle #引入了一个库 绘图库 海龟图
turtle.setup(1000,350,200,200)
turtle.penup()
turtle.fd(-400)
turtle.pendown()
turtle.pensize(50)
turtle.pencolor("green")
turtle.seth(-90)
for i in range(4):
turtle.circle(40,180)
turtle.circle(-40,180)
turtle.circle(40,180/2)
turtle.fd(100)
turtle.circle(40,180)
turtle.fd(100 * 2/3)
turtle.done()
|
578260161ba8f5285dddaa588c5739498e072562 | AxelRaze/Arreglo5Mult | /Arreglo5.py | 1,612 | 3.515625 | 4 |
class Arreglo5:
__Arreglo = []
__sumafilas = int(0)
__sumacolumnas = int(0)
__columnas = ''
__filas = int(0)
f = int(0)
c = int(0)
def crearDimensiones(self, f, c):
for a in range(f):
self.__Arreglo.append([0] * c)
print(self.__Arreglo)
def RellenarArreglo(self, f, c):
try:
for a1 in range(f):
for b1 in range(c):
var1 = int(input('Ingrese un número para rellenar el arreglo: '))
self.__Arreglo[a1][b1] = var1
except: ValueError
def SumaFilas(self):
for f in range(0, len(self.__Arreglo)):
self.__sumafilas = 0
for c in range(0, len(self.__Arreglo[f])):
self.__sumafilas = self.__sumafilas + self.__Arreglo[f][c]
self.__filas = self.__filas, self.__sumafilas
print(self.__Arreglo[f][c], '\t', end="")
print('Suma de la fila No.', f, '=', self.__sumafilas)
print('\n')
def SumaColumnas(self):
for f2 in range(0, len(self.__Arreglo)):
self.__sumacolumnas = 0
for c2 in range(0, len(self.__Arreglo[f2])):
self.__sumacolumnas = self.__sumacolumnas + self.__Arreglo[c2][f2]
print(self.__Arreglo[c2][f2], '\t', end="")
print('Suma de la columna No.', f2, '=', self.__sumacolumnas)
print('\n')
codigo = Arreglo5()
codigo.crearDimensiones(10, 10)
codigo.RellenarArreglo(10, 10)
codigo.SumaFilas()
codigo.SumaColumnas() |
3d8d2b4e44f047b5f4bfb149381140ac51a30299 | jleihe/Sandbox | /python/practice/calc/start.py | 460 | 4.0625 | 4 | # File Name: calc.py
# Written By: Joshua Leihe
# Purpose: Create a simple python script that takes a string input and translates it to a mathematical equation. The script should then return the result (or an explanation as to why there was an error).
from utils import commands
print "\nWelcome to Calc 0.1!"
print "Enter \"h\"for help and detailed list of commands!\n\n"
eq_str = raw_input("Calc 0.1 >> ")
sep(eq_str)
print "The equation entered was " + eq_str
|
5b4711b26f45c4e0e07fff3d6e4cf9f0e994576b | wzbbbb/LeetCode-OJ | /Sudoku Solver.py | 1,395 | 3.5625 | 4 | class Solution:
# @param board, a 9x9 2D array
# Solve the Sudoku by modifying the input board in-place.
# Do not return any value.
def chk(self,board,i,j, num):
b,sz=board,9
if str(num) in b[i]: return False
for k in range(sz):
if str(num) == b[k][j]: return False
if i in range(0,3): p=range(0,3)
if i in range(3,6): p=range(3,6)
if i in range(6,9): p=range(6,9)
if j in range(0,3): q=range(0,3)
if j in range(3,6): q=range(3,6)
if j in range(6,9): q=range(6,9)
for pi in p :
for qi in q:
if str(num) == b[pi][qi] : return False
return True
def fillin(self, board,finished=False):
sz=9
empty=False
for pi in range(sz): # find the next spot to fill
if empty: break
for qi in range(sz):
if board[pi][qi] == '.':
empty=True
i=pi; j=qi
break
if empty ==False:
return board,True
else:
for k in range(1,10):
if self.chk(board,i,j,k) :
st=board[i][:j] + [str(k)] +board[i][j+1:]
board[i]=st
board,finished=self.fillin( board, finished)
if finished==False:
st=board[i][:j] + ['.'] +board[i][j+1:]
board[i]=st
return board, finished
def solveSudoku(self, board,finished=False):
board=self.fillin(board)
|
f986fb948699d322c26bc4fd0fd456eb4b0f45ef | khwla23/Piaic | /start2.py | 287 | 4.09375 | 4 | user_name = input(" Enter your Password: ")
length = len(user_name)
if length <= 3:
print(" Your password is too weak")
print(" try again")
elif (length>3 and length<10) :
print(" Your password is Good and long")
elif (length > 10 ) :
print (" Your password is strong")
|
76226bb5247eeb1f19629632be91e220e14399d1 | mnevadom/pythonhelp | /2_condicionales/Ejercicio1.py | 441 | 4.125 | 4 | '''
Ejercicio 1:
Hacer un programa que pida 2 números y se de cuenta cuál de ellos es par,
o si ambos lo son.
'''
num1 = int(input("Digite un numero: "))
num2 = int(input("Digite otro numero: "))
if num1%2==0 and num2%2==0:
print("Ambos numeros son pares")
elif num1%2==0 and num2%2!=0:
print(f"{num1} es par")
elif num1%2!=0 and num2%2==0:
print(f"{num2} es par")
else:
print("Ambos numeros son impares") |
2c6fbaf8105fdb2756c06b29f1350d959b53c436 | phuonghle/lehoaiphuong-fundamentals-c4e19 | /Session02/session02 assignment/table_10_n.py | 464 | 4 | 4 | # Ask users to enter a number n, then print n x n 1’s and 0’s, consecutively
n = int(input("Enter a number: "))
for i in range(n):
if i % 2 == 0 :
for j in range(n):
if j % 2 == 1:
print(0, end=" ")
else:
print(1, end= " ")
else:
for j in range (n):
if j % 2 == 0:
print(0, end=" ")
else:
print(1, end=" ")
print() |
e5439b19866c0d71c19c9a2cf96854e37a147500 | GuhanSGCIT/Trees-and-Graphs-problem | /Factorial.py | 1,546 | 3.828125 | 4 | """
A factorial of a non-negative integer is defined as the product of all numbers from 1 to N inclusive.
The factorial of N is denoted by N!. By convention, 0!=1.
For example, 5!=5×4×3×2×1=120.
Your task is simple. You are given N! , where you have to find N . If multiple values exist for a single factorial,
find the largest one. It is guaranteed that a solution exists.
timing:1sec
level:3
Input:
The first line will contain T- number of testcases. Then the testcases follow.
Each testcase consists of a single line of input: one integer N!.
Output:
For each testcase, output in a single line N as explained in the problem statement.
Constraints
1≤T≤30
1≤N!<10^36
Sample Input:
2
1
24
Sample Output:
1
4
EXPLANATION:
For N!=1, multiple solutions exist. N=1 satisfies the conditions.
For N!=24, N=4 because 4×3×2×1=24.
input:
3
10
11
19
output:
3
3
3
input:
7
45
65
556
60
656
1251
8
1
output:
4
4
5
4
5
6
3
input:
1
10000
output:
7
input:
2
10
100
output:
3
4
hint:
First, check if the number is 1. If it is, print 1.
Otherwise, maintain a variable iii and set it to 0. While nnn is not 111, we need to increment i by 1.
We need to change nnn to ni\dfrac{n}{i}in (we divide n each time after we increase i). Then print the final i.
Implementation is simple.
"""
for i in range(int(input())):
a = int(input())
b = 1
while a >= 1 :
a = a//b
ans = b
b = b+1
print(ans-1)
|
ff723868b2ebda7484699785dfa6c905f2ccbe10 | maxvillev/resbaz2021 | /hellopanda.py | 319 | 3.90625 | 4 | #
# hellopanda.py - using pandas to read and plot a csv file
#
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("kungfu.csv", skiprows=3)
print("\n*** Po and the Furious Five ***\n")
print(df)
df.plot(x="Name",kind="bar")
plt.title("Po and the Furious Five")
#plt.savefig("kungfu.png")
plt.show()
|
20db25b4f726b986d5ad59109bcd099e8128121a | Khalid-Sultan/Section-2 | /recursive binary.py | 293 | 4.0625 | 4 | def main():
for value in range (10,48):
print("The binary value of",value,"base 10 =",decimalToBinary(value),"base 2")
def decimalToBinary(value):
result=""
while value!=0:
bit=value%2
result=str(bit)+result
value=value//2
return result
main()
|
22b74e7b62bebde25f095665026f8ae712d00423 | n1na-j/weekly-assignments-fds | /Week 2/dict_loginsystem.py | 1,712 | 4.15625 | 4 | # Login accounts
user_login_accounts = {
1: {"first name": "Jughead", "last name": "Jones", "email address": "jughead@riverdale.com", "password": "jughead_riverdale1"},
2: {"first name": "Archie", "last name": "Andrews", "email address": "archie@riverdale.com", "password": "archie_riverdale2"},
3: {"first name": "Veronica", "last name": "Lodge", "email address": "veronica@riverdale.com", "password": "veronica_riverdale3"},
4: {"first name": "Betty", "last name": "Cooper", "email address": "betty@riverdale.com", "password": "betty_riverdale4"},
5: {"first name": "Cheryl", "last name": "Blossom", "email address": "cheryl@riverdale.com", "password": "cheryl_riverdale5"},
}
# User login: ask for email address
user_email = input("Enter your email address: ")
# User login: ask for password
user_password = input("Enter your password: ")
# Identify first id_val
id_val = 1
# id_val has to be less than max length of dict. id's in order to go through the user_login_accounts
while int(id_val) < len(user_login_accounts):
# If so, look for id_val and account_info in user_login_account
for id_val, account_info in user_login_accounts.items():
# Check for valid email address and password
if user_email == account_info["email address"] and user_password == account_info["password"]:
print(user_email, "and", user_password, "are correct")
print("Hello,", account_info["first name"], account_info["last name"], ". You have successfully logged in")
break
# Give an error if email or password is not correct
else:
print("Failed to login. Password", user_password, "or email address", user_email," is not correct. Try again.")
break
# Make sure to stop this loop after running one time
break
|
1f511633739c6e1b48256e86cf84cea276d9e453 | Jabuf/projecteuler | /problems/problem3/Problem3.py | 679 | 3.609375 | 4 | """
https://projecteuler.net/problem=3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
from locals import *
def solution(x):
largest_prime_found = 0
first_prime = 2
biggest_prime = first_prime
primes = [first_prime]
root = sqrt(x)
while biggest_prime < root:
biggest_prime = primes[len(primes) - 1]
if is_multiple_of(x, biggest_prime):
largest_prime_found = biggest_prime
primes += [find_next_prime(primes)]
return largest_prime_found
with Timer() as timed:
print(solution(600851475143))
print("Seconds taken: {0}".format(timed.elapsed))
|
8e5b727f98616af771e09faba1390cc1e0985a95 | aaroncymor/python-data-structures-and-algorithms | /Array/compress.py | 2,349 | 4.09375 | 4 | def compress(s):
"""
1st step: get all unique characters.
e.g., AABBCCDDaabbccdd = ABCDabcd AABBAA = ABA
"""
unique = ""
temp = ""
for i in range(len(s)):
if i == 0:
unique += s[i]
temp = s[i]
if temp == s[i]:
pass
else:
unique += s[i]
temp = s[i]
"""
2nd step: for each unique letter check it in the given string for compression.
if unique letter is equal to the char of given string, count +=1
else, break the loop and change given string to s[count:].
e.g., unique =ABC given = AAABBBCC
first unique char is 'A' and will loop through AAABBBCC
while 'A' = given s[index] count +=1
when 'A' hits 'B' which are not equal at count 3,
given s will become [count:] which means it will turn to BBBCC
and break the loop so that unique will shift to 'B'
index starts at zero again checking BBBCC instead of AAABBBCC
"""
comp = ""
for c in unique:
i,count = 0,0
while i < len(s):
if c == s[i]:
count += 1
else:
s = s[count:]
break
i += 1
comp += c + str(count)
return comp
def compress_sol1(s):
"""
This solution compresses without checking. Known as the RunLength Compression algorithm.
"""
# Begin Run as empty string
r = ""
l = len(s)
# Check for length 0
if l == 0:
return ""
# Check for length 1
if l == 1:
return s + "1"
#Intialize Values
last = s[0]
cnt = 1
i = 1
while i < l:
# Check to see if it is the same letter
if s[i] == s[i - 1]:
# Add a count if same as previous
cnt += 1
else:
# Otherwise store the previous data
r = r + s[i - 1] + str(cnt)
cnt = 1
# Add to index count to terminate while loop
i += 1
# Put everything back into run
r = r + s[i - 1] + str(cnt)
return r
if __name__ == '__main__':
from nose.tools import assert_equal
class TestCompress(object):
def test(self, sol):
assert_equal(sol(''), '')
assert_equal(sol('AABBCC'), 'A2B2C2')
assert_equal(sol('AAABCCDDDDD'), 'A3B1C2D5')
print 'ALL TEST CASES PASSED'
# Run Tests
t = TestCompress()
t.test(compress) |
b8e0e77113625a64e5308b81e6290b5eb236215f | OptimisticPessimist/Teaching-Assistant-Python | /src/solution.py | 198 | 3.671875 | 4 | def add(a, b):
# return 3 # 最初は3を返すだけで a=1, b=2 の戻り値 3 を実現できる
return a + b # `a + b` でaとbがどんな値でもaとbの和を返すようになる
|
6877f2e6339a07f057ab632beb8f54772b7fdd1a | DVDBZN/Schoolwork | /CS136 Database Programming With SQL/PythonPrograms/PRA7 - Age Classifier/Python_AgeClassifier.py | 2,707 | 4.3125 | 4 | #Variables for calculation
baby = 0
toddler = 1
infant = 3
child = 5
teenager = 13
youngAdult = 20
adult = 31
seniorCitizen = 61
centennial = 100
recordHolder = 125
immortal = 1000
category = 0
#User input
age = int(raw_input("Enter your age: "))
#Find which range age fits into and sets category
if age < 0:
category = 0
elif age == 0:
category = 1
elif 1 <= age <= 2:
category = 2
elif 3 <= age <= 4:
category = 3
elif 5 <= age <= 12:
category = 4
elif 13 <= age <= 19:
category = 5
elif 20 <= age <= 30:
category = 6
elif 31 <= age <= 60:
category = 7
elif 61 <= age <= 99:
category = 8
elif 100 <= age <= 125:
category = 9
elif 126 <= age <= 999:
category = 10
else: #age > 999
category = 11
#List of responses. str([classification] - age) finds years until next classification
response = ["Apparently, you are a time traveler.\nWait " + str(baby - age) + " more years to become a baby, however that is supposed to work.",
"You are a baby. How are you typing and reading this?\nWait 1 more year to become a toddler.",
"You are a toddler. You still shouldn't be able to read this.\nWait " + str(infant - age) + " more years to become an infant.",
"You are an infant. You are a child prodigy if you can read this.\nWait " + str(child - age) + " more years to become a child.",
"You are a child. You should be able to read this.\nWait " + str( teenager - age) + " more years to become a teenager.",
"You are a teenager.\nWait " + str(youngAdult - age) + " more years to become a young adult.",
"You are a young adult. I would be surprised if you can't read this.\nWait " + str(adult - age) + " more years to become an adult.",
"You are an adult. You better be able to read this.\nWait " + str(seniorCitizen - age) + " more years to become a senior citizen.",
"You are a senior citizen. You might not be able to read this, again.\nWait " + str(centennial - age) + " more years to become a centennial.",
"You are a centennial. I bet you already received the letter from the president.\nWait " + str(recordHolder - age) + " more years to become a record holder.",
"Congratulations! You have broken a record!\nClaim your prize here: http://www.notascamatall.com/notavirustrustme.exe\nWait " + str(immortal - age) + " more years to become an immortal.",
"You are immortal.\nI have no idea what you are waiting for."]
#Prints appropriate response
print response[category]
#Hold program open
raw_input()
|
b1ebe5b9db8047242770616760cdab3db04ef0c7 | kinsonpoon/CUHK | /csci3320/asg2/ex1.py | 2,917 | 3.8125 | 4 | import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
def create_data(x1, x2, x3):
x4 = -4.0 * x1
x5 = 10 * x1 + 10
x6 = -1 * x2 / 2
x7 = np.multiply(x2, x2)
x8 = -1 * x3 / 10
x9 = 2.0 * x3 + 2.0
X = np.hstack((x1, x2, x3, x4, x5, x6, x7, x8, x9))
return X
def pca(X):
'''
# PCA step by step
# 1. normalize matrix X
# 2. compute the covariance matrix of the normalized matrix X
# 3. do the eigenvalue decomposition on the covariance matrix
# If you do not remember Eigenvalue Decomposition, please review the linear
# algebra
# In this assignment, we use the ``unbiased estimator'' of covariance. You
# can refer to this website for more information
# http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.cov.html
# Actually, Singular Value Decomposition (SVD) is another way to do the
# PCA, if you are interested, you can google SVD.
# YOUR CODE HERE!
'''
stdsc = StandardScaler()
X_std = stdsc.fit_transform(X)
cov_mat = np.cov(X_std,rowvar=False)
V,D = np.linalg.eig(cov_mat)
return [V, D]
####################################################################
# here V is the matrix containing all the eigenvectors, D is the
# column vector containing all the corresponding eigenvalues.
# return [V, D]
def main():
N = 1000
shape = (N, 1)
x1 = np.random.normal(0, 1, shape) # samples from normal distribution
x2 = np.random.exponential(10.0, shape) # samples from exponential distribution
x3 = np.random.uniform(-100, 100, shape) # uniformly sampled data points
X = create_data(x1, x2, x3)
#print(len(Y[1][0]))
######################################################
# Use the definition in the lecture notes,
# 1. perform PCA on matrix X
# 2. plot the eigenvalues against the order of eigenvalues,
# 3. plot POV v.s. the order of eigenvalues
# YOUR CODE HERE!
####################################################################
Y=pca(X)
#Z=[x for _,x in sorted(zip(Y[0],Y[1]),reverse=True)]
Y_sort=sorted(Y[0],reverse=True)
plt.plot(Y_sort)
plt.ylabel('Eigenvalues')
plt.xlabel('The order of eigenvalues')
plt.title('The eigenvalues against the order of eigenvalues')
plt.show()
#
var_exp = Y[0]
cum_var_exp = np.cumsum(var_exp)
plt.bar(range(9), var_exp, alpha=0.5, align='center',
label='individual explained variance')
plt.step(range(9), cum_var_exp, where='mid',
label='cumulative explained variance')
plt.ylabel('Explained variance ratio')
plt.xlabel('Principal components')
plt.title('POV v.s. the order of eigenvalues')
plt.legend(loc='best')
plt.tight_layout()
plt.show()
if __name__ == '__main__':
main()
|
507fffc5a595ca363cf60da69aed6c61b27547a0 | coledixon/Python-projects | /random_small_projects/Pokemon Game.py | 3,359 | 3.953125 | 4 | import time
global gold
global poke
gold = 0
poke = 0
def start():
print("\t\tGOTTA CATCH 'EM ALL!")
print("\n")
name = input("INPUT YOUR NAME: ")
print("\t\tINITIALIZING...")
time.sleep(1)
print("Hello, %s. Let's play a game." % name)
time.sleep(1)
print("The object of this game is to collect Pokemon.")
time.sleep(1)
print("After collecting the Pokemon, you sell them for gold.")
time.sleep(1)
choice = input("Do you want to play? y/n ")
if choice == "y":
begin()
elif choice == "n":
print("Fair enough. Bye..")
def money():
global poke
global gold
time.sleep(0.4)
print("Let's sell some Pokemon")
time.sleep(0.5)
amount = input("How many would you like to sell? ")
if amount == "1":
time.sleep(0.4)
print("You sold 1 Pokemon for 1 gold.")
poke = poke-1
gold = gold+1
print("You now have", +poke, " Pokemon and", +gold, " gold coin")
elif amount > "1" and poke == 0:
print("You don't have any Pokemon. Let's go catch some!")
begin()
elif amount == "2" and poke < 2:
print("You do not have enough Pokemon.")
begin()
elif amount == "2":
time.sleep(0.4)
print("You sold 2 Pokemon for 2 gold.")
poke = poke-2
gold = gold+2
print("You now have", +poke, " Pokemon and", +gold, " gold coins")
elif amount == "3" and poke < 3:
print("You do not have enough Pokemon.")
begin()
elif amount == "3":
time.sleep(0.4)
print("You sold 3 Pokemon for 3 gold.")
poke = poke-3
gold = gold+3
print("You now have", +poke, " Pokemon and", +gold, " gold coins")
def other():
global gold
global poke
print("1) SET THEM FREE")
time.sleep(0.5)
print("2) SELL THEM TO THE BUTCHER FOR MEAT")
time.sleep(0.5)
print("3) SKIN THEM AND MAKE A FINE COAT")
option = input("> ")
if option == "1":
print("You let your Pokemon go.")
poke = 0
begin()
elif option == "2":
print("Your Pokemon have been butchered and you have fashioned \nthem into a hearty stew.")
elif option == "3":
print("You craft a fine coat from your adorable Pokemon \nand leave their corpses in the gutter.")
def begin():
global poke
global gold
time.sleep(0.3)
print("You head out exploring.")
time.sleep(0.4)
print("You see a wild Pokemon!")
time.sleep(0.4)
pick = input("Do you want to catch this Pokemon? y/n ")
if pick == "y":
time.sleep(0.4)
print("You caught a Pokemon!")
poke = poke+1
time.sleep(0.3)
print("You currently have", +poke, " Pokemon.")
begin()
elif pick == "y" and poke == 3:
print("You have too many Pokemon. Try selling some.")
money()
elif pick == "n" and poke == 0:
time.sleep(0.3)
print("You can't get any gold unless you catch some Pokemon. \nThat's commerce.")
begin()
elif pick == "n" and poke >=1:
time.sleep(0.3)
sell = input("Do you want to sell a Pokemon? y/n ")
if sell == "y" and poke >= 1:
money()
elif sell == "n":
print("What do you want to do with your Pokemon then?")
other()
start()
|
55bc2960127b8a1ea4fe127b6628d53175d3de2f | SANDIPAN22/DSA | /greedyAlgo/coin change.py | 295 | 4.03125 | 4 | ## MINIMUM NUMBER COIN TO FULL FILL THE TOTAL VALUE
def coinChange(coins,value):
coins.sort(reverse=True)
while value:
for j in coins:
if value>=j:
print(j)
value-=j
break
coins=[1,2,5,20,50,100]
coinChange(coins,201) |
9acf48ee3199b69a0fa34542617acf5532a37b2b | will-hossack/Poptics | /examples/surface/SurfacePlot.py | 691 | 3.625 | 4 | """
Example program to create and display a few test surfaces
"""
from poptics.surface import CircularAperture, IrisAperture, SphericalSurface, ImagePlane
import matplotlib.pyplot as plt
def main():
# Make a set of surface
op = ImagePlane(-100,30)
ca = CircularAperture(-10,20)
ia = IrisAperture(50,15).setRatio(0.7)
fs = SphericalSurface(20,0.025,15,"BK7")
bs = SphericalSurface(30,-0.025,15,"air")
ip = ImagePlane(60,40)
# Plot them in a simple diagram
op.draw()
ca.draw()
ia.draw()
fs.draw()
bs.draw()
ip.draw()
plt.axis("equal") # Set the x/y axis to the same scale
plt.show()
main()
|
0af6f2a775a95f9d0869f635fe2c70746e087990 | JM0222/Algorithm-Study | /study-07.py | 598 | 3.65625 | 4 | # https://www.acmicpc.net/problem/9012
# 시간: 15분
n = int(input())
def vps(a):
stack = []
for i in a: # 문자열 순회하면서 '(' 나오면 스택에 append)
if i == "(":
stack.append(i)
else:
if stack: # ')' 나오면 pop (스택이 존재할경우)
stack.pop()
else:
print("NO")
return
if stack: # 스택이 남아있다면
print("NO")
return
else: # 다 비워지면
print("YES")
return
for i in range(n):
a = input()
vps(a) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.