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 |
|---|---|---|---|---|---|---|
b70a66201a3b43f5f1e12493586a7cab42da4fae | ZHANGW31/Learning-Python | /.vscode/FunctionWithReturnValue.py | 391 | 3.9375 | 4 | #type() returns an object type
#type can be called with a float the return value can be stored in a variable
#Example
object_type = type(2.33)
#use the return keyword in a function to return a value after exitiing the functon
def msg_double(phrase):
double = phrase + " " + phrase
return double
#save the return value in a variable
msg_2x = msg_double("let's go")
print(msg_2x) |
61334f64ff50881b2937477f9f5a80de1bac10c4 | nicosandller/python-game-of-life | /test_app.py | 677 | 3.96875 | 4 | import unittest
from board import Board
game = Board(10)
class TestStringMethods(unittest.TestCase):
def test_pos_to_analize(self):
#We need to test that neither of the positions in the set that results from pos_to_analize is outside dimensions
xmax = game.dim
ymax = game.dim
#add a cell on the dimension limit (pos_to_analize should not return a pos outside dimensions)
game.add_cell(pos=(game.dim ,game.dim))
#test that cells being returned are inside dimensions
for pos in game.pos_to_analize():
self.assertTrue(pos[0] <= xmax and pos[1] <= ymax)
if __name__ == '__main__':
unittest.main()
|
222a14c5c904a56b2f5ff83485dd830c1134149f | therealabdi2/Us_states_quiz | /main.py | 1,185 | 3.734375 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("50_states.csv")
all_states = data.state.to_list()
guessed_states = []
while len(guessed_states) < 50:
answer_state = screen.textinput(title=f"Guess the state {len(guessed_states)}/50 States Correct",
prompt="What's another state's name?").capitalize()
if answer_state == "Exit":
missed_states =[state for state in all_states if state not in guessed_states]
new_data = pandas.DataFrame(missed_states)
new_data.to_csv("states_to_learn.csv")
break
if answer_state in all_states:
guessed_states.append(answer_state)
state_info = data[data.state == answer_state]
state_xcor = int(state_info.x)
state_ycor = int(state_info.y)
state_pos = (state_xcor, state_ycor)
t = turtle.Turtle()
t.hideturtle()
t.penup()
t.setposition(state_pos)
t.write(f"{state_info.state.item()}", align="center", font=("Courier", 7, "bold"))
screen.exitonclick()
|
1e05e65118ad3df1c036470a0fc7b98fcd0b1ffc | pr0PM/c2py | /24.py | 721 | 4.21875 | 4 | # This is a program to implement the linear search technique in the
# given array to search an element.
# First we will take an array as input from the user
print('Enter the Array with any no of elements and spaces in between the consecutive elements: ')
l = [x for x in input().split()]
# Enter the element to be searched for
n = input('Enter the search : ')
# implement the search
# using for loop
'''
for i in l:
if i==n:
p = True
else:p = False
if p==True :
print('element present in the entered list !')
else : print('NO such element exists!!!!')
'''
for i in range(len(l)):
if l[i] == n:
print('Element found at position : '+ str(i+1))
# else : print('404 not found')
|
9a27272baf96c67f71b52395bccf82bca8e7fdba | rcsbiotech/learnerboi | /03_rosalind/old_stronghold_scripts/scripts/18_openReadingFrames.py | 7,707 | 3.734375 | 4 | #!/usr/bin/env python
"""
-------------------------------------------------------------------------------
18 - Open Reading Frames
http://rosalind.info/problems/orf/
Given: A DNA string s of length at most 1kbp in FASTA format
Return: Every distinct candidate protein string that can be translated from
ORFs of s, in any order.
Information DNA RNA
Start codon ATG AUG
Stop codon TAG,TGA,TAA UAG,UGA,UAA
-------------------------------------------------------------------------------
"""
## Bibliotecas
import sys ## Para leitura de arquivos
from Bio import SeqIO ## Para captura de arquivos FASTA
from Bio.Seq import Seq ## Processamento de sequências
from Bio.Alphabet import IUPAC ## Tradução de DNA em proteínas
import regex as re ## Para buscar padrões (regex)
## Minhas bibliotecas
from rcsilva import dna2rna
## Verifica se é float
def isfloat(x):
try:
float(x)
return True
except:
return False
## Pica strings 3 por 3
def split(str, num):
return [ str[start:start+num] for start in range(0, len(str), num) ]
## Faz o reverso complementar (3' -> 5')
def revcomp(str):
str_start = str[::-1]
revcomp = ""
for nucl in str_start:
if nucl == "A":
revcomp = revcomp + "T"
elif nucl == "T":
revcomp = revcomp + "A"
elif nucl == "C":
revcomp = revcomp + "G"
elif nucl == "G":
revcomp = revcomp + "C"
return(revcomp)
# Itens únicos
def unique(list1):
# intilize a null list
unique_list = []
# traverse for all elements
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
# print list
for x in unique_list:
print(x)
## Abre o arquivo
fasta_fh = open(sys.argv[1], 'r')
## Captura a sequência única
sequence = SeqIO.read(fasta_fh, "fasta")
strseq = str(sequence.seq)
## Guarda os frames ##
frames = {
"F1" : strseq,
"F2" : strseq[1::],
"F3" : strseq[2::],
"R1" : revcomp(strseq),
"R2" : revcomp(strseq)[1::],
"R3" : revcomp(strseq)[2::]
}
## Guarda as ORFs
possible_orfs = []
## Índice da lista que guarda as sequências
starting_orf = 0
## Flag para limpar a lista a cada passagem
starting_point_flag = 0
## Navega códon a códon, frame a frame
for frame, seq in frames.items():
#print("frame is: ", frame)
#print("seq is: ", seq)
flag_coding = 0
## Limpa as ORFs caso já seja uma segunda passagem
if starting_point_flag == 1:
possible_orfs.append("")
possible_orfs[starting_orf] = ""
## Para cada codon
for string in split(frames[frame], 3):
## Se for trinca
## Se for starting, começa o codificante
if string == "ATG":
# print("It is coding!")
## Declara codificante
flag_coding = 1
## Inicializa uma nova possível ORF
possible_orfs.append("")
starting_point_flag = 1
# Enquanto codificante, guarde as ORFs
if flag_coding > 0:
# print("ORF: ", starting_orf)
possible_orfs[starting_orf] = possible_orfs[starting_orf] + string
# Se chegar em um STOP codon, desmarque codificante
if string == "TAG" or string == "TGA" or string == "TAA":
flag_coding = 0
starting_orf = starting_orf + 1
# Se não for trinca, saia do for
if len(string) < 3:
flag_coding = 0
break
## Processa as ORFs:
## Cria suborfs de ORFS com + de uma metionina
clean_orfs = []
for orf in possible_orfs:
#print(orf)
for match in re.finditer('ATG', orf, overlapped=True):
s = match.start()
neworf = orf[s:len(orf)]
#print(neworf)
clean_orfs.append(neworf)
# print(*clean_orfs)
## Guarda as proteínas
proteins = []
for orf in clean_orfs:
if orf:
#print("ORF: ", orf)
RNA = dna2rna(orf)
prot = Seq(RNA, IUPAC.unambiguous_rna)
prot_final = prot.translate()
prot_final = prot_final[:-1]
proteins.append(prot_final)
# Filtra as proteínas com STOP no meio
proteins_clean = []
for seq in proteins:
strseq = str(seq)
if not re.search("\*", strseq):
proteins_clean.append(strseq)
# Finalmente, dá a saída
repeats = []
for prot in proteins_clean:
if prot not in repeats:
print(prot)
else:
repeats.append(prot)
# ## F1
# for match in re.finditer(r"ATG[A-Z]*(?=(TAG|TGA|TAA))", frames["F1"], overlapped=True):
# s = match.start() + 1
# SF1.append(s)
# for match in re.finditer(r"(TAG|TGA|TAA)", frames["F1"], overlapped=True):
# s = match.start() + 1
# EF1.append(s)
# ## F2
# for match in re.finditer(r"ATG[A-Z]*(?=(TAG|TGA|TAA))", frames["F2"], overlapped=True):
# s = match.start() + 1
# SF2.append(s)
# for match in re.finditer(r"(TAG|TGA|TAA)", frames["F2"], overlapped=True):
# s = match.start() + 1
# EF2.append(s)
# ## F3
# for match in re.finditer(r"ATG[A-Z]*(?=(TAG|TGA|TAA))", frames["F3"], overlapped=True):
# s = match.start() + 1
# SF3.append(s)
# for match in re.finditer(r"(TAG|TGA|TAA)", frames["F3"], overlapped=True):
# s = match.start() + 1
# EF3.append(s)
# print(frames["F1"])
# print(SF1)
# print(EF1)
# print(frames["F2"])
# print(SF2)
# print(EF2)
# print(frames["F3"])
# print(SF3)
# print(EF3)
"""
Seleciona por posição de splice:
"""
# finish_pos = 0
## Para cada posição de start
# for spos in start_pos:
# ## Para cada posição de finish
# for epos in end_pos:
# ## Se houverem ao menos 3 NTs;
# ## Se for a primeira ORF válida;
# if epos-spos > 2 and finish_pos == 0:
# print(strseq[spos-1:epos+2])
# nucl = dna2rna(strseq[spos-1:epos-1])
# nucl = Seq(nucl, IUPAC.unambiguous_rna)
# # print(nucl)
# # print(nucl.translate())
# finish_pos = finish_pos + 1
# finish_pos = 0
# test = Seq(dna2rna(strseq), IUPAC.unambiguous_rna)
# print(test.translate())
""" Old version
Splitting by ATG, my guess is a regex + splice is better
# ## Separa (split) por cada códon de start
# possible_orfs = re.split("ATG", string_seq)
# ## Auto-teste: Todas as ORFs
# # print(possible_orfs)
# possible_orfs = possible_orfs[1:]
# #print(*possible_orfs)
# ## Problema: Devem ser múltiplos de três
# pos_orfs_posit = 0
# for sequence in possible_orfs:
# sequence = str(sequence)
# # Auto-teste: tamanho da sequência
# # Verifica se é multiplo de 3
# #print("Original seq length: ", len(sequence))
# #print("Length/3: ", len(sequence)/3)
# size = len(sequence)
# # Verifica se é int ou float
# while size % 3 != 0:
# # print("Modulus is: ", size % 3)
# sequence = sequence[:-1]
# size = len(sequence)
# possible_orfs[pos_orfs_posit] = sequence
# # print("New size is: ", size)
# # print("New sequence is: ", sequence)
# # Avança a posição
# pos_orfs_posit += 1
# # print(possible_orfs)
# ## Após a tradução para RNA (função própria), traduza em proteína
# for seq_string in possible_orfs:
# rna_string = dna2rna(seq_string)
# print(rna_string)
# #nucl = "AUG" + Seq(rna_string, IUPAC.unambiguous_rna)
# #print(nucl.translate())
"""
|
257215dbbf6c82a03b93bf5e00dc517475d4ec27 | SpykeX3/NSUPython2021 | /problems-1/a-yakovlev/problem5.py | 336 | 3.90625 | 4 | def prime_multipliers(num):
first_num = num
res = []
for curr_del in range(2, int(num**(1/2)) + 1):
power = 0
while num % curr_del == 0:
num //= curr_del
power += 1
if power > 0:
res.append([curr_del, power])
if num != 1: res.append([num, 1])
return res
print(prime_multipliers(int(input("Enter some number ")))) |
d053ee69771f43c9deebd33634d2a5453ad9aac5 | chathaway-codes/gutenberg_readability | /src/score/apply_features.py | 1,889 | 3.671875 | 4 | """ This file defines a function which takens in a list of Gutenberg ID's,
a list of features to apply, and applies those features to the Gutenberg ID's
It then writes these features to a csv file specified in settings.FEATURE_CSV """
from process.story import Story
from settings import FEATURE_CSV
import csv
import os
def run_features(book_ids, features):
read_ids = []
fieldnames = ['book_id'] + [name for name in features]
if os.path.isfile(FEATURE_CSV):
with open(FEATURE_CSV, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
read_ids.append(int(row['book_id']))
else:
with open(FEATURE_CSV, 'a+') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
# Get a list of the books loaded
books = []
# Open the CSV file for writing; headers should be in the form of
# book_id,feature1,feature2,feature3...
for book_id in book_ids:
book = None
if int(book_id) in read_ids:
print "Already processed book", book_id
continue
else:
try:
book = Story(book_id)
print "Loaded book", book_id
except:
print "Error finding book", book_id
continue
book_results = {'book_id': book.book_id}
print "Processing book ", book.book_id
for name in features:
print "->", name
result = features[name](book)
print "--> done!"
book_results[name] = result
with open(FEATURE_CSV, 'a+') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow(book_results)
if __name__ == "__main__":
from process.index import all_functions
run_features([2701], all_functions)
|
b559a6aaaf7a260a0d8ba23eb26770657d732dbe | Aasthaengg/IBMdataset | /Python_codes/p02900/s570895769.py | 582 | 3.546875 | 4 | def main():
N, M = (int(i) for i in input().split())
def prime_factorize(n):
res = []
for i in range(2, n+1):
if i*i > n:
break
if n % i != 0:
continue
ex = 0
while n % i == 0:
ex += 1
n //= i
res.append((i, ex))
if n != 1:
res.append((n, 1))
return res
from math import gcd
g = gcd(N, M)
pf = prime_factorize(g)
ans = 1 + len(pf)
print(ans)
if __name__ == '__main__':
main()
|
fe5b7020f3adec2c09ac23a14110077ea162eb16 | harshchoudhary1998/Pytthon | /assignment1.py | 98 | 3.78125 | 4 | n=int(input("enter the number"));
ty={}
for i in range(1,n+1):
ty.update({i:i*i})
print(ty) |
ca6606aefa442cd82bb9c0331e27476bc6db9816 | GirishSrinivas/PythonProjects | /Coursera_Python/sample_module/ListsExmpl.py | 2,907 | 4.78125 | 5 | """
Lists Examples
"""
LIST1 = ['hello', 'world', 'python']
LIST2 = [2, 3, 4, 5, 6, 7, 'django']
LIST3 = ['hello', 24, 99.9]
print(LIST1)
print(LIST2)
print(LIST3)
# accessing lists using the index
print(LIST1[0])
print(LIST1[1])
print(LIST1[2])
# mutable example
LIST2[0] = 10
print(LIST2)
# length of lists and range() function
print('Length of LIST1: %d' % len(LIST1))
print(range(len(LIST1)))
print('Length of LIST2: %d' % len(LIST2))
print(range(len(LIST2)))
print('Length of LIST3: %d' % len(LIST3))
print(range(len(LIST3)))
# printing each element in the list TYPE - 1
print('\nLIST1\n')
for ele in LIST1:
print(ele)
print('\nLIST2\n')
for ele in LIST2:
print(ele)
print('\nLIST3\n')
for ele in LIST3:
print(ele)
# printing each element in the list using range() function
print('\nLIST1 using range()\n')
for i in range(len(LIST1)):
print(LIST1[i])
print('\nLIST2 using range()\n')
for ele in range(len(LIST2)):
print(LIST2[ele])
print('\nLIST3 using range()\n')
for ele in range(len(LIST3)):
print(LIST3[ele])
# printing each element in the list using enumerate() function
print('\nLIST1 using enumerate()\n')
for i, ele in enumerate(LIST1):
print(LIST1[i])
print(ele)
print('\nLIST2 using enumerate()\n')
for i, ele in enumerate(LIST2):
print(LIST2[i])
print('\nLIST3 using enumerate()\n')
for i, ele in enumerate(LIST3):
print(LIST3[i])
# concat multiple lists
print('\nConcat multiple lists:')
LIST = LIST1 + LIST2 + LIST3
print(LIST)
# slicing in lists
print('\nSlicing in lists:')
print(LIST[1:5])
print(LIST[:5])
print(LIST[4:])
print(LIST[:])
# lists methods
print('\nBuiltin lists methods')
X = list()
print(type(X))
print(dir(X))
X.append('Goutham')
X.append('Arjun')
X.append('Girish')
print('\nBefore sorting:')
print(X)
print('\nAfter sorting:')
X.sort()
print(X)
print(max(X))
# building a list
print('\nBuilding a list from scratch')
STUFF = list() # list constructor to instantiate an empty list
# empty list can be instantiated by a pair of empty square brackets, i.e. STUFF = []
# adding elements to the list
for i in range(5):
STUFF.append(i)
print(STUFF)
# the 'in' and 'not in' operator
print(10 in STUFF)
print(3 in STUFF)
print(5 not in STUFF)
print(max(STUFF)) # extracts the max element in the list
print(min(STUFF)) # extracts the min element in the list
print(sum(STUFF)) # calculates the sum of all the elements in the list
# summing n numbers
print('sum of N numbers')
NUMLIST = list()
while True:
NUM = raw_input('\nEnter a number or press \'done\'')
if NUM == 'done':
break
else:
try:
VAL = float(NUM)
NUMLIST.append(VAL)
except ValueError:
print('Enter proper input')
SUM = sum(NUMLIST)
print(SUM)
# strings and lists
print('strings and lists')
STR = 'Words with different length'
WORDS = STR.split()
print(WORDS)
|
cb2e30f16873c787351f5356f599d7eeab05c2e0 | llamo-unprg28/trabajo06_llamot.catter | /llamo/multiple7.py | 453 | 3.6875 | 4 | # mostrar en ciclo esta persona
#declaracion
edaad=0
import os
#INPUT
edad=int(os.sys.argv[1])
#PROCESSING
if (edad>0 and edad<=4):
print("se encuentra en la infancia")
if (edad>4 and edad<=12):
print("se encuentra en la niñez")
if (edad>12 and edad<=17):
print("se encuentra en la adolescencia")
if (edad>17 and edad<=25):
print("se encuentra en la juventud")
if (edad>26 and edad<=35):
print("se encuentra en la adultez")
|
947ee9af410cd0955cd67d9a78df62d71bcad529 | csalley95/COMP151 | /CSalleyLab1.py | 943 | 4.21875 | 4 | #Student: Christopher Salley
# Python program to check if the input number is prime or not
num = int(input("Enter a number: ")) # num is declared as in integer
if num > 1: # prime numbers are greater than 1
for i in range(2, num): # check for factors
if (num % i) == 0: # It will run through the for loop until remainder is zero
print(num, "is not a prime number") # when number is equal to zero it will print number is not prime
print(i, "times", num // i, "is", num)
break # stops the for loop when loop is met
else: # if num is only divisible by 1 and itself then its prime
print(num, "is a prime number")
else:
print(num, "is not a prime number") # if input number is less than or equal to 1, it is not prime
|
4eb6595475bf2aa60f1514e03f766c8541469473 | rakeshkannayyagari/seleniumPratice | /basicProg/SecondCalssforInheratence.py | 773 | 3.578125 | 4 | class SealingFan(object):
def __init__(self, company, color, status='available', makeyear='2021' ):
self.manufacturedcompany=company
self.color=color
self.available=status
self.makeyear=makeyear
def info(self):
print('Requested Fan is a sealing fan, manufactured by '+self.manufacturedcompany+ ' available in '+self.color+' color '+
' currently stock is '+self.available+' make year is '+self.makeyear)
def getorder(self):
print("Get the order from customer")
def packorder(self):
self.getorder()
print('Pack required number of orders')
def delever(self):
self.packorder()
print('Delever the order')
c1=SealingFan('Usha','Black')
c1.info()
c1.getorder()
|
44cb87f8dd08b19b65f16a83b91ce31c59282a6a | violachyu/Python_Challenge | /002.py | 1,327 | 4.28125 | 4 | ''' Python Challenge - 2
Use the function called morse_code. It will take 1 parameter, a word. For example: 'apple'.
Using the given morse code translation, return a single string with the word translated into morse code.
Ex: 'dot-dash-dot-dash-dash-dot-dot-dash-dash-dot-dot-dash-dot-dot-dot'
'''
def morse_code(word):
morse_dict = {
'a': 'dot-dash',
'b': 'dash-dot-dot-dot',
'c': 'dash-dot-dash-dot',
'd': 'dash-dot-dot',
'e': 'dot',
'f': 'dot-dot-dash-dot',
'g': 'dash-dash-dot',
'h': 'dot-dot-dot-dot',
'i': 'dot-dot',
'j': 'dot-dash-dash-dash',
'k': 'dash-dot-dash',
'l': 'dot-dash-dot-dot',
'm': 'dash-dash',
'n': 'dash-dot',
'o': 'dash-dash-dash',
'p': 'dot-dash-dash-dot',
'q': 'dash-dash-dot-dash',
'r': 'dot-dash-dot',
's': 'dot-dot-dot',
't': 'dash',
'u': 'dot-dot-dash',
'v': 'dot-dot-dot-dash',
'w': 'dot-dash-dash',
'y': 'dash-dot-dash-dash',
'z': 'dash-dash-dot-dot'
}
# enter your code below
result = ""
for index, letter in enumerate(word):
if index == 0:
result += f"{morse_dict[letter]}"
else:
result += f"-{morse_dict[letter]}"
return result |
feb8c2b3551a260dedffc2a1396e0b72f09713bc | zhudotexe/aoc_2019 | /14/1.py | 1,783 | 3.609375 | 4 | import collections
class Dependency:
def __init__(self, chemical, number):
self.chemical = chemical
self.number = number
@classmethod
def parse(cls, s):
num, chem = s.split(' ')
return cls(chem, int(num))
def __str__(self):
return f"{self.number} {self.chemical}"
class Reaction:
def __init__(self, outputs, inputs):
self.outputs = outputs
self.inputs = inputs
@classmethod
def parse(cls, s):
ins, outs = s.split(" => ")
return cls([Dependency.parse(c) for c in outs.split(', ')], [Dependency.parse(c) for c in ins.split(', ')])
def __str__(self):
return f"{', '.join([str(d) for d in self.inputs])} => {', '.join([str(d) for d in self.outputs])}"
def __repr__(self):
return str(self)
def run(fp):
reactions = {} # output (str): Reaction
with open(fp) as f:
reaction_data = [l.strip() for l in f.readlines() if l]
for reaction in map(Reaction.parse, reaction_data):
for out in reaction.outputs:
reactions[out.chemical] = reaction
print(reactions)
produced = collections.defaultdict(lambda: 0)
wanted = collections.defaultdict(lambda: 0, FUEL=1)
def execute(r):
for dep in r.inputs:
wanted[dep.chemical] += dep.number
for dep in r.outputs:
produced[dep.chemical] += dep.number
running = True
while running:
running = False
for chem, num in wanted.copy().items():
if produced[chem] < num and chem in reactions:
running = True
reaction = reactions[chem]
execute(reaction)
print(wanted['ORE'])
if __name__ == '__main__':
run(input("File: ") or 'in.txt')
|
7f18cf4075648d529d0b0c1e30b44536723806cd | iac-nyc/Python | /Python2.7/ichowdhury_2.3.py | 530 | 3.734375 | 4 | # Name : Iftekhar Chowdhury
# Date : Oct 31, 2015
# Homework 2.3
sample_text = """ And since you know how you cannot see yourself,
so well as by reflection, I, your glass,
will modestly discover to yourself,
that of yourself which you yet know not of. """
search_string = raw_input ('Please enter a text to replace:')
new_string = raw_input ('Please enter the replacement text: ')
count = sample_text.count(search_string)
print "{} replacements made".format(count)
new_text = sample_text.replace(search_string, new_string)
print new_text
|
e74c35f2b220f74484dc1dab8c5a80922fcfe613 | RishikaMachina/Trees-1 | /Problem_2.py | 678 | 3.75 | 4 | # Runs on Leetcode
# Runtime complexity - O(n^2)
# Memory complexity - O(n)
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not preorder or not inorder:
return None
root = TreeNode(preorder[0])
index = inorder.index(preorder[0])
left_inorder = inorder[:index]
right_inorder = inorder[index+1:]
left_preorder = preorder[1:1+index]
right_preorder = preorder[1+index:]
root.left = self.buildTree(left_preorder,left_inorder)
root.right = self.buildTree(right_preorder,right_inorder)
return root
|
e29968769dc60cafd4feae97bfe4098956838a93 | syx1999/123 | /3.5.py | 323 | 3.625 | 4 | num0=eval(input('请输入一个数字:'))
if num0<=1:
print('这不是质数')
elif num0==2:
print('这是一个质数')
else:
i=2
while i<num0:
if num0%i==0:
print('这不是一个质数')
break
i=i+1
else:
print('这是一个质数')
|
3a0113e9bf0512faeba53b1de1069dc6b2874707 | AlphaGarden/LeetCodeProblems | /Easy/Maximum_Subarray.py | 1,136 | 4.1875 | 4 | '''
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
Conclusion: Key point of the solution : we should know that the first thing to
solve a dynamic programming problem is to figure out the sub problem, and in this
question the sub problem is the
'''
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Brute Force Method
ans = nums[0]
for i in range(len(nums)):
for j in range(i,len(nums)):
ans = max(ans, sum(nums[i:j+1]))
return ans
# Optimized method
# Dynamic programming
def maxSubArray2(self,nums):
dp = []
dp.append(nums[0])
ans = dp[0]
for i in range(1,len(nums)):
dp.append(nums[i] + (dp[i-1] if dp[i-1] >0 else 0))
ans = max(ans,dp[i])
return ans
solution = Solution()
testcase1 = [-2,1,2]
print (solution.maxSubArray2(testcase1)) |
4ea38cf9c89fee0635a478d2358e04b2e3e3a2cd | Chunkygoo/Algorithms | /Heaps/mergeSortedArrays.py | 2,780 | 3.515625 | 4 | # O(NlogK + K) T O(N+K) S
def mergeSortedArrays(arrays):
sortedList = []
smallestElements = []
for i in range(len(arrays)):
smallestElements.append({"arrayIndex": i, "elementIndex": 0, "num": arrays[i][0]})
minHeap = MinHeap(smallestElements)
while not minHeap.isEmpty():
smallest = minHeap.remove()
arrayIndex, elementIndex, num = smallest["arrayIndex"], smallest["elementIndex"], smallest["num"]
sortedList.append(num)
if elementIndex != len(arrays[arrayIndex])-1:
minHeap.insert({"arrayIndex": arrayIndex, "elementIndex": elementIndex+1, "num": arrays[arrayIndex][elementIndex+1]})
return sortedList
class MinHeap:
def __init__(self, array):
# Do not edit the line below.
self.heap = self.buildHeap(array)
# O(1) T O(1) S
def isEmpty(self):
return len(self.heap)==0
# O(N) T O(1) S
def buildHeap(self, array):
lastIndex = (len(array)-1)
lastParentIndex = int((lastIndex-1)/2)
while lastParentIndex >= 0:
self.siftDown(lastParentIndex, array)
lastParentIndex -= 1
return array
# O(logN) T O(1) S
def siftDown(self, index, array):
while (2*index+1) <= len(array):
currentNode = array[index]["num"]
childOne, i1 = self.getChildOne(index, array)
childTwo, i2 = self.getChildTwo(index, array)
if min(childOne, childTwo) == childOne:
minChild = childOne
swapIndex = i1
else:
minChild = childTwo
swapIndex = i2
if minChild < currentNode:
self.swap(index, swapIndex, array)
index = swapIndex
else:
break
return array
# O(logN) T O(1) S
def siftUp(self, index, array):
while index >= 0:
parent, swapIndex = self.getParent(index)
if parent > self.heap[index]["num"]:
self.swap(index, swapIndex, array)
index = swapIndex
else:
break
return self.heap
# O(1) T O(1) S
def peek(self):
return self.heap[0]
# O(logN) T O(1) S
def remove(self):
self.swap(0, len(self.heap)-1, self.heap)
removed = self.heap[-1]
self.heap = self.heap[:-1]
self.siftDown(0, self.heap)
return removed
# O(logN) T O(1) S
def insert(self, value):
self.heap.append(value)
self.siftUp(len(self.heap)-1, self.heap)
# O(1) T O(1) S
def getChildOne(self, index, array):
if 2*index+1 <= len(array)-1:
return array[2*index+1]["num"], 2*index+1
else:
return float("inf"), -1
# O(1) T O(1) S
def getChildTwo(self, index, array):
if 2*index+2 <= len(array)-1:
return array[2*index+2]["num"], 2*index+2
else:
return float("inf"), -1
# O(1) T O(1) S
def getParent(self, index):
return self.heap[int((index-1)/2)]["num"], int((index-1)/2)
# O(1) T O(1) S
def swap(self, index1, index2, array):
array[index1], array[index2] = array[index2], array[index1] |
fbde6e9eec1d14bb0fd7c390817605f03392c32d | bpriddy83/Python-Labs | /Lab4C-unique-visitors.py | 992 | 4.03125 | 4 | # Brianna Priddy
# CSCI 101 MWF 12pm
# Lab 4C - unique visitors
# Request an input of a comma separated string (e.g. "orden, Azam, OrdeN, Nhan")
print("Enter a list of names separated with commas.")
inputNames = input("LIST>")
usedAlready = False
nameList = []
words = [word for word in inputNames.split(",")]
for word in words:
# if the used words list is empty, add the word
if len(nameList) == 0:
nameList.append(word)
# otherwise, if the word has been used already, let the program no
else:
for checkWord in nameList:
if checkWord == word:
usedAlready
print("\n", word, "was already used")
if not usedAlready:
nameList.append(word)
for name in nameList:
if not nameList[0]:
print(end=",")
print(name, end="")
for name in nameList:
if not nameList[0]:
print(end=",")
print(name, ",", nameList.count(name), end="") |
9cec2351b63ccc8e54d9f12446ebacb6fbe72987 | hofmanng/algoritmos-faccat | /prog094.py | 648 | 3.984375 | 4 | #
# Melhore o exercicio 93 para aceitar somente valor maior ou igual a
# zero para o numero lido e tambem para testar se o numero for igual a
# zero. O fatorial de zero e 1(0!=1).
#
# Declaracao das variaveis e entrada de dados
n = int(input("Insira um valor: "))
mlt = 1
# Testes condicionais e loop
if n >= 0:
if n == 0:
mlt = 1
print " = ", mlt
else:
for num in range(1, n + 1):
print num,
if num < n:
print "x",
mlt = mlt * num
else:
# Saida de dados
print " = ",mlt
else:
# Mensagem de erro
print("Valor invalido.")
|
0aee1795896ce4b7a18e5ab5307dedea75737d5c | CarloShadow/CodesByCJ | /Python/Exercicios/Coleções Python/Part 1/Ex18(inacabado).py | 664 | 3.875 | 4 | """
ler um número determinado de vetores
ler um número x
contar o multiplos do número x no vetor
mostrar os números na tela
"""
# lista = []
#
# for i in range(5):
# n = int(input('Digite valor: '))
# lista.append(n)
# for e in range(1):
# x = int(input('Digite para o calculo: '))
# if n % x == 0:
# print(x)
lista = []
iguais = []
for i in range(0, 5):
n = int(input('Digite valor: '))
lista.append(n)
x = int(input('Digite o número para o calculo: '))
if n % x == 0:
iguais.extend(x)
conta = iguais.count()
print(iguais)
print(conta)
else:
print(f'Esse número não é multiplo de {iguais.append(x)}')
|
4e9ce9f6c96cfcf5678a40311dfa043b77838453 | RayGutt/python | /python-basic-exercises/7.py | 249 | 4.625 | 5 | # Write a Python program to accept a filename from the user and print the extension of that
filename = input("Enter a filename: ")
extension = filename.split(".")
print("The extension for the file " + str(filename) + " is " + str(extension[-1]))
|
ccb96edd6d6d714dd41e5f966a58e9dd43f7293d | RY-2718/oasobi | /to_light_blue_coder_100_problems/patterns_search/16.py | 1,133 | 3.625 | 4 | memo = {}
def enumerate_patterns(parts):
if len(parts) == 1:
return [parts]
if str(parts) in memo:
return memo[str(parts)]
patterns = []
for i in range(len(parts)):
patterns += [
[parts[i]] + x for x in enumerate_patterns(parts[:i] + parts[i + 1 :])
]
memo[str(parts)] = patterns
return patterns
def binary_search(l, v, isOK):
ng = -1
ok = len(l)
while abs(ng - ok) > 1:
mid = (ng + ok) // 2
if isOK(l, mid, v):
ok = mid
else:
ng = mid
return ok
def main():
n = int(input())
p = list(map(int, input().split(" ")))
q = list(map(int, input().split(" ")))
patterns = enumerate_patterns(list(range(1, n + 1)))
def _isOK(l, mid, v):
m = l[mid]
for i in range(len(m)):
if v[i] > m[i]:
return False
elif v[i] < m[i]:
return True
return True
i_p = binary_search(patterns, p, _isOK)
i_q = binary_search(patterns, q, _isOK)
print(abs(i_p - i_q))
if __name__ == "__main__":
main() |
23c61bed26009e44a524a9739460fe035965fd81 | bala4rtraining/python_programming | /python-programming-workshop/Day3Solutions/KarthikAnswers/0331_hw10_shuffle_cards.py | 508 | 3.984375 | 4 |
# ooohh cool, i did not know this way, very nice
# no comments, the program is much better than the one
# I did
#create a deck of cards and shuffle it using a list
import random
cardList = []
for i in range(1,14) :
cardList.append("Club"+str(i))
cardList.append("Diamond"+str(i))
cardList.append("Heart"+str(i))
cardList.append("Spade"+str(i))
print("original pack...")
print(cardList)
print("after shuffling the pack...")
random.shuffle(cardList)
print(cardList)
|
c6d999197385ac11e3a0ec9f7fbd8c782dd70065 | helgelol/wcapp | /wcapp.py | 1,164 | 3.921875 | 4 | #!/usr/bin/python
# Takes input for yearly salary
def take_input1():
inputData1 = input("Ka du tjen i året? ")
# Check if input was int
try:
inputData1 = int(inputData1)
# If not int then prompts user
except ValueError:
print("Bruk tall, du tjen ikke bokstava. ")
# And tries again
inputData1 = take_input1()
return inputData1
# Takes input for yearly salary
def take_input2():
inputData2 = input("Kor lenge va du på dass? (minutta) ")
# Check if input was int
try:
inputData2 = int(inputData2)
# If not int then prompts user
except ValueError:
print("Bruk tall, kan du ikke klokka? ")
# And tries again
inputData2 = take_input2()
return inputData2
# Puts salary from variable
salary = take_input1()
# Puts time from variable
time = take_input2()
# Joins it together and tells you how much you earned
shitMoney = int((salary / 1850) / 60 * time)
# And prints it
#print('You earned '(shitmoney)' while sitting on the throne.')
print('Du tjent {} krona mens du satt å dreit.'.format(shitMoney)) |
e7c785d9e0a055f9eb64ed2c54cba09a00c2ad13 | ashsek/congruency | /helper.py | 1,588 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 14:11:37 2018
@author: ashwin
"""
congurent = []
class coordinate(object):
"""
coordinate class for easy storing of points
"""
def __init__(self,x,y):
self.x = x
self.y = y
def distance(self,other):
dx = self.x - other.x
dy = self.y - other.y
return (dx**2 + dy**2)**0.5
def __str__(self):
return "<%s,%s>"%(self.x, self.y)
def __repr__(self):
return "<%s,%s>"%(self.x, self.y)
class triangle(object):
"""
class triangle which keeps a record of sides
"""
def __init__(self,p1,p2,p3):
self.p1 = p1
self.p2 = p2
self.p3 = p3
def __str__(self):
return "Triangle(%s,%s,%s)"%(self.p1, self.p2, self.p3)
def __repr__(self):
return "Triangle(%s,%s,%s)"%(self.p1, self.p2, self.p3)
def sides(self):
s = []
s.append(self.p1.distance(self.p2))
s.append(self.p2.distance(self.p3))
s.append(self.p3.distance(self.p1))
s.sort()
return s
def ispossibletriangle(triang):
"""
This checks given any triangle object as input weather it is a valid triangle or not
"""
sp = triang.sides()
if sp[0] < sp[1] + sp[2]:
return True
else:
return False
def cong(t1,t2):
"""
t1 and t2 are two triangle objects , it appends the result of congurent triangles
"""
if t1.sides() == t2.sides():
congurent.append([t1,t2]) |
7cbf38c10ed93d437d70378070c1bd43b62fd8c6 | JustLunox/BMI-calculator | /BMI caculator.py | 467 | 4.28125 | 4 | # BMI calculator
name = raw_input("Please enter your name: ")
height_m = input("Please enter your height in meter: ")
weight_kg = input("Please enter your weight in kg: ")
def bmi_caculator(name, height_m, weight_kg):
bmi = weight_kg / (height_m ** 2)
print("bmi: ")
print(bmi)
if bmi < 25:
return name + " is not overweigth"
else:
return name + " is overweight"
result = bmi_caculator(name, height_m, weight_kg)
print(result)
|
0916307fba0caa5a7800d688e8782b966cc00308 | gabriellaec/desoft-analise-exercicios | /backup/user_089/ch54_2020_04_13_15_28_04_003493.py | 225 | 3.578125 | 4 | def calcula_fibonacci(n):
i = 0
CF = []
fib = []
fib.append(1)
fib.append(1)
while fib[i] < n:
fib[i+2] = fib[i] + fib[i+1]
i += 1
CF.append(fib[i+2])
return CF
|
14e7ff0554647d2f83ec9bbea65a182c9420ccaf | xuychen/Leetcode | /301-400/321-330/328-oldEvenLinkedList/oldEvenLinkedList.py | 1,380 | 3.890625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
odd = head
even_head = even = head.next if head else None
prev = None
while odd and even:
prev = odd
odd.next = even.next
odd = odd.next
if odd:
even.next = odd.next
even = even.next
if odd:
odd.next = even_head
elif prev:
prev.next = even_head
return head
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
odd_node = dummy_head = ListNode(None)
even_node = dummy_head2 = ListNode(None)
node = head
while node and node.next:
odd_node.next = node
even_node.next = node.next
odd_node = odd_node.next
even_node = even_node.next
node = even_node.next
if node:
odd_node.next = node
odd_node = odd_node.next
even_node.next = None
odd_node.next = dummy_head2.next
return dummy_head.next |
c7eacdcbfd5f1264a18296983df91a830cd03ed4 | maximashuev/mike_udemy_course | /while_for_loops.py | 270 | 3.578125 | 4 | """
"""
target=[1,2,3,4,5,6,7,8,9,10]
target_string="Python:Best course"
ind=3
while ind <len(target):
print(target[ind])
ind +=1
# counter=12
# while counter:
# print(counter)
# counter-=1
# while counter!=-10:
# print(counter)
# counter-=1
|
b13446fa392c290b30195d33b456749e9ae14054 | strickb2/Lab-Sheets | /2020-03-23/ca278/strickb2/recursion06.py | 472 | 3.921875 | 4 | #!/usr/bin/env python
import time
def countdown(num):
if num == 0:
print "LIFT OFF!"
else:
print num
time.sleep(0.1)
num = num - 1
countdown(num)
def search(the_str,letter):
if the_str == "":
return False
elif the_str[0] == letter:
return True
else:
return search(the_str[1:],letter)
def previous_two(n):
if n == 0:
return 0
if n == 1:
return 1
else:
return previous_two(n-1) + previous_two(n-2)
|
754f1944c53c0ee26e7b1f4510e1e4c890159207 | NityanandaBarbosa/Estrutura-de-Dados---Python | /PilhaEncadeada.py | 1,395 | 3.703125 | 4 | class No:
def __init__(self):
self.valor = None
self.prox = None
def setValor(self,valor):
self.valor = valor
def getValor(self):
return self.valor
def setProx(self, prox):
self.prox = prox
def getProx(self):
return self.prox
class Pilha:
def __init__(self):
self.topo = None
def setTopo(self, topo):
self.topo = topo
def push(self, valor):
novoNo = No()
novoNo.setValor(valor)
novoNo.setProx(self.topo)
self.setTopo(novoNo)
def pop(self):
if(Pilha.isEmpty(self)):
print("Pilha esta vazia, impossivel remover dado!")
else:
self.setTopo(self.topo.getProx())
def imprimir(self):
noAux = self.topo
impressao = True
while(impressao == True):
if(noAux.getProx() != None):
print(noAux.getValor())
noAux = noAux.getProx()
else:
print(noAux.getValor())
print("")
impressao = False
def isFull(self):
return False
def isEmpty(self):
if(self.topo == None):
return True
else:
return False
p1 = Pilha()
p1.push(45)
p1.push(49)
p1.imprimir()
p1.pop()
p1.imprimir()
p1.push(499)
p1.imprimir() |
9472e2c68ba75a10faffabcf705d1fc711f3f99a | Hyowon83/PythonStudy | /inSAT/practice/과제.py | 4,366 | 3.796875 | 4 | # x=input('x값을 입력하세요. : ')
# x=int(x)
# y=input('y값을 입력하세요. : ')
# y=int(y)
# if x<y:
# print(x)
# else:
# print(y)
# print()
# a=input('a=')
# a=int(a)
# b=input('b=')
# b=int(b)
# if a==b*4:
# print(a)
# else:
# print(b)
# print()
# val=input('값을 입력하세요. : ')
# val=int(val)
# if val%3==0:
# print(val,"입력한 값은 3의 배수입니다.")
# else:
# print(val,"입력한 값은 3의 배수가 아닙니다.")
# z=input('값을 입력하세요. : ')
# z=int(z)
# if z%3==0 and z%2==0:
# print(z,"입력한 값은 3과 2의 공배수입니다.")
# else:
# print(z)
# for i in range(0,13,2): //0부터 12까지 2씩 증가
# print(i)
# for i in range(13,0,-2): //13부터 1까지 2씩 감소
# print(i)
# for i in range(3,101,3): //3부터 100까지 3의배수
# print(i)
# n = int(input()) + 1
# sum = 0
# for i in range(1, n): //1부터 입력받은 값까지의 전체 합
# sum += i
# print(sum)
# sum = 0
# for i in range(1,101): //1부터 100까지의 전체 합
# sum = sum + i
# print(sum)
# sum = 0
# i = 1
# while i <= 10:
# sum = sum + i
# i = i + 1
# print(sum)
# i=-1
# while i < 30:
# print(i)
# i = i + 3
# #구구단
# for i in range(2, 10):
# for j in range(1, 10):
# #print(i,' * ',j,' = ',i*j)
# print("{} * {} = {}".format(i, j, i * j))
# print()
# #구구단2
# i = 2
# while i <= 9:
# j = 1
# while j <= 9:
# print("{} * {} = {}".format(i, j, i * j))
# j = j + 1
# i = i + 1
# print()
#### 6/19
# student = []
# n = input('이름 : ') # 홍길동
# while n != '':
# student.append({'name':n})
# n = input('이름 : ')
# print(student)
# student = []
# while True:
# # 학생의 이름을 입력받는다.
# name = input()
# if name == "": # 학생의 이름이 빈 문자열이라면 종료
# break
# else: # 빈 문자열이 아니라면 딕셔너리에 추가한다.
# student.append({"name": name})
# print(student)
# 각 학생의 이름, 영어점수, 수학점수를 입력받고
# 각 학생정보는 딕셔너리에 모든 학생은 리스트에 저장하세요
# students = []
# studentsList = []
# name = input('이름 : ')
# eng = input('영어점수 : ')
# math = input('수학점수 : ')
# allStudent = 0
# engTotal = 0
# mathTotal = 0
# while name != '':
# students.append({'name':name,'영어점수':eng,'수학점수':math})
# studentsList.append(name)
# name = input('이름 : ')
# eng = float(eng)
# math = float(math)
# allStudent += 1
# engTotal += eng
# mathTotal += math
# if name == '':
# break
# else:
# eng = input('영어점수 : ')
# math = input('수학점수 : ')
# print(students)
# print(studentsList)
# print("영어점수와 수학점수의 총 합: ",engTotal+mathTotal)
# print("영어 평균: ",engTotal/allStudent)
# print("수학 평균: ",mathTotal/allStudent)
#2
students = []
scores = [0.0, 0.0, 0.0, 0.0]
ENG_TOTAL = 0
MATH_TOTAL = 1
ENG_AVG = 2
MATH_AVG = 3
while True:
name = input("이름: ")
if name == "":
break
mat = float(input("수학 점수: "))
eng = float(input("영어 점수: "))
students.append({"이름": name, "수학 점수": mat, "영어 점수": eng})
for student in students:
scores[MATH_TOTAL] += student["수학 점수"]
scores[ENG_TOTAL] += student["영어 점수"]
scores[MATH_AVG] = scores[MATH_TOTAL] / len(students)
scores[ENG_AVG] = scores[ENG_TOTAL] / len(students)
print("수학 점수의 총합: {}".format(scores[MATH_TOTAL]))
print("영어 점수의 총합: {}".format(scores[ENG_TOTAL]))
print("수학 점수의 평균: {}".format(scores[MATH_AVG]))
print("영어 점수의 평균: {}".format(scores[ENG_AVG]))
#3 함수로 표현하는 방법
student = []
def getPoint(x):
eng = input('영어점수: ')
mat = input('수학점수: ')
d = {'name':x,'영어점수: ':eng,'수학점수: ':mat}
return d #실행된 함수의 결과를 반환해서 사라지지 않게한다.
while True:
name = input('이름: ')
if name == '':
break
student.append(getPoint(name)) #위에 정의된 함수 x자리에 name값을 넣는다. #return된 d값이 getPoint(name)에 들어간다.
print(student) |
1fca3aed36b5fa3e93d9e390ba9a4ea3fbcfcd03 | Wattyyy/LeetCode | /submissions/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/solution.py | 356 | 3.6875 | 4 | # https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
sentences = sentence.split(" ")
for i, word in enumerate(sentences):
if word.startswith(searchWord):
return i + 1
return -1
|
ee545e7952876990c2dcb892b9aaebf688ce1820 | shumbul/DSA | /Algorithms/Sorting Algorithms/Python/bubbleSort.py | 309 | 4.15625 | 4 | def bubbleSort(array):
n=len(array)
for i in range(0,n):
for j in range(i,n-i-1,-1):
if(array[j]<array[j-1]):
array[j],array[j-1]=array[j-1],array[j] #swapping process
return array
a=[1,2,4,3,0,6,7,8,12,11] #edit as needed
print(bubbleSort(a))
|
b823bb3cbd1a188ff7c203dd626bbc48d17f3891 | DonghaiYu/pyDP | /pyDP.py | 7,295 | 3.734375 | 4 | # -*- coding: utf8 -*-
# @Time : 2016/11/30 13:34
# @Author : Dylan东海
# @Site :
# @File : pyDP.py
# @Software: PyCharm Community Edition
"""
This is an implementation of Douglas-Peucker Algorithm, which can be used for trajectory compression.
When there are enough points in a trajectory, this algorithm can find the key point in the trajectory.
This tool support high dimension points.
depend on: numpy 1.11.2, python 3.5.2
"""
import numpy as np
import math
EARTH_RADIUS = 6378.137
'''
STANDARD = 0
MARS = 1
'''
def distance_point2line_standard(a, b, c, distance_index):
"""Calculate the distance from a point to a line on the plane, when the line is decided by two points.
the equation: |vector(ac)-vector(ab)·(vector(ac)·vector(ab)/|vector(ab)|²)|,
a, b decide a line, c is the target point.
:param a: the first line point
:param b: the second line point
:param c: the target point
:param distance_index: which fields in a point are considered when calculating distance
:return: the distance to line which is decided by point a and point b
"""
if len(a) != len(b) or len(a) != len(c):
print("there are different sizes between the points!")
return
for i in distance_index:
if i >= len(a):
print("fields index out of range")
return
af = []
bf = []
cf = []
for i in distance_index:
af.append(a[i])
bf.append(b[i])
cf.append(c[i])
a_f = np.array(af, dtype="float")
b_f = np.array(bf, dtype="float")
c_f = np.array(cf, dtype="float")
ab = a_f - b_f
bc = b_f - c_f
ac = a_f - c_f
return sum((ac - sum(ac * ab) / sum(ab**2) * ab)**2)**0.5
def distance_point2line_mars(a, b, c, distance_index):
"""Calculate the distance from a point to a line on the Mars(Gaode) coordinate system, when the line is decided by two points.
There must be longitude and latitude in each point, and the result is the actual distance from c to the line <a, b>,
the equation(Heron): (2 * sqrt(p(p-distance(a, b))(p-distance(b, c))(p-distance(a, c)))) / distance(a, b);
(p = (distance(a, b) + distance(b, c) + distance(a, c)) / 2)
a, b decide a line, c is the target point.
:attention: the result of this method may be smaller than the actual distance,
but we hope it is not matter when the 3 points are in a small area(e.g the urban area)
:param a: the first line point
:param b: the second line point
:param c: the target point
:param distance_index: which fields in a point are considered when calculating distance,
limit on 2(longitude, latitude)
:return: the distance to line which is decided by point a and point b on earth surface.
"""
if len(a) != len(b) or len(a) != len(c):
print("there are different size between the points!")
return
if len(a) < 2:
print("at least 2 dimensions are needed in your point")
return
if len(distance_index) != 2:
print("the longitude and latitude index are needed")
return
lng_index = distance_index[0]
lat_index = distance_index[1]
ab = mars_distance(a[lat_index], a[lng_index], b[lat_index], b[lng_index])
bc = mars_distance(b[lat_index], b[lng_index], c[lat_index], c[lng_index])
ac = mars_distance(a[lat_index], a[lng_index], c[lat_index], c[lng_index])
p = (ab + bc + ac) / 2
return 2 * math.sqrt(p * (p - ab) * (p - bc) * (p - ac)) / ab
def rad(d):
return d * math.pi / 180.0
def mars_distance(lat1, lng1, lat2, lng2):
"""
:param lat1: latitude of point1
:param lng1: longitude of point1
:param lat2: latitude of point2
:param lng2: longitude of point2
:return: the distance between point1 and point2 on the Mars(Gaode) coordinate system
"""
rad_lat1 = rad(lat1)
rad_lat2 = rad(lat2)
a = rad_lat1 - rad_lat2
b = rad(lng1) - rad(lng2)
s = 2 * math.asin(math.sqrt(math.pow(math.sin(a / 2), 2) +
math.cos(rad_lat1) * math.cos(rad_lat2) * math.pow(math.sin(b / 2), 2)))
s *= EARTH_RADIUS
return math.fabs(s * 1000)
def trajectory_compression(raw_trajectory, threshold, distance_index, distance_function):
"""
:param raw_trajectory: the trajectory data, exp: [[x1, y1], [x2, y2], ... , [xn, yn]]
:param threshold: distance threshold
:param distance_index: which fields in a point are considered when calculating distance
:param distance_function: method for calculating distance
:return: compressed trajectory
"""
if len(raw_trajectory) < 2:
print("less than 2 points in your trajectory!")
return
try:
threshold = float(threshold)
except:
print("can`t trans the threshold(type%s) to float" % type(threshold))
return
key_arr = [0 for i in range(len(raw_trajectory))]
key_arr[0] = 1
key_arr[len(raw_trajectory)-1] = 1
find_far_point(raw_trajectory, 0, len(raw_trajectory)-1, distance_index, threshold, key_arr, distance_function)
key_points = []
for i in range(len(key_arr)):
if key_arr[i] == 1:
key_points.append(raw_trajectory[i])
return key_points
def find_far_point(arr, i, j, distance_index, threshold, flag_arr, dist_fun):
"""
This function is used for finding the farthest points (to line (arr[i], arr[j])) in sub trajectory arr(i, j),
it recurs until there are no more points's distance is larger than threshold to the line. if a point is not
ignored in the trajectory, it's index in flag_arr will be set as 1, otherwise 0.
:param arr: trajectory data
:param i: start index
:param j: end index
:param distance_index: which fields in a point are considered when calculating distance
:param threshold: distance threshold
:param flag_arr: the flag array of useful or ignore for the trajectory points(0:ignore, 1:useful)
:param dist_fun: method for calculating distance
:return: none, but change the flag_arr
"""
if i > len(arr) or j > len(arr):
print("index out of range")
return
max_distance = float(0)
flag = -1
for k in range(i + 1, j):
d = dist_fun(arr[i], arr[j], arr[k], distance_index)
if d > max_distance:
max_distance = d
flag = k
if max_distance > threshold:
flag_arr[flag] = 1
find_far_point(arr, i, flag, distance_index, threshold, flag_arr, dist_fun)
find_far_point(arr, flag, j, distance_index, threshold, flag_arr, dist_fun)
'''
arrs = [[1, 1, 1, 'x'], [2, 2, 2, 'y'], [3, 3, 3, 'z']]
arrs2 = [[116.368904, 39.913423], [116.368904, 39.923423], [116.398258, 39.904600]]
narrs = trajectory_compression(arrs, "0.0007", [0, 1, 2], distance_point2line_plane)
narrs2 = trajectory_compression(arrs2, 100, [0, 1], distance_point2line_mars)
print(narrs2)
'''
'''
print(mars_distance(39.923423, 116.368904, 39.922501, 116.387271))
print(distance_point2line_mars([116.368904, 39.913423], [116.398258, 39.904600], [116.368904, 39.923423], [0, 1]))
'''
|
79218f04f060013e6bff41cfbb7e2366bfd3dd8d | NicolasLRx/CorreRomualdo | /introduccion.py | 1,900 | 3.640625 | 4 | import time
# Funcion para narrar la introduccion del juego
def Introduccion():
time.sleep(3)
print("A fines del 2019 un virus sin identificar se empieza a propagar China y luego por el")
time.sleep(2)
print("mundo. El caos y la desesperación invaden a toda la humanidad, que pronto se ve")
time.sleep(2)
print("encerrada en cuarentena. Luego de 1 año parecía que los científicos habían desarrollado")
time.sleep(2)
print("una vacuna para evitar que la gente siga muriendo, todo iba bien hasta que el virus muto")
time.sleep(2)
print("en una cepa muy contagiosa y poco mortal, que permaneció latente por varios años.\n")
time.sleep(3)
print("Ya casi todos habían recuperado sus antiguas vidas, la gente empezaba a olvidar los")
time.sleep(2)
print("barbijos y el alcohol en gel, y fue ahí cuando, por sorpresa, muchos empezaron a morir y")
time.sleep(2)
print("a las pocas horas regresaban a la vida atacando a todo aquel que encuentren a su paso.\n")
time.sleep(3)
print("Nadie estaba preparado para algo parecido...\n")
time.sleep(3)
print("Las pocas personas que nunca se contagiaron no tuvieron mas remedio que huir,")
time.sleep(2)
print("esconderse, aislarse en lugares remotos. Mientras el mundo quedaba a merced de los")
time.sleep(2)
print("caminantes.\n")
time.sleep(3)
print("Hoy, luego de casi 2 años después, te encuentras en algún lugar de Sudamérica y te")
time.sleep(2)
print("persigue una horda de zombies. Trata de escapar de ellos, eligiendo caminos que te")
time.sleep(2)
print("lleven a un lugar seguro ¡pero cuidado! Algunos conducen a la perdición... Veamos qué")
time.sleep(2)
print("tan lejos puedes acompañar a sin que muera...\n")
time.sleep(3)
print("Frente a ti tienes 2 caminos") |
c56971d5f31c6f4186bd5718533d83d25e7ca2ce | HyeonJun97/Python_study | /Chapter08/Chapter8_pb9.py | 498 | 3.546875 | 4 | def binaryToHex(binaryValue):
h=""
while binaryValue>0:
a=binaryValue%10000
b=0
for i in range(4):
b+=((a%10)*(2**i))
a//=10
if b>=0 and b<=9:
h=str(b)+h
else:
h=chr(ord('A')+b-10)+h
binaryValue//=10000
return h
def main():
binary=eval(input("이진수를 입력하세요: "))
s=binaryToHex(binary)
print("16진수: ", s)
main()
|
7e9822e9e0d73b1fe349d839ed98874b540acc8b | smartinsert/CodingProblem | /python_data_structures/trie/implementation.py | 3,424 | 3.671875 | 4 | from heapq import *
class TrieNode:
def __init__(self, char=''):
self.children = [None] * 26
self.is_end_word = False
self.char = char
def mark_as_leaf(self):
self.is_end_word = True
def unmark_as_leaf(self):
self.is_end_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def get_index(self, t):
return ord(t) - ord('a')
def insert(self, key):
if not key:
return
key = key.lower()
current_node = self.root
index = 0
for level in range(len(key)):
index = self.get_index(key[level])
if not current_node.children[index]:
current_node.children[index] = TrieNode(key[level])
# print(key[level] + " inserted")
current_node = current_node.children[index]
# Mark the last character as leaf
current_node.mark_as_leaf()
# print("'" + key + "' inserted")
def search(self, key):
if key is None:
return False
key = key.lower()
current_node = self.root
index = 0
for level in range(len(key)):
index = self.get_index(key[level])
if not current_node.children[index]:
return False
current_node = current_node.children[index]
if not current_node and current_node.is_end_word:
return True
return False
def top_k_suggestions(self, key, k):
suggestions = []
if not key or k == 0:
return suggestions
key = key.lower()
current_node = self.root
index = self.get_index(key)
if not current_node.children[index]:
return suggestions
current_node = current_node.children[index]
result = [key + word for word in self.find_words(current_node)]
heapify(result)
for num_word in range(k):
suggestions.append(heappop(result))
if not result:
break
return suggestions
def delete(self):
pass
def get_words(self, root, result, level, word):
# Leaf denotes end of a word
if root.is_end_word:
# current word is stored till the 'level' in the character array
temp = ""
for x in range(level):
temp += word[x]
result.append(str(temp))
for i in range(26):
if root.children[i]:
# Non-None child, so add that index to the character array
word[level] = chr(i + ord('a'))
self.get_words(root.children[i], result, level + 1, word)
def find_words(self, root):
result = []
word = [None] * 20
self.get_words(root, result, 0, word)
return result
def all_suggestions(trie: Trie, search_word, index, suggestions=None):
if not suggestions:
suggestions = []
if index < len(search_word):
suggestions = trie.top_k_suggestions(search_word[:index], 3)
else:
return suggestions
return suggestions + all_suggestions(trie, search_word, index + 1)
if __name__ == '__main__':
products = ["mobile", "mouse", "moneypot", "monitor", "mousepad"]
search_word = 'mouse'
trie = Trie()
for product in products:
trie.insert(product)
print(all_suggestions(trie, search_word, 1)) |
f95eb65dc9d0ab22ba47ba20fcd78180beaaaebe | stensaethf/Xword | /data_source.py | 4,147 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''DataSource - the interface class with the methods for accessing
our database.
By Sabastian Mugazambi and Fredrik Roenn Stensaeth; 2015'''
import psycopg2
import os.path
class DataSource:
"""
The DataSource class functions as an interface for accessing the database.
Methods:
- getAdjectivesListForWord(word)
- getVerbsListForWord(word)
- getAdverbsListForWord(word)
- getNounsListForWord(word)
-getDefinitionsListForWord(word)
"""
def __init__(self):
"""
Constructor for the DataSource database interface class. Nothing
will be set up here, besides the connection to the database.
"""
USERNAME = 'mugazambis'
DB_NAME = 'mugazambis'
# self.cursor = None
# Step 1: Read your password from the secure file.
try:
f = open(os.path.join('/cs257', USERNAME))
PASSWORD = f.read().strip()
f.close()
# PASSWORD = 'tiger474desktop'
except:
self.cursor = None
# Might need to un-nest this try-except.
try:
db_connection = psycopg2.connect(user=USERNAME,
database=DB_NAME,
password=PASSWORD)
self.cursor = db_connection.cursor()
# Might need to un-nest this try-except.
# try:
# self.cursor = db_connection.cursor()
# except:
# self.cursor = 1
except:
self.cursor = None
def getAdjectivesListForWord(self, word):
"""
Returns a list of the Adjectives associated with the word.
The adjectives are strings.
"""
if self.cursor == None:
return []
self.cursor.execute(
"SELECT * FROM associations WHERE word = %s;", (word,))
adjectives_raw = ""
for i in self.cursor:
adjectives_raw = i[5]
adjectives_list = adjectives_raw.split(" ,, ")
return adjectives_list
def getVerbsListForWord(self, word):
"""
Returns a list of the Verbs associated with the word.
The verbs are strings.
"""
if self.cursor == None:
return []
self.cursor.execute(
"SELECT * FROM associations WHERE word = %s;", (word,))
verbs_raw = ""
for i in self.cursor:
verbs_raw = i[4]
verbs_list = verbs_raw.split(" ,, ")
return verbs_list
def getAdverbsListForWord(self, word):
"""
Returns a list of the Adverbs associated with the word.
The adverbs are strings.
"""
if self.cursor == None:
return []
self.cursor.execute(
"SELECT * FROM associations WHERE word = %s;", (word,))
adverbs_raw = ""
for i in self.cursor:
adverbs_raw = i[3]
adverbs_list = adverbs_raw.split(" ,, ")
return adverbs_list
def getNounsListForWord(self, word):
"""
Returns a list of the Nouns associated with the word.
The nouns are strings.
"""
if self.cursor == None:
return []
command = "SELECT * FROM associations WHERE word = \'" + word + "\'"
self.cursor.execute(command)
nouns_raw = ""
for i in self.cursor:
nouns_raw = i[2]
nouns_list = nouns_raw.split(" ,, ")
return nouns_list
def getDefinitionsListForWord(self, word):
"""
Returns a list of the definitions of the word (there can be multiple
definitions). The definitions are strings.
"""
if self.cursor == None:
return []
self.cursor.execute(
"SELECT * FROM associations WHERE word = %s;", (word,))
definitions_raw = ""
for i in self.cursor:
definitions_raw = i[1]
definitions_list = definitions_raw.split(" ,, ")
return definitions_list
|
99d4df8ed491ac33cdd00d02a969bcdb90e1c01e | Anirban2404/LeetCodePractice | /746_minCostClimbingStairs.py | 569 | 4 | 4 | '''
You are given an integer array cost where cost[i] is the cost of ith step
on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
Example 1:
Input: cost = [10,15,20]
Output: 15
Explanation: Cheapest is: start on cost[1], pay that cost, and go to the top.
Example 2:
Input: cost = [1,100,1,1,1,100,1,1,100,1]
Output: 6
Explanation: Cheapest is: start on cost[0], and only step on 1s, skipping cost[3].
'''
|
6eeafbc4560a17301e813731624e93475c483598 | urinaldisa/Algorithms-Collection-Python | /Algorithms/dynamic_programming/knapsack/knapsack_naive_recursive.py | 1,498 | 4.1875 | 4 | # "Naive" Implementation of the knapsack problem
# Purpose is if having a bunch of items with a weight and corresponding value to each object.
# Which collection of objects should we choose such that we maximize the value restricted to
# a specific capacity of weight?
# Programmed by Aladdin Persson <aladdin dot persson at hotmail dot com>
# 2019-02-28 Initial programming
# 2019-03-04 Cleaned up code and included a tracking of which items to choose
def knapsack(n, C, W, v, items):
# if n == 0 we cannot index further (since we look at n-1), further if we have no more capacity
# then we cannot obtain more objects
if n == 0 or C == 0:
return 0, []
# If the weight is higher than our capacity then we can't pick it
elif W[n - 1] > C:
result, items = knapsack(n - 1, C, W, v, items)
# Recursively search through all choices
else:
tmp1, items1 = knapsack(n - 1, C, W, v, items) # exclude item
tmp2, items2 = knapsack(n - 1, C - W[n - 1], W, v, items) # include item
items = items2 + [n - 1] if (tmp2 + v[n - 1] > tmp1) else items1
result = max(tmp1, tmp2 + v[n - 1])
return result, items
if __name__ == "__main__":
# Run small example
weight = [1, 2, 4, 2, 5]
value = [5, 3, 5, 3, 2]
num_objects = len(weight)
capacity = 3
arr = [[None for i in range(capacity)] for j in range(num_objects)]
total_val_and_items = knapsack(num_objects, capacity, weight, value, [])
print(total_val_and_items) # items = []
|
99db2a67bf25a7ff5a9a90fac1ba11d540476c41 | ykcai/Python_ML | /homework/week9_homework_answers.py | 873 | 4.03125 | 4 | # Machine Learning Class Week 9 Homework Answers
import numpy as np
mat = np.arange(1, 26).reshape(5, 5)
print(mat)
'''0 1 2 3 4
[[ 1 2 3 4 5] 0
[ 6 7 8 9 10] 1
[11 12 13 14 15] 2
[16 17 18 19 20] 3
[21 22 23 24 25]]4
'''
# Question 1
# With the "mat" matrix, produce the given result in the comments
'''
Output: [[12, 13, 14, 15],
[17, 18, 19, 20],
[22, 23, 24, 25]]
'''
print(mat[2:, 1:])
# Question 2
# With the "mat" matrix, produce the given result in the comments
'''
Output: 20
'''
print(mat[3, 4])
# Question 3
# With the "mat" matrix, produce the given result in the comments
'''
Output: [[ 2],
[ 7],
[12]]
'''
print(mat[0:3, 1].reshape(3, 1))
# Question 4
# With the "mat" matrix, produce the given result in the comments
'''
Output: [[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]
'''
print(mat[3:])
|
f5ea9b634669d2c1558da50cc47c44535eb9e9c1 | bat7tp/IS211_Assignment4 | /search_compare.py | 6,483 | 3.90625 | 4 | import argparse
# other imports go here
import random
import time
def get_me_random_list(n):
"""Generate list of n elements in random order
:params: n: Number of elements in the list
:returns: A list with n elements in random order
"""
a_list = list(range(n))
random.shuffle(a_list)
#print(a_list)
return a_list
def sequential_search(a_list, item):
start = time.time()
print(float(start))
pos = 0
found = False
while pos < len(a_list) and not found:
if a_list[pos] == item:
found = True
else:
pos = pos+1
end = time.time()
print(float(end))
ss_time = end-start
print("Sequential Search took %20.17f:" % ss_time)
return found, ss_time
def ordered_sequential_search(a_list, item):
start = time.time()
pos = 0
found = False
stop = False
while pos < len(a_list) and not found and not stop:
if a_list[pos] == item:
found = True
else:
if a_list[pos] > item:
stop = True
else:
pos = pos + 1
end = time.time()
oss_time = end-start
print("Ordered Sequential Search took %10.7f:" % oss_time)
return found, oss_time
def binary_search_iterative(a_list, item):
start = time.time()
print(float(start))
first = 0
last = len(a_list) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if a_list[midpoint] == item:
found = True
else:
if item < a_list[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
end = time.time()
bsi_time = end-start
print("Binary Search Iterative took %10.7f:" % bsi_time)
return found, bsi_time
def binary_search_recursive(a_list, item):
if len(a_list) == 0:
return False
else:
midpoint = len(a_list) // 2
if a_list[midpoint] == item:
return True
else:
if item < a_list[midpoint]:
return binary_search_recursive(a_list[:midpoint], item)
else:
return binary_search_recursive(a_list[midpoint + 1:], item)
return found
if __name__ == "__main__":
"""Main entry point"""
ss_time_total_500 = 0
ss_time_total_1000 = 0
ss_time_total_5000 = 0
os_time_total_500 = 0
os_time_total_1000 = 0
os_time_total_5000 = 0
bsi_time_total_500 = 0
bsi_time_total_1000 = 0
bsi_time_total_5000 = 0
bsr_time_total_500 = 0
bsr_time_total_1000 = 0
bsr_time_total_5000 = 0
for i in range(100):
list_test_500 = get_me_random_list(500)
list_test_1000 = get_me_random_list(1000)
list_test_5000 = get_me_random_list(5000)
ss_found, ss_time_results_500 = sequential_search(list_test_500, -1)
ss_time_total_500 = ss_time_total_500 + ss_time_results_500
ss_found, ss_time_results_1000 = sequential_search(list_test_1000, -1)
ss_time_total_1000 = ss_time_total_1000 + ss_time_results_1000
ss_found, ss_time_results_5000 = sequential_search(list_test_5000, -1)
ss_time_total_5000 = ss_time_total_5000 + ss_time_results_5000
os_found, os_time_results_500 = ordered_sequential_search(sorted(list_test_500), 9999999)
os_time_total_500 = os_time_total_500 + os_time_results_500
os_found, os_time_results_1000 = ordered_sequential_search(sorted(list_test_1000), 9999999)
os_time_total_1000 = os_time_total_1000 + os_time_results_1000
os_found, os_time_results_5000 = ordered_sequential_search(sorted(list_test_5000), 9999999)
os_time_total_5000 = os_time_total_5000 + os_time_results_5000
bsi_found, bsi_time_results_500 = binary_search_iterative(sorted(list_test_500), -1)
bsi_time_total_500 = bsi_time_total_500 + bsi_time_results_500
bsi_found, bsi_time_results_1000 = binary_search_iterative(sorted(list_test_1000), -1)
bsi_time_total_1000 = bsi_time_total_1000 + bsi_time_results_1000
bsi_found, bsi_time_results_5000 = binary_search_iterative(sorted(list_test_5000), -1)
bsi_time_total_5000 = bsi_time_total_5000 + bsi_time_results_5000
bsr500_start = time.time()
bsr_found = binary_search_recursive(sorted(list_test_500), -1)
bsr500_finish = time.time()
bsr500_time = bsr500_finish-bsr500_start
bsr_time_total_500 = bsr_time_total_500 + bsr500_time
print("Binary Search Recursive took %10.7f:" % bsr500_time)
bsr1000_start = time.time()
bsr_found = binary_search_recursive(sorted(list_test_1000), -1)
bsr1000_finish = time.time()
bsr1000_time = bsr1000_finish - bsr1000_start
bsr_time_total_1000 = bsr_time_total_1000 + bsr1000_time
print("Binary Search Recursive took %10.7f:" % bsr1000_time)
bsr5000_start = time.time()
bsr_found = binary_search_recursive(sorted(list_test_5000), -1)
bsr5000_finish = time.time()
bsr5000_time = bsr5000_finish - bsr5000_start
bsr_time_total_5000 = bsr_time_total_5000 + bsr5000_time
print("Binary Search Recursive took %10.7f:" % bsr5000_time)
avg_search_time_ss_500 = ss_time_total_500/500
print(float(avg_search_time_ss_500))
avg_search_time_ss_1000 = ss_time_total_1000/1000
print(float(avg_search_time_ss_1000))
avg_search_time_ss_5000 = ss_time_total_5000 / 5000
print(float(avg_search_time_ss_5000))
avg_search_time_oss_500 = os_time_total_500 / 500
print(float(avg_search_time_oss_500))
avg_search_time_oss_1000 = os_time_total_1000 / 1000
print(float(avg_search_time_oss_1000))
avg_search_time_oss_5000 = os_time_total_5000 / 5000
print(float(avg_search_time_oss_5000))
avg_search_time_bsi_500 = bsi_time_total_500 / 500
print(float(avg_search_time_bsi_500))
avg_search_time_bsi_1000 = bsi_time_total_1000 / 1000
print(float(avg_search_time_bsi_1000))
avg_search_time_bsi_5000 = bsi_time_total_5000 / 5000
print(float(avg_search_time_bsi_5000))
avg_search_time_bsr_500 = bsr_time_total_500 / 500
print(float(avg_search_time_bsr_500))
avg_search_time_bsr_1000 = bsr_time_total_1000 / 1000
print(float(avg_search_time_bsr_1000))
avg_search_time_bsr_5000 = bsr_time_total_5000 / 5000
print(float(avg_search_time_bsr_5000))
|
7648ac0ba703246beb14c821d375a9f7886c1578 | denischebotarev/python1004 | /lesson6_hw1.py | 252 | 3.8125 | 4 | def user_phrase():
phrase = str(input('Enter phrase: '))
return phrase
def shifr():
secretnoe_slovo = ''
for bukva in user_phrase():
if bukva.isupper():
secretnoe_slovo += bukva
print(secretnoe_slovo)
shifr() |
c341fb3aa3d30dc9284201772785b3794ba205cf | Luuuuuucifer/untitled | /base/justfortest.py | 1,026 | 3.71875 | 4 | # -*- coding:utf-8 -*-
# s = 10
# number = ()
# print(number == None)
# for n in number:
# print(s * n)
# a = ' '
# print(a == None)
# print(len(a))
#
# b = 'abcd'
# print(b[0:])
# for n, value in enumerate(b):
# print(n, value)
# print(5, value)
# def findMinAndMax(L):
# min = max = 0
# for x in L:
# max = max > x and max or x
# min = min < x and x or min
# return (min or None, max or None)
# print(findMinAndMax([0, 1]))
# https://www.zhihu.com/question/20152384
# 尽管方法错了,但是依旧值得学习其中的想法
# min = max = 0
# x = 10
# a = False or 10
# b = False or False
# print (a, b)
# c = 2 and 1 or 3 and 4
# print (c)
# d = 1 or 2
# print (d)
# L = [1, 2, 3]
# l = 'aaa'
# print(l + 'str')
# K = list(L)
# print(K)
# print(K == L)
# for i in range(5):
# print(i)
# from enum import Enum
# Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
a = 1
# def aaa():
# print(a)
#
# aaa()
|
89373fbe274ab108c5f7295d27f348f61889c3bc | sujiea/hackerrank-codility | /queue.py | 439 | 3.65625 | 4 | #!/bin/python3
class MyQueue(object):
def __init__(self):
self.lifo = []
def peek(self):
return self.lifo[0]
def pop(self):
self.lifo.remove(self.lifo[0])
def put(self, value):
self.lifo.append(value)
queue = MyQueue()
queue.put(15)
queue.put(17)
print(queue.peek())
queue.put(25)
print(queue.peek())
queue.pop()
print(queue.peek())
queue.pop()
print(queue.peek())
|
ce687c7a5087b61559cb2b47804f22887741aaa2 | 3mjay/PY4E | /py4e/ex_08/ex_08_05.py | 1,109 | 4.3125 | 4 | # Write a program to read through the mail box data and when you find line that starts with “From”,
# you will split the line into words using the split function.
# We are interested in who sent the message, which is the second word on the From line.
#
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# You will parse the From line and print out the second word for each From line,
# then you will also count the number of From (not From:) lines and print out a count at the end.
# This is a good sample output with a few lines removed:
#
# python fromcount.py
# Enter a file name: mbox-short.txt
# stephen.marquard@uct.ac.za
# louis@media.berkeley.edu
# zqian@umich.edu
#
# [...some output removed...]
#
# ray@media.berkeley.edu
# cwen@iupui.edu
# cwen@iupui.edu
# cwen@iupui.edu
# There were 27 lines in the file with From as the first word
fname = input("Enter file name: ")
fhand = open(fname)
em_list = []
count = 0
for line in fhand:
if line.startswith("From"):
if line.startswith("From:"):
continue
count = count + 1
em_list = line.split()
print (em_list[1])
print ("There were", count, "lines in the file with From as the first word")
|
6d6d35a5b58f20b9edee95bbeb17024e68813c0c | CODENAMEMystic/iPadPython | /Alt Game/traffic sim.py | 1,890 | 3.53125 | 4 | import console, time, random
console.clear()
carPerMinute = 1
flow = 2
#A simple intersection, no roads just entry
#The light sequence
class Intersection():
def __init__(self):
self.sequence = 0
self.southR = 0
self.northR = 0
self.westR = 0
self.eastR = 0
self.waited = 0
def switchSequence(self):
self.waited = 0
if self.sequence >= 2:
self.sequence = 0
else:
self.sequence += 1
def doStuff(self, tick):
carPerMinute = random.randint(0,2)
if self.waited >= 6:
a.switchSequence()
if(self.sequence == 0):
self.southR += getCars()
self.northR += getCars()
self.westR += getCars()
self.eastR += getCars()
if tick % 6 == 0:
self.sequence += 1
if(self.sequence == 1):
if self.southR != 0:
self.southR -= flow
if self.southR < 0:
self.southR = 0
else:
self.waited += 1
if self.northR != 0:
self.northR -= flow
if self.northR < 0:
self.northR = 0
else:
self.waited += 1
self.westR += getCars()
self.eastR += getCars()
if self.sequence == 2:
if self.westR != 0:
self.westR -= flow
if self.westR < 0:
self.westR = 0
else:
self.waited += 1
if self.eastR != 0:
self.eastR -= flow
if self.eastR < 0:
self.eastR = 0
else:
self.waited += 1
self.northR += getCars()
self.southR += getCars()
def getCars():
return random.randint(0,3)
a = Intersection()
waited = 0
tick = 1
while tick < 100:
time.sleep(1)
console.clear()
a.doStuff(tick)
if tick % 10 == 0:
a.switchSequence()
tick += 1
print('North: ' + str(a.northR))
print('South: ' + str(a.southR))
print('West: '+str(a.westR))
print('East: '+str(a.eastR))
print('Sequence: ' +str(a.sequence))
print('Waited: '+str(a.waited)) |
3afb7c74a9b2cc6b8249e9d879a144c6366aff50 | renren82/fa | /bitoparate.py | 696 | 3.71875 | 4 | a=11
b=a<<3 # 将 a 左移三位
print("下面是十进制")
print(a)
print(b) # b=a*(2**3)
print("下面是二进制")
print(bin(a)) # 转化为二进制显示
print(bin(a)[2:]) # 切片,去掉前面的:0b
print(bin(b)[2:]) # 二进制右边补上三个000
a=3
b=2
print("二进制:"+bin(a)[2:]+" a十进制:%d"%a) # 显示二进制数
print("二进制:"+bin(b)[2:]+" b十进制:%d"%b)
print("按位与:"+bin(a&b)+" 位与后是:%d"%(a&b)) # 都是1才是1
print("按位或:"+bin(a|b)+" 位或后是:%d"%(a|b)) # 有1就是1
print("按位取反"+bin(~a)+" 位反后是:%d"%~a) # 结果是:a 的倒数-1
|
c4cfd51d559b15ad7b2d703341ea8f23807ef8c4 | sreedevi2906/sreedevi | /areaofatriangle.py | 140 | 4 | 4 | b=int(input("enter the breadth of a triangle"))
h=int(input("enter the height of a triangle"))
area=0.5*b*h
print("area of a triangle",area) |
128a1794811d4c7857a6e2667a061fba9d6e1c74 | MrBago/nibabel | /nibabel/casting.py | 13,905 | 3.921875 | 4 | """ Utilties for casting floats to integers
"""
from platform import processor
import numpy as np
class CastingError(Exception):
pass
def float_to_int(arr, int_type, nan2zero=True, infmax=False):
""" Convert floating point array `arr` to type `int_type`
* Rounds numbers to nearest integer
* Clips values to prevent overflows when casting
* Converts NaN to 0 (for `nan2zero`==True
Casting floats to integers is delicate because the result is undefined
and platform specific for float values outside the range of `int_type`.
Define ``shared_min`` to be the minimum value that can be exactly
represented in both the float type of `arr` and `int_type`. Define
`shared_max` to be the equivalent maximum value. To avoid undefined results
we threshold `arr` at ``shared_min`` and ``shared_max``.
Parameters
----------
arr : array-like
Array of floating point type
int_type : object
Numpy integer type
nan2zero : {True, False, None}
Whether to convert NaN value to zero. Default is True. If False, and
NaNs are present, raise CastingError. If None, do not check for NaN
values and pass through directly to the ``astype`` casting mechanism.
In this last case, the resulting value is undefined.
infmax : {False, True}
If True, set np.inf values in `arr` to be `int_type` integer maximum
value, -np.inf as `int_type` integer minimum. If False, set +/- infs to
be ``shared_min``, ``shared_max`` as defined above. Therefore False
gives faster conversion at the expense of infs that are further from
infinity.
Returns
-------
iarr : ndarray
of type `int_type`
Examples
--------
>>> float_to_int([np.nan, np.inf, -np.inf, 1.1, 6.6], np.int16)
array([ 0, 32767, -32768, 1, 7], dtype=int16)
Notes
-----
Numpy relies on the C library to cast from float to int using the standard
``astype`` method of the array.
Quoting from section F4 of the C99 standard:
If the floating value is infinite or NaN or if the integral part of the
floating value exceeds the range of the integer type, then the
"invalid" floating-point exception is raised and the resulting value
is unspecified.
Hence we threshold at ``shared_min`` and ``shared_max`` to avoid casting to
values that are undefined.
See: http://en.wikipedia.org/wiki/C99 . There are links to the C99 standard
from that page.
"""
arr = np.asarray(arr)
flt_type = arr.dtype.type
int_type = np.dtype(int_type).type
# Deal with scalar as input; fancy indexing needs 1D
shape = arr.shape
arr = np.atleast_1d(arr)
mn, mx = shared_range(flt_type, int_type)
if nan2zero is None:
seen_nans = False
else:
nans = np.isnan(arr)
seen_nans = np.any(nans)
if nan2zero == False and seen_nans:
raise CastingError('NaNs in array, nan2zero is False')
iarr = np.clip(np.rint(arr), mn, mx).astype(int_type)
if seen_nans:
iarr[nans] = 0
if not infmax:
return iarr.reshape(shape)
ii = np.iinfo(int_type)
iarr[arr == np.inf] = ii.max
if ii.min != int(mn):
iarr[arr == -np.inf] = ii.min
return iarr.reshape(shape)
# Cache range values
_SHARED_RANGES = {}
def shared_range(flt_type, int_type):
""" Min and max in float type that are >=min, <=max in integer type
This is not as easy as it sounds, because the float type may not be able to
exactly represent the max or min integer values, so we have to find the next
exactly representable floating point value to do the thresholding.
Parameters
----------
flt_type : dtype specifier
A dtype specifier referring to a numpy floating point type. For
example, ``f4``, ``np.dtype('f4')``, ``np.float32`` are equivalent.
int_type : dtype specifier
A dtype specifier referring to a numpy integer type. For example,
``i4``, ``np.dtype('i4')``, ``np.int32`` are equivalent
Returns
-------
mn : object
Number of type `flt_type` that is the minumum value in the range of
`int_type`, such that ``mn.astype(int_type)`` >= min of `int_type`
mx : object
Number of type `flt_type` that is the maximum value in the range of
`int_type`, such that ``mx.astype(int_type)`` <= max of `int_type`
Examples
--------
>>> shared_range(np.float32, np.int32)
(-2147483648.0, 2147483520.0)
>>> shared_range('f4', 'i4')
(-2147483648.0, 2147483520.0)
"""
flt_type = np.dtype(flt_type).type
int_type = np.dtype(int_type).type
key = (flt_type, int_type)
# Used cached value if present
try:
return _SHARED_RANGES[key]
except KeyError:
pass
ii = np.iinfo(int_type)
mn_mx = floor_exact(ii.min, flt_type), floor_exact(ii.max, flt_type)
_SHARED_RANGES[key] = mn_mx
return mn_mx
# ----------------------------------------------------------------------------
# Routines to work out the next lowest representable integer in floating point
# types.
# ----------------------------------------------------------------------------
try:
_float16 = np.float16
except AttributeError: # float16 not present in np < 1.6
_float16 = None
class FloatingError(Exception):
pass
def type_info(np_type):
""" Return dict with min, max, nexp, nmant, width for numpy type `np_type`
Type can be integer in which case nexp and nmant are None.
Parameters
----------
np_type : numpy type specifier
Any specifier for a numpy dtype
Returns
-------
info : dict
with fields ``min`` (minimum value), ``max`` (maximum value), ``nexp``
(exponent width), ``nmant`` (significand precision not including
implicit first digit) ``width`` (width in bytes). ``nexp``, ``nmant``
are None for integer types. Both ``min`` and ``max`` are of type
`np_type`.
Raises
------
FloatingError : for floating point types we don't recognize
Notes
-----
You might be thinking that ``np.finfo`` does this job, and it does, except
for PPC long doubles (http://projects.scipy.org/numpy/ticket/2077). This
routine protects against errors in ``np.finfo`` by only accepting values
that we know are likely to be correct.
"""
dt = np.dtype(np_type)
np_type = dt.type
width = dt.itemsize
try: # integer type
info = np.iinfo(dt)
except ValueError:
pass
else:
return dict(min=np_type(info.min), max=np_type(info.max),
nmant=None, nexp=None, width=width)
info = np.finfo(dt)
# Trust the standard IEEE types
nmant, nexp = info.nmant, info.nexp
ret = dict(min=np_type(info.min), max=np_type(info.max), nmant=nmant,
nexp=nexp, width=width)
if np_type in (_float16, np.float32, np.float64,
np.complex64, np.complex128):
return ret
info_64 = np.finfo(np.float64)
if dt.kind == 'c':
assert np_type is np.longcomplex
vals = (nmant, nexp, width / 2)
else:
assert np_type is np.longdouble
vals = (nmant, nexp, width)
if vals in ((112, 15, 16), # binary128
(info_64.nmant, info_64.nexp, 8), # float64
(63, 15, 12), (63, 15, 16)): # Intel extended 80
pass # these are OK
elif vals in ((52, 15, 12), # windows float96
(52, 15, 16)): # windows float128?
# On windows 32 bit at least, float96 appears to be a float64 padded to
# 96 bits. The nexp == 15 is the same as for intel 80 but nexp in fact
# appears to be 11 as for float64
return dict(min=np_type(info_64.min), max=np_type(info_64.max),
nmant=info_64.nmant, nexp=info_64.nexp, width=width)
elif vals == (1, 1, 16) and processor() == 'powerpc': # broken PPC
return dict(min=np_type(info_64.min), max=np_type(info_64.max),
nmant=106, nexp=11, width=width)
else: # don't recognize the type
raise FloatingError('We had not expected type %s' % np_type)
return ret
def as_int(x, check=True):
""" Return python integer representation of number
This is useful because the numpy int(val) mechanism is broken for large
values in np.longdouble.
It is also useful to work around a numpy 1.4.1 bug in conversion of uints to
python ints.
This routine will still raise an OverflowError for values that are outside
the range of float64.
Parameters
----------
x : object
integer, unsigned integer or floating point value
check : {True, False}
If True, raise error for values that are not integers
Returns
-------
i : int
Python integer
Examples
--------
>>> as_int(2.0)
2
>>> as_int(-2.0)
-2
>>> as_int(2.1) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
FloatingError: Not an integer: 2.1
>>> as_int(2.1, check=False)
2
"""
x = np.array(x)
if x.dtype.kind in 'iu':
# This works around a nasty numpy 1.4.1 bug such that:
# >>> int(np.uint32(2**32-1)
# -1
return int(str(x))
ix = int(x)
if ix == x:
return ix
fx = np.floor(x)
if check and fx != x:
raise FloatingError('Not an integer: %s' % x)
if not fx.dtype.type == np.longdouble:
return int(x)
# Subtract float64 chunks until we have all of the number. If the int is too
# large, it will overflow
ret = 0
while fx != 0:
f64 = np.float64(fx)
fx -= f64
ret += int(f64)
return ret
def int_to_float(val, flt_type):
""" Convert integer `val` to floating point type `flt_type`
Why is this so complicated?
At least in numpy <= 1.6.1, numpy longdoubles do not correctly convert to
ints, and ints do not correctly convert to longdoubles. Specifically, in
both cases, the values seem to go through float64 conversion on the way, so
to convert better, we need to split into float64s and sum up the result.
Parameters
----------
val : int
Integer value
flt_type : object
numpy floating point type
Returns
-------
f : numpy scalar
of type `flt_type`
"""
if not flt_type is np.longdouble:
return flt_type(val)
faval = np.longdouble(0)
while val != 0:
f64 = np.float64(val)
faval += f64
val -= int(f64)
return faval
def floor_exact(val, flt_type):
""" Get nearest exact integer to `val`, towards 0, in float type `flt_type`
Parameters
----------
val : int
We have to pass val as an int rather than the floating point type
because large integers cast as floating point may be rounded by the
casting process.
flt_type : numpy type
numpy float type. Only IEEE types supported (np.float16, np.float32,
np.float64)
Returns
-------
floor_val : object
value of same floating point type as `val`, that is the next excat
integer in this type, towards zero, or == `val` if val is exactly
representable.
Examples
--------
Obviously 2 is within the range of representable integers for float32
>>> floor_exact(2, np.float32)
2.0
As is 2**24-1 (the number of significand digits is 23 + 1 implicit)
>>> floor_exact(2**24-1, np.float32) == 2**24-1
True
But 2**24+1 gives a number that float32 can't represent exactly
>>> floor_exact(2**24+1, np.float32) == 2**24
True
"""
val = int(val)
flt_type = np.dtype(flt_type).type
sign = val > 0 and 1 or -1
aval = abs(val)
try: # int_to_float deals with longdouble safely
faval = int_to_float(aval, flt_type)
except OverflowError:
faval = np.inf
info = type_info(flt_type)
if faval == np.inf:
return sign * info['max']
if as_int(faval) <= aval: # as_int deals with longdouble safely
# Float casting has made the value go down or stay the same
return sign * faval
# Float casting made the value go up
biggest_gap = 2**(floor_log2(aval) - info['nmant'])
assert biggest_gap > 1
faval -= flt_type(biggest_gap)
return sign * faval
def int_abs(arr):
""" Absolute values of array taking care of max negative int values
Parameters
----------
arr : array-like
Returns
-------
abs_arr : array
array the same shape as `arr` in which all negative numbers have been
changed to positive numbers with the magnitude.
Examples
--------
This kind of thing is confusing in base numpy:
>>> import numpy as np
>>> np.abs(np.int8(-128))
-128
``int_abs`` fixes that:
>>> int_abs(np.int8(-128))
128
>>> int_abs(np.array([-128, 127], dtype=np.int8))
array([128, 127], dtype=uint8)
>>> int_abs(np.array([-128, 127], dtype=np.float32))
array([ 128., 127.], dtype=float32)
"""
arr = np.array(arr, copy=False)
dt = arr.dtype
if dt.kind == 'u':
return arr
if dt.kind != 'i':
return np.absolute(arr)
out = arr.astype(np.dtype(dt.str.replace('i', 'u')))
return np.choose(arr < 0, (arr, arr * -1), out=out)
def floor_log2(x):
""" floor of log2 of abs(`x`)
Embarrassingly, from http://en.wikipedia.org/wiki/Binary_logarithm
Parameters
----------
x : int
Returns
-------
L : int
floor of base 2 log of `x`
Examples
--------
>>> floor_log2(2**9+1)
9
>>> floor_log2(-2**9+1)
8
"""
ip = 0
rem = abs(x)
while rem>=2:
ip += 1
rem //= 2
return ip
|
eae8cd218a954c18e0c560e04ca9751511fddd70 | Fox27rus/SkillFactory | /21.py | 3,973 | 3.59375 | 4 | M = ['-' for i in range(1, 10)] # Создаем поле для игры
print('''Приветствую, дорогие игроки в крестики - нолики!
Правила игры просты: Вам надо выбирать клетку поля и писать его номер от 1 до 9,
где "1" находится в координате x1z1, "2" в y1z1 и т.д.''')
def playing_field(): # Функция для красивого поля
print(' ', 'x', 'y', 'z')
print(' -----')
print('x', '|', *M[6:9])
print('y', '|', *M[3:6])
print('z', '|', *M[0:3])
playing_field()
def player_1():
print('ходит игрок 1')
a = input('Введите число от 1 до 9 : ')
if a not in [str(i) for i in range(1, 10)]: # Проверка, что ввели цифру от 1 до 9
while a not in [str(i) for i in range(1, 10)]:
print('Вы ввели не то')
a = input('Введите число от 1 до 9 : ')
if 'x' not in M[int(a) - 1] and '0' not in M[int(a) - 1]: # Проверка, что поле не занято
M[int(a) - 1] = 'x'
else:
while True:
print('занято')
a = input('Введите число от 1 до 9 : ')
if a not in [str(i) for i in range(1, 10)]:
print('Вы ввели не то')
continue
if 'x' not in M[int(a) - 1] and '0' not in M[int(a) - 1]:
M[int(a) - 1] = 'x'
break
def player_2():
print('ходит игрок 2')
b = input('Введите число от 1 до 9 : ')
if b not in [str(i) for i in range(1, 10)]: # Проверка, что ввели цифру от 1 до 9
while b not in [str(i) for i in range(1, 10)]:
print('Вы ввели не то')
b = input('Введите число от 1 до 9 : ')
if 'x' not in M[int(b) - 1] and '0' not in M[int(b) - 1]: # Проверка, что поле не занято
M[int(b) - 1] = '0'
else:
while True:
print('занято')
b = input('Введите число от 1 до 9 : ')
if b not in [str(i) for i in range(1, 10)]:
print('Вы ввели не то')
continue
if 'x' not in M[int(b) - 1] and '0' not in M[int(b) - 1]:
M[int(b) - 1] = '0'
break
while True: # Цикл для игры
player_1()
# Проверка выигрышных комбинаций для первого игрока
if ('x' in M[0] and 'x' in M[1] and 'x' in M[2]) or ('x' in M[3] and 'x' in M[4] and 'x' in M[5]) or (
'x' in M[6] and 'x' in M[7] and 'x' in M[8]) or ('x' in M[0] and 'x' in M[3] and 'x' in M[6]) or (
'x' in M[1] and 'x' in M[4] and 'x' in M[7]) or ('x' in M[2] and 'x' in M[5] and 'x' in M[8]) or (
'x' in M[0] and 'x' in M[4] and 'x' in M[8]) or ('x' in M[2] and 'x' in M[4] and 'x' in M[6]):
playing_field()
print('Победил игрок 1!')
break
playing_field()
if '-' not in M: # Проверка варианта 'Ничья'
print('Ничья')
break
player_2()
# Проверка выигрышных комбинаций для второго игрока
if ('0' in M[0] and '0' in M[1] and '0' in M[2]) or ('0' in M[3] and '0' in M[4] and '0' in M[5]) or (
'0' in M[6] and '0' in M[7] and '0' in M[8]) or ('0' in M[0] and '0' in M[3] and '0' in M[6]) or (
'0' in M[1] and '0' in M[4] and '0' in M[7]) or ('0' in M[2] and '0' in M[5] and '0' in M[8]) or (
'0' in M[0] and '0' in M[4] and '0' in M[8]) or ('0' in M[2] and '0' in M[4] and '0' in M[6]):
playing_field()
print('Победил игрок 2!')
break
playing_field()
|
979a6941a82f7c71479c142f00b86c7f817ea6da | SimanAbdiali2020/sofiaa | /Desktop/SimanAssignmets/#make an array for the sorting of the selection.py | 618 | 4.1875 | 4 | #make an array for the sorting of the selection
array = [13,4,9,3,16,12]
def selectionSort(array):
n = len(array)
for i in range (n): #whatever the length of the array is how many times you are going to run the loop
#Initially assume the first element of the unsorted part as the minimum
minimum = i
for j in range (i+1, n):
if (array[j] < array[minimum]): #comparison operator
minimum = j
# swap the minimum element with the first element of the unsorted
temp = array[i]
array[i] = array[minimum]
array[minimum] = temp
return array
print(selection) |
942447e616ab91da6d2d35d1a4181ac60ac60a0f | daianasousa/POO | /LISTA DE EXERCÍCIOS/Semana_01_Atividade_02.py | 2,138 | 3.734375 | 4 | class Carro:
#ATRIBUTOS
nome = None
ano = None
cor = None
veloc_max = None
veloc_atual = None
estado = None
#METODOS
def ligar(self, estado):
if self.estado == 'ligar':
return 'ligar'
def desligar(self, estado):
if self.estado == 'desligar':
return 'desligado'
def acelerar(self,valor, estado):
if valor == 0:
if self.estado == 'desligado':
return 'Carro desligado'
elif self.estado == 'ligado':
self.veloc_atual = valor
if self.veloc_atual > self.veloc_max:
return f'Passou do limite de {self.veloc_max} '
else:
return self.veloc_atual
def parar(self, estado, veloc_atual):
if self.estado == 'parar':
self.veloc_atual = 0
if self.veloc_atual == 0:
return 'Carro Parado'
#OBJETO_1
fusca = Carro()
fusca.nome = 'fusca'
fusca.ano = 1965
fusca.cor = 'preto'
fusca.veloc_max = 80
fusca.veloc_atual = 20
fusca.estado = 'ligado'
#OBJETO_2
ferrari_sr2000 = Carro()
ferrari_sr2000.nome = 'ferrari_sr2000'
ferrari_sr2000.ano = 2014
ferrari_sr2000.cor = 'vermelho'
ferrari_sr2000.veloc_max = 300
ferrari_sr2000.veloc_atual = 0
ferrari_sr2000.estado = 'desligado'
fusca.acelerar(40, fusca.estado)
print(f'Velocidade atual do fusca e {fusca.veloc_atual} km/h')
ferrari_sr2000.acelerar(200, ferrari_sr2000.estado)
print(f'Velocidade atual da ferrari e {ferrari_sr2000.veloc_atual} km/h')
fusca.desligar('desligar')
print(f'Fusca {fusca.estado}')
ferrari_sr2000.ligar('ligar')
print(f'ferrari {fusca.estado}')
ferrari_sr2000.acelerar(320, ferrari_sr2000.estado)
print(f'Velocidade atual da ferrari e {ferrari_sr2000.veloc_atual} km/h')
ferrari_sr2000.parar('Pare', ferrari_sr2000.estado)
print(f'Ferrari {ferrari_sr2000.estado}')
ferrari_sr2000.desligar('desligar')
print(f'Ferrari {ferrari_sr2000.estado}')
fusca.ligar('ligar')
print(f'Fusca {fusca.estado}')
fusca.acelerar(100, fusca.estado)
print(f'{fusca.veloc_atual}')
fusca.desligar('desligar')
print(f'fusca {fusca.estado}')
|
87ec2e6566998dfe0c5f49024927dddc76377687 | zaarabuy0950/assignment-3 | /assign18.py | 1,268 | 4.1875 | 4 | """18. Find a package in the Python standard library for dealing with JSON.
Import the library module and inspect the attributes of the module.
Use the help function to learn more about how to use the module.
Serialize a dictionary mapping 'name' to your name and 'age' to your
age, to a JSON string. Deserialize the JSON back into Python."""
#python standard library for json is json
#importing json library
import json
print(dir(json))
# ['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', '__all__',
# '__author__', '__builtins__', '__cached__', '__doc__', '__file__',
# '__loader__', '__name__', '__package__', '__path__', '__spec__',
# '__version__', '_default_decoder', '_default_encoder', 'codecs',
# 'decoder', 'detect_encoding', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']
# help(json)
people = {
"first_name": "yuvi",
"age": 26
}
json_data = json.dumps(people, indent=2)
print(json_data)
print(json.loads(json_data))
#
#
# import json
# #help(json)
#
# # Serializing
# info = {
# "name": "Salina",
# "age": 22
# }
# with open("info.json", "w") as write_file:
# json.dump(info, write_file)
#
# # Deserializing
# with open("info.json", "r") as read_file:
# result = json.load(read_file)
#
|
bc480ff6c4f671d2b82baaaa066da91b8a1efa15 | chenpercy/DS | /queue+array.py | 1,980 | 3.96875 | 4 | class Queue:
def __init__(self, volume):
self.front = 0
self.size = 0
self.rear = volume - 1
self.queue = [None] * volume
self.volume = volume
def isFull(self):
return self.size == self.volume
def isEmpty(self):
return self.size == 0
def enqueue(self, data):
if self.isFull():
print("The queue is full")
return
self.rear = (self.rear + 1) % self.volume
self.queue[self.rear] = data
print(f"{data} enqueued into queue")
self.queue[self.rear] = data
self.size += 1
def dequeue(self):
if self.isEmpty():
print("The queue is empty")
return
print(f"{self.queue[self.front]} dequeued from queue")
self.front = (self.front + 1) % self.volume
self.size -= 1
def getfront(self):
if self.isEmpty():
print("The queue is empty")
return
return self.queue[self.front]
def getrear(self):
if self.isEmpty():
print("The queue is empty")
return
return self.queue[self.rear]
def showqueue(self):
temp = self.front
tempsize = 0
totalqueue = ""
while tempsize != self.size :
totalqueue += str(self.queue[temp % self.volume])
tempsize += 1
temp += 1
print(totalqueue)
# TEST
if __name__ == '__main__':
queue = Queue(10) # initialize the Queue
queue.dequeue() # TEST dequeue while data is empty
# enqueue
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(1)
queue.enqueue(8)
queue.enqueue(5)
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(1)
queue.enqueue(8)
queue.enqueue(5)
queue.enqueue(10)
queue.showqueue() # show queue data
# get front and rear data
print("Front : ", queue.getfront())
print("Rear : ", queue.getrear())
|
6508f912b4aead68b5c6ec4628570c25d1f95057 | chxj1992/leetcode-exercise | /subject_lcof/21/_1.py | 511 | 3.9375 | 4 | import unittest
from typing import List
class Solution:
def exchange(self, nums: List[int]) -> List[int]:
res = []
for i in nums:
if i % 2 == 1:
res.insert(0, i)
else:
res.append(i)
return res
class Test(unittest.TestCase):
def test(self):
s = Solution()
self.assertIn(s.exchange([1, 2, 3, 4]), [[1, 3, 2, 4], [1, 3, 4, 2], [3, 1, 2, 4], [3, 1, 4, 2]])
if __name__ == '__main__':
unittest.main()
|
2ef7c43c85cb928e6e38dc384f64ec55d2f5fa47 | CryoCardiogram/cppy | /knapsack.py | 740 | 3.640625 | 4 | #!/usr/bin/python3
"""
Knapsack problem in CPpy
Based on the Numberjack model of Hakan Kjellerstrand
"""
from cppy import *
import numpy as np
# Problem data
n = 10
np.random.seed(1)
values = np.random.randint(0,10, n)
weights = np.random.randint(1,5, n)
capacity = np.random.randint(sum(weights)*.2, sum(weights)*.5)
# Construct the model.
x = BoolVar(n)
constraint = [ sum(x*weights) <= capacity ]
objective = sum(x*values)
model = Model(constraint, maximize=objective)
print(model)
# Statistics are returned after solving.
stats = model.solve()
# Variables can be asked for their value in the found solution
#print("Value:", objective.value())
print("Solution:", x.value())
print("In items: ", [i+1 for i,val in enumerate(x.value()) if val])
|
a4ce0abb1d46814be9546b61ad2429916a26fafc | Rociorangel/Patrones | /Strategy.py | 714 | 3.625 | 4 | from abc import ABC, abstractmethod
class sistemaOperativo(ABC):
@abstractmethod
def actualizacionPeriodica():
pass
def SeguridadRobusta():
pass
def gamaAlta():
pass
class Linux(sistemaOperativo):
def ActualizacionPeriodica(self):
print("sistema operativo es muy robusto en cuestion de seguridad")
class Windows(sistemaOperativo):
def SeguridadPeriodica(self):
print("es una sistema operativo que se actualiza constantemente")
class Mac (sistemaOperativo):
def gamaAlta(self):
print("es un sistema operativo de gama alta")
class SoftwarePrincipal:
def __init__(self):
self.tiposistemaoperativo = sistemaOperativo()
|
85137306e021692bb9f1cd76462794b36b8445e0 | Xiaoctw/LeetCode1_python | /树/二叉树的序列化和反序列化_297.py | 1,781 | 3.6875 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def __init__(self):
self.idx = 0
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
p = root
stack, nodes = [], []
while stack or p:
if p:
nodes.append(str(p.val))
stack.append(p)
p = p.left
else:
nodes.append('None')
p = stack.pop()
p = p.right
nodes.append('None')
return ' '.join(nodes)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
list1 = data.split(' ')
self.idx = 0
return self.constructTree(list1)
def constructTree(self, list1):
if self.idx >= len(list1) or list1[self.idx] == 'None':
self.idx += 1
return None
val = int(list1[self.idx])
self.idx += 1
node = TreeNode(val)
node.left = self.constructTree(list1)
node.right = self.constructTree(list1)
return node
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
if __name__ == '__main__':
codec = Codec()
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node1.left = node2
node1.right = node3
node3.left = node4
node3.right = node5
str1 = codec.serialize(node1)
root = codec.deserialize(str1)
print(str1)
|
1a05ce002616d94c203870417f302ce4bede88fa | 16dprice/cs475 | /src/doc_classification/text_classification_demo_1.py | 3,240 | 3.546875 | 4 | # following the tutorial at the following:
# https://towardsdatascience.com/machine-learning-nlp-text-classification-using-scikit-learn-python-and-nltk-c52b92a7c73a
import numpy as np
# load the training data
# will load the test data later
from sklearn.datasets import fetch_20newsgroups
twenty_train = fetch_20newsgroups(subset='train', shuffle=True)
# print(twenty_train.target_names) # prints all the categories
# print("\n".join(twenty_train.data[0].split("\n")[:3])) # prints first line of the first data file
# this is a way of counting term frequency
# ultimately, this is poor because it gives more weight to longer documents (long doc = more words)
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(twenty_train.data)
# print(X_train_counts.shape)
# this will do a tf-idf (term frequency times inverse document frequency) calculation
from sklearn.feature_extraction.text import TfidfTransformer
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
print(X_train_tfidf.shape) # (n_samples, n_features)
# Time for some classification!
########################################################################################################################
############################################## Naive Bayes Classification ##############################################
# there are many variants of NB, but this is the one that the tutorial uses
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
text_clf_nb = Pipeline([
('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', MultinomialNB()),
])
# this trains the classifier
text_clf_nb = text_clf_nb.fit(twenty_train.data, twenty_train.target)
# now to test the classifier
twenty_test = fetch_20newsgroups(subset='test', shuffle=True)
predicted_nb = text_clf_nb.predict(twenty_test.data)
print(np.mean(predicted_nb == twenty_test.target))
############################################ SVM (Support Vector Machines) #############################################
from sklearn.linear_model import SGDClassifier
text_clf_svm = Pipeline([
('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf-svm', SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, n_iter_no_change=5, random_state=42))
])
text_clf_svm = text_clf_svm.fit(twenty_train.data, twenty_train.target)
predicted_svm = text_clf_svm.predict(twenty_test.data)
print(np.mean(predicted_svm == twenty_test.target))
########################################### Grid Search (Parameter Tuning) #############################################
from sklearn.model_selection import GridSearchCV
# create a list of parameters we would like to tune and define what those paramaters can be
parameters = {
'vect__ngram_range': [(1, 1), (1, 2)],
'tfidf__use_idf': (True, False),
'clf__alpha': (1e-2, 1e-3),
}
# this screws up my computer for some reason
# TODO: fix it
# gs_clf = GridSearchCV(text_clf_nb, parameters, n_jobs=-1) # n_jobs = -1 => use all cores available
# gs_clf.fit(twenty_train.data, twenty_train.target)
#
# print(gs_clf.best_score_)
# print(gs_clf.best_params_) |
205c3b9a52bf17a0606e4a2ba8bbb612114b507d | m-sz/projekt-grupowy-caveworld | /shared/net/network/network.py | 1,064 | 3.734375 | 4 | from abc import ABC, abstractmethod
class Network(ABC):
"""
Abstract class for Network, which is responsible for maintaining
a connection/serving the network and call the registered callbacks upon
receiving bound messages.
Argument names nomenclature is:
message - a proper message object
data - a raw or wrapped by protocol, data, which should be unwrapped to use
protocol - responsible for wrapping and unwrapping messages. Currently
the only protocol implementation adds an ID to every message, to be
correctly constructed on the receiving side.
"""
def __init__(self):
self.callbacks = {}
def bind(self, bindings : dict):
self.callbacks.update(bindings)
def call(self, message, *args, **kvargs):
if message.__class__ in self.callbacks:
self.callbacks[message.__class__](message, *args, **kvargs)
@abstractmethod
def process(self):
"""
Process the incoming messages and call their associated callbacks.
"""
pass |
25a17cd5a6c449bff7029463d7fa79b60f369d85 | qnddkrasniqi/prod-python-practice | /tkinter-lessons/texts.py | 438 | 3.8125 | 4 | import tkinter as tk
window = tk.Tk()
text_box = tk.Text()
text_box.pack()
def get_text():
txt = text_box.get('1.0', '2.5')
print(txt)
def insert_text():
text_box.insert(tk.END, 'Hello')
get_btn = tk.Button(
master=window,
text='Get text',
command=get_text
)
insert_btn = tk.Button(
master=window,
text='Insert text',
command=insert_text
)
get_btn.pack()
insert_btn.pack()
window.mainloop()
|
76951050fc99fc6d061358cbd0db8d8eef76285b | chocholik/Programovani_s_Pavlem_Berankem | /Ukol 1U3.py | 423 | 3.671875 | 4 | '''
###Úkol 1U3 - Generování polymeru
Napište program, který přijme od uživatele tvar monomeru (např.: CH2) a z kolika monomerů se polymer skládá (např.: 4) a program na obrazovku vypíše pomocí opakování řetězců tvar takového polymeru (např.: CH2-CH2-CH2-CH2)
'''
monomer = input("Zadej monomer: ")
nasobek = int(input("Zadej násobek: "))
polymer = (monomer + "-")*(nasobek-1)+monomer
print (polymer) |
96da63cfcb7bac63d593019c645c491aa3838f18 | AnonKour/Linux-and-Git-Tutorial | /exampleProject/sphere.py | 319 | 4.4375 | 4 | #This script calculates the surface area of a sphere.
pi = 3.14
def calculate_SA():
radius = -1
while not (radius > 0):
user_input = input("Type the radius of the cube in cm: ")
try:
radius = int(user_input)
except ValueError:
print("That's not an integer!")
return 4*pi*(radius^2); |
ba47e3cd9b2f0525aa7792df77b9bf56179c7917 | Anjali-M-A/Code | /Code_3linear.py | 437 | 4.0625 | 4 | #Script for Linear Sequential Search Algorithm
def LinearSearch(list,key):
for i in range (len(list)): #range is i=0 to len(list)
if key == list[i]: #key will be compared to the 1st elelment of list
print("key element is found at index",i)
return i
else:
print("not found")
list= [2,3,4,5,6,7] #len(list) is 5
key =1
print(list)
LinearSearch(list,key)
|
b1eb98cfe6d52ae07d0c4f090701f88b82165d3e | Arielilloillo/Prueba | /Project.py | 2,456 | 3.921875 | 4 | class Person:
name=""
gender=""
class Student(Person):
color=""
calification=""
def __init__(self,name,color,gender):
self.name=name
self.color=color
self.gender=gender
class Teacher(Person):
students=[Student("Rorro Pirroro", "normal","male"), Student("Zafiro","black","female)
def evaluate(self,student):
for i in self.students:
if i.name==student:
calification=input("What calification deserves?: ")
i.calification=calification
class Library():
books=["Baldor", "Lord of the rings", "Bible"]
def delete_book(self):
delete=input("Which book do you want?: ").title
self.books.remove(delete)
def add_book(self):
add=input("What book do you want to add?: ").title
self.books.append(add)
class Interface:
library=Library()
students=[Student("Rorro Pirroro", "normal","male"), Student("Zafiro","black","female"), Student("Ariel","black","male"),Student("Daniela","normal","female")]
teacher=Teacher()
def show_interface(self):
decision=input("Select your rol: 1)Teacher. 2)Student. ")
if decision=="1":
self.run_teacher()
elif decision=="2":
self.run_student()
else:
print("Invalid option.")
def run_student(self):
repeat=True
while repeat:
option=input("Select action: 1)Study. 2)Get drunk. 3)Get book. 4)Add book. 5)Salir. ")
if option=="1":
print("I'm studing.")
elif option=="2":
print("Pist and then exist.")
elif option=="3":
self.library.add_book()
elif option=="4":
self.library.delete_book()
elif option=="5":
repeat=False
else:
print("Invalid option.")
def run_teacher(self):
repeat=True
while repeat:
option=input("Select action: 1)Teach. 2)Evaluate. 3)Salir. ")
if option=="1":
print("Teaching in classroom.")
elif option=="2":
evaluate=input("Select student:").title
self.teacher.evaluate(evaluate)
elif option=="3":
repeat=False
else:
print("Invalid option.") |
0098327d6985a0cee1a1f1c045c2966a0a92ba3f | vaporwavefm/PythonNotes | /DriversLicenseTest.py | 1,818 | 4.15625 | 4 | # George Juarez
'''
The local driver’s license office has asked you to create an application that grades the written
portion of the driver’s license exam. The exam has 20 multiple-choice questions. Here
are the correct answers:
1. B 6. A 11. B 16. C
2. D 7. B 12. C 17. C
3. A 8. A 13. D 18. B
4. A 9. C 14. A 19. D
5. C 10. D 15. D 20. A
Your program should store these correct answers in a list. The program should read the
student’s answers for each of the 20 questions from a text file and store the answers in
another list. (Create your own text file to test the application.) After the student’s answers
have been read from the file, the program should display a message indicating whether the
student passed or failed the exam. (A student must correctly answer 15 of the 20 questions
to pass the exam.) It should then display the total number of correctly answered questions,
the total number of incorrectly answered questions, and a list showing the question numbers
of the incorrectly answered questions.
'''
correctAnsDatabase = ['B','D','A','A','C','A','B','A','C','D','B','C','D','A','D','C','C','B','D','A']
def main():
userFile = open(input("Enter the file you wish to grade: "),'r')
i = 0
totalCorrect = 0
userList = []
for line in userFile:
userList.append(line.rstrip('\n'))
i += 1
for i in range(0,20):
if(userList[i] == correctAnsDatabase[i]):
totalCorrect = totalCorrect + 1
print("You scored", totalCorrect,"out of 20.")
if(totalCorrect >= 15):
print("You passed!")
else:
print("You failed.")
userFile.close()
# call main
main()
|
fe0b1a5b3813158d580c4acab94e31c6ae20cfd7 | surendhar-code/Python-Programs | /Basic Programs/clear_list.py | 758 | 4.375 | 4 | # Clearing a list using different methods
#Method 1 - using clear() function
lst=[5,6,9,2,1,3,4,7]
print("List before clearing using clear() function : ",lst)
lst.clear()
print("List after clearing using clear() : ",lst)
#Method 2 - using reinitialization empty list
lst=[5,6,9,2,1,3,4,7]
print("List before clearing using reinitialization method : ",lst)
lst2=[]
lst=lst2
print("List after clearing using reinitialization method : ",lst)
#Method 3 - using del method
lst=[5,6,9,2,1,3,4,7]
print("List before clearing using del() : ",lst)
del(lst[:])
print("List after clearing using del() method : ",lst)
#Method 4 - using *=0
lst=[5,6,9,2,1,3,4,7]
print("List before clearing using *=0 : ",lst)
lst *=0
print("List after clearing using *=0 : ",lst)
|
3477de7be95e800c564efbfd4dba97bf14116ceb | mavb86/ejercicios-python | /seccion3/ejercicio15.py | 522 | 4.15625 | 4 | # Ejercicio 15
# Dadas dos variables numéricas A y B, que el usuario debe teclear, se pide realizar un algoritmo que intercambie
# los valores de ambas variables y muestre cuanto valen al final las dos variables.
print("****************************")
print("* SECCION 3 - EJERCICIO 15 *")
print("****************************")
a = int(input("Introduce el valor de la variable A:"))
b = int(input("Introduce el valor de la variable B:"))
aux = a
a = b
b = aux
print("Nuevo valor de A:", a)
print("Nuevo valor de B:", b)
|
baa7bcd8f41cf184cb2ab6148d5783ca8dfaa283 | MrinaliniTh/Algorithms | /Arrays/Product_without_self.py | 994 | 3.921875 | 4 | # Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements
# of nums except nums[i].
# Iterative approach: Space O(n), Time O(n)
# Take a product from left side
# Take a product from right side
# multiply with the left and right product
# Example:
# left_product = [1,1,1,1] , right_product = [1,1,1,1] initially
# after multiplying from left side left_product = [1,1,2,6]
# after multiplying from right side right_product = [24,12,4,1]
# return product from both list
def productExceptSelf(nums: list) -> list:
left_product = [1] * len(nums)
right_product = [1] * len(nums)
i = 1
while i < len(nums):
left_product[i] = left_product[i-1] * nums[i-1]
i += 1
j = len(nums) - 2
while j >= 0:
right_product[j] = right_product[j+1] * nums[j+1]
j -= 1
return [left_product[i] * right_product[i] for i in range(len(nums))]
print(productExceptSelf([1,2,3,4]))
|
38ea64c9e90dced78d42c5114c6377f242c182dd | ViartX/PyProject | /lesson5_5.py | 628 | 4.25 | 4 | # 5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
import random
numbers_sum = 0
f_text = open("lesson5_5.txt", 'w')
for i in range(1, 101):
new_number = random.randint(1, 101)
f_text.write(str(new_number) + " ")
numbers_sum += new_number
f_text.close()
print(f"Сумма чисел в файле равна {numbers_sum}") |
748af97e71f5a9de11069e055fde6189bda5898d | jchen49gsu/coding_practice | /429. N-ary Tree Level Order Traversal.py | 751 | 3.71875 | 4 |
from collections import deque
class TreeNode(object):
def __init__(self,x,children):
self.val = x
self.children = children
class Solution(object):
"""docstring for Solution"""
def levelOderTraversal(self,root):
queue = deque()
res = []
if root is None:
return res
queue.append(root)
while queue:
size = len(queue)
l = []
for i in xrange(size):
node = queue.popleft()
l.append(node.val)
for child in node.children:
if child is not None:
queue.append(child)
res.append(l)
return res
children1 = [TreeNode(5,[]),TreeNode(6,[])]
children2 = [TreeNode(3,children1),TreeNode(2,[]),TreeNode(4,[])] #要是list
root = TreeNode(1,children2)
s = Solution()
print s.levelOderTraversal(root)
|
75cd0e2793dfb8af32fc9d4c7a948a5afa4cf8b9 | shiwei92/learn_python | /Chapter7/parrot.py | 1,395 | 4.15625 | 4 | #input()向用户输出提示并获取用户输入,将输入存储在一个变量中
#message=input("Tell me something,and I will repeat it back to you:")
#print(message)
#使用int()获取数值输入
'''age=input("How old art you?")
if(int(age)>18):
print("old enough")
else:
print("no admission")'''
'''current_number=1
while current_number<5:
print(current_number)
current_number+=1
prompt="Do you know my name?"
message=""
while message!="quit":
message=input(prompt)
if message!="quit":
print(message)'''
#使用while循环处理列表和字典
unconfirmed_users=["jack","stark","rogers"]
confirmed_users=[]
while unconfirmed_users:
current_user=unconfirmed_users.pop()
print("Verify user: "+current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print (confirmed_user.title())
while 'rogers' in confirmed_users:
confirmed_users.remove('rogers')
print(confirmed_users)
responses={}
polling_active=True
while polling_active:
name=input("\nWhat is your name?")
response=input("\nWhich mountain would you like to climb someday?")
responses[name]=response
repeat=input("Would you like to let another person respond?(yes/no)?")
if repeat=="no":
polling_active=False
print("--Poll Results--")
for name,mountain in responses.items():
print(name+" want to climb "+mountain)
|
ff85aa4859ab91dadeb32a803851a1bc270460c5 | theonemule/ce2c | /005 -- Loops/while-loop.py | 80 | 3.984375 | 4 | x = 0
while (x < 3):
print("x: ", x)
x = x + 1
print ("All done.") |
e00645a8d31688e4c65c43b5517ae362461fedd0 | Luke3133/Python-SoundSynthesis | /BasicSineWaveGeneration.py | 3,169 | 3.625 | 4 | """
This is a Python project which outputs an infinitely long sine wave, programmed by Emily Glover.
It works by using callbacks from pyaudio to request the next set of data for the buffer.
The SineOscillator class could be instantiated many times with different frequencies. To output the sum of waves,
an oscillator controller class should be produced which can get the frame across all active oscillators.
"""
import numpy as np
import pyaudio
BUFFER_SIZE = 1024 # How many samples to send to the audio processor buffer
SAMPLE_RATE = 44100 # How many samples per second to generate
NOTE_AMP = 0.5 # Master volume
freq = 200 # The frequency of the note we wish to produce
class SineOscillator:
# This produces a single instance of a sine oscillator. To use multiple oscillators per voice or multiple voices
# with sine waves, we must create instances for each oscillator.
def __init__(self, Frequency, Samplerate=SAMPLE_RATE, Position=0):
self.Frequency = Frequency # Frequency of the oscillator
self.SampleRate = Samplerate # Sample rate of project
# Keep track of how much of the wave has been sent to the buffer already
# i.e. upon sending the first lot of data, we have sent BUFFER_SIZE samples. Therefore,
# Position will equal BUFFER_SIZE so that next time we can send BUFFER_SIZE+1 to 2*BUFFER_SIZE.
self.Position = Position
def getframe(self):
# This function returns the next set of samples to the callback
increment = (2 * np.pi * self.Frequency) / self.SampleRate # Calculate a single sample
# The output returns a list which contains the samples in the range(position, position+buffer)
output = [count * increment for count in range(self.Position, self.Position + BUFFER_SIZE)]
self.Position += BUFFER_SIZE # Increase the position ready for the next callback
return np.sin(output) # Return the sin of the output
Osc1 = SineOscillator(freq) # Instantiate the class SineOscillator with frequency freq
# The function callback is called when the audio buffer is ready to be filled with more data.
def callback(in_data, frame_count, time_info, status):
# Osc1.getframe will return an array of numbers with length BUFFER_SIZE
# The data is then converted to float16 which is required by pyaudio
data = np.array(Osc1.getframe()).astype(np.float16)
# Return the data and also tell pyaudio to fill the buffer and continue playing
return data, pyaudio.paContinue
# The following lines open the audio stream and use stream_callback to call the above function when the buffer is ready
# to receive more audio.
p = pyaudio.PyAudio()
stream = p.open(
rate=SAMPLE_RATE,
channels=1,
format=pyaudio.paInt16,
output=True,
frames_per_buffer=BUFFER_SIZE,
stream_callback=callback
)
stream.start_stream()
# The following code is used to keep the program looping forever. To end the project early, add an event listener and
# update x to be greater than y.
x, y = 1, 2
try:
while True:
if x > y:
print("true")
finally:
stream.stop_stream()
stream.close()
p.terminate()
|
77b161680bc2daf57b3edfcf9dadcbe4412d435f | NiuNiu-jupiter/Leetcode | /Premuim/428. Serialize and Deserialize N-ary Tree.py | 3,065 | 3.953125 | 4 | """
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize an N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that an N-ary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following 3-ary tree
as [1 [3[5 6] 2 4]]. Note that this is just an example, you do not necessarily need to follow this format.
Or you can follow LeetCode's level order traversal serialization format, where each group of children is separated by the null value.
For example, the above tree may be serialized as [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].
You do not necessarily need to follow the above suggested formats, there are many more different formats that work so please be creative and come up with different approaches yourself.
Constraints:
The height of the n-ary tree is less than or equal to 1000
The total number of nodes is between [0, 10^4]
Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
"""
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
serial = []
def preorder(node):
if not node:
return
serial.append(node.val)
for child in node.children:
preorder(child)
serial.append("#") # indicates no more children, continue serialization from parent
return
preorder(root)
return serial
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: Node
"""
if not data:
return None
data = collections.deque(data)
root = Node(data.popleft(), [])
def helper(node):
if not data:
return
while data[0] != "#": # add child nodes with subtrees
value = data.popleft()
child = Node(value, [])
node.children.append(child)
helper(child)
data.popleft() # discard the "#"
helper(root)
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
|
7d5a9563c564232b1895ab877aacf2bf3c470a86 | karalienes/Python | /For_2.py | 254 | 3.515625 | 4 | #Fig. 3.23:fig03_23.
#calculating compound interest(bırlesık faız hesaplama)
principal=20000
rate=.05
print"Year %21s" % "Amount on deposit"
for year in range(1,61):
amount =principal *( 1.0 + rate)** year
print"%4d%21.2f" % (year , amount)
|
d5c35e9490eb5b84db8b451ca422ddc89b41fb05 | Pallavi2000/heraizen_internship | /internship/mod2/labqns/qns10.py | 144 | 3.8125 | 4 | N = int(input("Enter a value: "))
i = 1
count = 0
while True:
print(i,end = " ")
count += 1
i += 1
if count == N:
break
|
458b444f7686bbe6703d9b3d7a24f66a4c95b9e5 | abbasmalik514/30_Days_Coding_Challenge_HackerRank | /Day_22_Binary_Search_Trees/Script.py | 1,154 | 3.90625 | 4 | # Finding Height of a BST
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def heightFinder(self,node,height):
left_height=0
right_height=0
if node.left is not None:
left_height=self.heightFinder(node.left,height+1)
if node.right is not None:
right_height = self.heightFinder(node.right,height+1)
if height<left_height:
height=left_height
if height<right_height:
height=right_height
return height
def getHeight(self,root):
return self.heightFinder(root,0)
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
height=myTree.getHeight(root)
print(height)
|
36ab95ae2da5b4881ea11aad7ad3e0b404b77b7c | raqune89/CodeWars | /Unique In Order.py | 738 | 4.125 | 4 | # Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.
# For example:
# unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
# unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D']
# unique_in_order([1,2,2,3,3]) == [1,2,3]
def unique_in_order(iterable):
# create a list with the results
solution_list = []
#
for i in iterable:
if len(solution_list) < 1 or not i == solution_list[len(solution_list) - 1]:
solution_list.append(i)
return solution_list
print(unique_in_order('aAAabCCcdeFFgH'))
|
4f58ada4735822a1533d880631faf2a684f6da39 | gupeng351578076/PythonCode | /senior/demog2.py | 404 | 3.5625 | 4 | __author__ = 'mocy'
#coding:UTF-8
#针对字典的迭代操作
zd = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
for k,v in zd.items():
print(k,":",v)
#判断一个对象是否可以迭代
from collections import Iterable
print(isinstance(1234,Iterable))
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
for i,value in enumerate(['成功','失败','骄傲','谦虚']):
print(i,value)
|
0024ec3ae43436434f2d3051b90edf44c9c3ec6f | JaneNjeri/Think_Python | /ex_09_4_1.py | 598 | 4.21875 | 4 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 27.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 9. Case study: word play
# Exercise 9.4
# Write a function named uses_only that takes a word and a string
# of letters, and that returns True if the word contains only
# letters in the list.
def uses_only(word, string):
for letter in word:
if letter not in string:
return False
return True
print(uses_only('banana', 'anb'))
print(uses_only('banana', 'ane'))
#END |
a00b66865bb1641e976b9456de0ec938c444fef4 | Naruto-Zhao/HDU-Summer | /暑期作业/作业一/Logistic_Regression.py | 4,140 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
class Logistic_Regression():
"""
本类用于实现逻辑回归,使用的梯度下降的优化方法
"""
def __init__(self, W):
self.W = W # 初始化W值
def one_calc(self, X_train, y_train, reg):
"""
执行一次训练
:param X_train: 训练集
:param y_train: 标签
"""
output = 1.0 / (1 + np.exp((-1) * (X_train.dot(self.W)))) # 前向计算一次
loss = (-1) * np.sum(y_train * np.log(output) + (1 - y_train) * np.log(1 - output)) # 计算似然函数的值
loss = loss / X_train.shape[0] + reg * np.sum(self.W * self.W) # 加上正则项
# 计算W的梯度,使用反向传播算法
dW = (-1) * np.sum((y_train - output).T * X_train.T, axis = 1).reshape((-1, 1))
dW += 2 * reg * self.W
return loss, dW
def train(self, X_train, y_train, num_iters = 1000, alpha = 0.01, reg = 0.01):
"""
进行多次训练,不断优化w,b值
:param X_train: 训练数据
:param y_train: 标签
:param num_iters: 训练迭代次数
:param alpha: 学习率
:param reg: 正则项系数
"""
loss_history = []
for i in range(num_iters):
loss, dW = self.one_calc(X_train, y_train, reg)
# 不断更新W的值
self.W -= alpha * dW
loss_history.append(loss)
return loss_history
def predict(self, X):
output = 1.0 / (1 + np.exp((-1) * (X.dot(self.W)))) # 前向计算一次
output[output >= 0.5] = 1
output[output < 0.5] = 0
return output.reshape(output.shape[0])
def Show(self, loss):
"""
此函数用于将数据和训练模型进行可视化
:param loss: 损失值历史
"""
plt.figure(figsize=(10,8))
plt.subplot(1,1,1)
plt.plot(loss)
plt.title("Loss History")
plt.xlabel("Train Numbers")
plt.ylabel("Loss")
plt.show()
def colicTest(): #对马这个数据进行处理
'''
读取数据
:return: 列表形式
'''
frTrain = open('horse/horseColicTraining.txt')
frTest = open('horse/horseColicTest.txt')
trainingSet = []
trainingLabels = []
testSet = []
testLabels = []
for line in frTrain.readlines():
currLine = line.strip().split('\t')
lineArr = []
for i in range(21):
lineArr.append(float(currLine[i]))
trainingSet.append(lineArr)
trainingLabels.append(float(currLine[21]))
for line in frTest.readlines():
currLine = line.strip().split('\t')
lineArr = []
for i in range(21):
lineArr.append(float(currLine[i]))
testSet.append(lineArr)
testLabels.append(float(currLine[21]))
X_train, y_train, X_test, y_test = np.array(trainingSet), np.array(trainingLabels), np.array(testSet), np.array(testLabels)
# 对数据进行归一化,否则数据会溢出
X_train = (X_train - np.mean(X_train, axis = 0)) / np.std(X_train, axis = 0)
X_test = (X_test - np.mean(X_test, axis = 0)) / np.std(X_test, axis = 0)
X_train = np.hstack([X_train, np.ones((X_train.shape[0], 1))])
X_test = np.hstack([X_test, np.ones((X_test.shape[0], 1))])
return X_train, y_train, X_test, y_test
def main():
"""
这里的数据集为死马活马
"""
X_train, y_train, X_test, y_test = colicTest()
W = np.random.randn(X_train.shape[1],1)
classifier = Logistic_Regression(W)
loss = classifier.train(X_train, y_train.reshape((-1,1)), num_iters=1000, alpha=0.0001, reg = 0.0001)
X_train_predict = classifier.predict(X_train)
X_test_predict = classifier.predict(X_test)
# 分别输出模型在训练集和测试集中的精度
print("Train accuracy: %.4lf" % np.mean(X_train_predict == y_train))
print("Test accuracy: %.4lf" % np.mean(X_test_predict == y_test))
classifier.Show(loss)
main()
|
68eef5b7da0c2605f5cfd9b7b1d19f497b6e7b1d | EarlWicked/project-Euler | /euler_12.py | 337 | 3.578125 | 4 | # tringle divs
divisor = 0
i = 0
num = 0
#creating the triangle
while True:
i= i + 1
num = num + i
divisor = 0
for j in range (1, num+1):
if num % j == 0 :
divisor = divisor +1
if (divisor) >= 200:
break
print (num)
|
c2b71a16ef15a06b15c749d300dd1165208f299b | anuragpratap05/HackerRank | /re.split().py | 158 | 3.671875 | 4 | # HackerRank
HackerRank learning python, since infosys has arrived.....
regex_pattern = r"\W+"
import re
print("\n".join(re.split(regex_pattern, input())))
|
7ef377894c836ebd167b036f19509e7278b993ce | CaptnH00k/PythonCourse | /blatt-04/WordCount.py | 2,784 | 4.21875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright 2017, University of Freiburg,
Chair of Algorithms and Data Structures.
Hannah Bast <bast@cs.uni-freiburg.de>
Axel Lehmann <lehmann@cs.uni-freiburg.de>
Author: Leon Gnädinger <leon.gnaedinger@gmail.com>.
"""
import re
from HashMap import HashMap
class WordCount:
def __init__(self):
self.hash_map = HashMap(3000)
def read_text_file(self, file_path):
"""
Read in a text file and add all words to the Internal
HashMap. Value will be updated to how often the word was
found.
Copyright:
Code taken and minimally modified
from public/code/vorlesung-04/python/words_main.py
Original written by Hannah Bast and Axel Lehmann.
Args:
file_path (string) - path to text file to read in
Examples:
>>> wc = WordCount()
>>> wc.read_text_file('./WordCount.TIP')
>>> wc.hash_map.lookup('to')
7
>>> wc.hash_map.lookup('freiburg')
4
>>> wc.hash_map.lookup('wordcount')
6
>>>
"""
with open(file_path) as fh:
for line in fh:
for word in re.split('\W+', line):
word = word.lower()
if len(word):
count = self.hash_map.lookup(word) + 1
self.hash_map.insert(word, count)
def compute_frequency_lines(self):
"""
Figures out the 500 most occuring words currently in our HashMap
and returns them as [(word, frequency)]. First element will be highest
occuring word, last least occuring word.
Returns:
List of word/frequency pairs
Examples:
>>> wc = WordCount()
>>> wc.read_text_file('WordCount.TIP')
>>> mow = wc.compute_frequency_lines()
>>> mow[0]
'1\\t9\\twc'
>>> mow[1]
'2\\t7\\tto'
>>> mow[-1]
'120\\t1\\tcomputefrequencylines'
"""
word_frequencies = self.hash_map.get_key_value_pairs()
sorted_word_frequencies = sorted(
word_frequencies,
key=(lambda kv: kv[1]),
reverse=True
)
most_occuring_words = []
i = 1
for (word, frequency) in sorted_word_frequencies[:500]:
most_occuring_words.append(
str(i) + "\t" + str(frequency) + "\t" + word
)
i += 1
return most_occuring_words
if __name__ == "__main__":
wc = WordCount()
wc.read_text_file("./pruefungsordnung.txt")
most_occuring_words = wc.compute_frequency_lines()
f = open('words.txt', 'w')
for line in most_occuring_words:
f.write(line + "\r\n")
f.close()
|
f660faf8d46843dfd2bf8b454c9ebebef8ff7f61 | Susaposa/Homwork_game- | /solutions/1_python_review_solution.py | 2,213 | 4.21875 | 4 | # REMINDER: Only do one challenge at a time! Save and test after every one.
print('Challenge 1 -------------')
# Challenge 1:
# Create 3 variables with your name, your favorite color, and how many hours of
# sleep you got last night. Print out all 3 values using "print".
name = 'Orlando Bloom'
favorite_color = 'Yellow'
how_much_sleep = 6
print('My name is', name, ' and I like the color', favorite_color)
print('I got ', how_much_sleep, 'hours of sleep last night.')
print('Challenge 2 -------------')
# Challenge 2:
# Create a list of your favorite authors.
authors_list = [
'Douglas Adams',
'Ursula Le Guin',
'J.K. Rowling',
'Mary Shelley',
'Oscar Wilde',
]
print('Challenge 3 -------------')
# Challenge 3:
# Write an "if-statement" to check if the first author on that list is equal to
# "Douglas Adams". If it is, print "Don't panic!". Otherwise, print "Panic!"
if authors_list[0] == 'Douglas Adams':
print("Don't Panic!")
else:
print("Panic!")
print('Challenge 4 -------------')
# Challenge 4:
# Using a while loop, write code to "loop through" your favorite authors,
# printing each one on a separate line, along with its index
i = 0
length = len(authors_list)
while i < length:
print(i, authors_list[i])
i += 1
print('Challenge 5 -------------')
# Challenge 5:
# Using "input", create a while loop that keeps on looping until the user says
# "Stop". Have it print back whatever they say each time it loops.
answer = None
while answer != 'Stop':
answer = input('Stop? ')
print('You said: ', answer)
print('-------------')
# Bonus Challenge:
# Create a chat bot!
# Using a dictionary and a while / input loop, every time a user enters text
# check in the dictionary for a pre-set set of replies (e.g. "hi" responds with
# "hello").
replies = {
'hello': 'hi',
'hi': 'hi',
'hey': 'hey you',
'how are you?': 'i am okay....',
'are you a robot?': 'OF COURSE NOT... .....are you a robot?',
'are you human?': 'OF COURSE... .....are you a robot?',
'no': 'sure.....',
'yes': 'i thought so',
}
answer = None
while answer != 'goodbye' and answer != 'bye':
answer = input('? ')
if answer in replies:
print(replies[answer])
else:
print('hmmm..')
|
01699fb302f17f7c52bc01fa4afd878bff075013 | ericwebsite/ericwebsite.github.io | /src/python/balckjack.py | 1,223 | 3.90625 | 4 | import random
print("#########################\n")
print("# Welcome to Black Jack #\n")
print("#########################\n")
min_card = 1
max_card = 10
while True:
answer = input("Would you like to start new game? (y/n)\n")
if answer != 'y':
break
cards =[random.randint(min_card, max_card), random.randint(min_card, max_card)]
print (" Your cards: ", cards)
while True:
answer = input("Would you like a new card? (y/n)\n")
if answer != 'y':
break
cards.append(random.randint(min_card, max_card))
print (" Your cards: ", cards)
yourpoints = sum(cards)
if yourpoints > 21:
print ("basted!!\n You lose.\n")
else:
print ("My turn")
mypoints = 0
cards = []
while mypoints < 15:
cards.append(random.randint(min_card, max_card))
mypoints = sum(cards)
print(" My cards: ", cards)
if mypoints > 21:
print("Blasted!! You win\n")
print ("You: {}, Me: {}".format(yourpoints, mypoints))
mypoints = sum(cards)
if (yourpoints >= mypoints):
print("You win!!\n")
else:
print("You lose!!\n")
|
989e397709908e65047acb672f678325552d4df1 | vitcmaestro/hunter2 | /freq_in_one.py | 165 | 3.515625 | 4 | import collections
n = int(input(""))
a = list(map(int,input().split()))
freq = dict(collections.Counter(a))
for x,y in freq.items():
if(y==1):
print(x)
|
0c5b93fc2602defe4716e1518622e84c80ff4b9e | domino32/ga306 | /wall-painting.py | 138 | 3.59375 | 4 | print('how many gallons do you have')
gallon = int(input())
lpg = .264172
gpl = 3.78541
print = (str(int(gallon) * 3.78541)
|
160d96daf106cce4acaed889b9d9e54ad8733e4c | JaiJun/Codewar | /8 kyu/You only need one - Beginner.py | 625 | 3.875 | 4 | """
You will be given an array a and a value x.
All you need to do is check whether the provided array contains the value.
Array can contain numbers or strings. X can be either.
Return true if the array contains the value, false if not.
I think best solution:
def check(seq, elem):
return elem in seq
https://www.codewars.com/kata/57cc975ed542d3148f00015b
"""
def check(seq, elem):
if elem in seq:
print(True)
return True
else:
print(False)
return False
if __name__ == '__main__':
seq = [66, 101]
elem = 66
check(seq, elem) |
e2d29209198d1bf0a5f5d30460ca0878e61181ce | ShalomVanunu/SelfPy | /Targil9.1.1.py | 459 | 3.53125 | 4 |
def are_files_equal(file1, file2):
content_file1_object = open(file1,'r').read()
content_file2_object = open(file2,'r').read()
if content_file1_object == content_file2_object:
print(True)
else:
print(False)
def main(): # Call the function func
are_files_equal(r"C:\Users\Shalom\PycharmProjects\Selfpy\vacation.txt",r"C:\Users\Shalom\PycharmProjects\Campus\work.txt")
# False
if __name__ == "__main__":
main()
|
9d614be6013dc4a72d81f07bef2667699aa050fc | hebertomoreno/PythonScr | /isPhoneNumberRegex.py | 338 | 4.1875 | 4 | #import the Regex module
import re
#Create a Regex object with a raw string (r'')
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
#Pass the string you want to search
#Returns a Match object
mo = phoneNumRegex.search('My number is 415-555-4242.')
#Call the Match object´s group() method
print('Phone number found: ' + mo.group())
|
2675363ef23a18d3d0f168ac99b8bc0861ddb416 | atshaman/SF_FPW | /C1/T181/cat.py | 1,639 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Описание класса Cat в рамках учебного задания 1.8.1"""
class Cat():
_genders = {'male': 0, 'm': 0, 'мужской': 0, 'м': 0, 'female': 1, 'f': 1, 'женский': 1, 'ж': 1}
def __init__(self, gender, age, name):
self.gender = gender
self.age = age
self.name = name
@property
def gender(self):
if self._gender == 0:
return 'мужской'
else:
return 'женский'
@gender.setter
def gender(self, value):
try:
self._gender = self._genders[value.lower()]
except KeyError:
print('Пол должен быть одним из: ' + '/'.join(list(self._genders.keys())))
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if int(value) > 0 and int(value) < 100:
self._age = value
else:
raise ValueError('Возраст должен быть целым положительным числом в диапазоне от 0 до 100')
@property
def name(self):
return self._name.capitalize()
@name.setter
def name(self, value):
if value.isalpha() and len(value) < 20:
self._name = value.lower()
else:
raise ValueError('Имя должно быть текстовой строкой до длинной до 20 символов')
def get_info(self):
return ('Питомец {0}, возраст {1}, пол {2}'.format(self.name, self.age, self.gender))
|
3028be8d4963a5c9729eeb2c18ea8ceed594f37c | czhnju161220026/LearnPython | /chapter8/ListCopy.py | 242 | 3.671875 | 4 | # encoding=utf-8
if __name__ == '__main__':
l1 = [1, 2, 3, 4]
l2 = list(l1)
print(l2, id(l2))
l3 = l1[:]
print(l3, id(l3))
l4 = [1, 2, 3, [4, 5, 6]]
l5 = list(l4) # shallow copy
l5[3].append(7)
print(l4)
|
4e09ee16784d6879eb44f787e4287d2897037184 | markusos/project-euler | /014/sequence.py | 733 | 3.90625 | 4 | #!/usr/bin/python
import math
sequenceLength = {}
def nextNumber(n):
if n % 2 == 0:
return n / 2
else:
return 3 * n + 1
def sequence(start):
global sequenceLength
seq = [1]
n = start
while n != 1 and n not in sequenceLength:
seq.append(n)
n = nextNumber(n)
if n in sequenceLength:
length = len(seq) + sequenceLength[n]
else:
length = len(seq)
l = length
for n in seq:
sequenceLength[n] = l
l -= 1
return length
def longestCollatzSequence():
longest = 0
start = 0
for n in range(1, 1000000):
l = sequence(n)
if l > longest:
longest = l
start = n
return start
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.