blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
1f2b1c0f66ca6d9b116a1d86c5097cbaa0bd41e7 | pvsreenivas/BillingSoftware-SalesTax | /TaxCalc/ReceiptGenerate.py | 1,137 | 3.609375 | 4 | # 01a, 07Apr2021, SreenivasK, Initial code
from typing import List, Dict
from .TotalCalc import TotalCalc
class ReceiptGenerate:
def __init__(self):
self.product_list: List[str] = []
def receipt_generate(self):
"""
Returns:
None
"""
print("Ready to bill the cart.")
print("Please enter the products in the format: [QUANTITY] [PRODUCT NAME] at [COST PER PRODUCT]")
print("Example: 1 book at 12.49\n")
self.product_list = []
cont: int = True
print("Enter the sale details: \n")
while cont:
prod: str = input()
if prod:
self.product_list.append(prod.strip(" "))
else:
cont = False
total_calc: TotalCalc = TotalCalc(self.product_list)
taxed_product_list: List = total_calc.get_receipt_product_list()
print("***********Receipt***********")
for taxed_product in taxed_product_list:
print("{}".format(taxed_product))
print("**********Thank You**********")
print("*********Visit Again*********\n")
|
ba76365aa5bf69e54e4ee4cba9ebb4ef7c6daf97 | arehy/Elvenar | /tesztek/radioButton.py | 540 | 3.84375 | 4 | from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = StringVar(root, '1')
R1 = Radiobutton(root, text="Kristály", variable=var, value='kristaly', command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Márvány", variable=var, value='marvany', command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Drágakő", variable=var, value='dragako', command=sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop() |
792d0ff1f1bf339810b83c2b3f1c6f9aa637ea86 | sofiyuh/ProgramAssignments | /dictionarypractice.py | 855 | 3.578125 | 4 | groceries = {"chicken": "$1.59", "beef": "$1.99", "cheese": "$1.00", "milk": "$2.50"}
NBA_players = {"Lebron James": 23, "Kevin Durant": 35, "Stephen Curry": 30, "Damian Lillard": 0}
PHONE_numbers = {"Mom": 5102131197, "Dad": 5109088833, "Sophia": 5106939622}
shoes = {"Jordan 13": 1, "Yeezy": 8, "Foamposite": 10, "Air Max": 5, "SB Dunk": 20}
chicken_price = groceries["chicken"]
print(chicken_price)
beef_price = groceries["beef"]
print(beef_price)
cheese_price = groceries["cheese"]
print(cheese_price)
milk_price = groceries["milk"]
print(milk_price)
Lebron_number = NBA_players["Lebron James"]
print(Lebron_number)
Kevin_number = NBA_players["Kevin Durant"]
print(Kevin_number)
NBA_players["Lebron James"] = 6
jersey_number = NBA_players["Lebron James"]
print(jersey_number)
NBA_players["Lebron James"] -= 17
jersey_number = NBA_players["Lebron James"]
print(jersey_number) |
d59bd150cb4fcb379cb959b9310cf1204d06b65a | asolisn/Ejercicios-de-la-S9 | /class Ordenar.py | 440 | 3.59375 | 4 | class Ordenar
def__init__(self,lista):
self.lista=lista
def recorrerElemento(self):
for ele in self.lista:
print(ele)
def recorrerPosicion(self):
for pos,ele in self.lista.items():
print(pos,ele)
lista = [2,3,1,5,8,10]
ord1 = Ordenar(lista)
ord1.recorrerElemento()
ord1.recorrerPosicion() |
d160a250d883ed92ce1b9effd217a4d5177b3bfc | FullStackToro/Python_Orden_por_Inserci-n | /main.py | 633 | 3.90625 | 4 |
#Los datos en el arreglo son ordenados de menor a mayor.
def ordenamientoPorInserccion(num):
#Recorre todas las posiciones del arreglo
for x in range (len(num)):
#No es necesario evaluar con un solo valor
if x==0:
pass
else:
#Comparación e intercambio (en caso de que el numero ubicado en lugar predecesor sea mayor)
for y in range (x,0,-1):
if num[y]<num[y-1]:
num[y-1],num[y]=num[y],num[y-1]
ouput="Arreglo modificado: {}".format(num)
return ouput
if __name__ == '__main__':
print(ordenamientoPorInserccion([6,5,3,1,8,7,2,4]))
|
acdd2bf6a695151004880dffae1d509918fb7b59 | jpcirqueira/Grafos1_Fofocando | /criagrafo.py | 514 | 3.953125 | 4 |
def main():
h = {}
numnos = int(input('digite o numero de pessoas:\n'))
for i in range(0,numnos):
vizinhos = []
nomeno = input('represente a pessoa por um nome ou numero ' + str(i) + ' :')
numvizinhos = int(input('digite o numero de conhecidos do ' + str(nomeno) + ' :' ))
for j in range(0,numvizinhos):
vizinho = input('indique o ' + str(j+1) + ' conhecido:')
vizinhos.append(vizinho)
h[str(nomeno)] = vizinhos
return h
|
d4a3251bdf830118e2c04dd9cdff7c74ab1c1e1c | IanMK-1/Password-locker | /password_locker_test.py | 2,975 | 3.703125 | 4 | import unittest
from User import User
class TestPasswordLocker(unittest.TestCase):
def setUp(self) -> None:
"""Method that define instructions to be ran before each test method"""
self.new_locker_account = User("Ian", "Mwangi", "ianmk", "1234567")
def test_init(self):
"""Test to check if the objects are being instantiated correctly"""
self.assertEqual(self.new_locker_account.first_name, "Ian")
self.assertEqual(self.new_locker_account.last_name, "Mwangi")
self.assertEqual(self.new_locker_account.username, "ianmk")
self.assertEqual(self.new_locker_account.password, "1234567")
def test_save_user_details(self):
"""Test_save_user_details tests if details of a new user are being saved"""
self.new_locker_account.save_user_details()
self.assertEqual(len(User.user_list), 1)
def tearDown(self) -> None:
"""tearDown method define instruction to be run before each test method"""
User.user_list = []
def test_save_multiple_user_details(self):
"""Test_save_multiple_user_details saves details of multiple users"""
self.new_locker_account.save_user_details()
user_test_details = User("joe", "mark", "joe123", "lockedaccount")
user_test_details.save_user_details()
self.assertEqual(len(User.user_list), 2)
def test_get_user_account_by_username_password(self):
"""test_get_user_account_by_username is a test that obtains locker account based on username and password"""
self.new_locker_account.save_user_details()
user_test_details = User("joe", "mark", "joe123", "lockedaccount")
user_test_details.save_user_details()
got_user_account = User.get_user_account("joe123", "lockedaccount")
self.assertEqual(got_user_account.first_name, user_test_details.first_name)
def test_delete_user_account_by_username_password(self):
"""test_delete_user_account_by_username is a test that deletes locker account based on username and password"""
self.new_locker_account.save_user_details()
user_test_details = User("joe", "mark", "joe123", "lockedaccount")
user_test_details.save_user_details()
got_account = User.get_user_account("joe123", "lockedaccount")
got_account.del_user_account()
self.assertEqual(len(User.user_list), 1)
def test_check_if_user_exists(self):
self.new_locker_account.save_user_details()
user_test_details = User("joe", "mark", "joe123", "lockedaccount")
user_test_details.save_user_details()
user_exists = User.user_exist("joe123", "lockedaccount")
self.assertTrue(user_exists)
def test_display_user_details(self):
"""test_display_user_details tests if the available user account is being displayed"""
self.assertEqual(User.display_user_details(), User.user_list)
if __name__ == '__main__':
unittest.main()
|
419e9c5cbb652df0abccd13ca68273bc18327cd9 | jadugnap/python-problem-solving | /Task4-predict-telemarketers.py | 1,300 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
text.csv columns: sending number (string), receiving number (string), message timestamp (string).
call.csv columns: calling number (string), receiving number (string), start timestamp (string), duration in seconds (string)
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
text_senders = set([t[0] for t in texts])
text_receivers = set([t[1] for t in texts])
call_receivers = set([c[1] for c in calls])
whitelist = call_receivers.union(text_senders, text_receivers)
# print("\n".join(sorted(whitelist)))
callers = sorted(set([c[0] for c in calls if c[0] not in whitelist]))
print("These numbers could be telemarketers: ")
print("\n".join(callers))
|
33a9b899adfee643bc01dfb05d9291fbec3d65c0 | JiahuanChen/homework2 | /simulator_v2.py | 10,991 | 3.5 | 4 | #! /usr/bin/python
"""
Try to finished all three extra tasks. I used Gaussian distribution for the
reason that it is the most common distribute in statistics.
"""
import sys
import math
import string
import random
from optparse import OptionParser
#add functions
parser = OptionParser()
parser.add_option("--calc", help="calculate length and distribution")
parser.add_option("--save", help="save the parameter file, must follow --calc \
or --load")
parser.add_option("--load", help="load the parameter file")
parser.add_option("--k", help="report dinucleotide and higher-order \
compositional statistics, must follow the \'--calc\',e.g. --calc .fa --k n")
parser.add_option("--insert", help="insert motifs to the parameter file. \
To use this function, just enter [script] --insert paramterfile, and you'll \
see instructions.")
(options, args) = parser.parse_args()
length = 70
def checkinput(arg):
if len(arg) == 1:
return 1;
elif arg[1] == "--calc":
if len(arg) == 3 or arg[3] == "--save" or arg[3] == "--k":
return 2
else:
return -1
elif arg[1] == "--load":
if len(arg) == 3 or arg[3] == "--save":
return 3
else:
return -1
elif arg[1] == "--insert":
return 4
else:
return -1
#input: list of ditribution(dictionary) and sequence_length(int)
#function: generate random sequences that can be devided by 3
#return: list of unchecked sequences
def generate_sequences(distribution,sequence_length):
sequences = []
count = 0
for single_dis in distribution:
seq = []
for i in range(0,int(round(single_dis["A"]*sequence_length[count]))):
seq.append("A")
for i in range(0,int(round(single_dis["T"]*sequence_length[count]))):
seq.append("T")
for i in range(0,int(round(single_dis["C"]*sequence_length[count]))):
seq.append("C")
for i in range(0,int(round(single_dis["G"]*sequence_length[count]))):
seq.append("G")
count += 1;
random.shuffle(seq)
s = ''.join(seq)
while(len(s) %3 != 0):
s += str(random.choice(["A","T","C","G"]))
sequences.append(s)
return sequences
#input: list of unchecked sequences
#function: check start and stop codon
#return: list of checked sequences
def check(sequences):
new_sequences = []
for seq in sequences:
if(seq[0:3] != "ATG"):
seq = "ATG" + seq[3:]
for i in range(3,len(seq)-3,3):
if (seq[i:i+3] == "TAA"
or seq[i:i+3] == "TAG"
or seq[i:i+3] == "TGA"):
seq = seq[:i] + random.choice(["A","C","G"]) + seq[i+1:]
if (seq[len(seq)-3:len(seq)] != "TAA"
or seq[len(seq)-3:len(seq)] != "TAG"
or seq[len(seq)-3:len(seq)] != "TGA"):
seq = seq[:len(seq)-3] + random.choice(["TAA","TAG","TGA"])
new_sequences.append(seq)
return new_sequences
#input: list of sequences
#function: computedistribution
#return: list of distribution
def compute_distribution(sequences):
distribution = []
for seq in sequences:
dictionary = {"A":float(0),"C":float(0), "T":float(0),"G":float(0)}
for nucleotide in seq:
dictionary[nucleotide] += 1
for i in dictionary:
dictionary[i] /= len(seq)
distribution.append(dictionary)
return distribution
#input: list of distributions, sequences, names, filename
#function: generate parameter file
#file format: line1: name1; line2: length; line3: distribution(0~1),
#line4:user-specified motifs, etc..
def save_parameter(distributions,sequences,names,filename):
f = open(filename,"w")
for i in range(0,len(names)):
f.write(names[i]+"\n")
f.write(str(len(sequences[i]))+"\n")
for dis in distributions[i]:
f.write(dis+ " ")
f.write(str(distributions[i][dis])+ " ")
f.write("\n")
f.write("\n")
f.close()
#input:list of names and sequences
#function: print names and sequences to screen
def print_sequences(sequences,names):
for i in range(0,len(names)):
print("%s %d bp" %(names[i], len(sequences[i])))
for j in range(0, len(sequences[i]), length):
print(sequences[i][j:j+length])
#input: filename(string)
#functions: load names and sequences
#return: list of names and sequences
def openfile(filename):
file = open(filename)
sequence = []
name = []
count = -1
for line in file.readlines():
if line[0] == '>':
line = line.replace('\n','')
name.append(line)
sequence.append('')
count += 1
else:
sequence[count] += line
for i in range(0,count+1):
sequence[i] = sequence[i].replace('\n','')
return name,sequence
#input list of sequences lengths
#function: generate gaussian distribution and then random lengths
#return:list of random sequences lengths
def gaussian(seq_len):
average_len = 0.0
for seq in seq_len:
average_len += seq
average_len /= len(seq_len)
diviation = 0.0
for seq in seq_len:
diviation += (average_len - seq)**2
diviation = math.sqrt(diviation)
new_len = [];
for i in range(0,len(seq_len)):
new_len.append(random.gauss(average_len,diviation))
return new_len
#input: filename
#function: get lists of names,sequence_length,distributions for parameter file
#return:lists of names,sequence_length,distributions,motifs
def loadparams(filename):
file = open(filename)
names = []
sequence_length = []
distributions = []
motifs = []
count = 0
for line in file.readlines():
line = line.replace('\n','')
if count == 0:
names.append(line)
count += 1
elif count == 1:
sequence_length.append(int(line))
count += 1
elif count == 2:
dictionary = {}
s = line.split(" ")
for i in range(0,8,2):
dictionary[s[i]] = float(s[i+1])
distributions.append(dictionary)
count += 1;
elif count == 3:
motifs.append(line)
count = 0
return names,sequence_length,distributions,motifs
#input: k(k-nucleotide), list of sequences
#function: split sequences every k nucleotides and records them in a dictionary
#The distribution is show by how many times the k-nucleotide appears
def k_mers(k, sequences):
distribution = []
for seq in sequences:
dictionary = {}
for i in range(0,len(seq),k):
if dictionary.get(seq[i:i+k]) == None:
dictionary[seq[i:i+k]] = 1
else:
dictionary[seq[i:i+k]] += 1
distribution.append(dictionary)
print(distribution)
#input: list of sequences and motifs
#function: generate a random position except the at begining and the ending,
# then replace the position with the motifs
#return: list of sequences
def insert_motif(sequences,motifs):
for i in range(0,len(sequences)):
position = random.randint(1,(len(sequences[i])-len(motifs[i]))/3)
position *= 3
sequences[i] = sequences[i][:position] + motifs[i]\
+sequences[i][position+len(motifs):]
return sequences
#input: filename
#function: add motif to parameter
def edit_param(filename):
names,sequence_length,distributions,motifs = loadparams(filename)
print("There are "+str(len(names))+" sequences. Which sequence do you\
want to edit? Enter 0 to exit")
f = open(filename,"r")
contant = f.readlines()
f.close()
f = open(filename,"w")
index = input("Enter a sequence index:")
if (index> len(names)):
print("Out of range.")
while(index != 0 and index <= len(names)):
mof = raw_input("Enter the motif:")
mof_validation = True
if len(mof)%3 != 0:
mof_validation = False
for i in range(0,len(mof),3):
for i in range(3,len(mof)-3,3):
if (mof[i:i+3] == "TAA"
or mof[i:i+3] == "TAG"
or mof[i:i+3] == "TGA"):
mof_validation = False
if mof_validation:
mof += "\n"
contant[index*4-1] = mof
else:
print("Motif is not validated! Please check your motif!")
index = input("Enter a sequence index:")
if (index> len(names)):
print("Out of range.")
f.writelines(contant)
f.close()
# entrance
if __name__ == '__main__':
task = checkinput(sys.argv)
if task == 1:
#for no argument, the distribution is set to 0.25 evenly
distribution = [
{"A":float(0.25),"C":float(0.25), "T":float(0.25),"G":float(0.25)}]
sequence_length = [996]
sequences = generate_sequences(distribution,sequence_length)
sequences = check(sequences)
distributions = compute_distribution(sequences)
names = [">sequence1"]
filename = "mypara.txt"
save_parameter(distributions,sequences,names,filename)
print_sequences(sequences,names)
elif task == 2:
names, sequences = openfile(sys.argv[2])
distributions = compute_distribution(sequences)
sequence_length = []
for seq in sequences:
sequence_length.append(len(seq))
print(sequence_length)
sequence_length = gaussian(sequence_length)
sequences = generate_sequences(distributions,sequence_length)
sequences = check(sequences)
print_sequences(sequences,names)
if len(sys.argv) == 5:
if sys.argv[3] == "--save":
save_parameter(distributions,sequences,names,sys.argv[4])
elif sys.argv[3] == "--k":
k_mers(int(sys.argv[4]), sequences)
elif task == 3:
names,sequence_length,distributions,motifs = loadparams(sys.argv[2])
#use gaussian distribution to generate new lengths
#but the diviation will become rediculously large(several hundreds)
#thus the random sequences saperate in a very large range
sequence_length = gaussian(sequence_length)
sequences = generate_sequences(distributions,sequence_length)
sequences = check(sequences)
sequences = insert_motif(sequences,motifs)
print_sequences(sequences,names)
if len(sys.argv) == 5:
save_parameter(distributions,sequences,names,sys.argv[4])
elif task == 4:
edit_param(sys.argv[2])
else:
print("Please check your input!")
|
a4b024fe5edf1f5da39078c8d52034ba303a98cc | schirrecker/Math | /Math with Python.py | 397 | 4.15625 | 4 | from fractions import Fraction
try:
a = Fraction(input("Enter a fraction: "))
b = Fraction(input("Enter another fraction: "))
except ValueError:
print ("You entered an invalid number")
except ZeroDivisionError:
print ("You can't divide by zero")
else:
print (a+b)
def is_factor (a, b):
if b % a == 0:
return True
else:
return False
|
09772c3ab8555b1b1e33b480f7fb02dedc8dfacc | schirrecker/Math | /Censor text.py | 278 | 3.84375 | 4 | def censor(text, word):
list = text.split()
newlist = []
for w in list:
if w == word:
newlist.append(len(w)*"*")
else:
newlist.append(w)
return " ".join(newlist)
print (censor("Hi there Ismene", "Ismene"))
|
5ad4cf6a9e1acb0834dcb0d663d83e0db1417a46 | schirrecker/Math | /mathematical_functions.py | 109 | 3.546875 | 4 | def equation(a,b,c,d):
''' solves equations of the form ax + b = cx + d'''
return (d - b)/(a - c)
|
b105489d556e2941fa532c828bb47f8f19e4ea8d | hahapang/py_tutor | /Ch_11_TEST/names.py | 967 | 3.9375 | 4 | # Данная прога предназначена для проверки правильности работы функции
# get_formatted_name(), расположенной в файле name_function.py (Ex. 1).
# Данная функция строит полное имя и фамилию, разделив их пробелами и
# преобразуя первый символы слов в заглавные буквы.
# Проверка проводится путем импорта функции get_formatted_name() из модуля
# name_function.
from name_function import get_formatted_name
print("Enter 'q' at any time ti quit.")
while True:
first = input("\nPlease give me a first name: ")
if first =='q':
break
last = input("Please give me a last name: ")
if last =='q':
break
formatted_name = get_formatted_name(first, last)
print(f"\tNeatly formatted name: {formatted_name}.")
|
258b95d7a40c7c62c7b195cc4fffd038e2ba0373 | hahapang/py_tutor | /magic_number.py | 320 | 3.703125 | 4 | # Аналогичнофайлу из предыдущего коммита.
# Условие answer (17) не равго 42. Так как условие
# истино - блок с отступом выполняется!
#
answer = 17
if answer != 42: #1
print("That is not correct answer.Please tre again!")
|
6aa4ee170811b133b8d66b3bc6ae6c87812412bf | christislord12/Panda3D-Project-Collection | /panda3dcgshaders/8.py | 8,642 | 3.5 | 4 | """
Like 0.py we restart from scratch and create a basic example with one point
light, that only supports diffuse lighting. There is no shader attached to this
example. If you do not understand this sample then open the Panda3D manual and
try to understand e.g. the Disco-Lights sample.
When we talk about lighting we talk about an "effect" that we can see with our
eyes. Live is a game, just with better graphic. Lighting is still something you
may do your own research and invent a cool new idea, no one had before. We often
only approximate lighting and invent new terms that do not exist in reality e.g.
there is no specular light in real live. For better lighting we often need to
pre calculate some values in an often slow pre process. We start here only with
one basic lighting model: Diffuse Lighting.
The basic idea of diffuse lighting is: The steeper the angle between the light
and a surface, the less light particles can reach the surface. The following
figures show an example with a directional light and a wall.
1. 100% of the light reaches the wall.
2. ~50% of the light reaches the wall.
3. 0% of the light reaches the wall.
| /
1. -> | 2. -> / 3. -> ---
| /
If no light reaches a wall, the wall cannot reflect any light particles and
therefore you cannot see anything. This idea is only one basic idea. This idea
e.g. says nothing about the fact that if a wall reflects some light, it may be
possible that this light reaches another wall, which may reflect this light
particles once more.
Given that there is one wall behind another wall:
| |
-> | |
| |
If we translate our idea to this situation, it means, that both walls got the
same amount of light, because the angle between the light surface and the light
source is equal for both walls. This is of course dead wrong, because the first
wall occludes the second wall, so there is more or less no light at all.
The default lighting model the fixed function pipeline offers to Panda3D has
tons of flaws, even though it helps to increase realism. Let us stick to this
mediocre lighting model for now (better lighting models are often extremely slow
and only with tricks you may use them in 60 FPS applications).
To calculate how much light reaches our triangle (or wall) we need a tool that
helps us to distinguish if a triangle looks toward a light source or not. One
possibility to do this is a surface normal. In the preceding examples we assumed
that the surface normal is perpendicular to the surface. This is not always
true, as we see later, therefore we like to define a normal at least for each
triangle (or face). When you have a look at the cube.egg once more you see that
for every polygon, a normal is specified. If Panda3D needs to triangulate the
model for the GPU it assigns every triangle, that belongs to the same polygon,
the same normal.
That is not the whole truth, in fact, the GPU likes to have a normal for every
vertex. Why this is a good idea, is shown by another example. Open the enclosed
figures.svg or figures.png and look at figure 8-1. If we have a cube, there are
at least two possibilities to assign normals. The visual difference you may see
later is that the left cube has sharp edges, while the right cube has smooth
edges (on the right cube, the normals on each corner have a small gap in
between, this gap is only here to see that every vertex has a normal). Metal
like objects may have sharper edges while wooden objects may not. An artist may
influence how a model looks like (with lighting enabled) if he/she modifies the
normals. Back to our "whole truth" problem. As you can see it is impossible to
create a smooth cube if every polygon or triangle only has one normal. We need
at least one normal for every vertex.
The cube.egg model is an example of cube with sharp edges, while the
cube-smooth.egg model is an example of a cube with smooth edges. Try to see the
difference between this two files.
The fixed function pipeline of a GPU (that is the pipeline Panda3D uses if there
is no call to setShader or setAutoShader) is not that sophisticated. Better said
the GPUs were not powerful enough to calculate this very simple lighting model
per fragment/pixel, they only can calculate it per vertex. The larger your
triangles on your screen, the falser the result.
One more definition for diffuse lighting is, that it does not depend on the
viewers position. That is not true for all effects e.g. the "output" of a mirror
depends on the viewers position. Specular lighting simulates a mirror like
effect for lights and therefore depends on the viewers position.
Diffuse lighting is especially suited for rough surfaces, because of our
definition that the surfaces should distribute light in any direction,
independent of any other environmental effects.
Back to our problem: We have a surface normal, we have a light position and we
say that only this two things should matter. We now can calculate a direction
vector from the light to our triangle. Because it is a point light, that
distributes light in any direction, this assumption is correct. After this first
operation we calculate the angle between this direction and surface normal.
Based on this angle we can calculate how much diffuse light we have on a
triangle.
| |
1. -> <-| 2. -> |->
| |
In example 1. we have 100% diffuse light while in the example 2. there is 0%
diffuse lighting.
There are two possibilities to calculate this angle. We do some trigonometry, or
we use the dot product. Both ideas are equivalent, but the second is faster to
calculate.
Read the following page to get in-depth information.
http://en.wikipedia.org/wiki/Dot_product
We will later see how to calculate exactly each of this steps. I only like to
introduce some concepts here.
"""
import sys
import math
import direct.directbase.DirectStart
from direct.interval.LerpInterval import LerpFunc
from pandac.PandaModules import PointLight
base.setBackgroundColor(0.0, 0.0, 0.0)
base.disableMouse()
base.camLens.setNearFar(1.0, 50.0)
base.camLens.setFov(45.0)
camera.setPos(0.0, -20.0, 10.0)
camera.lookAt(0.0, 0.0, 0.0)
root = render.attachNewNode("Root")
"""
We set up a default point light here. You may modify the color of the light, but
in the next examples we assume, that the light has no attenuation and is white.
There is a dummy model attached to this node, to see where the light should be.
Because this light is parented to render, and we only enable light on the cubes,
this model does not influence the lighting nor is it lit by the light itself.
"""
pointlight = PointLight("Light")
light = render.attachNewNode(pointlight)
modelLight = loader.loadModel("misc/Pointlight.egg.pz")
modelLight.reparentTo(light)
"""
DIRTY
Replace cube.egg with cube-smooth.egg and try to understand why both outputs
differ.
"""
modelCube = loader.loadModel("cube.egg")
cubes = []
for x in [-3.0, 0.0, 3.0]:
cube = modelCube.copyTo(root)
cube.setPos(x, 0.0, 0.0)
cube.setLight(light)
cubes += [ cube ]
base.accept("escape", sys.exit)
base.accept("o", base.oobe)
"""
We move around our light. Because this basic application only supports per
vertex lighting you often can see some odd artifacts if only one vertex of a
face is lit.
The bounding box around all cubes ranges from (-4.0, -1.0, -1.0) to (4.0, 1.0,
1.0). Therefore we set the radius of the virtual sphere (the motion path of the
light) to something that is only a little bit larger than 4.0. This helps later
to see the visual difference from per vertex lighting to per pixel lighting.
"""
def animate(t):
radius = 4.3
angle = math.radians(t)
x = math.cos(angle) * radius
y = math.sin(angle) * radius
z = math.sin(angle) * radius
light.setPos(x, y, z)
def intervalStartPauseResume(i):
if i.isStopped():
i.start()
elif i.isPaused():
i.resume()
else:
i.pause()
interval = LerpFunc(animate, 10.0, 0.0, 360.0)
base.accept("i", intervalStartPauseResume, [interval])
def move(x, y, z):
root.setX(root.getX() + x)
root.setY(root.getY() + y)
root.setZ(root.getZ() + z)
base.accept("d", move, [1.0, 0.0, 0.0])
base.accept("a", move, [-1.0, 0.0, 0.0])
base.accept("w", move, [0.0, 1.0, 0.0])
base.accept("s", move, [0.0, -1.0, 0.0])
base.accept("e", move, [0.0, 0.0, 1.0])
base.accept("q", move, [0.0, 0.0, -1.0])
run()
|
618105d73f3df6c48f4760c14401e7ef202b66af | christislord12/Panda3D-Project-Collection | /panda3dcgshaders/2.py | 2,227 | 3.5 | 4 |
"""
The first useful sample. After this tutorial we are able to draw our cubes,
which look like cubes. With our knowledge we are not able to color them
correctly, but we can do some nice stuff and see the result. If everything is
black this time, something must be wrong.
"""
import sys
import direct.directbase.DirectStart
base.setBackgroundColor(0.0, 0.0, 0.0)
base.disableMouse()
base.camLens.setNearFar(1.0, 50.0)
base.camLens.setFov(45.0)
camera.setPos(0.0, -20.0, 10.0)
camera.lookAt(0.0, 0.0, 0.0)
root = render.attachNewNode("Root")
modelCube = loader.loadModel("cube.egg")
cubes = []
for x in [-3.0, 0.0, 3.0]:
cube = modelCube.copyTo(root)
cube.setPos(x, 0.0, 0.0)
cubes += [ cube ]
shader = loader.loadShader("2.sha")
"""
DIRTY
Try to disable the shader on the root node and then enable it only on one or two
cubes and see what happens. You can do this before you start to modify the
shader.
"""
root.setShader(shader)
#cubes[0].setShader(shader)
#cubes[2].setShader(shader)
"""
DIRTY
If you have tested how you can enable/disable a shader on individual nodes, and
how the scene graph works with shaders, you can modify this lines (comment or
remove the three Python lines above) and load two shaders at the same time. e.g.
2.sha and 1.sha. Apply 2.sha to one cube, and 1.sha to another cube. Because
1.sha does nothing the cube with this shader should disappear.
"""
#shader1 = loader.loadShader("1.sha")
#shader2 = loader.loadShader("2.sha")
#cubes[0].setShader(shader2)
#cubes[1].setShader(shader1)
"""
DIRTY
Do you like to see the model matrix of each cube? You may only understand this
if you read the comment for vshader in 2.sha.
"""
#for cube in cubes:
# print cube.getMat()
base.accept("escape", sys.exit)
base.accept("o", base.oobe)
def move(x, y, z):
root.setX(root.getX() + x)
root.setY(root.getY() + y)
root.setZ(root.getZ() + z)
base.accept("d", move, [1.0, 0.0, 0.0])
base.accept("a", move, [-1.0, 0.0, 0.0])
base.accept("w", move, [0.0, 1.0, 0.0])
base.accept("s", move, [0.0, -1.0, 0.0])
base.accept("e", move, [0.0, 0.0, 1.0])
base.accept("q", move, [0.0, 0.0, -1.0])
run()
|
0c07ac63e4e0c8bdb25ff27d3f18419705cc3506 | AnkitaPisal1510/list | /listmagic1.py | 746 | 3.625 | 4 | m=[
[8,3,4],
[1,5,9],
[6,7,2]
]
A=15
k=0
while k<len(m):
column=0
sum=0
l=len(m[k])
while column<l:
sum=sum+m[k][column]
column+=1
print(sum,"column")
x=sum+sum+sum
k+=1
print(x)
i=0
while i<len(m):
row=0
sum1=0
while row<len(m[i]):
sum1+=m[row][row]
row+=1
print(sum1,"row")
h=sum1+sum1+sum1
i+=1
print(h)
s=m[0][0]+m[1][1]+m[2][2]
d=m[0][2]+m[1][1]+m[2][0]
if s==A:
if d==A:
mn=s+d
print("diagonal:",mn)
if sum==sum1==A:
print("it is majic square")
else:
print("it is not majic square")
else:
print("oit is not majic square")
else:
print("it is not majic square")
|
ee51b89083daa92736666f1712448406f4b118c3 | AnkitaPisal1510/list | /listdifference.py | 149 | 3.546875 | 4 | #difference
# l=[1,2,3,4,5,6]
# p=[2,3,1,0,6,7]
# i=0
# j=[]
# while i<len(p):
# if l[i] not in p:
# j.append(l[i])
# i+=1
# print(j) |
d9ebfa0746c3b2daf9bb4796bc910aaa34842e8a | AnkitaPisal1510/list | /listmagic.py | 713 | 3.5625 | 4 | #
#majic square
# a=[
# [8,3,8],
# [1,5,9],
# [6,7,2]
# ]
# row1=row2=row3=0,0,0
# col1=col2=col3=0,0,0
# dia1=dia2=0,0
# i=0
# b=len(a)
# while i<b:
# c=len(a[i])
# j=0
# while j<c:
# if i==0:
# row1=row1+a[i][j]
# col1=col+a[j][i]
# elif i==1:
# row2=row2+a[i][j]
# col2=col2+a[j][i]
# else:
# row3=row3+a[i][j]
# col3=col3+a[j][i]
# j+=1
# i+=1
# m=0
# k=2
# while m<c:
# dia1=dia1+a[m][m]
# dia2=dia2+a[m][k]
# m+=1
# k-=1
# if row1==row2==row3==col1==col2==col3==dia1==dia2:
# print("it is majic square")
# else:
# print("it is not majic")
|
e085c19faf6fe9e11e547c31d30f02e8f29a9d4f | superxingzai/bhattacharyya-distance | /bhatta_dist.py | 4,095 | 3.75 | 4 | """
The function bhatta_dist() calculates the Bhattacharyya distance between two classes on a single feature.
The distance is positively correlated to the class separation of this feature. Four different methods are
provided for calculating the Bhattacharyya coefficient.
Created on 4/14/2018
Author: Eric Williamson (ericpaulwill@gmail.com)
"""
import numpy as np
from math import sqrt
from scipy.stats import gaussian_kde
def bhatta_dist(X1, X2, method='continuous'):
#Calculate the Bhattacharyya distance between X1 and X2. X1 and X2 should be 1D numpy arrays representing the same
# feature in two separate classes.
def get_density(x, cov_factor=0.1):
#Produces a continuous density function for the data in 'x'. Some benefit may be gained from adjusting the cov_factor.
density = gaussian_kde(x)
density.covariance_factor = lambda:cov_factor
density._compute_covariance()
return density
#Combine X1 and X2, we'll use it later:
cX = np.concatenate((X1,X2))
if method == 'noiseless':
###This method works well when the feature is qualitative (rather than quantitative). Each unique value is
### treated as an individual bin.
uX = np.unique(cX)
A1 = len(X1) * (max(cX)-min(cX)) / len(uX)
A2 = len(X2) * (max(cX)-min(cX)) / len(uX)
bht = 0
for x in uX:
p1 = (X1==x).sum() / A1
p2 = (X2==x).sum() / A2
bht += sqrt(p1*p2) * (max(cX)-min(cX))/len(uX)
elif method == 'hist':
###Bin the values into a hardcoded number of bins (This is sensitive to N_BINS)
N_BINS = 10
#Bin the values:
h1 = np.histogram(X1,bins=N_BINS,range=(min(cX),max(cX)), density=True)[0]
h2 = np.histogram(X2,bins=N_BINS,range=(min(cX),max(cX)), density=True)[0]
#Calc coeff from bin densities:
bht = 0
for i in range(N_BINS):
p1 = h1[i]
p2 = h2[i]
bht += sqrt(p1*p2) * (max(cX)-min(cX))/N_BINS
elif method == 'autohist':
###Bin the values into bins automatically set by np.histogram:
#Create bins from the combined sets:
# bins = np.histogram(cX, bins='fd')[1]
bins = np.histogram(cX, bins='doane')[1] #Seems to work best
# bins = np.histogram(cX, bins='auto')[1]
h1 = np.histogram(X1,bins=bins, density=True)[0]
h2 = np.histogram(X2,bins=bins, density=True)[0]
#Calc coeff from bin densities:
bht = 0
for i in range(len(h1)):
p1 = h1[i]
p2 = h2[i]
bht += sqrt(p1*p2) * (max(cX)-min(cX))/len(h1)
elif method == 'continuous':
###Use a continuous density function to calculate the coefficient (This is the most consistent, but also slightly slow):
N_STEPS = 200
#Get density functions:
d1 = get_density(X1)
d2 = get_density(X2)
#Calc coeff:
xs = np.linspace(min(cX),max(cX),N_STEPS)
bht = 0
for x in xs:
p1 = d1(x)
p2 = d2(x)
bht += sqrt(p1*p2)*(max(cX)-min(cX))/N_STEPS
else:
raise ValueError("The value of the 'method' parameter does not match any known method")
###Lastly, convert the coefficient into distance:
if bht==0:
return float('Inf')
else:
return -np.log(bht)
def bhatta_dist2(x, Y, Y_selection=None, method='continuous'):
#Same as bhatta_dist, but takes different inputs. Takes a feature 'x' and separates it by class ('Y').
if Y_selection is None:
Y_selection = list(set(Y))
#Make sure Y_selection is just 2 classes:
if len(Y_selection) != 2:
raise ValueError("Use parameter Y_selection to select just 2 classes.")
#Separate x into X1 and X2:
X1 = np.array(x,dtype=np.float64)[Y==Y_selection[0]]
X2 = np.array(x,dtype=np.float64)[Y==Y_selection[1]]
#Plug X1 and X2 into bhatta_dist():
return bhatta_dist(X1, X2, method=method)
|
25d9bba08eb6b53c6ec5125f0f1386ebd3c375f8 | tsuji-tomonori/prog | /numer0n/items/double.py | 900 | 3.75 | 4 | from module import standard_numer0n as nm
def use(info,turn,digit=3):
while True:
idx = input(f"{info[not turn]['name']}:表示させたい桁を指定してください")
fin_flag, idx = check_idx(idx)
if fin_flag: break
else: print(idx)
print("{0}さんの[{1}]桁目の数値は[{2}]です".format(
info[turn]["name"],
idx,info[turn]["ans"][idx-1]))
value, eb = nm.call(info,turn)
print("{} -> {} : {} ({})".format(info[turn]["name"],
info[not turn]["name"],eb,value))
if nm.isfin(eb,digit):
return (True,turn)
else: return (False,turn)
def check_idx(idx):
if not idx.isdigit():
return (False,"整数値ではありません")
idx = int(idx)
if not (1 <= idx <= 3):
return (False,"範囲外の数値を入力しています")
return (True ,idx)
|
9fa0e009c15e00016bfae128e68515f6aaa87e5d | rohanyadav030/cp_practice | /is-digit-present.py | 865 | 4.1875 | 4 | # Python program to print the number which
# contain the digit d from 0 to n
# Returns true if d is present as digit
# in number x.
def isDigitPresent(x, d):
# Breal loop if d is present as digit
if (x > 0):
if (x % 10 == d):
return(True)
else:
return(False)
else:
return(False)
# function to display the values
def printNumbers(n, d):
# Check all numbers one by one
for i in range(0, n+1):
# checking for digit
if (i == d or isDigitPresent(i, d)):
print(i,end=" ")
# Driver code
n = 20
d = 5
print("n is",n)
print("d is",d)
print("The number of values are")
printNumbers(n, d)
'''
******************* output **********************
n is 47
d is 7
The number of values are
7 17 27 37 47
n is 20
d is 5
The number of values are
5 15
'''
|
702ae99a588af50dc3eb3077d6752c61f341b309 | DmitriBabin/babin_homework | /factorial_sequence.py | 376 | 3.703125 | 4 | import math
import itertools as it
class Factorial:
class Factorialiter:
def __init__(self):
self.i = 1
self.z = 1
def __next__(self):
self.z *= self.i
self.i += 1
return self.z
def __iter__(self):
return Factorial.Factorialiter()
for w in it.islice(Factorial(), 10):
print(w)
|
590dce90d6867aac4436f0c675c0f7266086ee87 | DmitriBabin/babin_homework | /euclidian_algorithm.py | 876 | 3.609375 | 4 | import random as rd
import math
a_number = rd.randint(1, 100)
b_number = rd.randint(1, 100)
print('gcd(',a_number,',',b_number,')')
print('Значение, полученное встроенным алгоритмом = ', math.gcd(a_number,b_number))
def gcd(a_number,b_number):
if b_number == 0:
return a_number
else:
return gcd(b_number, a_number % b_number)
print('Значение, полученное встроенным алгоритмом = ', gcd(a_number,b_number))
def extended_gcd(a_number,b_number):
if a_number == 0:
return (0, 1)
else:
x_num , y_num = extended_gcd(b_number % a_number, a_number)
return ( y_num - (b_number // a_number) * x_num, x_num)
print(a_number, '*', extended_gcd(a_number,b_number)[0], '+', b_number,
'*', extended_gcd(a_number,b_number)[1], '=' , gcd(a_number,b_number))
|
2b125895636c4f44e67d61b346faf6f9e0ffebd5 | Andy245Liu/Timato | /screentimer.py | 3,807 | 3.5 | 4 | from datetime import datetime
import sqlite3
import sys
import time
import pyautogui
if sys.version_info[0] == 2:
import Tkinter
tkinter = Tkinter
else:
import tkinter
from PIL import Image, ImageTk
first = 0
first2 = 0
#python C:\Users\Ahmad\Desktop\disptest.py
conn = sqlite3.connect('Data.db')
cursor = conn.execute("SELECT Name, Type, Weighting, MentalEffort, Deadline, Duration, ScreenBlock, StartTime from data") # SQL DB Imported
Name = []
Type = []
Weight = []
Mental = []
Deadline = []
Duration = []
Block = []
StartTime = []
for row in cursor:
Name.append(row[0]) # STR
Type.append(row[1]) # STR
Weight.append(row[2]) #INT
Mental.append(row[3]) # INT
Deadline.append(row[4]) # STR
Duration.append(row[5]) # INT
Block.append(row[6]) # INT
StartTime.append(row[7]) # STR
# print "ID = ", row[0]
# print "NAME = ", row[1]
# print "ADDRESS = ", row[2]
# print "SALARY = ", row[3], "\n"
def findact(h, m, hour, minute, dur):
for i in range(len(h)):
timestart = h[i] * 60 + m[i]
timeend = timestart + dur[i]
if((hour*60 + minute) >= timestart and (hour*60 + minute) < timeend):
return i
return 1000
def checkassign(hour,minute, Deadline):
for i in range(len(Deadline)):
temp = Deadline[i].find(":")
temptime = int(Deadline[i][temp-2])*600 + int(Deadline[i][temp-1]) * 60 + int(Deadline[i][temp+1]) * 10 + int(Deadline[i][temp+2])
if(temptime - (hour*60+minute) <= 30 and temptime - (hour*60+minute) >= 0):
return True
return False
minlist = []
hourlist = []
dur = []
for i in range(len(StartTime)):
a = StartTime[i]
temp = a.find(":")
minlist.append(int(a[temp+1]) * 10 + int(a[temp+2]))
hourlist.append(int(a[temp-2]) * 10 + int(a[temp-1]))
dur.append(int(Duration[i]))
#INSIDE LOOP
while True:
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
temp = dt_string.find(":")
hour = 0
minute = 0
hour = int(dt_string[temp-2]) * 10 + int(dt_string[temp-1])
minute = int(dt_string[temp+1]) * 10 + int(dt_string[temp+2])
overall = hour*60 + minute
breaktimes = []
a = findact(hourlist, minlist, hour, minute, dur)
if (a!= 1000):
if(Block[a] == 1 and checkassign(hour, minute, Deadline) == False):
freq = int(100/Mental[a])
breakt = int(10/Mental[a])
sum = 0
x = 0
while(sum < dur[i]):
breaktimes.append((hourlist[a] * 60 + minlist[a]) + freq*(x+1) + breakt * x)
sum+=freq*(x+1) + breakt * x
x+=1
for k in range(len(breaktimes)):
if(breaktimes[k] <= overall and overall < breaktimes[k] + breakt):
if(first == 0):
pyautogui.keyDown('alt')
pyautogui.press('tab', presses=2)
pyautogui.keyUp('alt')
first += 1
else:
pyautogui.hotkey('alt', 'tab')
time.sleep(0.1)
pyautogui.hotkey('ctrl', 'shift', 'e')
time.sleep(60*breakt)
pyautogui.hotkey('shift', 'a')
break
time.sleep(60)
# for i in range(2):
# if(first == 0):
# pyautogui.keyDown('alt')
# pyautogui.press('tab', presses=2)
# pyautogui.keyUp('alt')
# first += 1
# else:
# pyautogui.hotkey('alt', 'tab')
# time.sleep(0.1)
# pyautogui.hotkey('ctrl', 'shift', 'e')
# time.sleep(10)
# pyautogui.hotkey('shift', 'a')
# time.sleep(10)
|
82a3d01659c41567c0dde03c3e14585503b96295 | tianwen0110/find-job | /target_offer/print_list_reverse.py | 632 | 4.0625 | 4 | class listnode(object):
def __init__(self, x=None):
self.val = x
self.next = None
class solution(object):
def reverse_list(self, first):
if first.val == None:
return -1
elif first.next == None:
return first.val
nextnode = first
l = []
while nextnode != None:
l.insert(0, nextnode.val)
nextnode = nextnode.next
return l
node1 = listnode(10)
node2 = listnode(11)
node3 = listnode(13)
node1.next = node2
node2.next = node3
singleNode = listnode(12)
test = listnode()
S = solution()
print(S.reverse_list(node1)) |
ffd5c6d21ea6dd7630628a0c00af7f7959c710c1 | tianwen0110/find-job | /target_offer/从上到下打印二叉树.py | 1,024 | 4 | 4 |
'''
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
'''
'''
相当于按层遍历, 中间需要队列做转存
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class solution(object):
def printF(self, tree):
if tree == None:
return None
list1 = []
list1.append(tree)
list2 = []
while list1 != []:
list2.append(list1[0].val)
if list1[0].left != None:
list1.append(list1[0].left)
if list1[0].right != None:
list1.append(list1[0].right)
list1.pop(0)
print(list2)
pNode1 = TreeNode(8)
pNode2 = TreeNode(6)
pNode3 = TreeNode(10)
pNode4 = TreeNode(5)
pNode5 = TreeNode(7)
pNode6 = TreeNode(9)
pNode7 = TreeNode(11)
pNode1.left = pNode2
pNode1.right = pNode3
pNode2.left = pNode4
pNode2.right = pNode5
pNode3.left = pNode6
pNode3.right = pNode7
s = solution()
s.printF(pNode1) |
ac78fe36eec01c1077bb1b3f83a454912d917bf0 | tianwen0110/find-job | /target_offer/正则表达式匹配.py | 1,364 | 3.703125 | 4 |
'''
请实现一个函数用来匹配包括'.'和'*'的正则表达式。
模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。
在本题中,匹配是指字符串的所有字符匹配整个模式。
例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
'''
class solution(object):
def match(self, string, pattern):
if type(string)!=str or type(pattern)!=str:
return None
i = 0
j = 0
length = len(string)
while i != length:
if j>=len(pattern):
return False
if string[i]==pattern[j]:
i = i+1
j = j+1
elif pattern[j]=='*':
if string[i]==pattern[j+1]:
i = i+1
j = j+2
elif string[i]==string[i-1]:
i = i+1
else:
return False
elif pattern[j] == '.':
i = i+1
j = j+1
elif pattern[j+1]=='*':
j = j+2
if j ==len(pattern):
return True
else:
return False
s = solution()
a = 'a.a'
b = 'ab*ac*a'
k = 'aaa'
c = 'aa.a'
d = 'ab*a'
print(s.match(k,d))
|
0855187a0284322baae4436ab56ffef37c7aed84 | tianwen0110/find-job | /target_offer/search_in_2dArray.py | 1,533 | 3.765625 | 4 | '''
在一个二维数组中,每一行都按照从左到右递增的顺序排序
每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
'''
class Solution(object):
def find(self, array, target):
if type(target) != int and type(target) != float:
return False
elif array == []:
return False
elif type(array[0][0]) != int and type(array[0][0]) != float:
return False
m = len(array)
n = len(array[0])
if target < array[0][0] or target > array[m-1][n-1]:
return False
i = 0
j = n - 1
while i < n and j >= 0:
if array[i][j] < target:
i = i + 1
elif array[i][j] == target:
return True
else:
j = j - 1
return False
array = [[1, 2, 8, 9],
[2, 4, 9, 12],
[4, 7, 10, 13],
[6, 8, 11, 15]]
array2 = []
array3 = [['a', 'b', 'c'],
['b', 'c', 'd']]
array4 = [[62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80],[63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81],[64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82],[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83],[66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84],[67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85]]
findtarget = Solution()
print(findtarget.find(array4, 10))
|
7e349fc201f85a485b7a4da089951ddfaa61b2aa | lxndrblz/DHBW-Programmierung | /Semester_1/Probeklausur.py | 1,221 | 3.953125 | 4 | #encoding=utf-8
'''
99 Bottles of Beer
'''
bottles = 99
while bottles > 1:
print(str(bottles) + " bottles of beer on the wall," + str(bottles) + " bottles of beer. If one of those bottles should happen to fall")
bottles -= 1
print("One (last) bottle of beer on the wall,")
print("One (last) bottle of beer.")
print("Take it down, pass it around,")
print("No (more) bottles of beer on the wall.")
'''
Check Palindrom
'''
p = "regallager"
def check_palindrom(s):
return s == s[::-1]
print(check_palindrom(p))
# Sollte True ergeben
'''
Palindrom Wert
Erweitern Sie Ihr Programm um die Funktion palindrom_wert, die eine float-Zahl zurückliefert
'''
p = "regallager"
def palindrom_wert(s):
vokale = "aeiou"
anzahl_konsonant = 0.0
for c in s:
if c not in vokale:
anzahl_konsonant += 1
return float(anzahl_konsonant / len(s))
print(palindrom_wert(p))
# Sollte 0.6 ergeben
'''
Check palindrom Satz
'''
p = "sei fein, nie fies"
def check_palindrom_satz(s):
#Alle Satzzeichen entfernen
pattern = "!@#$%^&*()[]{};:,./<>?\|`~-=_+ "
for c in pattern:
s = s.replace(c, "")
return bool(s == s[::-1])
print(check_palindrom_satz(p))
# Sollte True sein
|
b6b91917c0e09643e6138b40f20e32eb8a088706 | lxndrblz/DHBW-Programmierung | /Semester_1/Aufgaben Moodle/Hash.py | 1,656 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import string
import random
import itertools
from random import randint
def hashthis(s):
h = 0
base = 1
for char in s:
h += ord(char) * base
base *= 26
return h
# Funktion generiert Passwort mittels eines kartesischen Produktes aus dem Buchstabenarray
def bruteforcelinear(h):
# Buchstaben in array umwandeln
buchstaben = string.ascii_lowercase
buchstabenarray = []
for char in buchstaben:
buchstabenarray.append(char)
password = ''
cartesianproduct = []
# Anzahl an Stellen
maxstellen = 5
# ArgumentListe für cartesisches Produkt erzeugen
for i in range(0, maxstellen):
cartesianproduct.append(buchstabenarray)
for pwcombinations in itertools.product(*cartesianproduct):
# Jede Kombination prüfen
for c in pwcombinations:
password += str(c)
if h == hashthis(password):
return password
password = ''
# Generiert Passwort aus zufälligen Kombinationen
def bruteforce(h):
buchstaben = string.ascii_lowercase
while True:
password = ''
# Zufaellige Länge
for i in range(randint(0, 10)):
# Zufaellige Buchstaben
c = random.choice(buchstaben)
password = password + c
if h == hashthis(password):
break
return password
hashwert = hashthis(str(raw_input("Ihr Passwort: ")))
print "Hash Wert: " + str(hashwert)
print "Passwort war (zufall) verfahren " + str(bruteforce(hashwert))
print "Passwort war (linear) verfahren " + str(bruteforcelinear(hashwert))
|
ffa05f9466c855d31dc19f6b1bf18f4d79a4802b | lxndrblz/DHBW-Programmierung | /Semester_2/ObjektOrientierung/Simulation/SimHuman/matches.py | 1,525 | 3.546875 | 4 | import names
import random
from SimHuman.men import men
from SimHuman.women import women
class matches(men, women):
def __init__(self, match_men, match_women):
self.__men = match_men
self.__women = match_women
self.__kids = []
#Ability to compare couples
def __eq__(self, second):
if self.__men == second.__men and self.__women == second.__women:
return True
else:
return False
def print(self):
print("Couple: " + self.__men.get_name() +"+"+ self.__women.get_name())
def print_kids(self):
for kid in self.__kids:
print ("\t" + kid.get_name())
def make_kids(self):
#Condition for getting kids in General
if (len(self.__kids) < 3) and 18 < self.__men.get_age() < 50 and 18 < self.__women.get_age() < 50 and self.__women.get_kids() < 4:
newkids = []
#Probablity to get kids:
if random.random()*len(self.__kids) < 0.2:
#Twins or just a single kid
for i in range(random.randint(1,3)):
if random.randint(0,2) == 0:
newkids.append(men(names.get_first_name(gender='male'), 0))
else:
newkids.append(women(names.get_first_name(gender='female'), 0,0))
self.__women.increase_baby_counter()
self.__kids.append(newkids)
return newkids
def get_kids(self):
return self.__kids |
ca9aed93c5422314ee6882a20224ea361401a82d | lxndrblz/DHBW-Programmierung | /Semester_1/Aufgaben Moodle/guess.py | 443 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randint
AnzahlVersuche = 1
ZufallsWert = randint(1,20)
print "Bitte eine Zahl zwischen 1 und 20 auswählen!"
guess = int(input("Ihr Tip: "))
while guess != ZufallsWert:
AnzahlVersuche += 1
if(guess>ZufallsWert):
print "Zahl ist kleiner"
else:
print "Zahl ist größer"
guess = int(input("Ihr neuer Tip: "))
print "Versuche: " + str(AnzahlVersuche) |
18bde0bbb7b8f371cbbab5d3a73310f823fa3570 | amrutha1352/4040 | /regularpolygon.py | 280 | 4.28125 | 4 | In [46]:
X= float(input("Enter the length of any side: "))
Y= int(input("Enter the number of sides in the regular polygon: "))
import math
numerator= math.pow(X,2)*Y
denominator= 4*(math.tan(math.pi/Y))
area= numerator/denominator
print("The area of the regular polygon is:",area) |
34e739ba20d456fad59dbc99ebab0d74be0830d0 | folivetti/Category4Programmers | /Monad/monadsLista.py | 393 | 3.5 | 4 | def bind(xs, k):
return (y for x in xs for y in k(x))
def geralista(x):
return [2*x]
def triples(n):
return ( (x,y,z) for z in range(1, n+1)
for x in range(1, z+1)
for y in range(x, z+1)
if (x**2 + y**2 == z**2))
for t in triples(10):
print(t)
print(list(bind([1,2,3], geralista)))
|
34c467f6bcb628d403321d30b29644d35af003f3 | jonesm1663/cti110 | /cti 110/P3HW2.py | 543 | 4.28125 | 4 | # CTI-110
# P3HW2 - Shipping Charges
# Michael Jones
# 12/2/18
#write a program tha asks the user to enter the weight of a package
#then display shipping charges
weightofpackage = int(input("Please enter the weight of the package:"))
if weightofpackage<= 2:
shippingcharges = 1.50
elif weightofpackage < 7:
shippingcharges = 3.00
elif weightofpackage < 11:
shippingcharges = 4.00
else:shippingcharges = 4.75
print("package weighs"+str(weightofpackage)+", you pay"+ \
format(shippingcharges,",.2f"))
|
619ebd59a6875ca0c6feb9a2074ba5412215c4ae | jonesm1663/cti110 | /cti 110/P3HW1.py | 820 | 4.4375 | 4 | # CTI-110
# P3HW1 - Roman Numerals
# Michael Jones
# 12/2/18
#Write a program that prompts the user to enter a number within the range of 1-10
#The program should display the Roman numeral version of that number.
#If the number is outside the range of 1-10, the program should display as error message.
userNumber = int(input("Please enter a number"))
if userNumber ==1:
print("1")
elif userNumber ==2:
print("II")
elif userNumber ==3:
print("III")
elif userNumber ==4:
print("IV")
elif userNumber ==5:
print("V")
elif userNumber ==6:
print("VI")
elif userNumber ==7:
print("VII")
elif userNumber ==8:
print("VIII")
elif userNumber ==9:
print("IX")
elif userNumber ==10:
print("X")
else:
print("Error: Please enter a number between 1 and 10.")
|
dba3fcfadbf30efd044878c01b985dfe8e2e9f91 | vishwesh5/HackerRank_Python | /Basic_Data_Types/lists.py | 602 | 3.890625 | 4 | # lists.py
# Link: https://www.hackerrank.com/challenges/python-lists
def carryOp(cmd, A):
cmd=cmd.strip().split(' ')
if cmd[0]=="insert":
A.insert(int(cmd[1]),int(cmd[2]))
elif cmd[0]=="print":
print(A)
elif cmd[0]=="remove":
A.remove(int(cmd[1]))
elif cmd[0]=="append":
A.append(int(cmd[1]))
elif cmd[0]=="sort":
A.sort()
elif cmd[0]=="pop":
A.pop()
elif cmd[0]=="reverse":
A.reverse()
return A
if __name__ == '__main__':
N = int(input())
A = []
for i in range(N):
A=carryOp(input(),A)
|
c60a5ffaf75adcbf8d8959e3b544c390a412b4bc | ryan-hill83/updated-calc | /input.py | 840 | 4.03125 | 4 | from calculator import addition, subtraction, multipication, division
while True:
try:
first = int(input("First Number: "))
operand = input("Would you like to +, -, * or / ? ")
second = int(input("Second Number: "))
if operand == "+":
addition(first, second)
break
elif operand == "-":
subtraction(first, second)
break
elif operand == "*":
multipication(first, second)
break
elif operand == "/":
division(first, second)
break
else:
print("Please enter a valid operand.")
except ValueError:
print("Please enter numbers only!")
quit = input("To quit the program, please press q then hit enter.").lower()
if quit == "q":
import sys
sys.exit(0)
|
ca7dfd42e32443a52c05e2d443398136b2311243 | fjesser/datascience | /syntax/m_see_data.py | 5,392 | 3.578125 | 4 | import datetime as dt
import numpy as np
import pandas as pd
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
def export_dataset_description_to_csv(dataset):
'''
Function takes description of dataset and saves it as csv
Input:
dataset: pd.dataFrame object
Returns:
nothing, saves csv-file
'''
described_data = dataset.describe(include="all")
described_data.to_csv("../output/description.csv")
def print_occurence_of_object_types(dataset):
'''
Function prints how often each manifestation of non-numeric columns appears
Input:
dataset: pd.dataFrame object
Returns:
nothing, prints to console
'''
for variable in dataset.columns:
if dataset[variable].dtype == 'object':
print(dataset[variable].value_counts())
def fix_meal_manifestations(dataset):
'''
Function adds undefined meals to SC meals (according to kaggle, Undefined/SC - no meal)
Input:
dataset: pd.dataFrame object
Returns:
dataset: pd.dataFrame object in which SC = Undefined + SC from input
'''
dataset['meal'] = dataset['meal'].replace(to_replace="Undefined", value="SC")
return(dataset)
def convert_date_per_row(row):
'''
Function creates a date object by reading the year, month and date of arrival per row
Input:
dataset: a row of the hotel dataset as pd.Series
Returns:
dataset: a date object including the arrival date
'''
year = row['arrival_date_year']
month = row['arrival_date_month']
day = row['arrival_date_day_of_month']
month = month.capitalize()
months_string = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
months_numeric = [i for i in range(1, 13)]
months = dict(zip(months_string, months_numeric))
numeric_date = date(year, months[month], day)
return(numeric_date)
''' My try to get the arrival_date as a date object. Uses apply and is thus really slow (seconds).
For optimization, read this link: https://stackoverflow.com/questions/52673285/performance-of-pandas-apply-vs-np-vectorize-to-create-new-column-from-existing-c
hotel_data['arrival_date'] = hotel_data.apply(convert_date, axis=1)
'''
def convert_date_in_dataset(dataset):
'''
This function is taken from Felix; my try is commented out
'''
dataset['arrival_date'] = ((dataset.arrival_date_year.astype(str) +
dataset.arrival_date_month +
dataset.arrival_date_day_of_month.astype(str)
)
.pipe(pd.to_datetime, format="%Y%B%d")
)
# dataset['arrival_date'] = dataset.apply(convert_date_per_row, axis=1)
return(dataset)
# hotel_data['arrival_date'] = hotel_data.apply(convert_date, axis=1, args=(
# hotel_data['arrival_date_year'], hotel_data['arrival_date_month'], hotel_data['arrival_date_day_of_month']))
def create_days_spent_column(dataset):
'''
Both reservation_status_date and arrival_date have to be dateobjects!
TODO: Write a unit test for it and convert if needed
'''
dataset['reservation_status_date'] = pd.to_datetime(dataset['reservation_status_date'])
dataset['days_spent'] = np.where(dataset['reservation_status'] == 'Check-Out',
(dataset['reservation_status_date'] - dataset['arrival_date']).dt.days, np.nan)
return(dataset)
# hotel_data['arrival_date'] = pd.to_datetime(hotel_data['arrival_date'])
def create_cost_column(dataset):
'''
Create a cost value that is the average daily rate times the total days days_spent
'''
dataset['cost'] = np.where(dataset['reservation_status'] == 'Check-Out',
dataset['adr'] * dataset['days_spent'], dataset['adr'])
return(dataset)
def set_noshows_to_na(dataset):
'''
Set occurences of "No-Show" in reservation_status column to NA
'''
dataset['reservation_status'] = np.where(dataset['reservation_status'] == 'No-Show', np.nan, dataset['reservation_status'])
return(dataset)
def get_final_dataset():
'''
Load the hotel dataset and prepare it for plotting
Input: nothing
Returns: pd.dataFrame object that contains the hotel data in tidy format and
with new columns for the arrival_date, total days spent and cost for the stay
Unnecessary columns are deleted
'''
# Load hotel data set from input folder
dataset = pd.read_csv("../input/hotel_bookings.csv")
# Add new columns
dataset = convert_date_in_dataset(dataset)
dataset = create_days_spent_column(dataset)
dataset = create_cost_column(dataset)
dataset = fix_meal_manifestations(dataset)
dataset = set_noshows_to_na(dataset)
# Delete now Unnecessary columns
dataset.drop(['arrival_date_year', 'arrival_date_month',
'arrival_date_day_of_month', 'adr', 'reservation_status_date'], axis=1)
return(dataset)
def write_final_dataset(dataset):
'''
Create a csv-file with the final dataset, that was curated
'''
dataset.to_csv("../input/hotel_bookings_mh.csv")
if __name__ == '__main__':
hotel_data = get_final_dataset()
write_final_dataset(hotel_data)
|
3e25c1171d4f8d10702ccee6660760d06ff1153a | manabled/01-Hello-Class | /02 guess.py | 1,085 | 4.0625 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.6/bin
import sys
import random
assert sys.version_info >= (3,4), "This script requires at least Python 3.4"
guessesTaken = 0
maxGuesses = 5
numRange = 30
print("Welcome to Guess the Number")
print("I'm thinking of a number between 1 and 30")
print("You have 5 attempts to guess the correct number")
number = random.randint(1,numRange)
for guessesTaken in range(maxGuesses):
guess = input('Guess the number: ')
try:
guess = int(guess)
if guess < number:
print("close, but too low")
if guess < number - 5:
print("too low")
if guess > number:
print("close, but too high")
if guess > number + 5:
print("too high")
if guess == number:
break
except ValueError:
print("please enter a valid integer")
if guess == number:
guessesTaken = str(guessesTaken + 1)
print('Well done, you guessed the number in '+ guessesTaken +' attempts')
if guess != number:
number = str(number)
print('You are out of attempts. The number I was thinking of was ' + number + '.')
|
812198bdc5e9bdb1f745f2a0196ee9b8d4f7029d | rlaqhdwns/django1 | /django1/src/files/files/2019/02/09/a1.py | 1,442 | 3.5 | 4 | '''
def defaultfun(a,b,c,d,e,f=20,g=10):
pass
def func(a=5,b=10,*args, **kwarges):
pass
def print_info(**kwarges):#딕셔너리 타입
print(kwarges)
def sum(*args):#튜플 타입
print (args)
isum = 0
for i in args:
isum += i
return isum
print(sum())
print(sum(10,20,30,40,55,123,1255,))
a=[1,2,3,4,5,6,7,8,]
print(sum(*a))
print_info(name='아무개', age=99)
diction={'name':'홍길동','age':28}
print_info(**diction)
def add(a,b):
return a+b
def dec(a,b):
return b-a
diction={'a':5, 'b':100}
print('add()', add(**diction))
print('dec()', dec(**diction))
'''
#클래스 : 변수 + 함수 묶음
#클래스를 통해서 객체를 생성할 수 있음
#객체는 독립적인 데이터를 가지고 있어서 객체들간에 충돌이 일어나지 않는다.
class Cookie():
pass #이 부분이 미완성일지언정 계속 진행 시킬 수 있다.
#객체생성 : 클래스이름()
a = Cookie()
b = Cookie()
print('a에 저장된 쿠키객체 : ', a)
print('b에 저장된 쿠키객체 : ', b)
#__name__ 변수의 값으로 해당파일이 실행된건지 임포트에 의해 실행된건지 확인할수 있다.
if __name__ == '__main__' : #테스트용 코드를 분리할 수 있음
a = Family()
b = Family()
print(a.lastname, b.lastname)
Family.lastname = "이" #클래스.클래스변수 = 값 >
|
677ce91ae856a4c1d6135c7a48327fc47bc41f05 | derejmi/Algorithm-questions-python | /valid_parenthesis.py | 1,062 | 3.796875 | 4 | class Solution:
def isValid(self, s: str) -> bool:
#have a hashtable which has the opening parenthesis as keys and the closing as values
#loop over the string
#if string in ht - add opening p to stack
#else compare string to the last parenthesis in the stack (pop off the stack) - i.e. if ht[lp] == str:
#if they are not equal return false
#after the loop check if the stack still has a length if it does - return False
#return True
hashtable = {"{":"}","[":"]","(":")"}
stack = []
for str in s:
if str in hashtable:
stack.append(str)
else:
if len(stack) > 0:
open = stack.pop()
if hashtable[open] != str:
return False
else:
return False
if len(stack) > 0:
return False
return True
|
6a569d1796355a0393f3e4f9af40644d8d50acb1 | Linshengyi-William/CS362-InClassActWeek7 | /unittest/test_palindrome.py | 696 | 3.984375 | 4 |
import unittest
import palindrome
print("Please enter a string.")
inp = input("String is: ")
class TestCase(unittest.TestCase):
def test_inputType(self):
self.assertEqual(type(inp),type("string"))
def test_returnType(self):
result = palindrome.isPalindrome(inp)
self.assertEqual(type(result),type(True))
def test_correctResult(self):
result = palindrome.isPalindrome(inp)
for i in range(0,len(inp)):
if inp[i] != inp[len(inp)-i-1]:
correct_result = False
break
correct_result = True
self.assertEqual(result,correct_result)
if __name__ == '__main__':unittest.main()
|
818ad247228ec2770d9d7c77e604cf6a2259a2d5 | Tanya-2000/CYSEC-GRP-2- | /PYTHON ASSIGNMENT 2/QUES-5.py | 262 | 3.859375 | 4 | def has_33(nums):
for x in range(0,len(nums)):
if nums[x] ==[3] and nums[x+1]==[3]:
return True
else:
return False
print(has_33([1, 3, 3]) )
print(has_33([1, 3, 1, 3]))
print(has_33([3, 1, 3])) |
521215542619ce7e49fe00e8617227d1a73401bc | AkshayLavhagale/Pylint_Coverage | /fixed_triangle.py | 1,321 | 4.0625 | 4 | """ Name - Akshay Lavhagale
HW 01: Testing triangle classification
The function returns a string that specifies whether the triangle is scalene,
isosceles, or equilateral, and whether it is a right triangle as well. """
def classify_triangle(side_1, side_2, side_3):
"""Triangle classification method"""
try:
side_1 = float(side_1)
side_2 = float(side_2)
side_3 = float(side_3)
except ValueError:
raise ValueError("The input value is not number")
else:
[side_1, side_2, side_3] = sorted([side_1, side_2, side_3])
if (side_1 + side_2 < side_3 and side_1 + side_3 < side_2 and side_2 + side_3 < side_1) or (
side_1 or side_2 or side_3) <= 0:
return "This is not a triangle"
else:
if round(((side_1 ** 2) + (side_2 ** 2)), 2) == round((side_3 ** 2), 2):
if side_1 == side_2 or side_2 == side_3 or side_3 == side_1:
return 'Right and Isosceles Triangle'
else:
return 'Right and Scalene Triangle'
elif side_1 == side_2 == side_3:
return "Equilateral"
if side_1 == side_2 or side_1 == side_3 or side_2 == side_3:
return "Isosceles"
else:
return "Scalene"
|
3818d7844a22ff4d6587b5d50b55ee99a9b2a724 | MaryHak/Machine-Learning-course | /random forest/logistic_regression.py | 1,945 | 3.765625 | 4 | """
Implementation of logistic regression
"""
import numpy as np
def sigmoid(s):
"""
sigmoid(s) = 1 / (1 + e^(-s))
"""
return 1 / (1 + np.exp(-s))
def normalize(X):
"""
This function normalizes X by dividing each column by its mean
"""
norm_X = np.ones(X.shape[0])
feature_means = [np.mean(norm_X)]
for elem in X.T[1:]:
feature_means.append(np.mean(elem))
elem = elem / np.mean(elem)
norm_X = np.column_stack((norm_X, elem))
return norm_X, feature_means
def gradient_descent(X, Y, epsilon=1e-8, l=1, step_size=1e-4, max_steps=1000):
"""
Implement gradient descent using full value of the gradient.
:param X: data matrix (2 dimensional np.array)
:param Y: response variables (1 dimensional np.array)
:param l: regularization parameter lambda
:param epsilon: approximation strength
:param max_steps: maximum number of iterations before algorithm will
terminate.
:return: value of beta (1 dimensional np.array)
"""
beta = np.zeros(X.shape[1])
X, feature_means = normalize(X)
for _ in range(max_steps):
res = []
for j in range(1, X.shape[1]):
S = 0
for i in range(X.shape[0]):
temp = sigmoid(X[i].dot(beta)) - Y[i]
S = S + temp*X[i, j]
res.append((S[0] + (l / feature_means[j]**2)*beta[j])/(X.shape[0]))
res = np.array(res)
res0 = 0
S = 0
for i in range(X.shape[0]):
temp = sigmoid(X[i].dot(beta)) - Y[i]
S = S + temp*X[i, 0]
res0 = S[0] /(X.shape[0])
new_beta_zero = beta[0] - step_size * res0
new_beta = np.array([new_beta_zero, *(beta[1:] - step_size * res)])
if sum((beta - new_beta)**2) < (sum(beta**2) * epsilon):
return new_beta, np.array(feature_means)
beta = new_beta
return beta, np.array(feature_means)
|
8b11a247b8f6e9ed329e29c7bee289db888e09b7 | JustinLaureano/nfl-stats | /Notes.py | 1,415 | 3.6875 | 4 | """
collect all players and stats
step 1: collect raw data and save it
get schedule
get game id
get game data
loop through range
save all data collected in a file i.e. player_stats_17.py
collect all stats in file
dict or class
class DataToDict():
def __init(self, dictionary):
for k, v in dictionary.items():
setattr(self, k, v)
class Player():
def __init(self, playerid, name, team):
self.playerid = playerid
self.name = name
self.team = team
ex dict:
player_dict = {}
def collect stats(load file)
player_dict[name] = item[name]
home or away
abbr
score
stats
defense
ast
ffum
int
name
sk
tkl
fumbles
kicking
kickret
passing
att
comp
ints
name
tds
twopta
twoptm
yds
punting
puntret
receiving
long
lngtd
name
rec
tds
twopta
twoptm
yds
rushing
att
lng
tngtd
name
tds
twopta
twoptm
yds
team
load stats
loop, add stats to dict
"""
|
06aec43fb274b37e7e5d8d92809c3d45c8912adf | Mandyp-ool/Lesson2 | /ex3.py | 1,434 | 4.09375 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить, к какому времени года относится месяц (зима, весна, лето, осень). Напишите решения через list и dict.
season_list = ['зима', 'весна', 'лето', 'осень']
season_dict = {0:'зима', 1:'весна', 2:'лето', 3:'осень'}
month = int(input("Введите месяц в виде целого числа от 1 до 12: "))
if month == 1 or month == 2 or month == 12:
print("Месяц относится к времеи года -", season_list[0])
print("Месяц относится к времеи года -", season_dict.get(0))
elif month == 3 or month == 4 or month == 5:
print("Месяц относится к времеи года -", season_list[1])
print("Месяц относится к времеи года -", season_dict.get(1))
elif month == 6 or month == 7 or month == 8:
print("Месяц относится к времеи года -", season_list[2])
print("Месяц относится к времеи года -", season_dict.get(2))
elif month == 9 or month == 10 or month == 11:
print("Месяц относится к времеи года -", season_list[3])
print("Месяц относится к времеи года -", season_dict.get(3))
|
2afd83f3ea59d217f622b7abdfbfce2055639b38 | ucabtyi/playground | /py/b_tree.py | 5,541 | 3.890625 | 4 | import sys
class Node:
def __init__(self, value, l=None, r=None):
self.value = value
self.l = l
self.r = r
def __str__(self):
s = "value: " + str(self.value)
if self.l:
s += " L: %s" % str(self.l.value)
else:
s += " L: None"
if self.r:
s += " R: %s" % str(self.r.value)
else:
s += " R: None"
# return str(self.value)
return s
class BTree:
def __init__(self):
self.root = None
def __repr__(self):
def _repr(node):
if node:
print str(node)
print "goto L"
_repr(node.l)
print "search result: %s" % str(node)
print "goto R"
_repr(node.r)
if self.root:
_repr(self.root)
else:
print None
def _left(self, node_value, new_value):
return new_value < node_value
def _right(self, node_value, new_value):
return new_value > node_value
def add_v(self, value):
def _add_v(node, value):
if value == node.value:
print "equals..."
return
elif self._left(node.value, value):
if node.l:
_add_v(node.l, value)
else:
node.l = Node(value)
else:
if node.r:
_add_v(node.r, value)
else:
node.r = Node(value)
if self.root is None:
self.root = Node(value)
else:
_add_v(self.root, value)
def find_v(self, value):
def _find_v(node, value):
if value == node.value:
print "found..."
return node
elif self._left(node.value, value):
if node.l:
_find_v(node.l, value)
else:
print "not found..."
return None
else:
if node.r:
_find_v(node.r, value)
else:
print "not found..."
return None
if self.root:
_find_v(self.root, value)
else:
print "not found..."
return None
def print_t(self):
thislevel = [self.root]
while thislevel:
nextlevel = list()
for n in thislevel:
print n.value,
if n.l: nextlevel.append(n.l)
if n.r: nextlevel.append(n.r)
print
thislevel = nextlevel
def revert(self):
def _revert(node):
if node:
node.l, node.r = _revert(node.r), _revert(node.l)
return node
if self.root:
_revert(self.root)
def max_sum_l2l(self):
def max_sum_path(node, opt):
if node is None:
return 0
l_sum = max_sum_path(node.l, opt)
r_sum = max_sum_path(node.r, opt)
if node.l and node.r:
# important -- result only valid for a node contains both children
# otherwise no leaf to leaf
opt[0] = max(opt[0], l_sum+r_sum+node.value)
print "current max: " + str(opt)
return max(l_sum, r_sum) + node.value
return node.value + l_sum + r_sum
opt = [-sys.maxint-1]
max_sum_path(self.root, opt)
print "result: " + str(opt)
def max_sum_n2n(self):
def max_sum_path(node, opt):
if node is None:
return 0
l_sum = max_sum_path(node.l, opt)
r_sum = max_sum_path(node.r, opt)
# 4 situations -- node only, node + left max, node + right max, node + both max(go through)
opt[0] = max(opt[0], node.value, node.value+l_sum, node.value+r_sum, node.value+l_sum+r_sum)
if node.l and node.r:
# max path sum -- can only count one side
return max(max(l_sum, r_sum) + node.value, node.value)
else:
return max(node.value + l_sum + r_sum, node.value)
opt = [-sys.maxint-1]
max_sum_path(self.root, opt)
print "result: " + str(opt)
def main(args):
tree = BTree()
# tree.add_v(5)
# tree.add_v(9)
# tree.add_v(6)
# tree.add_v(7)
# tree.add_v(4)
# tree.add_v(3)
# tree.add_v(1)
# tree.add_v(8)
# tree.add_v(11)
# tree.add_v(10)
tree.root = Node(10)
tree.root.l = Node(-1)
tree.root.r = Node(-2)
# tree.root.l = Node(5)
# tree.root.r = Node(6)
# tree.root.l.l = Node(-8)
# tree.root.l.r = Node(1)
# tree.root.l.l.l = Node(2)
# tree.root.l.l.r = Node(6)
# tree.root.r.l = Node(3)
# tree.root.r.r = Node(9)
# tree.root.r.r.r= Node(0)
# tree.root.r.r.r.l = Node(4)
# tree.root.r.r.r.r = Node(-1)
# tree.root.r.r.r.r.l = Node(10)
# tree.root.l = Node(2)
# tree.root.r = Node(10);
# tree.root.l.l = Node(20);
# tree.root.l.r = Node(1);
# tree.root.r.r = Node(-25);
# tree.root.r.r.l = Node(3);
# tree.root.r.r.r = Node(4);
# print tree.root
# print str(tree.__repr__())
tree.print_t()
# tree.revert()
print "#####"
# tree.print_t()
# tree.find_v(111)
# tree.max_sum_l2l()
tree.max_sum_n2n()
if __name__ == "__main__":
main(sys.argv[1:])
|
bfb650ee9eb5e44a26f2a114ee7810e388c0dccc | FlyingPumba/algo3 | /hanoi.py | 1,828 | 3.8125 | 4 | #!/usr/bin/env python
import sys
import os
import time
if len(sys.argv) > 2:
print "Too many arguments"
sys.exit()
elif len(sys.argv) == 2:
n = int(sys.argv[1])
else:
print "Too few arguments"
sys.exit()
# helper functions
def display():
os.system('clear')
print "T1: ", list(reversed(towers[0]))
print "T2: ", list(reversed(towers[1]))
print "T3: ", list(reversed(towers[2]))
def attemptMove(i):
destination = []
if len(towers[i]) == 0:
return destination
for j in xrange(3):
if abs(j-i) == 1 and (len(towers[j]) == 0 or towers[i][0] < towers[j][0]):
destination.append(j)
return destination
# initialize
towers = [[],[],[]]
for i in xrange(1,n+1):
towers[0].append(i)
display()
a = raw_input('')
last_destination_tower = -1
last_origin_tower = -1
while len(towers[2]) != n:
# check which tower should move next
origin_tower = -1
destination_tower = -1
for origin_tower in xrange(3):
possible_destinations = attemptMove(origin_tower)
if len(possible_destinations) == 0:
continue
found = False
for destination_tower in possible_destinations:
if not (destination_tower == last_origin_tower and origin_tower == last_destination_tower):
last_origin_tower = origin_tower
last_destination_tower = destination_tower
found = True
break
if found:
break
#print next_tower
disc = towers[origin_tower][0]
towers[origin_tower] = towers[origin_tower][1:]
if origin_tower < destination_tower:
towers[origin_tower + 1][:0] = [disc]
else:
towers[origin_tower - 1][:0] = [disc]
display()
#time.sleep(0.25) # sleep 250 milliseconds
a = raw_input('')
|
1ce3182ee7cc93e36e6104f6352ccfcc2d592a57 | BrayanRuiz/AprendiendoPython | /Compara.py | 658 | 3.921875 | 4 | # Compara.py
# Autor: Brayan Javier Ruiz Navarro
# Fecha de Creación: 15/09/2019
numero1=int(input("Dame el numero uno: "))
numero2=int(input("Dame el numero dos: "))
salida="Numeros proporcionados: {} y {}. {}."
if (numero1==numero2):
# Entra aqui si los numeros son iguales
print(salida.format(numero1, numero2,"Los numeros son iguales"))
else:
# Si los numeros NO son iguales
if numero1>numero2:
# Chequea si el primer numero es mayor al segundo.
print(salida.format(numero1, numero2,"El mayor es el primero"))
else:
# Ahora si el numero mayor es el segundo
print(salida.format(numero1, numero2,"El mayor es el segundo")) |
18f0fe41b07500f4cc067520d7fc1a40c95382df | hafizmuhammadhamza/LearningPython | /Assignment3/Untitled-1.py | 1,951 | 4.09375 | 4 | Assignment#3
## calculator
val1 = input("Enter first value")
val2 = input("Enter 2nd value")
operator = input("Enter operator")
val1 = int(val1)
val2 = int(val2)
if operator == '+' :
val = val1+val2
print(val,"answer")
elif operator == '-':
val = val1-val2
print(val,"answer")
elif operator =='/' :
val = val1 / val2
print(val,"answer")
elif operator =='*' :
val = val1 * val2
print(val,"answer")
elif operator =='**' :
val = val1 ** val2
print(val,"answer")
else:
print("entetr correct value")
output:
Enter first value2
Enter 2nd value5
Enter operator**
32 answe
## For adding key value in dictionary
customer_detail={
"First name":"Hamza",
"Last name":"Abid",
"Email" : "Hamzaabid4075@gmail.com"
}
for customer_inf in customer_detail.keys():
print(customer_inf,"keys")
output:
First name keys
Last name keys
Email keys
##For sum all numeric values
val = {"A":24,"B":20,"c":20,"D":19}
total= sum(vl.values())
print(total)
output:
83
## To chek if given key already exist in dictonary
list = {1: 2, 2:20, 3 :4, 5 :30, 6 :50, 7 :70}
def a_keypresent(n):
if n in list:
print("key is present in the dictionary")
else:
print("key is not present in dictionary")
a_keypresent(3)
a_keypresent(4)
output:
key is present in the dictionary
key is not present in dictionary
## python program to chk if there is any numeric values in this list using for loop
num_list = [2,4,8,10,12,14,15,16,17,19]
user_input = int(input("Enter the number"))
if user_input in num_list :
print(f'{user_input}exist in this list!')
else:
print(f'{user_input}does not exist in this list!')
## duplicate values from list
list = [1,2,3,2,4,6,9,6,10]
length_of_list = len(list)
duplicate_values =[]
for i in range(length_of_list):
k = i+1
for j in range(k,length_of_list):
if list[i] == list[j]and list[i]not in duplicate_values:
duplicate_values.append(list[i])
print(duplicate_values) |
14f729286c7dd1baad31e91de84f32623aaf4ea3 | curiousboey/Split_expense | /main.py | 5,449 | 3.75 | 4 | import numpy as np
import cv2
import matplotlib.pyplot as plt
Total = int(input("Please enter the total expense: "))
people_money = {'A':0,'Su':0,'Sa':0,'B':0,'Sh':0,'D':0,'K':0, 'U':0, 'J':0}
exclude_person= input("Are there people to exclude from the list? (y/n): ")
exclude_name2 = 'y'
while exclude_name2 == 'y' or exclude_name2 == 'Y':
if exclude_person == 'y' or exclude_person == 'Y':
exclude_name = input('Enter the name of person: ')
del people_money[exclude_name]
exclude_name2 = input('Are there more people to exclude from the list? (y/n): ')
else:
pass
people = list(people_money.keys())
money = list(people_money.values())
no_donor = int(input('Enter the number of donor: '))
donor_name = []
donor_money = []
for i in range(no_donor):
donor_name_ask= input('Enter the name of donor: ')
donor_name.append(donor_name_ask)
donor_money_ask= int(input('Enter the amount given: '))
donor_money.append(donor_money_ask)
people_money[donor_name_ask]= donor_money_ask
ask_changes= input('Did anyone keep the changes? (y/n): ')
if ask_changes == 'y' or ask_changes == 'Y':
ask_changes_name = input('Who keeps the changes?: ')
changes_amount = sum(donor_money) - Total
people_money[ask_changes_name] = abs(donor_money[donor_name.index(ask_changes_name)]-changes_amount)
else:
pass
expense_per_head = Total/len(people_money)
print('Total expenses per person: ',expense_per_head)
confirm_expense_per_head = input('Do you want to proceed with this expenses per head? (y/n): ')
if confirm_expense_per_head == 'y' or confirm_expense_per_head == 'Y':
pass
else:
expense_per_head = int(input('Enter the approx. expenses per head: '))
print('Approx. expenses per person: ', expense_per_head)
people = list(people_money.keys())
money = list(people_money.values())
final_giver_name= []
final_giver_amount= []
final_receiver_name= []
final_receiver_amount= []
final_neutral_name= []
for j in range(len(people_money)):
if money[j] < expense_per_head:
final_giver_name.append(people[j])
final_giver_amount.append(abs(money[j]-expense_per_head))
elif money[j] == expense_per_head:
final_neutral_name.append(people[j])
else:
final_receiver_name.append(people[j])
final_receiver_amount.append(abs(money[j] - expense_per_head))
Final_text= []
while not(final_receiver_name == [] or final_giver_name == []):
n = final_receiver_amount[0] // expense_per_head
for l in range(n + 1):
if final_giver_amount == []:
pass
else:
if final_receiver_amount[0] < final_giver_amount[0]:
Final_text.append(final_receiver_name[0] + ' receives ' + str(final_receiver_amount[0]) + ' from ' + final_giver_name[0])
print(final_receiver_name[0] + ' receives ' + str(final_receiver_amount[0]) + ' from ' + final_giver_name[0])
final_receiver_name.pop(0)
final_giver_amount[0] = final_giver_amount[0] - final_receiver_amount[0]
final_receiver_amount.pop(0)
else:
Final_text.append(final_receiver_name[0] + ' receives ' + str(final_giver_amount[0]) + ' from ' + final_giver_name[0])
print(final_receiver_name[0] + ' receives ' + str(final_giver_amount[0]) + ' from ' + final_giver_name[0])
final_receiver_amount[0] = final_receiver_amount[0] - final_giver_amount[0]
final_giver_name.pop(0)
final_giver_amount.pop(0)
print(np.array(Final_text))
# create figure
fig = plt.figure(figsize=(10, 20))
plt.ylim([0,5])
# setting values to rows and column variables
rows = 4
columns = 3
# reading images
Image1 = cv2.imread('Image1_B.jpg')
Image2 = cv2.imread('Image2_Sa.jpg')
Image3 = cv2.imread('Image3_Sh.jpg')
Image4 = cv2.imread('Image4_Su.jpg')
Image5 = cv2.imread('Image5_D.jpg')
Image6 = cv2.imread('Image6_K.jpg')
Image7 = cv2.imread('Image7_A.jpg')
Image8 = cv2.imread('Image8_U.jpg')
Image9 = cv2.imread('Image9_J.jpg')
for r in range(len(Final_text)):
plt.text(0.1, 4.9-(r/6), Final_text[r], fontsize=12)
plt.title("Expenses Calculation",
fontsize='20',
backgroundcolor='green',
color='white',loc='right')
# Adds a subplot at the 1st position
fig.add_subplot(rows, columns, 4)
# showing image
plt.imshow(Image1)
plt.axis('off')
plt.title("Bhupendra(B)")
# Adds a subplot at the 2nd position
fig.add_subplot(rows, columns, 5)
# showing image
plt.imshow(Image2)
plt.axis('off')
plt.title("Sarita(Sa)")
# Adds a subplot at the 3rd position
fig.add_subplot(rows, columns, 6)
# showing image
plt.imshow(Image3)
plt.axis('off')
plt.title("Shikheb(Sh)")
# Adds a subplot at the 4th position
fig.add_subplot(rows, columns, 7)
# showing image
plt.imshow(Image4)
plt.axis('off')
plt.title("Sulav(Su)")
fig.add_subplot(rows, columns, 8)
# showing image
plt.imshow(Image5)
plt.axis('off')
plt.title("Dibesh(D)")
fig.add_subplot(rows, columns, 9)
# showing image
plt.imshow(Image6)
plt.axis('off')
plt.title("Kritika(K)")
fig.add_subplot(rows, columns, 10)
# showing image
plt.imshow(Image7)
plt.axis('off')
plt.title("Aabhash(A)")
fig.add_subplot(rows, columns, 11)
# showing image
plt.imshow(Image8)
plt.axis('off')
plt.title("Urmila(U)")
fig.add_subplot(rows, columns, 12)
# showing image
plt.imshow(Image9)
plt.axis('off')
plt.title("Jitendra(J)")
|
10fed4644051512c170e4b7486046b989ea914e7 | bencheng0904/Python200818_2 | /turtle05.py | 220 | 3.640625 | 4 | import turtle
screen=turtle.Screen
screen
a = turtle.Turtle()
n=int(input("你要幾邊形:"))
for i in range(n):
a.forward(100)
a.left(360/n)
turtle.done()
|
2a02c14e29e2394226df08d57d452ff6c1feab68 | ShrutiAgarwal10/tathastu_week_of_code | /day2/program3.py | 396 | 3.796875 | 4 | s=0
sp=6
for i in range(1,5):
for j in range(1,s+1):
print(" ", end="")
s=s+1
print("*",end="")
for k in range(1,sp+1):
print(" ",end="")
sp=sp-2
print("*")
s=3
sp=0
for i in range(1,5):
for j in range(1,s+1):
print(" ", end="")
s=s-1
print("*",end="")
for k in range(1,sp+1):
print(" ",end="")
sp=sp+2
print("*")
|
e8c123bc4f74385b8c83d21d1d16e806c67c3e29 | ShrutiAgarwal10/tathastu_week_of_code | /day2/program2.py | 249 | 4 | 4 | n=int(input("Enter the number: "))
if(n<0):
print("Incorrect Input")
else:
print("Fibonacci series is: ")
a=0
b=1
print(a, b, end=" ")
for i in range(1,n-1):
c=a+b
print ( c, end=" ")
a=b
b=c
|
2a7106f28502efe3d57e692d8428236b14921945 | ShrutiAgarwal10/tathastu_week_of_code | /day2/program5.py | 263 | 4.0625 | 4 | for i in range(3,0,-1):
print(i, end="")
for j in range(1,i):
print("*", end="")
print(i,end="")
print()
for i in range(1,4):
print(i, end="")
for j in range(1,i):
print("*", end="")
print(i,end="")
print()
|
439f0067ee46a8dc51afb93675750c267ec6a54a | kimhyunkwang/algorithm-study-02 | /2주차/김윤주/숫자 나라 특허 전쟁.py | 107 | 4.09375 | 4 | num = int(input())
sum=0
for i in range(num):
if i % 3 ==0 or i % 5 ==0:
sum = sum+i
print(sum) |
3bf16699407123dc74114f452f88bfd6f33914be | kimhyunkwang/algorithm-study-02 | /3주차/김현광/해치웠나.py | 181 | 3.640625 | 4 | fight = input()
villain = fight.count("(")
hero = fight.count(")")
if fight[0] == ")":
print("NO")
elif villain > hero or villain < hero:
print("NO")
else:
print("YES") |
b3e26a6e084e4c1b3b14358483e02e8901d52116 | kimhyunkwang/algorithm-study-02 | /4주차/정소원/4주차_암호 만들기.py | 281 | 3.71875 | 4 | n = int(input())
words = [input() for _ in range(n)]
def encryption(s):
alpha = [chr(ord('A')+i) for i in range(26)]
res = ''
for c in s:
idx = (ord(c)-ord('A')+1) % 26
res += alpha[idx]
return res
for word in words:
print(encryption(word))
|
c86c5802eedd1316f0ccd88e91213661ba00ceaf | kimhyunkwang/algorithm-study-02 | /3주차/강현우/근거 없는 자신감.py | 230 | 3.75 | 4 | score = list(map(int, input().split()))
score.pop(0)
average = sum(score) / len(score)
good_student = 0
for i in score:
if i > average:
good_student += 1
print("{:.3f}%".format(round(good_student/len(score)*100,3))) |
47ccf26e0a4109f42effb74ebfabbdf5814242e7 | kimhyunkwang/algorithm-study-02 | /2주차/김현광/무어의 법칙[Moore's Law].py | 108 | 3.71875 | 4 | n = int(input())
SUM = 0
n_str = str(2**n)
for i in range(len(n_str)):
SUM += int(n_str[i])
print(SUM) |
d08aa6822d4f277870069b700c232c8b5550c3a0 | kimhyunkwang/algorithm-study-02 | /2주차/심재민/숫자 나라 특허 전쟁.py | 233 | 3.84375 | 4 | # 숫자 나라 특허 전쟁
N = int(input())
three = []
five = []
for i in range(1, N):
if i % 3 == 0:
three.append(i)
elif i % 5 == 0:
five.append(i)
num = three + five
print(sum(set(num))) |
698b8212c16b1a11a5fb9d63af5db687d404039f | beyzakilickol/week1Friday | /algorithms.py | 953 | 4.1875 | 4 | #Write a program which will remove duplicates from the array.
arr = ['Beyza', 'Emre', 'John', 'Emre', 'Mark', 'Beyza']
arr = set(arr)
arr = list(arr)
print(arr)
#-------Second way------------------------
remove_dups = []
for i in range(0, len(arr)):
if arr[i] not in remove_dups:
remove_dups.append(arr[i])
print(remove_dups)
#-------------Assignment 2-------------------------
#Write a program which finds the largest element in the array
arr = [3,5,7,8,9,14,24,105]
print(max(arr))
#-------------Assignment 3--------------------------------
#Write a program which finds the smallest element in the array
print(min(arr))
# stringArr = ['beyza', 'cem', 'ramazan', 'ak', 'ghrmhffjhfd', 'yep']
# print(min(stringArr)) # returns ak in alphabetical order
#------------Assigment 4----------------------------------
#Write a program to display a pyramid
string = "*"
for i in range(1, 18 , 2):
print('{:^50}'.format(i * string))
|
34da44a06b3aa45cf48daa2bb0f967289adaa72b | ArunDhwaj/python | /myoops/oops_depth.py | 297 | 3.59375 | 4 | class Book:
def __init__(self, name, pageNumber):
self.name = name
self.pageNumber = pageNumber
hindi = Book('Hindi', 200)
java = Book('Java', 590)
#english.name = 'English'
#english.pageNumber = 2000
print(hindi.name, hindi.pageNumber)
print(java.name, java.pageNumber)
|
7676878c6cf7c1395fde4e3f4f96a650b08556c9 | ajh1143/HackerRank_Practice | /TripletComparison.py | 1,048 | 3.59375 | 4 | #Compare values in equal positions of two arrays, awarding a point to the array with the greater value in the comparison point.
#If values are equal, no points will be awarded for that comparison.
#Return a list of values indicating the score for each array owner, named Alice and Bob
#!/bin/python3
import os
import sys
def solve(a0, a1, a2, b0, b1, b2):
aliceScore = 0
bobScore = 0
alice = [a0, a1, a2]
bob = [b0, b1, b2]
for t in range(3):
if alice[t] == bob[t]:
pass
elif alice[t] > bob[t]:
aliceScore +=1
else:
bobScore += 1
return aliceScore, bobScore
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
a0A1A2 = input().split()
a0 = int(a0A1A2[0])
a1 = int(a0A1A2[1])
a2 = int(a0A1A2[2])
b0B1B2 = input().split()
b0 = int(b0B1B2[0])
b1 = int(b0B1B2[1])
b2 = int(b0B1B2[2])
result = solve(a0, a1, a2, b0, b1, b2)
f.write(' '.join(map(str, result)))
f.write('\n')
f.close()
|
73c8c88528e7c980308ade1d8f59545bd9fee2e1 | McSwellian/3414-Hackbots-FRC-scouting | /Manual Data Entry.py | 1,074 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 11 00:12:39 2018
@author: Maxwell Ledermann
"""
import pickle
import os
def is_number(inpt):
try:
float(inpt)
return True
except ValueError:
return False
while(True):
print("Type 'exit' or 'x' at any time to safely exit the program.")
team_number = input("Enter team number: ")
if team_number in ("exit","x"):
break
if is_number(team_number) == True:
match_number = input("Enter match number, leave blank to cancel: ")
if match_number in ("exit","x"):
break
elif match_number != "" and is_number(match_number) == True:
scan = input("Press enter to begin scan, type any other value to cancel: ")
if scan in ("exit","x"):
break
elif scan == "":
keyword = True
pickle.dump((team_number,match_number,keyword), open( "entry data.p", "wb" ))
keyword = False
clear = lambda: os.system('cls')
clear() |
32f05d2f45e3bad3e2014e1ba768a6b92d4e67b6 | soumyadc/myLearning | /python/statement/loop-generator.py | 575 | 4.3125 | 4 | #!/usr/bin/python
# A Generator:
# helps to generate a iterator object by adding 1-by-1 elements in iterator.
#A generator is a function that produces or yields a sequence of values using yield method.
def fibonacci(n): #define the generator function
a, b, counter = 0, 1, 0 # a=0, b=1, counter=0
while True:
if(counter > n):
return
yield a
a=b
b=a+b
counter += 1
it=fibonacci(5) # it is out iterator object here
while True:
try:
print (next(it))
except:
break
print("GoodBye")
|
7400c080f5ce15b3a5537f436e3458772b42d801 | soumyadc/myLearning | /python/tkinter-gui/hello.py | 737 | 4.21875 | 4 | #!/usr/bin/python
from Tkinter import *
import tkMessageBox
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
# Code to add widgets will go here...
# Tk root widget, which is a window with a title bar and other decoration provided by the window manager.
# The root widget has to be created before any other widgets and there can only be one root widget.
top = Tk()
L1= Label(top, text="Hello World")
L1.pack(side=LEFT)
# Button, when clicked it calls helloCallBack() function
B1=Button(top, text="Hello", command=helloCallBack)
B1.pack(side=RIGHT)
# The window won't appear until we enter the Tkinter event loop
# Our script will remain in the event loop until we close the window
top.mainloop()
|
f79177c85731cb3d855362ae429046af9f26755b | soumyadc/myLearning | /python/tkinter-gui/label-dynamic-content.py | 433 | 3.59375 | 4 | #!/usr/bin/python
from Tkinter import *
import tkMessageBox
def counter_label(L2):
counter = 0
L2.config(text="Hello World")
top = Tk()
top.title("Counting Seconds")
logo= PhotoImage(file="/home/soumyadc/Pictures/Python.png")
L1= Label(top, image=logo).pack(side="right")
L2 = Label(top, fg="green").pack(side="left")
counter_label(L2)
B1=Button(top, text='stop', width=25, command=top.destroy).pack()
top.mainloop()
|
c553dbc7c7a4d74904c17b53cd050f1448648d2f | tavu/nao_footsteps | /footstep_handler/src/footstep_handler/stepQueue.py | 1,077 | 3.59375 | 4 | import copy
class StepQueue(object):
_steps = None
_nextStep = 0
def __init__(self):
self._steps = []
self._nextStep = 0
return
def clear(self):
self._steps = []
self._nextStep = 0
return
def addStep(self, step):
new_step = copy.deepcopy(step)
self._steps.append(new_step)
return
def addSteps(self, steps):
#self._steps = copy.deepcopy(steps)
self._steps.extend(copy.deepcopy(steps) )
self._nextStep = 0
return
def isEmpty(self):
return len(self._steps) == 0
def isFInished(self):
if self.isEmpty() :
return True
if len(self._steps) <= self._nextStep :
return True
return False
def size(self):
return len(self._steps)
def nextStep(self):
if self.isFInished():
return None
nextStep = self._steps[self._nextStep]
self._nextStep = self._nextStep +1
return nextStep
|
09605e5fb1a9abd9463bb22d7aa5476a461cdf0a | maarjaryytel/python | /Tund_2/loop.py | 898 | 3.75 | 4 | #while
#for
#index=100
#teineIndex=10
#print(index)
#while index<=10:
#print(teineIndex)
#index+=1
#index+=100
#if index==5:
# print(index)
#break
#continue
#else:
#print("Condition is false")
#fruits=["apple", "banana", "cherry"]
#for x in fruits:
#print(x)
#for x in range(2,60,3): #see viimane nr tõstab 3 võrra
#print(x)
#pass kui ma ei taha siin midagi kuvada, siis panen pass,
#siis ta läheb edasi
#else:
#print("finished!")
#for x in range(11): #10 korda
#for x in range(11): #10 korda
#print(x) #ehk kuvab 2 korda järjest
cars=["Audi", "BMW", "Ford", "Mazda", "Peugeot"]
print(cars)
vastus = input("Vali nimekirjast oma lemmik: ")
#for car in cars: see on vale
#print(cars.index(vastus))
for car in cars:
print(cars.index(car)) #(cars.index(vastus)) |
10ba8e8b576debb45c7fe3d6fb9caa72fcad6c60 | maarjaryytel/python | /Tund_4/kolmnurk.py | 701 | 3.625 | 4 | def kolmnurga_funktsioon():
kolmnurgaAlus=int(input("Sisesta kolmnurga alus (cm): "))
kolmnurgaKõrgus= int(input("Sisesta kolmnurga kõrgus (cm): "))
kolmnurgaPindala=kolmnurgaAlus*kolmnurgaKõrgus/2
##print("Vastus on: ", kolmnurgaPindala) #parem on returni kasutada
return kolmnurgaPindala
def ruudu_funktsioon():
ruuduKylg=int(input("Sisesta ruudu külg (cm): "))
ruuduPindala= ruuduKylg*ruuduKylg
return ruuduPindala
def ristkyliku_funktsioon():
kyljePikkus=int(input("Sisesta ristküliku külje pikkus (cm): "))
kyljeLaius=int(input("Sisesta ristküliku külje laius (cm): "))
ristkylikuPindala= kyljePikkus*kyljeLaius
return ristkylikuPindala
|
c3d8d2b2ed1064d21443522737f47d4320f60e16 | donariumdebbie/BaekjoonOnlineJudge | /1000/1008.py | 393 | 3.546875 | 4 | # Completed 2017-08-20
# correct code
from __future__ import division
input_numbers = raw_input()
int_nums = [int(item) for item in input_numbers.split()]
print int_nums[0]/int_nums[1]
# first submitted : correct but runtime error
# import numpy as np
# input_numbers = raw_input()
# int_nums = [int(item) for item in input_numbers.split()]
# print np.true_divide(int_nums[0],int_nums[1]) |
11be5b7d615e15e376720def2715bed5b84a43e6 | ybgirgin3/tkinter-CRM-gui | /2main.py | 6,807 | 3.5625 | 4 | from tkinter import *
from tkinter import ttk
import sqlite3
root = Tk()
root.geometry("800x500")
db_name = "tkinter_db.sqlite3"
# create db or connect one
conn = sqlite3.connect(db_name)
c = conn.cursor()
# create table
c.execute("""CREATE TABLE if not exists table1 (
ID integer,
numara INTEGER,
adi TEXT,
soyadi TEXT,
telefonu INTEGER)
""")
# commit changes
conn.commit()
conn.close()
def query_database():
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute("SELECT * FROM table1")
records = c.fetchall()
from pprint import pprint
pprint(records)
print()
global count
count = 0
"""for record in records:
print(recor d)"""
for record in records:
if count % 2 == 0:
my_tree.insert(parent="", index="end", iid=count, text="", values = (record[0], record[1], record[2], record[3], record[4]), tags=('evenrow',) )
else:
my_tree.insert(parent="", index="end", iid=count, text="", values = (record[0], record[1], record[2], record[3], record[4]), tags=('oddrow',) )
count += 1
conn.commit()
conn.close()
# add style
style = ttk.Style()
style.theme_use('default')
style.configure("Treeview", background="#D3D3D3D", foreground="black", rowheight=25, fieldbackground="#D3D3D3")
style.map("Treeview", background=[('selected', '#347083')])
tree_frame = Frame(root)
tree_frame.pack(pady=10)
tree_scroll = Scrollbar(tree_frame)
tree_scroll.pack(side=RIGHT, fill=Y)
my_tree = ttk.Treeview(tree_frame, yscrollcommand=tree_scroll.set, selectmode="extended")
my_tree.pack()
tree_scroll.config(command=my_tree.yview)
# columns
my_tree['columns'] = ('ID', 'Numara', 'Adi', 'Soyadi', 'Telefonu')
# formt colum
my_tree.column("#0", width=0)
my_tree.column("ID", anchor = W)
my_tree.column("Numara", anchor = W)
my_tree.column("Adi", anchor=CENTER)
my_tree.column("Soyadi",anchor=CENTER)
my_tree.column("Telefonu",anchor=CENTER)
# headings
my_tree.heading("#0", text="LABEL", anchor=W)
my_tree.heading("ID", text="ID", anchor=CENTER)
my_tree.heading("Numara", text="Numara", anchor=CENTER)
my_tree.heading("Adi", text="Adi", anchor=CENTER)
my_tree.heading("Soyadi", text="Soyadi", anchor=CENTER)
my_tree.heading("Telefonu", text="Telefonu", anchor=CENTER)
# add data
my_tree.tag_configure('oddrow', background='white')
my_tree.tag_configure('evenrow', background='lightblue')
# add record entry boxes
data_frame = LabelFrame(root, text="Kayıtlar")
data_frame.pack(fill="x", expand="yes", padx=20, side="left")
# labelları ekle
id_label = Label(data_frame, text="id")
id_label.grid(row=0, column=1, padx=10, pady=10)
id_entry = Entry(data_frame)
id_entry.grid(row=1, column=1, padx=10, pady=10)
# ogrenci no
ogrenci_no_label = Label(data_frame, text="Öğrenci No")
ogrenci_no_label.grid(row=2, column=1, padx=10, pady=10)
ogrenci_no_entry = Entry(data_frame)
ogrenci_no_entry.grid(row=3, column=1, padx=10, pady=10)
ogrenci_adi_label = Label(data_frame, text="Adi")
ogrenci_adi_label.grid(row=4, column=1, padx=10, pady=10)
ogrenci_adi_entry = Entry(data_frame)
ogrenci_adi_entry.grid(row=5, column=1, padx=10, pady=10)
ogrenci_soyadi_label = Label(data_frame, text="Soyadi")
ogrenci_soyadi_label.grid(row=6, column=1, padx=10, pady=10)
ogrenci_soyadi_entry = Entry(data_frame)
ogrenci_soyadi_entry.grid(row=7, column=1, padx=10, pady=10)
ogrenci_telefonu_label = Label(data_frame, text="Telefonu")
ogrenci_telefonu_label.grid(row=8, column=1, padx=10, pady=10)
ogrenci_telefonu_entry = Entry(data_frame)
ogrenci_telefonu_entry.grid(row=9, column=1, padx=10, pady=10)
# clear entry boxes
def clear_entries():
id_entry.delete(0, END)
ogrenci_no_entry.delete(0, END)
ogrenci_adi_entry.delete(0, END)
ogrenci_soyadi_entry.delete(0, END)
ogrenci_telefonu_entry.delete(0, END)
# select records
def select_records(e):
# clear entry boxes
id_entry.delete(0, END)
ogrenci_no_entry.delete(0, END)
ogrenci_adi_entry.delete(0, END)
ogrenci_soyadi_entry.delete(0, END)
ogrenci_telefonu_entry.delete(0, END)
# grap record nauber
selected = my_tree.focus()
# grap value
values = my_tree.item(selected, "values")
# output entry boxes
id_entry.insert(0, values[0]),
ogrenci_no_entry.insert(0, values[1])
ogrenci_adi_entry.insert(0, values[2])
ogrenci_soyadi_entry.insert(0, values[3])
ogrenci_telefonu_entry.insert(0, values[4])
def update_record():
#selected = select_records()
selected = my_tree.focus()
print(selected)
my_tree.item(selected, text="", values=(id_entry.get(), ogrenci_no_entry.get(), ogrenci_adi_entry.get(), ogrenci_soyadi_entry.get(), ogrenci_telefonu_entry.get()))
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute("""UPDATE table1 SET
numara = :no,
adi = :name,
soyadi = :surname,
telefonu = :phone
WHERE oid = :oid""",
{
'no': ogrenci_no_entry.get(),
'name': ogrenci_adi_entry.get(),
'surname': ogrenci_soyadi_entry.get(),
'phone': ogrenci_telefonu_entry.get(),
'oid': id_entry.get(),
})
conn.commit()
conn.close()
clear_entries()
id_entry.delete(0, END)
ogrenci_no_entry.delete(0, END)
ogrenci_adi_entry.delete(0, END)
ogrenci_soyadi_entry.delete(0, END)
ogrenci_telefonu_entry.delete(0, END)
# add new record
def add_record():
conn = sqlite3.connect(db_name)
c = conn.cursor()
# control entry field
if len(id_entry.get()) == 0:
print("boş eleman")
elif len(id_entry.get()) > 0:
c.execute("INSERT INTO table1 VALUES (:id, :no, :name, :surname, :phone )",
{
'id': id_entry.get(),
'no': ogrenci_no_entry.get(),
'name': ogrenci_adi_entry.get(),
'surname': ogrenci_soyadi_entry.get(),
'phone': ogrenci_telefonu_entry.get(),
})
conn.commit()
conn.close()
id_entry.delete(0, END)
ogrenci_no_entry.delete(0, END)
ogrenci_adi_entry.delete(0, END)
ogrenci_soyadi_entry.delete(0, END)
ogrenci_telefonu_entry.delete(0, END)
# clear tree view
my_tree.delete(*my_tree.get_children())
query_database()
def remove_record():
# remove from tree
x = my_tree.selection()[0]
my_tree.delete(x)
# remove from database
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute("DELETE from table1 WHERE oid=" + id_entry.get())
conn.commit()
conn.close()
clear_entries()
# add buttons
button_frame = LabelFrame(root, text="Buttons")
button_frame.pack(fill='x', expand='yes', padx=20, side="right")
add_button = Button(button_frame, text="Ekle", command=add_record)
add_button.grid(row=0, column=0, padx=10, pady=10)
update_button = Button(button_frame, text="Güncelle", command=update_record)
update_button.grid(row=1, column=0, padx=10, pady=10)
delete_button = Button(button_frame, text="Sil", command=remove_record)
delete_button.grid(row=2, column=0, padx=10, pady=10)
# bind tree
my_tree.bind("<ButtonRelease-1>", select_records)
query_database()
update_record()
root.mainloop()
|
00810e6d82eadcefd857be63319e07356c69cf77 | stewartad/goodcop-dadcop | /player.py | 3,247 | 3.515625 | 4 | import pygame, constants
class Player(pygame.sprite.Sprite):
# constrctor class that takes x, y coordinates as parameters
def __init__(self, x, y):
# call parent constructor
pygame.sprite.Sprite.__init__(self)
# set sprite image and rectangle
self.image = pygame.image.load("goodcop.png")
self.rect = self.image.get_rect()
# set position
self.rect.x = x
self.rect.y = y
# set width and height
self.width = self.rect.width
self.height = self.rect.height
# set velocity and acceleration
self.dx = 0
self.dy = 0
self.ay = constants.GRAV
# set variable to retrieve platforms from main
self.walls = None
def moveLeft(self):
# Move in negative x direction
self.dx = -constants.X_VEL
def moveRight(self):
# Move in positive x direction
self.dx = constants.X_VEL
def jump(self):
# Move down 2 pixels and check for collision, then move back up 2 pixels
self.rect.y += 2
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
self.rect.y -=2
# jump if sprite is on the ground, or collided with a platform
if self.checkGround() or len(block_hit_list)>0:
self.dy = -constants.Y_VEL
self.rect.y -= 4
def stop(self):
# set x velocity to zero to stop movement
self.dx = 0
def checkGround(self):
onGround = False
# if bottom of rectangle is greater than or equal to the screen height,
# then the sprite is on the ground
if self.rect.bottom >= constants.SCR_HEIGHT:
onGround = True
return onGround
def addGrav(self):
# If platform moves, this ensures player moves with it
if self.dy == 0:
self.dy = 1
else:
self.dy -= constants.GRAV
if self.checkGround():
# If on the ground, negate gravity
self.dy = 0
self.rect.y = constants.SCR_HEIGHT - self.height
def update(self):
# Account for gravity
self.addGrav()
# move in x direction
self.rect.x += self.dx
# check if x movement resulted in collision
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
if self.dx > 0:
self.rect.right = block.rect.left
if self.dx < 0:
self.rect.left = block.rect.right
# check if x movement goes off screen
if self.rect.right >= constants.SCR_WIDTH:
self.rect.right = constants.SCR_WIDTH
elif self.rect.x <= 0:
self.rect.x = 0
# move in y direction
self.rect.y += self.dy
# check if y movement resulted in collision
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
if self.dy > 0:
self.rect.bottom = block.rect.top
if self.dy < 0:
self.rect.top = block.rect.bottom
self.dy=0
|
29c1733f39888ca54099d2e15a762d8d748c06f9 | opiroi/sololearn_python | /assistant/python_iterators_and_generators.py | 1,556 | 4.5 | 4 |
def iteration_over_list():
"""Iteration over list elements.
:return: None
"""
print("##### ##### iteration_over_list ##### #####")
for i in [1, 2, 3, 4]:
print(i)
# prints:
# 1
# 2
# 3
# 4
def iteration_over_string():
"""Iteration over string characters.
:return: None
"""
print("##### ##### iteration_over_string ##### #####")
for i in "python":
print(i)
# prints:
# p
# y
# t
# h
# o
# n
def iteration_over_dictionary():
"""Iteration over dictionary elements.
:return: None
"""
print("##### ##### iteration_over_dictionary ##### #####")
for i in {"x": 1, "y": 2, "z": 3}:
print(i)
# prints:
# z
# y
# x
def iteration_over_file_line():
"""Iteration over file lines.
:return: None
"""
print("##### ##### iteration_over_file_line ##### #####")
for line in open("a.txt"):
print(line)
# prints:
# first line
# second line
def iteration_practical_usage():
"""Efficient usage examples of iterations.
1. list join
2. dictionary join
3. string list
4. dictionary list
:return: None
"""
print("##### ##### iteration_practical_usage ##### #####")
print(",".join(["a", "b", "c"]))
# prints as string: 'a,b,c'
print(",".join({"x": 1, "y": 2}))
# prints as string: 'y,x'
print(list("python"))
# prints as list: ['p', 'y', 't', 'h', 'o', 'n']
list({"x": 1, "y": 2})
# prints as list: ['y', 'x']
|
a80e193e474dbf030fe16d22c4bcc50dba20d6f9 | lionfish0/QueueBuffer | /QueueBuffer/__init__.py | 3,484 | 4.1875 | 4 | from multiprocessing import Queue, Value, Manager
import threading
class QueueBuffer():
def __init__(self,size=10):
"""Create a queue buffer. One adds items by calling the put(item) method.
One can wait for new items to be added by using the blocking pop() method
which returns the index and the item that have been added. One can read
items that have been added previously using the read(index) method.
The constructor takes one optional argument, size, which means older items
are deleted."""
self.inbound = Queue() #an internal queue to manage the class properly in a thread safe manner.
self.index = Value('i',0) #index of next item to be added.
self.manager = Manager()
self.buffer = self.manager.list() #the buffer we will store things in.
self.size = size #the maximum size of the buffer
self.newitem = Queue() #a blocking event to control the pop method
t = threading.Thread(target=self.worker) #the worker that will run when items are added.
t.start() #start the worker
self.newitemindex = 0 #index of items to pop
def len(self):
"""Get the number of items that have been added. This doesn't mean they all remain!"""
return self.index.value
def unpopped(self):
"""Return the number of items still to pop"""
return self.newitem.qsize()
def worker(self):
"""
Helper function, internally blocks until an item is added to the internal
queue, this is then added into our buffer, and various indices are sorted.
"""
while True:
item,index = self.inbound.get()
if index is None:
self.buffer.append(item)
self.index.value = self.index.value + 1 #index of next item for buffer
if len(self.buffer)>self.size:
del self.buffer[0]
self.newitem.put(None)
else:
self.buffer[len(self.buffer)+(index - self.index.value)] = item
def put(self,item,index=None):
"""
Add an item to the queue.
"""
self.inbound.put((item,index))
def read(self,getindex):
"""Read item at index getindex. Returns the item. Fails if item no longer exists."""
if getindex<0:
#print("Indicies are non-negative")
return None
try:
bufinx = len(self.buffer)+(getindex - self.index.value)
if bufinx<0:
#print("This item has been deleted, try increasing the queue size")
return None
return self.buffer[bufinx]
except IndexError:
#print("This item doesn't exist yet")
return None
def pop(self):
"""Blocks until a new item is added. Returns the index and the item.
!Item remains in the QueueBuffer, so 'pop' is slightly misleading.
It will return (index,None) if the item has already been lost from the buffer."""
self.newitem.get() #blocks until an item is added, using a queue for this to ensure that only one worker is triggered.
#if self.newitemindex+1==self.index: self.newitem.clear()
index = self.newitemindex
item = self.read(index)
self.newitemindex += 1
return index, item
|
e85970fdb453b4554290f61d7b0ef3ecc7ae0028 | knoixs/Heard_First | /ceshi.py | 1,241 | 3.578125 | 4 | # class A(object):
# def go(self):
# print "go A go!"
#
# def stop(self):
# print "stop A stop!"
#
# def pause(self):
# raise Exception("Not Implemented")
#
#
# class B(A):
# def go(self):
# super(B, self).go()
# print "go B go"
#
#
# class C(A):
# def go(self):
# super(C, self).go()
# print "go C go!"
#
#
# class D(B, C):
# def go(self):
# super(D, self).go()
# print "go D go!"
#
# def stop(self):
# super(D, self).stop()
# print "stop D stop!"
#
# def pause(self):
# print "wait D wait!"
#
#
# class E(B, C):
# pass
#
#
# a = A()
# b = B()
# c = C()
# d = D()
# e = E()
#
# print a.go()
# print b.go()
# print c.go()
# print d.go()
# print e.go()
#
class Node(object):
def __init__(self, sName):
self._lChildren = []
self.sName = sName
def __repr__(self):
return "<Node '{}'>".format(self.sName)
def append(self, *args, **kwargs):
self._lChildren.append(*args, **kwargs)
def print_all_1(self):
print self
for oChild in self._lChildren:
oChild.print_all_1()
def print_all_2(self):
def gen(o):
pass
|
e667b9b82d8e19fbbbe80b48ea77c3ed37d45528 | sathishtammalla/PythonLearning | /Week2/collectionsdemo.py | 8,842 | 4.03125 | 4 | from collections import Counter
colls = ['Write a Python program that takes mylist = ["WA", "CA", "NY"] and add “IL” to the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”] and print the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”] and print position/Index of CA in the list using list index function.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”] and print position/index of each item in the list using list index function.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and sort the list using list sort function.',
'Write a Python program that takes mylist = ["Seattle", "Bellevue", "Redmond", “Issaquah”] and print it using for loop.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”] and print it respective state names (Ex: WA is Washington] for each item in the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times WA appeared in the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times WA and CA appeared in the list.',
'Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times each state appeared in the list.',
'Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print sum of all the items in the list.',
'Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print large number from the list.',
'Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print middle number from the list.',
'Write a Python program that takes mylist = [“CAL”, “SEA”, “PIT”, “CAL”] and print the string that appeared more than once.',
'Write a Python program that takes mylist = [“CAL”, “SEA”, “PIT”, “CAL”] and remove duplicates from the list.',
'Write a Python program that takes mylist = [“CAL”, “SEA”, “PIT”, “CAL”, “POR”, “KEN”, “NJC”] and remove all even items in the list.',
'Write a Python program that takes mylist = [“CALIFORNIA”, “SEATTLE”, “PIT”] and print number of characters in each item in the list.',
'Write a Python program that takes list1 = [“WA”, “CA”] and list2 = [“Washinton”, “California] and create a list3 = [“WA”, “Washington”, “CA”, “California”].',
'Write a Python program that takes mylist = [6, 2, 7, 3, 4, 5] and sort the list ascending without using sort function.',
'Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print second largest number from the list.',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and print the tuple using for loop',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and print first item using index.',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and change first item = “NJ” and print.',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and check if “CA” exists and print.',
'Write a Python program that takes mytuple = ("WA", "CA", "NY") and print length of the tuple.'
]
# print(colls)
print(colls[0])
mylist = ['WA', 'CA', 'NY']
print(f'Items in list : {mylist}')
print("Adding 'IL' to the list")
mylist.append('IL')
print(f'Items in list after adding : {mylist}')
print(colls[1])
print(f'Current Items in mylist : {mylist}')
print(colls[2])
print(f'Index position of "CA" is : {mylist.index("CA")}')
print(colls[3])
for index, value in enumerate(mylist):
print(f'Index : {index} Value : {value}')
print(colls[4])
mylist = ['WA', 'CA', 'NY', 'IL', 'WA', 'CA', 'WA']
print(f'My list is before sorting {mylist}')
mylist.sort()
print(f'The Sorted list is : {mylist}')
print(colls[5])
cities = ["Seattle", "Bellevue", "Redmond", "Issaquah"]
print(f'Cities in the list {cities}')
print('Looping and printing each city')
for c in cities:
print(c)
print(colls[6])
states = ['WA', 'CA', 'NY', 'IL']
st_name = ['Washington', 'California', 'New York', 'Illinois']
print(f'Printing full names of the STATES {states}')
for index, value in zip(states, st_name):
print(f'{index} - {value}')
print(colls[7])
states = ['WA', 'CA', 'NY', 'IL', 'WA', 'CA', 'WA']
print(f'States in the list {states}')
print(f'Count of "WA" in the list {states.count("WA")}')
print(colls[8])
states = ['WA', 'CA', 'NY', 'IL', 'WA', 'CA', 'WA']
print(f'States in the list {states}')
print(f'Count of "WA" and "CA" in the list {states.count("WA")} and {states.count("CA")}')
print(colls[9])
states = ['WA', 'CA', 'NY', 'IL', 'WA', 'CA', 'WA']
print(f'States in the list {states}')
print(f'Count of each element in the list {Counter(states)}')
for key, value in dict(Counter(states)).items():
print(f'State :{key} Count : {value}')
print(colls[10])
l = [1, 2, 3, 4, 5]
print(f'Items in the list {l}')
print(f'Printing sum of all the items : {sum(l)}')
print(colls[11])
l = [1, 2, 3, 4, 5]
print(f'Items in the list {l}')
print(f'Printing largest number in the list : {max(l)}')
print(colls[12])
l = [1, 2, 3, 4, 5]
print(f'Items in the list {l}')
print(f'Printing middle number from the list : {(l[int(len(l) / 2)])}')
print(colls[13])
li = ['CAL', 'SEA', 'PIT', 'CAL', 'SEA']
print(f'Items in list {li}')
print(f'Printing items that appeared more than 1 ')
for key, value in dict(Counter(li)).items():
if value > 1:
print(f'{key} - {value}')
print(colls[14])
li = ['CAL', 'SEA', 'PIT', 'CAL', 'SEA']
print(f'Items in list {li}')
print(f'Printing items after removing duplicates')
for key, value in dict(Counter(li)).items():
print(key)
print('Removing duplicates using set..')
st = set(li)
print(st)
print(colls[15])
states = ['CAL', 'SEA', 'PIT', 'CAL', 'POR', 'KEN', 'NJC']
print(f'Items in the list {states}')
print(f'remove only even items from the list and print')
states = states[1::2]
print(states)
print(colls[16])
li = ['CALIFORNIA', 'SEATTLE', 'PIT']
print(f'Items in the list {li}')
print('Printing Characters in each item of the list')
for i in li:
print(f'Item : {i} No of Chars {len(i)}')
print(colls[17])
list1 = ['WA', 'CA']
list2 = ['Washinton', 'California']
print(f'2 lists {list1} and {list2}')
print('Adding 2 lists')
list3 = list1 + list2
print(f'Items in list 3 after adding {list3}')
print(colls[18])
mylist = [6, 2, 7, 3, 4, 5]
print(f'Items in the list {mylist}')
print('printing items in ascending order without using Sort function')
sort_list = []
for i in range(len(mylist)):
num = min(mylist)
sort_list.append(num)
idx = mylist.index(num)
mylist.pop(idx)
print(sort_list)
print(colls[19])
li = [4, 5, 2, 8, 3, 1]
print(f'Items in the list {li}')
print('printing the second largest item in the list')
print(f'Second largest number in the list {sorted(li)[-2:-1:]}')
print(colls[20])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
print('Printing them one by one')
for i in mytuple:
print(i)
print(colls[20])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
print(f'Printing first item using Index -> {mytuple[0]}')
print(colls[21])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
mytuple = ("NJ",) + mytuple[1::]
print(f'Replacing first item with "NJ" -> {mytuple}')
print(colls[22])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
print(f'Checking if "CA" exists -> {"CA" in mytuple}')
print(colls[23])
mytuple = ('WA', 'CA', 'NY')
print(f'Items in the tuple {mytuple}')
print(f'Printing length of Tuple {len(mytuple)}')
print('Set Exercises.....')
myset = {"NFL", "Cricket", "Baseball"}
print(f'printing set items -- printing without order.... {myset}')
print('Adding "Soccer" to Set ')
myset.add('Soccer')
print(f'printing set items after adding -- printing without order.... {myset}')
print('Using pop to remove item and print which item popped out')
popped = myset.pop()
print(f'Popped out items from set is : {popped}')
print('Set operations...intersect between two sets')
myset1 = {"NFL", "Cricket", "Baseball"}
myset2 = {"NFL", "Cricket", "Soccer"}
myset3 = {"NFL","Cricket"}
print(f' Set 1 {myset1} and set 2 {myset2}')
print(f'Set interset {myset1.intersection(myset2)}')
print(f'Set different 1 minus 2 {myset1.difference(myset2)}')
print(f'Set different 2 minus 1 {myset2.difference(myset1)}')
print(f'Set union {myset2.union(myset1)}')
print(f' Set 1 {myset1} and set 2 {myset3}')
print(f'Set 1 is superset of 3 -> {myset1.issuperset(myset3)}')
|
d9416fcdf18c6288f5c0777de675ae3fcf9f599c | sathishtammalla/PythonLearning | /factorial.py | 1,273 | 4.09375 | 4 | 5# Regular Factorial Function
def factorial(n):
num = n
fact = 1
if n > 900:
print('Number is too big..Enter a number less than 900')
n = 1
while num > 1:
fact = fact * num
num = num - 1
#print(fact)
print('Factorial of ' + str(n) + ' is ' + str(fact))
# Recursive Factorial Function
def rec_fact(n):
return 1 if(n <=1) else (n * rec_fact(n-1))
def check_if_number(n):
try:
n = int(n)
rn = 'Y'
return rn
except:
rn = 'N'
return rn
# Global Infinite Loop....
print('This is a Factorial Program....'+'\n')
while True:
print('Enter a number between 1 and 900 to find a factorial or press x to exit')
entry = input()
if entry == 'x' or entry =='X':
print('Thanks for using Factorial Program.! Hope you found it useful!')
break
#else if
else:
if check_if_number(entry) == 'Y':
#factorial(int(entry))
if int(entry) > 900:
print('Number is too big..Enter a number less than 900')
else:
print('Factorial of '+ entry +' is ' + str(rec_fact(int(entry))))
else:
print("This is not a Valid number..please enter a Positive number")
|
7b3a4e66395735192270abc17f1c77bc8d5ee5bd | newjoseph/Python | /Kakao/String/parentheses.py | 2,587 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# parentheses example
def solution(p):
#print("solution called, p is: " + p + "\n" )
answer = ""
#strings and substrings
#w = ""
u = ""
v = ""
temp_str = ""
rev_str = ""
#number of parentheses
left = 0
right = 0
count = 0
# flag
correct = True;
#step 1
#if p is an empty string, return p;
if len(p) == 0:
#print("empty string!")
return p
# step 2
#count the number of parentheses
for i in range(0, len(p)):
if p[i] == "(" :
left += 1
else:
right += 1
# this is the first case the number of left and right are the same
if left == right:
u = p[0: 2*left]
v = p[2*left:]
#print("u: " + u)
#print("v: " + v)
break
# check this is the correct parenthese ()
for i in range(0, len(u)):
#count the number of "("
if u[i] == "(":
count += 1
# find ")"
else:
# if the first element is not "("
if count == 0 and i == 0 :
#print("u: "+ u +" change to false")
correct = False
break
# reduce the number of counter
count -= 1
if count < 0:
correct = False
break;
else:
continue
"""
for j in range(1, count + 1):
print("i is " + "{}".format(i) + " j is " + "{}".format(j) + " count: " + "{}".format(count) + " lenth of u is " + "{}".format(len(u)))
#
#if u[i+j] == "(" :
if count < 0:
print( " change to false " + "i is " + "{}".format(i) + " j is " + "{}".format(j) + " count: " + "{}".format(count))
correct = False
break
else:
continue
"""
# reset the counter
count = 0
#print( "u: " + u + " v: " + v)
#if the string u is correct
if correct == True:
temp = u + solution(v)
#print(" u is " + u +" CORRECT! and return: " + temp)
return temp
# if the string u is not correct
else:
#print(" u is " + u +" INCORRECT!")
#print("check: " + check)
temp_str = "(" + solution(v) + ")"
# remove the first and the last character
temp_u = u[1:len(u)-1]
# change parentheses from ( to ) and ) to (
for i in range(len(temp_u)):
if temp_u[i] == "(":
rev_str += ")"
else:
rev_str += "("
#print("temp_str: " + temp_str + " rev_str: " + rev_str)
answer = temp_str + rev_str
#print("end! \n")
return answer
|
d17f0a5bc03b4ac03c3c9ed841d221d67866e268 | Rahul-Chaudhary-2301/Tic-Tac-Toe-Python | /Tic_Tac_Toe.py | 982 | 3.640625 | 4 | #Tic Tac Toe
from Player import Player
from UI import UI
from Game import Game
if __name__ == '__main__':
print('Wellcome to X O')
print(' 1] Play with CPU\n 2] Play with Human \n 3]Exit')
opt = int(input('>'))
if opt == 1:
pass
sel = input('Select X / O : ')
if sel == 'X':
Player1 = Player('X')
Computer = Player('O','COMPUTER')
Board = UI()
G = Game(Player1,Computer,Board,mode='C')
G.play()
else:
Player2 = Player('O')
Computer = Player('X','COMPUTER')
Board = UI()
G = Game(Computer,Player2,Board,mode='C')
G.play()
elif opt == 2:
Player1 = Player('X')
Player2 = Player('O')
Board = UI()
G = Game(Player1,Player2,Board,mode='H')
G.play()
elif opt == 3:
exit()
|
40834ff71cc6200a7028bd1d8a7cacf42c9f886e | nicolaetiut/PLPNick | /checkpoint1/sort.py | 2,480 | 4.25 | 4 | """Sort list of dictionaries from file based on the dictionary keys.
The rule for comparing dictionaries between them is:
- if the value of the dictionary with the lowest alphabetic key
is lower than the value of the other dictionary with the lowest
alphabetic key, then the first dictionary is smaller than the
second.
- if the two values specified in the previous rule are equal
reapply the algorithm ignoring the current key.
"""
import sys
def quicksort(l):
"""Quicksort implementation using list comprehensions
>>> quicksort([1, 2, 3])
[1, 2, 3]
>>> quicksort('bac')
['a', 'b', 'c']
>>> quicksort([{'bb': 1, 'aa': 2}, {'ba': 1, 'ab': 2}, {'aa': 1, 'ac': 2}])
[{'aa': 1, 'ac': 2}, {'aa': 2, 'bb': 1}, {'ab': 2, 'ba': 1}]
>>> quicksort([])
[]
"""
if l == []:
return []
else:
pivot = l[0]
sub_list = [list_element for list_element in l[1:]
if list_element < pivot]
lesser = quicksort(sub_list)
sub_list = [list_element for list_element in l[1:]
if list_element >= pivot]
greater = quicksort(sub_list)
return lesser + [pivot] + greater
def sortListFromFile(fileName, outputFileName):
"""Sort list of dictionaries from file. The input is a file containing
the list of dictionaries. Each dictionary key value is specified on
the same line in the form <key> <whitespace> <value>. Each list item
is split by an empty row. The output is a file containing a list of
integers specifying the dictionary list in sorted order. Each integer
identifies a dictionary in the order they were received in the input
file.
>>> sortListFromFile('nonexistentfile','output.txt')
Traceback (most recent call last):
...
IOError: [Errno 2] No such file or directory: 'nonexistentfile'
"""
l = []
with open(fileName, 'r') as f:
elem = {}
for line in f:
if line.strip():
line = line.split()
elem[line[0]] = line[1]
else:
l.append(elem)
elem = {}
l.append(elem)
f.closed
with open(outputFileName, 'w+') as f:
for list_elem in quicksort(l):
f.write(str(l.index(list_elem)) + '\n')
f.closed
if __name__ == "__main__":
if (len(sys.argv) > 1):
sortListFromFile(sys.argv[1], 'output.txt')
else:
print "Please provide an input file as argument."
|
3e6a7cde7bc3639de439ae27c55bf17cc34a5dcd | Michellinian/unit-3 | /snakify_practice/square.py | 92 | 3.921875 | 4 | # A program that takes a number and prints its square
a = int(input())
b = (a ** 2)
print(b) |
532a675840c95eefc4fe9a27f6b5cebe5658bcd7 | Michellinian/unit-3 | /snakify_practice/prevNext.py | 116 | 3.9375 | 4 | # Read the integer numbers and prints its previous and next numbers
num = int(input())
print(num - 1)
print(num + 1) |
235fd1475b420583988d3f61962a2a043b719b5b | Michellinian/unit-3 | /snakify_practice/signFunc.py | 190 | 4.03125 | 4 | # For the given integer X print 1 if it's positive
# -1 if it's negative
# 0 if it's equal to zero
num = int(input())
if num < 0:
print(-1)
elif num == 0:
print(0)
else:
print(1) |
4fe12c2ab9d4892088c5270beb6e2ce5d96debb1 | chapman-cs510-2016f/cw-03-datapanthers | /test_sequences.py | 915 | 4.3125 | 4 | #!/usr/bin/env python
import sequences
# this function imports the sequences.py and tests the fibonacci function to check if it returns the expected list.
def test_fibonacci():
fib_list=sequences.fibonacci(5)
test_list=[1,1,2,3,5]
assert fib_list == test_list
#
### INSTRUCTOR COMMENT:
# It is better to have each assert run in a separate test function. They are really separate tests that way.
# Also, it may be more clear in this case to skip defining so many intermediate variables:
# assert sequences.fibonacci(1) == [1]
#
fib_list=sequences.fibonacci(1)
test_list=[1]
assert fib_list == test_list
fib_list=sequences.fibonacci(10)
test_list=[1,1,2,3,5,8,13,21,34,55]
assert fib_list == test_list
# test to make sure negative input works
fib_list=sequences.fibonacci(-5)
test_list=[1,1,2,3,5]
assert fib_list == test_list
|
1480d01f8e418339339087623e55c93c3a01ee86 | pdtrang/COMP8295-Binf-Algorithm | /suffixarr.py | 712 | 3.546875 | 4 | seq = 'THECATISINTHEHAT'
query = 'IN'
def Search_str(seq,query):
idx = []
for i in range(len(seq)-len(query)+1):
if (query == seq[i:i+len(query)]):
idx.append(i)
return idx
def Search(seq, query):
l, r = 0, len(SA)-1
while l<=r:
mid = (l+r)//2
print(l, mid, r, seq[SA[mid]:])
if seq[SA[mid]:].startswith(query):
return SA[mid]
if query < seq[SA[mid]:]:
r = mid - 1
else:
l = mid + 1
return -1
def BuildSA(seq):
SA = []
for i in range(len(seq)):
SA.append(i)
SA.sort(key=lambda k: seq[k:])
return SA
def PrintSA(SA):
for i in range(len(SA)):
print('%3d %3d %s' %(i, SA[i], seq[SA[i]:]))
SA=BuildSA(seq)
PrintSA(SA)
print("query", query)
print(Search(seq, query))
|
82568658ecaa75070b2bb60c20f49c59c43f0672 | kenguoasd/ichw | /currency.py | 2,559 | 4.09375 | 4 | #!/usr/bin/env python3
"""currency.py:用来进行货币的换算的一个函数
__author__ = "Wenxiang.Guo"
__pkuid__ = "1800011767"
__email__ = "1450527589@qq.com"
"""
from urllib.request import urlopen #如作业说明,在Python中访问URL
a = input() #a为输入的第一个变量
b = input() #b为输入的第二个变量
c = input() #c为输入的第三个变量
def exchange(currency_from, currency_to, amount_from): #定义所需要的exchange函数,括号里为三个变量
"""Returns: amount of currency received in the given exchange.
In this exchange, the user is changing amount_from money in
currency currency_from to the currency currency_to. The value
returned represents the amount in currency currency_to.
The value returned has type float.
Parameter currency_from: the currency on hand
Precondition: currency_from is a string for a valid currency code
Parameter currency_to: the currency to convert to
Precondition: currency_to is a string for a valid currency code
Parameter amount_from: amount of currency to convert
Precondition: amount_from is a float"""
cf = currency_from #把第一个自变量currency_from换成简单的cf
ct = currency_to #把第二个自变量currency_to换成简单的ct
af = amount_from #把第三个自变量amount_from换成简单的af
web = 'http://cs1110.cs.cornell.edu/2016fa/a1server.php?from='+cf+'&to='+ct+'&amt='+af #这是把三个自变量输入到网址中得到一个字符
doc = urlopen(web) #如作业说明所讲访问这个网页
docstr = doc.read() #如作业说明
doc.close() #如作业说明
jstr = docstr.decode('ascii') #通过ascii码进行转化
s = jstr.split(':')[2] #将所得字符串以:分割并取第三部分
q = eval(s)[0] #将所取部分换成列表格式并取第一部分
p = q.split()[0] #将所得到的浮点数+空格+字母按空格分开并提取数字
return(p) #得到所需数字
print(exchange(a,b,c)) #执行函数
def testa():
"""定义一个用来检查exchange函数的函数"""
assert(str(17.13025) == exchange('USD','CNY','2.5')) #判断前后是否相同
def testall():
"""定义一个检查所有的函数(这里就一个)"""
testa() #执行函数testa()
print('It tests passed') #输出字符
testall() #执行testall()
|
c653a9e13975ea2ed34ad45f98c04c07e712e0a8 | Chooo4u/Decision-Tree | /problem3.py | 15,165 | 3.59375 | 4 | import math
import numpy as np
from collections import Counter
#-------------------------------------------------------------------------
'''
Problem 3: Decision Tree (with Descrete Attributes)
In this problem, you will implement the decision tree method for classification problems.
You could test the correctness of your code by typing `nosetests -v test1.py` in the terminal.
'''
#-----------------------------------------------
class Node:
'''
Decision Tree Node (with discrete attributes)
Inputs:
X: the data instances in the node, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the node, p is the number of attributes.
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
i: the index of the attribute being tested in the node, an integer scalar
C: the dictionary of attribute values and children nodes.
Each (key, value) pair represents an attribute value and its corresponding child node.
isleaf: whether or not this node is a leaf node, a boolean scalar
p: the label to be predicted on the node (i.e., most common label in the node).
'''
def __init__(self,X,Y, i=None,C=None, isleaf= False,p=None):
self.X = X
self.Y = Y
self.i = i
self.C= C
self.isleaf = isleaf
self.p = p
#-----------------------------------------------
class Tree(object):
'''
Decision Tree (with discrete attributes).
We are using ID3(Iterative Dichotomiser 3) algorithm. So this decision tree is also called ID3.
'''
#--------------------------
@staticmethod
def entropy(Y):
'''
Compute the entropy of a list of values.
Input:
Y: a list of values, a numpy array of int/float/string values.
Output:
e: the entropy of the list of values, a float scalar
Hint: you could use collections.Counter.
'''
#########################################
## INSERT YOUR CODE HERE
c = Counter()
for y in Y:
c[y] = c[y]+1
list_Y = c.keys()
p_y = []
for y in list_Y:
p_y.append(c[y])
n = sum(p_y)
e = 0
for i in range(len(p_y)):
e += - p_y[i]/n * math.log((p_y[i]/n), 2)
#########################################
return e
#--------------------------
@staticmethod
def conditional_entropy(Y,X):
'''
Compute the conditional entropy of y given x.
Input:
Y: a list of values, a numpy array of int/float/string values.
X: a list of values, a numpy array of int/float/string values.
Output:
ce: the conditional entropy of y given x, a float scalar
'''
#########################################
## INSERT YOUR CODE HERE
cx = Counter(X)
list_X = cx.keys()
p_x = []
for x in list_X:
p_x.append(cx[x])
nx = sum(p_x)
XY = []
for (x, y) in zip(X, Y):
XY.append([x, y])
ce = 0
for x in list_X:
newy = []
for i in range(len(XY)):
if XY[i][0] == x:
newy.append(XY[i][1])
ce += cx[x] / nx * ( Tree.entropy(newy))
#########################################
return ce
#--------------------------
@staticmethod
def information_gain(Y,X):
'''
Compute the information gain of y after spliting over attribute x
Input:
X: a list of values, a numpy array of int/float/string values.
Y: a list of values, a numpy array of int/float/string values.
Output:
g: the information gain of y after spliting over x, a float scalar
'''
#########################################
## INSERT YOUR CODE HERE
g = Tree.entropy(Y) - Tree.conditional_entropy(Y, X)
#########################################
return g
#--------------------------
@staticmethod
def best_attribute(X,Y):
'''
Find the best attribute to split the node.
Here we use information gain to evaluate the attributes.
If there is a tie in the best attributes, select the one with the smallest index.
Input:
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the node, p is the number of attributes.
Y: the class labels, a numpy array of length n. Each element can be int/float/string.
Output:
i: the index of the attribute to split, an integer scalar
'''
#########################################
## INSERT YOUR CODE HERE
glist = []
for i in range(len(X)):
g = Tree.information_gain(X[i,:],Y)
glist.append(g)
i = np.argmax(glist)
#########################################
return i
#--------------------------
@staticmethod
def split(X,Y,i):
'''
Split the node based upon the i-th attribute.
(1) split the matrix X based upon the values in i-th attribute
(2) split the labels Y based upon the values in i-th attribute
(3) build children nodes by assigning a submatrix of X and Y to each node
(4) build the dictionary to combine each value in the i-th attribute with a child node.
Input:
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the node, p is the number of attributes.
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
i: the index of the attribute to split, an integer scalar
Output:
C: the dictionary of attribute values and children nodes.
Each (key, value) pair represents an attribute value and its corresponding child node.
'''
#########################################
## INSERT YOUR CODE HERE
Xi = X[i]
cXi = Counter(Xi)
list_Xi = cXi.keys()
C = {}
for x in list_Xi:
id = []
for j in range(len(X[0])):
if Xi[j] == x:
id.append(j)
# xt = X[:,j].T
# y = Y[j]
# xilist.append(xt)
# ylist.append(y)
# submatX = (np.matrix(xilist)).T
# submatY = np.array(ylist)
submatX = X[:,id]
submatY = Y[id]
C[x] = Node(submatX, submatY)
#########################################
return C
#--------------------------
@staticmethod
def stop1(Y):
'''
Test condition 1 (stop splitting): whether or not all the instances have the same label.
Input:
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
Output:
s: whether or not Conidtion 1 holds, a boolean scalar.
True if all labels are the same. Otherwise, false.
'''
#########################################
## INSERT YOUR CODE HERE
if np.all(Y == Y[0]):
s = True
else:
s = False
#########################################
return s
#--------------------------
@staticmethod
def stop2(X):
'''
Test condition 2 (stop splitting): whether or not all the instances have the same attributes.
Input:
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the node, p is the number of attributes.
Output:
s: whether or not Conidtion 2 holds, a boolean scalar.
'''
#########################################
## INSERT YOUR CODE HERE
if len(X[0]) == 1:
s = True
else:
x = X[:,0]
X2 = np.copy(X)
for j in range(len(X[0])):
X2[:,j] = x
if np.all(X == X2):
s = True
else:
s = False
#########################################
return s
#--------------------------
@staticmethod
def most_common(Y):
'''
Get the most-common label from the list Y.
Input:
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
Here n is the number data instances in the node.
Output:
y: the most common label, a scalar, can be int/float/string.
'''
#########################################
## INSERT YOUR CODE HERE
cY = Counter(Y)
top1 = cY.most_common(1)
y = top1[0][0]
#########################################
return y
#--------------------------
@staticmethod
def build_tree(t):
'''
Recursively build tree nodes.
Input:
t: a node of the decision tree, without the subtree built.
t.X: the feature matrix, a numpy float matrix of shape n by p.
Each element can be int/float/string.
Here n is the number data instances, p is the number of attributes.
t.Y: the class labels of the instances in the node, a numpy array of length n.
t.C: the dictionary of attribute values and children nodes.
Each (key, value) pair represents an attribute value and its corresponding child node.
'''
#########################################
## INSERT YOUR CODE HERE
t.p = Tree.most_common(t.Y)
# if Condition 1 or 2 holds, stop recursion
if Tree.stop1(t.Y) or Tree.stop2(t.X):
t.isleaf = True
t.i = None
t.C = None
return
else:
# t.isleaf = False
# find the best attribute to split
t.i = Tree.best_attribute(t.X, t.Y)
t.C = Tree.split(t.X, t.Y, t.i)
# recursively build subtree on each child node
for leaf in t.C:
Tree.build_tree(t.C[leaf])
#########################################
#--------------------------
@staticmethod
def train(X, Y):
'''
Given a training set, train a decision tree.
Input:
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the training set, p is the number of attributes.
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
Output:
t: the root of the tree.
'''
#########################################
## INSERT YOUR CODE HERE
t = Node(X,Y, i=None,C=None, isleaf= False,p=None)
Tree.build_tree(t)
#########################################
return t
#--------------------------
@staticmethod
def inference(t,x):
'''
Given a decision tree and one data instance, infer the label of the instance recursively.
Input:
t: the root of the tree.
x: the attribute vector, a numpy vectr of shape p.
Each attribute value can be int/float/string.
Output:
y: the class label, a scalar, which can be int/float/string.
'''
#########################################
## INSERT YOUR CODE HERE
# predict label, if the current node is a leaf node
if t.isleaf == True:
y = t.p
pass
else:
children = t.C
if children.get(x[t.i]) == None:
y = t.p
pass
else:
y = Tree.inference(children[x[t.i]],x)
#########################################
return y
#--------------------------
@staticmethod
def predict(t,X):
'''
Given a decision tree and a dataset, predict the labels on the dataset.
Input:
t: the root of the tree.
X: the feature matrix, a numpy matrix of shape p by n.
Each element can be int/float/string.
Here n is the number data instances in the dataset, p is the number of attributes.
Output:
Y: the class labels, a numpy array of length n.
Each element can be int/float/string.
'''
#########################################
## INSERT YOUR CODE HERE
# Y = np.empty(shape=(len(X[0])), dtype = 'str')
Y = []
for j in range(len(X[0])):
y = Tree.inference(t,X[:,j])
Y.append(y)
Y = np.array(Y)
#########################################
return Y
#--------------------------
@staticmethod
def load_dataset(filename='data1.csv'):
'''
Load dataset 1 from the CSV file: 'data1.csv'.
The first row of the file is the header (including the names of the attributes)
In the remaining rows, each row represents one data instance.
The first column of the file is the label to be predicted.
In remaining columns, each column represents an attribute.
Input:
filename: the filename of the dataset, a string.
Output:
X: the feature matrix, a numpy matrix of shape p by n.
Each element is a string.
Here n is the number data instances in the dataset, p is the number of attributes.
Y: the class labels, a numpy array of length n.
Each element is a string.
Note: Here you can assume the data type is always str.
'''
#########################################
## INSERT YOUR CODE HERE
file = np.loadtxt(filename, dtype = str, delimiter = ',')
Y = file[1:,0]
X = file[1:,1:].T
#########################################
return X,Y
|
0bfc113811d704a2aad0b1698df54706fd8e8cb0 | ruifgomes/exercises | /numeros_10-20.py | 405 | 4 | 4 | #numeros de 10 a 20
#for sequencia in range(10,20):
# print(sequencia)
resultado = float(input("Insira o seu resultado: "))
if 0 >= resultado or resultado >= 20:
print("Resultado invalido")
elif resultado <= 10:
print("Insulficiente :( ")
elif resultado <= 14:
print("Bom :| ")
elif resultado >14:
print("Muito Bom :D ")
# print("Resultado de teste não correto")
|
f6f19b9d52b40d3f2f560d70864f669ca4da5df0 | vdaytona/UNSWResearch | /Fitting/FittingPowerSearchingMethod.py | 3,209 | 3.640625 | 4 | '''
Created on 15 Nov 2016
to fit the curve using power search method
@author: vdaytona
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from sklearn.metrics import r2_score
# 1. read in data
rawData = pd.read_csv(".\Data\data.csv", header = None)
x_data = rawData[0].values
x_data = [float(x) for x in x_data]
y_data = rawData[1].values
#weight_data = rawData[2].values
def func1(x,a,b,c,d):
return a + b * np.exp(-np.power((x/c),d))
def square_score_func1(x,y,a,b,c,d):
y_predict = []
for x_value in x:
y_predict.append(func1(x_value, a, b, c, d))
square_score_fitted = r2_score(y,y_predict)
#print square_score_fitted
return square_score_fitted
def drange(start, stop, step):
r = start
while r < stop:
yield r
r += step
if __name__ == '__main__':
# 2. Preprocess if necessary
# 3. set the function and search range and interval of parameter
# function: a + b * exp(-(x/c)^d)
a_start = 0.00025
a_end = 0.00035
a_interval = 0.000005
a = [x for x in drange(a_start, a_end, a_interval)]
b_start = 0.0004
b_end = 0.0005
b_interval = 0.000005
b = [x for x in drange(b_start, b_end, b_interval)]
c_start = 1500
c_end = 3000
c_interval = 20
c = [x for x in drange(c_start, c_end, c_interval)]
d_start = 0.34
d_end = 0.44
d_interval = 0.01
d = [x for x in drange(d_start, d_end, d_interval)]
# 4. calculate the best combination due to correlation coefficient
loop = len(a) * len(b) * len(c) * len(d)
print loop
result = []
loop_now = 0
for a_value in a:
for b_value in b:
for c_value in c:
for d_value in d:
r2_square_fiited = square_score_func1(x_data,y_data,a_value,b_value,c_value,d_value )
result.append((a_value,b_value,c_value,d_value,r2_square_fiited))
loop_now +=1
print (str(loop) + " in all, now is " + str(loop_now) + " the r2_square is " + str(r2_square_fiited) + " , finished " + str(float(loop_now) / float(loop) * 100) + " percent ")
result_sorted = sorted(result, key = lambda result : result[4],reverse=True)
# 5. output the best 10000 result and all result
result_pd = pd.DataFrame(data=result_sorted)
timeNow = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
fileName_best = './Result/' + timeNow + '_FittingPowerSearch_best' + '.csv'
fileName_all = './Result/' + timeNow + '_FittingPowerSearch' + '.csv'
result_pd[0:20000].to_csv(fileName_best,header = None)
#result_pd.to_csv(fileName_all,header = None)
#result_pd = pd.to_csv
# 6. Draw the best result of fitting
#y_fit = []
#for x_value in x_data:
# y_fit.append(func1(x_value, result_sorted[0][0], result_sorted[0][1], result_sorted[0][2], result_sorted[0][3]))
#print result_sorted[0]
#print y_fit
#print y_data
#plt.plot(x_data, y_data)
#plt.plot(x_data,y_fit)
#plt.show() |
32531f0772951f2fd6642fe775445c7c29cc266e | vsevolodzakk/alien_invasion | /alien_game/ship.py | 1,996 | 3.734375 | 4 | import pygame
from pygame.sprite import Sprite
class Ship():
def __init__(self, game_settings, screen):
"""Инициирует корабль и задает его начальную позицию"""
self.screen = screen
self.game_settings = game_settings
# Загрузка изображения корабля
self.image = pygame.image.load('images/rocket.png')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
#
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
#Saving ship center coordiantes
self.center = float(self.rect.centerx)
#Movement flag
self.moving_right = False
self.moving_left = False
def update(self):
"""Updates position according to flag state"""
if self.moving_right and self.rect.right < self.screen_rect.right:
self.center += self.game_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
self.center -= self.game_settings.ship_speed_factor
self.rect.centerx = self.center
def blitme(self):
"""Рисует кораблю в текущей позиции"""
self.screen.blit(self.image, self.rect)
class Bullet(Sprite):
def __init__(self, game_settings, screen, ship):
"""Bullet object appears"""
super().__init__()
self.screen = screen
#Bullet creation in (0,0) position
self.rect = pygame.Rect(0, 0, game_settings.bullet_width, game_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
#Bullet center coordiantes
self.y = float(self.rect.y)
self.color = game_settings.bullet_color
self.speed = game_settings.bullet_speed
def update(self):
"""Translate bullet on the screen"""
#Bullet position update in float
self.y -= self.speed
#Rect position update
self.rect.y = self.y
def draw_bullet(self):
"""Bullet on the screen"""
pygame.draw.rect(self.screen, self.color, self.rect) |
d109b9b4d0728b734b104b99d3d9ae19e6a4bf26 | msg4rajesh/Building-Data-Science-Applications-with-FastAPI | /chapter2/chapter2_list_comprehensions_02.py | 189 | 3.515625 | 4 | from random import randint, seed
seed(10) # Set random seed to make examples reproducible
random_elements = [randint(1, 10) for i in range(5)]
print(random_elements) # [10, 1, 7, 8, 10]
|
c5ba4eb1584f0a92159ac2930bb899e45d45651d | msg4rajesh/Building-Data-Science-Applications-with-FastAPI | /chapter11/chapter11_compare_operations.py | 366 | 3.65625 | 4 | import numpy as np
np.random.seed(0) # Set the random seed to make examples reproducible
m = np.random.randint(10, size=1000000) # An array with a million of elements
def standard_double(array):
output = np.empty(array.size)
for i in range(array.size):
output[i] = array[i] * 2
return output
def numpy_double(array):
return array * 2
|
eb0c93ebd736a18a087959cfd68d713e07a965a2 | msg4rajesh/Building-Data-Science-Applications-with-FastAPI | /chapter4/chapter4_standard_field_types_01.py | 230 | 3.515625 | 4 | from pydantic import BaseModel
class Person(BaseModel):
first_name: str
last_name: str
age: int
person = Person(first_name="John", last_name="Doe", age=30)
print(person) # first_name='John' last_name='Doe' age=30
|
4f053e59411e550fde83e90311951c77f0143a0d | jackgoode123/variables | /what is your name.py | 160 | 3.875 | 4 | #jackgoode
#09-09-2014
#what is your name
first_name = input ("please enter your first name: ")
print (first_name)
print ("hi {0}!".format(first_name))
|
ddd45e09f38821920c652af1a89b10c607674806 | cem05/108 | /unique_conversionround.py | 1,186 | 4.03125 | 4 | #unique conversion problem, something different
#Currency Conversion to Euros from US Dollars
#1 EURO (EUR) = 1.2043 U.S. dollar (USD)
#from https://www.wellsfargo.com/foreign-exchange/currency-rates/ on 10/23/2018
print('This program can be used to convert to Euros from US Dollars.')
print('The exchage rate was taken from https://www.wellsfargo.com/foreign-exchange/currency-rates/ on 10/03/2018, and was 1 EURO (EUR) = 1.2187 U.S. dollar (USD)')
Euro = 1
USD = 1.2043
print('\n')
usd_exchanged = input('Enter amount of whole dollars to be converted: ')
usd_exchanged = int(usd_exchanged)
euro_received = usd_exchanged//USD
print('You receive',int(round(euro_received)),'Euros, rounded down to the nearest Euro, as we only convert to whole Euros.')
#conversion fee from WellsFargo is 7$ flat fee if converting under 1000 USD
#and free at or above 1000 USD and over free
print('The conversion fee from WellsFargo is 7$ flat fee if converting under 1000 USD and free at or above 1000 USD')
if usd_exchanged >= 1000: print('You owe Wells Fargo',(usd_exchanged),'dollars.')
if usd_exchanged < 1000: print('You owe Wells Fargo',(usd_exchanged + 7),'dollars.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.