blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a4914ff88648056203b5dbc002212033e663c1d2 | AlexUrtubia/ordenamiento-py | /bubble/bubble-sort.py | 1,418 | 3.984375 | 4 | arr = [8,5,2,6,9,3,1,4,0,7]
def bubblesort(lista):
contador = 0
#print("Orden original :",lista)
for j in range (len(lista)-1):
# print("\n","-"*60,"\nIteración número n",j,"(Desde",lista[0],"hasta",lista[len(lista)-1-j],")")
for i in range (len(lista)-1-j): # Al colocar "-j", estoy indicando que revise desde el anterior al último número,
# pues ese siempre será el número más grande bajo la priemra iteración
contador += 1
#print("\n","*"*80,"\nindex",i,"valor",lista[i])
# print("\n","*"*80,"\ncomparando ",lista[i],"con",lista[i+1])
if lista[i] > lista[i+1]:
lista[i],lista[i+1]=lista[i+1],lista[i]
# print(lista[i+1],"Es mayor que " ,lista[i])
# print("Se cambia ",lista[i],"por -->",lista[i+1])
# print("El arreglo ahora queda así :",lista)
# else:
# print("No se cambia porque ",lista[i+1],"no es mayor que",lista[i])
# print("\nLista al final de esta iteración: ",lista)
#print("\n","-"*80,"\nLista final :",lista)
print("Cantidad de evaluaciones :",contador) # sin "j" en (len(lista)-1-j), en el segundo for,
#la cantidad de evaluaciones casi se duplica, esto consume muchos más recrusos
return(lista)
print(bubblesort(arr)) |
289890765775d8902825ad2f61a7145ef89f254c | SokolovAM/cardgame | /Drunkard.py | 3,130 | 3.6875 | 4 | # Card game "Drunkard"
class Card:
suits=['spades','hearts','diamands','clubs']
values=[None,None,'2','3',
'4','5','6','7','8','9','10',
'Jack','Queen','King','Ace']
def __init__(self,v,s):
"""suit & values - integers"""
self.value = v
self.suit = s
def __lt__(self,c2):
if self.value < c2.value:
return True
if self.value == c2.value:
if self.suit < c2.suit:
return True
else:
return False
return False
def __gt__(self,c2):
if self.value > c2.value:
return True
if self.value == c2.value:
if self.suit > c2.suit:
return True
else:
return False
return False
def __repr__(self):
#Give value and suit of the card
v = self.values[self.value] + ' of ' + self.suits[self.suit]
return v
from random import shuffle
class Deck:
#Deck forming
def __init__(self):
self.cards=[]
for i in range(2,15):
for j in range(4):
self.cards.append(Card(i, j))
shuffle(self.cards)
def rm_card(self):
#Remove card from deck
if len(self.cards) == 0:
return
return self.cards.pop()
class Player:
#Player's status
def __init__(self,name):
self.name = name
self.wins = 0
self.card = None
class Game:
def __init__(self):
name1 = input('Input the name of first player: ')
name2 = input('Input the name of second player: ')
self.deck=Deck()
self.p1 = Player(name1)
self.p2 = Player(name2)
def wins(self,winner):
w = "{} taking the card".format(winner)
return w
def draw(self, p1n, p2n,p1c, p2c):
d = "{} putting {}\n{} putting {}".format(p1n,p1c,p2n,p2c)
print(d)
def gameplay(self):
cards=self.deck.cards
print('Start game!')
while len(cards) >= 2:
msg = 'Press X to exit, press any other button to start the game: '
res = input(msg)
if res.upper() == 'X':
break
p1c = self.deck.rm_card()
p2c = self.deck.rm_card()
p1n = self.p1.name
p2n = self.p2.name
self.draw(p1n, p2n,p1c, p2c)
if p1c > p2c:
self.p1.wins +=1
self.wins(p1n)
else:
self.p2.wins +=1
self.wins(p2n)
win = self.winner(self.p1, self.p2)
print('-'*50)
print('{} wins: {}'.format(p1n,self.p1.wins))
print('{} wins: {}'.format(p2n,self.p2.wins))
print("Game over! {}".format(win))
def winner(self, p1, p2):
if p1.wins > p2.wins:
return p1.name + ' is winner!'
if p1.wins < p2.wins:
return p2.name + ' is winner!'
return "Draw!"
game = Game()
game.gameplay()
|
6f75090e24993f2d59d06c3988cbf63052aa5795 | adamchalmers/eliot_quantified_health | /raw_generator.py | 8,332 | 3.578125 | 4 | import datetime
import os
import subprocess
import string
from collections import defaultdict
"""
This generates a .html file with a visualization of data from a .csv file.
This file MUST be placed in the same folder as "data.csv"
"""
# These are the config parameters. Change them if you're using a different CSV structure.
INPUT_FOLDER = "raw_data" # contains csv files
OUTPUT_FOLDER = "output" # will contain the output website
DATA_FIELDS_NUMBER = [1, 2, 3] # measurement fields which are numbers
DATA_FIELDS_ENUM = [8] # fields whose value is an enumerated set of strings, e.g. sleep.
HTML_HEADER = "<html><head><title>Visualizing your body</title><style>body {font-family: sans-serif;}</style></head><body>"
def read_data(f, col):
"""Yields (date, minute, measurement) 3tuples.
Measurement is some recorded value, e.g. body heat, air measurement etc."""
with open(f) as input_file:
input_file.readline()
i = 0
try:
# 'line' will typically look like:
# 2015-04-01 23:58:00,94.1,92.8,56,0,5.41,1.0,,deep,
for line in input_file:
fields = line.split(",")
# If the field starts with letters, assume it's string data.
# Otherwise try to make it a number
# Otherwise turn it into -1
if len(fields[col]) > 0 and fields[col][0] in string.letters:
measurement = fields[col]
else:
try:
measurement = float(fields[col])
except ValueError:
measurement = -1
# Find the date/time this row takes place in
entry_date, entry_time = fields[0].split(" ")
year, month, day = map(int, entry_date.split("-"))
hour, minute, second = map(int, entry_time.split(":"))
# Calculate the date and which minute of the day it is.
minute_num = hour*60 + minute
try:
date = datetime.datetime(year, month, day)
except ValueError as e:
print day, month, year
print
print
raise e
i += 1
yield (date, minute_num, measurement)
except Exception as e:
print "(Line %d) %s in file %s" % (i, str(e), f)
raise e
def group_by_day_numbers(input_files, col):
"""Returns a dictionary where the date is a key, and the value is a list of (minute_num, measurement) pairs."""
days = defaultdict(list)
min_measurement = 999
max_measurement = 0
for f in input_files:
for line in read_data(f, col):
date, minute_num, measurement = line
days[date].append((minute_num, measurement))
if measurement > 0 and measurement > max_measurement:
max_measurement = measurement
if measurement > 0 and measurement < min_measurement:
min_measurement = measurement
return days, min_measurement, max_measurement
def group_by_day_enums(input_files, col):
"""Dictionary of (date, value) pairs. Value is a string. Don't look for min/max."""
days = defaultdict(list)
for f in input_files:
for line in read_data(f, col):
date, minute_num, measurement = line
days[date].append((minute_num, measurement))
return days
def html_numbers(input_files, title, col):
"""Generates an HTML table containing numeric data from all input files."""
yield "<h1>%s</h1><table style='border-spacing: 0; white-space:nowrap;'>\n" % title
days, min_measurement, max_measurement = group_by_day_numbers(input_files, col)
for day in sorted(days):
# Strip out just the important part of the date
daystr = str(day)[:10]
yield "<tr><td>%s</td>" % daystr
# Each minute becomes one cell in the table, colored according to measurement.
for minute, measurement in days[day]:
if measurement > -1:
measurement = color_map(min_measurement, max_measurement, measurement)
color = "rgb(%d,0,%d)" % (measurement, 255-measurement)
else:
color = "rgb(0,0,0)"
yield "<td style='background-color:%s;'>" % color
yield "</tr>"
yield "</table>"
# Output a legend showing which values have which color
yield "<br><h2>Legend</h2><table><tr>"
yield "<td style='background-color: rgb(0,0,0); color: white'>Data missing</td>"
yield key_row(min_measurement, max_measurement, min_measurement)
yield key_row(min_measurement, max_measurement, (min_measurement*0.75 + max_measurement*0.25))
yield key_row(min_measurement, max_measurement, (min_measurement + max_measurement) / 2)
yield key_row(min_measurement, max_measurement, (min_measurement*0.25 + max_measurement*0.75))
yield key_row(min_measurement, max_measurement, max_measurement)
yield "</tr></table>"
def html_enums(input_files, title, col):
"""Generates an HTML table containing the enumerated string data from all input files."""
legend = {"rem": "#33CCFF",
"light": "#3399FF",
"deep": "#3366FF",
"unknown": "#8c8c8c",
"interruption": "#0f0",
"": "#aaa",
-1: "#000",
}
yield "<h1>Visualizing dataset '%s'</h1><table style='border-spacing: 0; white-space:nowrap;'>\n" % title
days = group_by_day_enums(input_files, col)
for day in sorted(days):
# Strip out just the important part of the date
daystr = str(day)[:10]
yield "<tr><td>%s</td>" % daystr
# Each minute becomes one cell in the table, colored according to measurement.
for minute, measurement in days[day]:
yield "<td style='background-color:%s;'>" % legend[measurement]
yield "</tr>"
yield "</table>"
yield "<br><h2>Legend</h2><table><tr>"
# Output a legend showing which values have which color
for measurement, color in legend.items():
yield "<td style='background-color: %s; color: white'>%s</td>" % (color, measurement)
yield "</tr></table>"
def key_row(l, h, measurement):
"""Outputs a legend cell for a numeric measurement, showing what color measurements of that value have."""
return "<td style='background-color: rgb(%d,0,%d); color: white'>%s F</td>" % (color_map(l, h, measurement), 255-color_map(l, h, measurement), measurement)
def color_map(l, h, n):
"""Given a value n in the range [l,h],
map n to its corresponding value in the range [0,255].
"""
return (n - l)/(h-l) * 255
def make_index(headers):
# Make the main index file, which links to the individual dataset files.
index_file = "%s/index.html" % OUTPUT_FOLDER
# Overwrite the index file:
with open(index_file, "w") as out:
out.write(HTML_HEADER)
out.write("<h1>Datasets available:</h1><select>")
out.write("<option value='-'>-</option>")
# Add a link to each dataset page:
with open(index_file, "a") as out:
for col in DATA_FIELDS_ENUM + DATA_FIELDS_NUMBER:
title = headers[col]
out.write("<option value='%s'>%s</option>" % (title, title))
out.write("</select><script src='script.js'></script>")
out.write("<p><a id='dataset'></a><p><iframe src='' width='900' height='600'><p>Your browser does not support iframes.</p></iframe>")
out.write("</body></html>")
def visualize():
# Find all files in the input directory
print "Reading files from %s..." % INPUT_FOLDER
files = ["%s/%s" % (INPUT_FOLDER, f) for f in os.listdir(INPUT_FOLDER)]
print "Reading %d fields across %d files..." % ((len(DATA_FIELDS_ENUM) + len(DATA_FIELDS_NUMBER)), len(files))
# Get the column headers from one of the files
with open(files[0]) as f:
headers = f.readline().split(",")
# Write the HTML to the output files.
lines_out = 0
for cols, fn in [(DATA_FIELDS_NUMBER, html_numbers), (DATA_FIELDS_ENUM, html_enums)]:
# For each column, create a file that shows that column's dataset across all input data files.
for col in cols:
# Clear the output file
filename = "%s/%s.html" % (OUTPUT_FOLDER, headers[col])
with open(filename, "w") as out:
out.write(HTML_HEADER)
# Write the dataset table
with open(filename, "a") as out:
# Write a row to the table. Rows are taken from all days.
for string in fn(files, headers[col], col):
out.write(string)
lines_out += 1
if lines_out % 10000 == 0:
print "Writing line %d" % lines_out
out.write("</body></html>")
print "Output to %s." % filename
make_index(headers)
if __name__ == "__main__":
visualize()
|
930769a7763c346dbb9b1a4723146a7e5aadec0b | asalex04/11_duplicates | /duplicates.py | 1,586 | 3.515625 | 4 | import os
import hashlib
import argparse
import collections
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
'path',
help='path to root directory'
)
return parser
def get_duplicates(dir_path):
filenames_with_pathes_dict = collections.defaultdict(list)
for root, dirs, file_names in os.walk(dir_path):
for filename in file_names:
fullpath = os.path.join(root, filename)
file_hash = get_file_hash_md5(fullpath)
filenames_with_pathes_dict[file_hash].append(fullpath)
return filenames_with_pathes_dict
def get_file_hash_md5(file_for_hash):
hasher = hashlib.md5()
blocksize = 1024 * 1024
with open(file_for_hash, 'rb') as file:
buff = file.read(blocksize)
hasher.update(buff)
return hasher.hexdigest()
def print_path_duplicate_file(files_duplicates):
print('Scanning... {}'.format(files_duplicates))
for _, list_of_duplicates in files_hash_and_path_dict.items():
if len(list_of_duplicates) > 1:
print('\nDuplicates:')
print('\n'.join(list_of_duplicates))
if __name__ == '__main__':
parser = get_parser()
list_of_filepaths = parser.parse_args().path
if os.path.isdir(list_of_filepaths):
files_hash_and_path_dict = get_duplicates(list_of_filepaths)
if files_hash_and_path_dict:
print_path_duplicate_file(list_of_filepaths)
else:
print('Nothing found in {}'.format(list_of_filepaths))
else:
print('Enter existing directory')
|
2719ae133af19405f7e3d048695f861129ea5d97 | nicollebanos/Programacion | /Clases/listas.py | 1,693 | 4.21875 | 4 |
nombres = ['Santy','Samu','Aleja','Dani']
print(nombres)
print(nombres[2])
nombres.append('Mauricio')
print(nombres)
print(nombres[2])
edades = [18, 19, 20, 17,32, 12, 15, 13]
estaturas = [1.62, 1.80, 1,67, 1.89]
# al último
print(edades[-2])
print(edades[0:2])
print(edades[:3])
print(edades[2:])
print(edades[:])
#Orden
edades.sort()
print(edades)
edades.sort(reverse=True)
print(edades)
#mayor y menor de la lista
mayor = max(edades)
print(mayor)
menor = min(edades)
print(menor)
#como contamos cuantos elementos hay?
largoListaEdades = len(edades)
print(largoListaEdades)
#como contamos cuantos elementos hay?
largoListaNombres = len(nombres)
print(largoListaNombres)
#Como sumamos elementos?
sumaEdades = sum(edades)
print(sumaEdades)
#Como calculo el promedio
promedioEdades = sumaEdades/largoListaEdades
print(promedioEdades)
#eliminar un elemento
edades.pop(2)
print(edades)
#nombres --> ciclo for y las listas
largoListaEdades = len(edades)
for indice in range (largoListaEdades):
print(edades[indice])
#listado nombres largo
largoListaEdades = len(nombres)
for indice in range (largoListaNombres):
print(nombres[indice])
#posiciones lista par
posicionesPares = []
largoListaEdades = len(edades)
for posicion in range (largoListaEdades):
if(edades[posicion]%2 == 0):
posicionesPares.append(posicion)
print(edades)
print(posicionesPares)
#solo cuando nos interese mostrar la lista
for edad in edades:
print(edad)
for nombre in nombres:
print(nombre)
print(posicion)
posicion+=1
posicion = 0
posicionesPares = []
for edad in edades:
if(edad%2 == 0):
posicionesPares.append(posicion)
posicion+=1
print(posicionesPares)
|
294165904c563f79a9207ecf9aae40eb35de0dff | deanantonic/exercises | /zhiwehu/q14.py | 559 | 3.953125 | 4 | """
Question 14
Level 2
Question:
Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
"""
seq = raw_input("Enter a sentence containing uppercase and lowercase letters:")
print "UPPER CASE", sum(c.isupper() for c in seq)
print "LOWER CASE", sum(c.islower() for c in seq)
|
05a5bc5093d9fe8b60042b422cb74073065937eb | muru4a/python | /reverse_integer.py | 279 | 3.65625 | 4 | #reverse interger
def reverse1(s):
if s < 0:
return -reverse(-s)
result=0
while (s>0):
result=result*10+s%10
s//=10
return result if result <= 0x7fffffff else 0
if __name__ == "__main__":
print(reverse(121))
print(reverse1(456))
|
551827fa90839d534ee75975a12dbb39ccc98f32 | Administrator859/Countdown-GUI | /count.py | 626 | 3.78125 | 4 | from tkinter import *
t = 0
def set_timer():
global t
t = t+int(e1.get())
return t
def countdown():
global t
if t > 0:
l1.config(text=t)
t = t-1
l1.after(1000, countdown)
elif t==0:
print("end")
l1.config(text="Goo")
root = Tk()
root.geometry("180x150")
l1 = Label(root, font="times 20")
l1.grid(row=1, column=2)
times = StringVar()
e1 = Entry(root, textvariable=times)
e1.grid(row=3, column=2)
b1 = Button(root, text="SET", width=20, command=set_timer)
b1.grid(row=4, column=2, padx=20)
b2 = Button(root, text="START", width=20, command=countdown)
b2.grid(row=6, column=2, padx=20)
root.mainloop()
|
484a8fdf6cbedf1d97112f44cc84b02cc75ae7ad | adityachhajer/CST_JIET_Assignments | /Aditya_Chhajer/13may2020/3.py | 293 | 3.90625 | 4 | def gcd(a, b):
if (a == 0):
return b
if (b == 0):
return a
if (a == b):
return a
if (a > b):
return gcd(a - b, b)
return gcd(a, b - a)
a=int(input())
b=int(input())
print("gcd: ",gcd(a,b))
print("lcm is:",(a*b) / gcd(a,b)) |
af70a32360e0a630988d6ec0ef59aa9c5012365e | pjok1122/Interview_Question_for_Beginner | /DataStructure/codes/max_heap.py | 1,671 | 3.625 | 4 | SIZE = 1024
class heap:
def __init__(self):
self.list = [-1]*SIZE
self.len = 0
def push(self, val):
self.len += 1
self.list[self.len] = val
index = self.len
while index//2:
if self.list[index] > self.list[index//2]:
self.list[index], self.list[index //
2] = self.list[index//2], self.list[index]
index = index//2
else:
break
def pop(self):
value = self.list[1]
self.list[1] = self.list[self.len]
self.list[self.len] = -1
self.len -= 1
self.heapify()
return value
def heapify(self):
max_pos = 1
max_val = self.list[1]
parent = 1
while 2*parent <= self.len:
left_child = 2*parent
right_child = 2*parent + 1
if(left_child <= self.len and max_val < self.list[left_child]):
max_pos = left_child
max_val = self.list[left_child]
if(right_child <= self.len and max_val < self.list[right_child]):
max_pos = right_child
max_val = self.list[right_child]
if(parent == max_pos):
break
self.list[max_pos] = self.list[parent]
self.list[parent] = max_val
parent = max_pos
def get_all_items(self):
print(self.list[1:self.len+1])
h = heap()
h.push(-8)
h.push(-2)
h.push(-5)
h.push(-3)
h.push(-1)
h.get_all_items()
print(h.pop())
# h.get_all_items()
print(h.pop())
print(h.pop())
print(h.pop())
print(h.pop())
# print(h.pop())
|
7677ccf0294d4d9c0583a5e55ea8a0130cbfdd7f | deb91049/leetcode | /盛最多水的容器/solution.py | 893 | 3.53125 | 4 | # 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
#
# 说明:你不能倾斜容器。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/container-with-most-water
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def maxArea(self, height: List[int]) -> int:
i, j, res = 0, len(height) - 1, 0
while i < j:
if height[i] < height[j]:
res = max(res, height[i] * (j - i))
i += 1
else:
res = max(res, height[j] * (j - i))
j -= 1
return res
|
ce610be1f371fe02b7e89c0e926b20f0b0fcbc4d | Bahram3110/d11_w3_t1 | /task4.py | 184 | 3.640625 | 4 | dict_ = {'a': 6, 'b': 3, 'c': 10}
test_dict = {key:'Foo'if value%3==0 else 'Bar' if value%5==0 else "none" for key,value in dict_.items()if value%3==0 or value%5==0}
print(test_dict) |
43645f5ab668731f2909b37094dfb3801bdeef69 | LucasMonteiroi/python-course | /exercises/dictionaries.py | 671 | 4.03125 | 4 | # We will use dictonaries and some methods
person = {'name': 'Lucas', 'age': 27, 'country':'Brazil'}
print('Person: ' + str(person))
print('Person Keys: ' + str(person.keys()))
print('Person Values: ' + str(list(person.items())))
print()
print('Formated values')
print()
for k, v in person.items() :
print(str(k) + ': ' + str(v))
print()
print('Search values')
print()
if 'name' in person :
print('Field name found in person with value: ' + person['name'])
print('Age found in person with value: ' + str(person.get('age', 0)))
print('Hello my name is ' + str(person['name']) + ', with ' + str(person['age']) + ' old and I am from ' + str(person['country']))
|
35d666bfcb06cc2836fe0dd184227fb84f763b1c | xiaolinzi-xl/Play-Leetcode-Explore | /algorithm/primary_algorithm/array/leetcode_217.py | 219 | 3.65625 | 4 | class Solution:
def containsDuplicate(self, nums):
duplicate = set()
for ele in nums:
if ele in duplicate:
return True
duplicate.add(ele)
return False
|
d96634989ab1c28f5154087cc88ca21869a293f3 | raphoshi/Microlon | /Games/Modulo-01/Python/04-Loops/Exercicio de input e outros comandos.py | 937 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# Crie um código onde o usuário entre com:
# Nome:
# Senha:
# A mensagem sugira se o nome e a senha forem iguais
#
# In[ ]:
nome = input ("Qual o seu nome? ")
senha = input ("Insira uma senha ")
while nome == senha:
print ("Nome de usuário e senha são iguais")
senha = input ("Insira uma nova senha: ")
# In[ ]:
nome = input ("Qual o seu nome? ")
senha = input ("Insira uma senha ")
if nome == senha:
print ("Nome de usuário e senha são iguais")
else:
print ("Usuário criado com sucesso")
# In[ ]:
nome = input ("Qual o seu nome? ")
senha = input ("Insira uma senha ")
for cadastro in nome == senha:
print ("Nome de usuário e senha são iguais")
# In[2]:
nome = input ("Qual o seu nome? ")
senha = input ("Insira uma senha ")
if nome == senha:
print ("Nome de usuário e senha são iguais")
else:
print ("Usuário criado com sucesso")
# In[ ]:
|
abc2a57d310a0e1f242551f7af79f17b34535ff7 | eyasyasir/COMP208 | /Assignment 2/parentheses.py | 2,639 | 4.3125 | 4 | # Author: [Eyas Hassan]
# Assignment 1, Question 2
def find_first(s, letter): #function which searches for first parenthesis '(' from left of string
for i in range(len(s)): #for loop evaluates every characte in string 's' and compares it to variable 'letter', if true, the index at which the condition is true is returned (i.e position of '(')
if s[i] == letter:
return i
return None #if there are no paranthesis in the string, none is returned
def find_last(s, letter): #function which searches for last parenthesis ')' from left of string
i = -1
while i >= (- len(s)): #while loop evaluates every characte in string 's' and compares it to variable 'letter', if true, the index at which the condition is true is returned (i.e position of ')')
if s[i] == letter:
return i
i = i - 1
return None #if there are no paranthesis in the string, none is returned
def get_comma_phrase(s): #funtion which replaces '(' with ',' and removes ')' from string 's'
letter = "(" #setting variable 'letter' to string '(' in order to call function 'find_first()'
a = find_first(s, letter) #function 'find_first()' is called with parameters 's' and 'letter', assigned to variable 'a'
letter = ")" #setting variable 'letter' to string ')' in order to call function 'find_first()'
b = find_last(s, letter) #function 'find_last()' is called with parameters 's' and 'letter', assigned to variable 'b'
phrase = s[a + 1 : b] #string slicing on 's' to give segment of string 's' between '(' and ')', assigned to variable ' phrase
phrase = "{}".format(",") + phrase #'.format()' method is used to insert ',' in the beginning of 'phrase', assigned to variable 'phrase'
s = s[ : a] + phrase #altered segment of 's' ('phrase') is added to unaltered segment of 's', assigned to variable 's'
return s #function returns value of 's'
def get_comma_string(s): #function which counts how many paranthesis pairs exist in 's' and calls fucntion 'get_comma_phrase()' the required number of times
counter = 0
for parenthesis in range(len(s)): #iterating through every character in string 's'
if s[parenthesis] == "(": #if a paranthesis '(' is found, the counter is updated
counter += 1
i = 0
while i < counter: #while loop which runs until all parenthesis pairs are removed from 's'
s = get_comma_phrase(s)
i = i + 1
return s #function returns value of 's'
s = input("Enter text: ") #taking user input and assigning it to variable 's'
print(get_comma_string(s)) #value of function 'get_comma_string(s)' is printed to screen
|
cd655b76261484257e0eebf5962464b17b825013 | sammyrTX/Python-Baseball_Project | /Baseball_Proj_Main.py | 973 | 3.875 | 4 | ###############################################################################
"""Baseball Game Simulator
Python v3.7
This is a simple simulator that runs through a baseball game. It shows
the results of each at bat by team for each inning. Results at bat
are determined at random. If there is a tie after nine innings, the
game will go into extra innings.
Primary goal is to use Python as the language and apply the appropriate
data structures. Future features may be added.
"""
###############################################################################
# Functions
from baseball_funcs.game_set_up import start_game
from baseball_funcs.innings import innings_nine
# ***** MAIN SECTION *****
if __name__ == "__main__":
# Set up batting order and start game
batting_lineup, batting_lineup_keep = start_game()
# Play nine innings
innings_nine(batting_lineup, batting_lineup_keep)
print("\n*** END OF GAME ***")
|
ddb16179e34289a654bec5eb5459f1c9020d4af2 | Emanoel580/ifpi-ads-algoritmos2020 | /Lista 03 Repetição for/fabio_q25_for.py | 657 | 3.90625 | 4 | n = int(input('Eleitores: '))
c1 = 0
c2 = 0
c3 = 0
votos_nulos = 9
votos_brancos = 0
for i in range(1, n+1):
opção_voto = int(input("voto:" ))
if opção_voto == 1:
c1 +=1
if opção_voto == 2:
c2 +=1
if opção_voto == 3:
c3 += 1
if opção_voto == 9:
votos_nulos +=1
if opção_voto == 0:
voto_branco +=1
print('---contando os votos---')
if c1 > c2 and c1 > c3:
print('vencedor:',(c1))
elif c2 > c1 and c2> c3:
print('vencedor:',(c2))
elif c3 > c1 and c3 > c2:
print('vencedor:', (c3))
else:
print('Haverá 2° Turno das Eleiçoes !!')
|
0064137166184504f8e31ce0e8f22eb2e1a10269 | macloo/python_examples | /dice_with_random.py | 597 | 4.09375 | 4 | # this dice game is not the greatest, but it runs and
# can be used a basis for a better dice game
from random import randint
score = 0
again = "y"
print # blank line
def dice(score, again):
d1 = randint(1, 6)
d2 = randint(1, 6)
roll = d1 + d2
if roll == 7:
print "Rolled %d and %d. You lose." % (d1, d2)
again = "n"
else:
score += roll
print "Rolled %d." % roll,
again = raw_input("Roll again? y/n ")
return score, again
while again != "n":
score, again = dice(score, again)
print "Game over! Final score:", score
print
|
bb53ddab382a1b2ea4e4695e2c720768faaca524 | ShashankPatil20/Crash_Course_Python | /Week_2/Functions.py | 471 | 4.21875 | 4 | def greeting(name, department):
print("Welcome", name)
print("You are from ", department)
greeting('Bill', 'Admin')
'''
Flesh out the body of the print_seconds function so that it prints the total amount of seconds given the hours,
minutes, and seconds function parameters. Remember that there are 3600 seconds in an hour and 60 seconds in a minute.
'''
def print_seconds(hours, minutes, seconds):
print(hours*3600+minutes*60+seconds)
print_seconds(1,2,3) |
ea535304df854f10c4179fe8a6fbe5976a5cc691 | tic0uk/python-100daysofcode | /day-15-coffee_maker.py | 3,308 | 4.1875 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
balance = {
"money": 0
}
def print_report(resources_list, available_balance):
"""Return all available resources from resources dictionary"""
water_left = resources_list["water"]
milk_left = resources_list["milk"]
coffee_left = resources_list["coffee"]
total_money = available_balance["money"]
return f"Water: {water_left}ml \nMilk: {milk_left}ml \nCoffee: {coffee_left}g \nMoney: ${total_money:0.2f}"
def process_coins():
"""Take user input of coins and returns the sum of them"""
print("Please insert coins.")
quarters = int(input("how many quarters?: ")) * 0.25
dimes = int(input("how many dimes?: ")) * 0.10
nickels = int(input("how many nickels?: ")) * 0.05
pennies = int(input("how many pennies?: ")) * 0.01
total = quarters + dimes + nickels + pennies
return total
def check_resources(drink):
"""Check there is sufficient resources and return true or false"""
ingredients_to_deduct = (MENU[drink]["ingredients"])
for key in ingredients_to_deduct:
if resources[key] < ingredients_to_deduct[key]:
print(f"Sorry there is not enough {key}.")
return False
return True
def check_transaction(coins_inserted, cost_drink, machine_balance):
"""check that enough money has been inserted, give change and return the cost balance"""
if coins_inserted < cost_drink:
return False
else:
if coins_inserted > cost_drink:
change_given = coins_inserted - cost_drink
print(f"Here is ${change_given:0.2f} in change.")
return machine_balance + cost_drink
def make_coffee(drink):
"""deduct the ingredients from overall resources"""
ingredients_to_deduct = (MENU[drink]["ingredients"])
for key in ingredients_to_deduct:
resources[key] -= ingredients_to_deduct[key]
get_me_coffee = True
while get_me_coffee:
order = input(" What would you like? (espresso/latte/cappuccino): ").lower()
if order == "off":
get_me_coffee = False
# Print Report on resources
elif order == "report":
print(print_report(resources, balance))
elif order == "latte" or order == "cappuccino" or order == "espresso":
enough_resources = check_resources(order)
if enough_resources:
total_inserted = process_coins()
cost_of_drink = (MENU[order]["cost"])
machine_money = balance["money"]
enough_money = check_transaction(total_inserted, cost_of_drink, machine_money)
if not enough_money:
print("Sorry that's not enough money. Money refunded.")
else:
balance["money"] = enough_money
make_coffee(order)
print(f"Here is your {order}. Enjoy!")
|
d7499d5577c65a56fff6ca174a47c3a20c8706a7 | kji0205/py | /cookbook/CHAPTER02/2.9.py | 492 | 3.59375 | 4 | """유니코드 텍스트 노멀화"""
import unicodedata
s1 = 'Spicy Jalape\u00f1o'
s2 = 'Spicy Jalapen\u0303o'
# print(s1)
# print(s2)
# print(s1 == s2)
# print(len(s1))
# print(len(s2))
#
t1 = unicodedata.normalize('NFC', s1)
t2 = unicodedata.normalize('NFC', s2)
print(t1 == t2)
print(ascii(t1))
t3 = unicodedata.normalize('NFD', s1)
t4 = unicodedata.normalize('NFD', s2)
print(t3 == t4)
# print(t3)
print(ascii(t3))
#
s = '\ufb01'
# print(s)
# print(unicodedata.normalize('NFD', s))
|
f4b93bab8e9d12b569fd63fec07dcfc90dd86233 | tkremer72/Python-Masterclass | /3.ListsAndTuples/1.Sequences/buy_computer.py | 2,520 | 3.953125 | 4 | available_parts = ["computer",
"monitor",
"keyboard",
"mouse",
"mouse pad",
"hdmi cable",
"dvd drive",
"memory",
"webcam",
"speakers",
"microphone",
"headset"
]
# valid_choices = [str(i) for i in range(1, len(available_parts) + 1)]
valid_choices = []
for i in range(1, len(available_parts) + 1):
valid_choices.append(str(i))
# print(valid_choices)
current_choice = "-"
computer_parts = [] # Create an empty list
while current_choice != "0":
# if current_choice in "123456":
if current_choice in valid_choices:
index = int(current_choice) - 1
chosen_part = available_parts[index]
if chosen_part in computer_parts:
# already there, remove it.
print("Removing {}".format(current_choice))
computer_parts.remove(chosen_part)
else:
print("Adding {}".format(current_choice))
computer_parts.append(chosen_part)
print("Your list now contains: {}".format(computer_parts))
# if current_choice == '1':
# computer_parts.append("computer")
# elif current_choice == '2':
# computer_parts.append("monitor")
# elif current_choice == '3':
# computer_parts.append("keyboard")
# elif current_choice == '4':
# computer_parts.append("mouse")
# elif current_choice == '5':
# computer_parts.append("mouse pad")
# elif current_choice == '6':
# computer_parts.append("hdmi cable")
else:
# print("Please add options from the list below: ")
# print("1: computer")
# print("2: monitor")
# print("3: keyboard")
# print("4: mouse")
# print("5: mouse pad")
# print("6: hdmi cable")
# print("0: to exit")
# for part in available_parts:
# print("{0}: {1}".format(available_parts.index(part) + 1, part))
print("Please add options from the list below:")
for number, part in enumerate(available_parts): # use the enumerate function to get the part and the index
# below we use replacement for the number and the part
print("{0}: {1}".format(number + 1, part)) # add 1 to the index to get the correct list number
current_choice = input()
print(computer_parts)
|
f7c16810757eecbd20e5968950ceacb03b9a1c2b | Isaac-d17/Final | /HerenciaAnimales.py | 593 | 3.921875 | 4 | import Animales
class Elefante(Animales.Animales):
"""Importamos el modulo Animales y le heredamos todos sus metodos y atributos, construimos metodos especificios para los elefantes"""
def tomar_agua(self,tipo_agua,cantidad_agua):
if(tipo_agua.lower()=="limpia"):
self.cantidad_agua+=cantidad_agua
else:
print("El agua no es adecuada, busquemos otro lugar")
def Comer(self,tipo_alimento,cantidad_comer):
if(tipo_alimento.lower()=="mani"):
self.cantidad_alimento+=cantidad_comer
self.tipo_alimento=tipo_alimento
else:
print("Solo me alimento de manies") |
d131648e39e5362d0b9605a9e185ab56c1422710 | mhossain25/CIS1051_Final_Project | /cashFlowDiagram.py | 8,475 | 4.09375 | 4 | import matplotlib.pyplot as plt
def checkIntInput(arg): # found code on https://pynative.com/python-check-user-input-is-number-or-string/#:~:text=To%20check%20if%20the%20input%20string%20is%20an%20integer%20number,using%20the%20int()%20constructor.&text=To%20check%20if%20the%20input%20is%20a%20float%20number%2C%20convert,using%20the%20float()%20constructor.
# checks an argument if it is an integer
try:
an_arg = int(arg)
return True
except ValueError:
return False
def checkStrInput(arg):
# checks an argument if it is a string
try:
an_arg = str(arg)
return True
except ValueError:
return False
def checkFloatInput(arg):
# checks an argument if it is a float
try:
an_arg = float(arg)
return True
except ValueError:
return False
def horizoninput(horizon):
# turns the inputted value into an integer and adds 1 to include the last value then returns that value
horizon = int(horizon)+1
return horizon
def singularCashFlow(horizon):
# allows a user to input each cash flow for each time increment
cashFlow = []
for i in range(horizon):
cashFlag = False # error trapping, doesn't allow user to continue unless they type in an int or a float
while cashFlag == False:
theCash = input("Please enter the cash flow for time step " + str(i) + ": ")
if checkFloatInput(theCash) == True or checkIntInput(theCash) == True:
theCash = float(theCash)
cashFlag = True
else:
print("Please input a number for your cash flow.")
cashFlow.append(theCash) # once the while loop is exited, the value is added to the cash flow
return cashFlow
def uniformSeriesCashFlow(horizon,seriesCash):
cashFlow = [seriesCash]*horizon # this creates a list that has the series value that is horizon values long
return cashFlow
def gradientSeriesCashFlow(horizon,firstCash,increment):
cashFlow = []
for i in range(horizon):
if i == 0:
cashFlow.append(0) # the first year is 0 in a gradient series
else:
cashFlow.append(firstCash+(i-1)*increment) # the gradient series has an intital value
return cashFlow # then changes linearly
def cashFlowDiagram(years,cashList):
yearsList = list(range(0,years)) # this creates and manages the bar plot with given horizon and cash flow
cfd = plt.bar(yearsList,cashList,width = .1,tick_label = yearsList)
plt.bar_label(cfd) # learned this at https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html
plt.show()
def worthOfSeries(horizon,cashFlow,percentInterest):
# present worth formula = FV*(1+i)^(-n)
interest = percentInterest/100 # converts percent interest into a decimal
futureWorth = 0
presentWorth = 0
for i in range(horizon):
futureWorth += cashFlow[i] # sum of each value in the series
presentWorth += cashFlow[i]*(1+interest)**(-i) # adds the present value of each value moving forward in time
futureWorth = round(futureWorth)
presentWorth = round(presentWorth)
annualWorth = round(presentWorth*((interest*(1+interest)**horizon)/(-1+(1+interest)**horizon))) # annual worth formula
print("The future worth of the series is {}.".format(futureWorth))
print("The present worth of the series is {}.".format(presentWorth))
print("The annual worth of the series is {}.".format(annualWorth))
def mainProgram():
# traps errors of horizon
horizonFlag = False
while horizonFlag == False:
horizon = input("What is the length of time (horizon) you'll be looking at? ")
if checkIntInput(horizon) == True: # requires integer input
if int(horizon) > 0: # input cannot be zero
horizon = int(horizon)+1
horizonFlag = True # breaks loop
else:
print("Please input an integer number greater than 0. ")
else:
print("Please input an integer number greater than 0. ")
numberSeriesFlag = False # similiar to the horizon error check
while numberSeriesFlag == False:
numberOfSeries = input("Please enter how many series you plan to include. ")
if checkIntInput(numberOfSeries) == True:
if int(numberOfSeries) > 0:
numberOfSeries = int(numberOfSeries)
numberSeriesFlag = True
else:
print("Please input an integer number greater than 0. ")
else:
print("Please input an integer number greater than 0. ")
previousCashFlow = []
for i in range(numberOfSeries):
choiceFlag = False # checks for strings that are S,U, or H, otherwise user cannot continue
while choiceFlag == False:
choice = input("Please input 'S' for individual cash flows,\ninput 'U' for uniform series cash flow,\nor input 'G' for gradient series cash flow. ")
if checkStrInput(choice) == True:
if choice.upper() == 'S' or choice.upper() == 'U' or choice.upper() == 'G':
choice = choice.upper()
choiceFlag = True
else:
print("You should input 'S','U', or 'G' to indicate what series you want to add. Please try again. ")
else:
print("You should input 'S','U', or 'G' to indicate what series you want to add. Please try again. ")
if choice == 'S':
cashFlow = singularCashFlow(horizon)
elif choice == 'U':
seriesFlag = False # error traps the uniform cash value until a float is given
while seriesFlag == False:
seriesCash = input("Please enter the cash amount for the uniform series. ")
if checkFloatInput(seriesCash) == True:
seriesCash = float(seriesCash)
seriesFlag = True
else:
print("Please input a float for your desired uniform series amount. ")
cashFlow = uniformSeriesCashFlow(horizon,seriesCash) # calls function to calculate cash flow
elif choice == 'G':
firstCashFlag = False # two error traps for each input for the gradient series
while firstCashFlag == False:
firstCash = input("Please enter the initial amount for the gradient series. ")
if checkFloatInput(firstCash) == True:
firstCash = float(firstCash)
firstCashFlag = True
else:
print("Please input a float for your desired gradient series starting value. ")
incrementFlag = False
while incrementFlag == False:
increment = input("Please enter the change per year for the gradient series. ")
if checkFloatInput(increment) == True:
increment = float(increment)
incrementFlag = True
else:
print("Please input a float for your desired change in each year of the series. ")
cashFlow = gradientSeriesCashFlow(horizon,firstCash,increment)
if i == 0:
previousCashFlow = cashFlow # only useful if there's more than one series
else: # code found on https://www.geeksforgeeks.org/python-adding-two-list-elements/
cashFlow = [sum(j) for j in zip(cashFlow,previousCashFlow)] #sums a tuple to get a list again
previousCashFlow = cashFlow
percentFlag = False # interest error trapping
while percentFlag == False:
percentInterest = input("What is the interest rate of the series? ")
if checkFloatInput(percentInterest) == True:
if float(percentInterest) != 0: # requires a value greater than 0 because there's a singularity there
percentInterest = float(percentInterest)
percentFlag = True
else:
print("Please input a valid float that is not 0. ")
else:
print("Please input a valid float that is not 0. ")
worthOfSeries(horizon,cashFlow,percentInterest) # calculates present, future, and annual worth
cashFlowDiagram(horizon,cashFlow) # creates the cash flow diagram
return
mainProgram() |
343187bde5fc4dfd641e7cbfa9a17b53e0e5e180 | AaronAS2016/Sudoku_Solver_EDD | /solver.py | 2,118 | 3.75 | 4 | class Solver():
def valid(self, board, number, position, dimension=9):
# Check row
for i in range(len(board[0])):
if board[position[0]][i] == number and position[1] != i:
return False
# Check column
for i in range(len(board)):
if board[i][position[1]] == number and position[0] != i:
return False
# Check box
box_x = position[1] // 3
box_y = position[0] // 3
for i in range(box_y * 3, box_y * 3 + (dimension // 3)):
for j in range(box_x * 3, box_x * 3 + (dimension // 3)):
if board[i][j] == number and (i, j) != position:
return False
return True
def solve(self, board, dimension=9):
find = self.find_empty(board)
if not find:
return board
else:
row, column = find
for i in range(1, dimension + 1):
if self.valid(board, i, (row, column), dimension):
board[row][column] = i
solucion = self.solve(board)
if solucion:
return solucion
board[row][column] = 0
return False
def print_board(self, board):
""" Print a board 9x9 """
for i in range(len(board)):
# Every 3 rows print a separator
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - -")
for j in range(len(board[0])):
# Every 3 column print a separator
if j % 3 == 0 and j != 0:
print(" | ", end="")
# Check if is last column to make the jump line
if j == 8:
print(board[i][j])
else:
print(str(board[i][j]) + " ", end="")
def find_empty(self, board):
""" In a board find the first element empty in a tuple """
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None
|
26e3e01baf2733a8416c0c43b1fbcaff9f76d3b9 | Zahirgeek/learning_python | /OOP/8.1.py | 545 | 4.1875 | 4 | #属性案例
#创建Student类,描述学生类
#学生具有Student.name属性
#但name格式并不统一
#可以用增加一个函数,然后自动调用的方式,但很蠢
class Student():
def __init__(self, name, age):
self.name = name
self.age = age
#构造函数调用setName
self.setName(name)
def intro(self):
print("Hi,my name is {0}".format(self.name))
def setName(self, name):
self.name = name.upper()
s1 = Student("Zahir LIU", 18)
s2 = Student("za", 20)
s1.intro()
s2.intro() |
86b341befaac9cadcfb6eb21f382ef8b7a0f45a9 | wantwantwant/tutorial | /L2基础类型控制语句/判断类型《6》.py | 407 | 4.03125 | 4 | # 判断变量类型
#类型不同,input()返回字符串
# '1' + 3
# type(), 判断变量类型
a = 1
b = 1.5
c = 'hello'
d = True
type(a) # <class'int'>
type(b) # <class'float'>
type(c) #<class'str'>
type(d) #<class'bool'>
# isinstance(值,类型)
# 如果值属于类型的话返回True
isinstance(1,int) # True
isinstance(1,float) # False
isinstance('小明',float) # False
|
0890fff49cda921df2c555719ef1df96c874b4fc | lf2225/Python-the-Hard-Way-exercises | /Blackjack/Deck.py | 905 | 3.890625 | 4 | import random
import itertools
Suits = 'cdhs'
Ranks = '23456789TJQKA'
class Deck(object):
def __init__(self):
print 'I am entering the init routine of Deck'
self.CardShoe = tuple(''.join(card) for card in itertools.product(Ranks, Suits))
self.NumberOfCards = len(self.CardShoe)
self.Shuffle()
print 'I am exiting the init routine of Deck'
#shuffle all 52 cards, return shuffled deck (new CardShoe)
def Shuffle(self):
self.ShuffleDeck = random.sample(self.CardShoe, 52)
print "Print shuffleDeck", self.ShuffleDeck
#interaction of the deck class, namely dealing cards to the assigned players
def DealOneCard(self):
print 'I am at the start of the DealOneCard routine'
self.OneCard = (random.sample(self.ShuffleDeck, 1))[0]
print "Deal card", self.OneCard
self.ShuffleDeck.remove(self.OneCard)
print "deck with removed card", self.ShuffleDeck
return self.OneCard
|
73230e25e6194575e682ff6d5d6f5a4f8fa73dd1 | KephM/Python_Portfolio | /Term 1/Mad Libs Assignment/Mad Libs Assignment.py | 242 | 3.5 | 4 | #Kephryn Merkley
#Mad Libs Input Assignment
#9-11-19
name = "Pierre"
noun = "Bat"
verb = "run"
num = 50
msg = str.format("Last week at practice {} forgot his {} at home. So the coach made him {} {} laps!",name,noun,verb,num)
print(msg)
|
c1d7901b3e27966f28a24d3688c6d07d5066e088 | Mahadevan007/c-and-python-problems | /arrange_adjacent.py | 421 | 3.8125 | 4 | def arrange_adjacent(arr):
mid = len(arr)/2
firstarr = []
secondarr = []
resultarr = []
for i in range(0,mid):
firstarr.append(arr[i])
for i in range(mid,len(arr)):
secondarr.append(arr[i])
for i range(0,mid+1):
resultarr.append(firstarr[i])
resultarr.append(secondarr[i])
return resultarr
arr = list(map(int,input().split()))
print(arrange_adjacent(arr)) |
4fbe75d4600b72423e6ea7c5498635fd3f1055e9 | a-abramow/MDawsonlessons | /lessons/Chapter 06/6_01.py | 879 | 3.90625 | 4 | def instructions():
print(
"""
Добро пожаловать на ринг игры Крестики Нолики.
Чтобы сделать ход, ыыедите число от 0 до 8. Числа
соответствуют полям, как указано ниже:
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 | 8
Приготовься к бою, жалкий людишка. Познай силу процессора!\n """
)
print("Это инструкция к игре в 'Крестики-Нолики':")
instructions()
print("Это та же самая инструкция к игре в 'Крестики-Нолики':")
instructions()
print("Надеюсь, теперь смысл игры ясен.")
input("\n\nНажмите Enter, чтобы выйти.")
|
594fa0f2af78a35ac7654e273dcaf120449829e5 | mingweihe/leetcode | /_0164_MaximumGap.py | 1,364 | 3.546875 | 4 | import math
class Solution(object):
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
conclusion: linear sort:
1. bucket sort
2. radix sort
3. counting sort
"""
# Approach 2 bucket sort
if len(nums) < 2: return 0
maxi, mini = max(nums), min(nums)
if maxi == mini: return 0
avg_gap = int(math.ceil((maxi - mini) / float(len(nums) - 1)))
buckets = [[None, None] for _ in xrange(len(nums))]
for x in nums:
bucket = buckets[(x - mini) / avg_gap]
bucket[0] = x if bucket[0] is None else min(bucket[0], x)
bucket[1] = x if bucket[1] is None else max(bucket[1], x)
buckets = [x for x in buckets if x[0] is not None]
return max(buckets[i][0] - buckets[i - 1][1] for i in xrange(1, len(buckets)))
# Approach 1 radix sort
# if len(nums) < 2: return 0
# def radix_sort(A):
# for i in xrange(10):
# s = [[] for _ in xrange(10)]
# for x in A:
# s[x/10**i%10].append(x)
# A = [b for a in s for b in a]
# return A
# sorted_array = radix_sort(nums)
# return max(map(lambda x: x[1]-x[0], zip(sorted_array, sorted_array[1:])))
|
504a9ab1c07b2f30306974538839bb535c7c7b6b | ErioY/Choose_Exerceses-Python | /对三个变量排序.py | 621 | 3.8125 | 4 | '''
@Autor: ErioY
@Date: 2019-10-16 20:56:13
@Email: 1973545559@qq.com
@Github: https://github.com/ErioY
@LastEditors: ErioY
@LastEditTime: 2019-10-18 11:50:43
'''
# 设有三个变量a,b,c,分别对三个变量赋值,并对三个变量进行排序。如a=5,b=7,c=6,则排序结果为b>c>a
# a = int(input("请输入第一个值:"))
# b = int(input("请输入第二个值:"))
# c = int(input("请输入第三个值:"))
a = 5
b = 7
c = 6
num = {
"a": a,
"b": b,
"c": c
}
num = sorted(num.items(), key=lambda m: m[1], reverse=True)
print("升序结果为:", num[0][0], ">", num[1][0], ">", num[2][0])
print(num) |
68b71ef9186a843d67280d2f75c125b76ca3e54b | kaushikamaravadi/Python_Practice | /Transcend/spiral.py | 618 | 3.90625 | 4 | """Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
"""
def spiral(n):
sum = 1
value = 0
lev = 1
for i in range(1,n):
value = value + 2
l = 0
while(l < 4):
l = l + 1
lev = value + lev
sum = sum + lev
return (sum)
spiral(501)
|
994ab0491deacb237765e492ae45bbc53a2310f7 | irekpi/Flynerd | /4/zbiory.py | 388 | 3.671875 | 4 | zbior = {'adam': 'men',
'alex': 'men',
'kasia': 'wom',
'ola': 'wom'}
imie = input('podaj imie')
if imie in list(zbior.keys()):
print(imie, zbior[imie])
else:
print('podaj imie bo nie ma w bazie')
gender = input('podaj m lub z')
if gender == 'm':
zbior[imie] = 'men'
else:
zbior[imie] = 'wom'
print(list(zbior.keys()))
|
bad7d0e70f189c663faf7152accf4b96ef0e2a2e | ferromauro/python3_dojo | /Modulo_5/lezione_5_6.py | 852 | 3.609375 | 4 | #! /usr/bin/env python3
###############################
### EREDITARIETA' ###
###############################
class Animale:
def __init__(self, name, sound):
self._name = name
self._sound = sound
print('Ho creato un animale')
def restituisci_nome(self):
print(self._name)
def sound(self):
print(self._sound)
class Gatto(Animale):
def __init__(self, name, sound, action):
super().__init__(name,sound)
print('Ho creato un GATTO!')
self._action = action
def agisci(self):
print(self._action)
def main():
#x = Animale('Bingo', 'Bau!')
#x.restituisci_nome()
#x.sound()
y = Gatto('Pallina', 'Miao', 'Graffia')
y.restituisci_nome()
y.sound()
y.agisci()
if __name__ == "__main__":
main()
|
af19a64aa1bfa2d2e3833a29ee2473aeed464e9e | Cantimploras/ArenaOfValorDB | /aovdb/sqlite_DB.py | 1,770 | 3.78125 | 4 | import sqlite3
from personajes import Personaje
conn = sqlite3.connect('jDbArena.db')
c = conn.cursor()
'''
# CREACION DE LA TABLA
c.execute("""CREATE TABLE personajes (
nombre text,
apodo text,
rol text,
precioOro real,
precio real,
maxHP real,
maxMana real,
movSpeed real,
armor real,
magicDefense real
)""" )
'''
def __init__(self, dataFrame_subscriber_content):
self.dataFrame_subscriber_content = dataFrame_subscriber_content
def insert_per(per):
with conn:
c.execute("INSERT INTO personajes VALUES (:nombre, :apodo, :rol, :precioOro, :precio, :maxHP, :maxMana, :movSpeed, :armor, :magicDefense)",{'nombre': per.nombre, 'apodo': per.apodo, 'rol': per.rol , 'precioOro': per.precioOro, 'precio': per.precio, 'maxHP': per.maxHP, 'maxMana': per.maxMana, 'movSpeed': per.movSpeed, 'armor': per.armor, 'magicDefense': per.magicDefense})
def buscar_por_precioOro(precioOro):
c.execute("SELECT * FROM personajes WHERE precioOro=:precioOro", {'precioOro': precioOro})
return c.fetchall()
def buscar_por_nombre(nombre):
c.execute("SELECT * FROM personajes WHERE nombre=:nombre", {'nombre': nombre})
return c.fetchall()
def buscar_todo():
c.execute("SELECT * FROM personajes")
return c.fetchall()
'''
# CREACION DE PERSONAJES
ejLaurie = Personaje('Lauriel','The Archangel','Mage','18888 Monedas',' 1199 TR','3019','490','340','87 / 12.6%','50 / 7.6%')
insert_per(ejLaurie)
ejRaz = Personaje('Raz','Asesino','13888 Monedas',' 999 TR','3235','0','390','89 / 12.9%','50 / 7.6%')
insert_per(ejRaz)
'''
'''
#Buscar por Nombre
test = buscar_por_nombre('Raz')
print(test)
'''
#conn.close() |
83d166f26a25566c6505fd1cdb2a7d98071f08ba | ogbanugot/Queuing-theory | /interface.py | 3,846 | 4.125 | 4 | import queue_formula
'''
interface with the queue_formula module
'''
menu = '''
Here is a list of the functions available\n
1. Traffic intensity
2. Average number of items in the system \n
3. Average number of elements in the queue, when there is queue\n
4. Average number of elements in the queue inlcuding times when there is no queue\n
5. Average time in the queue\n
6. Average time in the system\n
7. Probability of queueing on arrival\n
8. Probability of not queueing on arrival\n
9. Probabilty of n elements in the system at anytime\n
10. Probability of n or more elements in the system\n
Enter the number of your choice to start, 0 to quit->'''
def main():
choice = int(input(menu))
while choice != "q":
if choice == 1:
lamda = input("Enter arrival rate")
mieu = input("Enter service rate")
trf_ints = queue_formula.traffic_intensity(lamda,mieu)
print ("Traffic intensity =",trf_ints)
choice = int(input(menu))
elif choice == 2:
rho = input("Enter Traffic intensity")
avg_num = queue_formula.avg_num_items_sys(rho)
print ("Average number of items in the system = ",avg_num)
choice = int(input(menu))
elif choice == 3:
rho = input("Enter Traffic intensity")
avg_num = queue_formula.avg_num_items_queue(rho)
print ("Average number of elements in the queue When there is queue = ",avg_num)
choice = int(input(menu))
elif choice == 4:
rho = input("Enter Traffic intensity")
avg_num = queue_formula.avg_num_items_nqueue(rho)
print ("Average number of elements in the queue including times When there is no queue = ",avg_num)
choice = int(input(menu))
elif choice == 5:
rho = input("Enter Traffic intensity")
mieu = input("Enter service rate")
avg_time = queue_formula.avgtime_in_queue(rho,mieu)
time = str(avg_time)
print ("Average time in the queue = "+time+ "mins")
choice = int(input(menu))
elif choice == 6:
rho = input("Enter Traffic intensity")
mieu = input("Enter service rate")
avg_time = queue_formula.avgtime_in_system(rho,mieu)
time = str(avg_time)
print ("Average time in the system = "+time+ "mins")
choice = int(input(menu))
elif choice == 7:
rho = input("Enter Traffic intensity")
print ("The probability of queueing on arrival = ",rho)
choice = int(input(menu))
elif choice == 8:
rho = input("Enter Traffic intensity")
prob = queue_formula.prob_not_queuing(rho)
print ("The probability of not queueing on arrival = ",prob)
choice = int(input(menu))
elif choice == 9:
rho = input("Enter Traffic intensity")
number = input("Enter number")
prob = queue_formula.prob_n_elements_queue(rho,number)
print ("The probability of n elements in the system at any time = ",prob)
choice = int(input(menu))
elif choice == 10:
rho = input("Enter Traffic intensity")
number = input("Enter number")
prob = queue_formula.prob_n_or_more(rho,number)
print ("The probability of n or more elements in the system at any time = ",prob)
choice = int(input(menu))
else:
break
main()
|
4136cd98b721da791ece7c0fcb68e36da4876c59 | thientt03/C4E26 | /C4E26/Dark.py/checklogin.py | 708 | 4 | 4 | # username = input("Nhập username : ")
# password = input("Nhập password : ")
loop = True
while loop:
username = input("Nhập username : ")
password = input("Nhập password : ")
if not (username.isalnum() and password.isalnum()):
print("Sai username hoặc password")
else:
if username == "admin" and password == "admin":
print("Đăng nhập thành công ^^")
print("Hello!!")
elif username == "salesman" and password == "salesman":
print("Đăng nhập thành công ^^")
print("Say hi !!")
else:
print("Who are you??")
loop = False
|
66c643563261cb4c695da13d93d2b3689c02711a | quanaimaxiansheng/1805python | /17day/2-不定长参数.py | 339 | 3.546875 | 4 | def d_sum(a,b,*args,**kwargs):
'''
print(a)
print(b)
print(*args)
print(**kwargs)
'''
while True:
p=0
for i in range(*args):
p+=i
if i>6:
continue
for j in range(**kwargs):
z=int(j['values'])
x=int(j['values'])
print("和为%d"%(a+b+p+z+x))
d={"age":12,"weight":24}
t=(1,2,3,4,5,6,)
d_sum(1,2,*t,**d)
|
f4c7d6226d25444f032dab840410b6503d9de31b | estensen/algorithms | /data_structures/binary_search_tree.py | 1,366 | 3.796875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(self, val):
if val <= self.data:
if not self.left:
self.left = Node(val)
else:
self.left.insert(val)
else:
if not self.right:
self.right = Node(val)
else:
self.right.insert(val)
def contains(self, val):
if val == self.data:
return True
elif val < self.data:
if not self.left:
return False
else:
return self.left.contains(val)
else:
if not self.right:
return False
else:
return self.right.contains(val)
def print_in_order(self):
if self.left:
self.left.print_in_order()
print(self.data)
if self.right:
self.right.print_in_order()
def print_pre_order(self):
print(self.data)
if self.left:
self.left.print_pre_order()
if self.right:
self.right.print_pre_order()
def print_post_order(self):
if self.left:
self.left.print_post_order()
if self.right:
self.right.print_post_order()
print(self.data)
|
be6b2b70fada6629166f0d05887f426274fdf22d | Photooon/spell-correct | /tokenize_model.py | 590 | 3.6875 | 4 | import nltk
def word_tokenize(sent: str):
nltk.data.path.append('/Users/lw/Code/toolkit/nltk_data')
words = nltk.word_tokenize(sent)
# words = [word_trim(word) for word in sent.split(' ') if word] # split and remove the empty string
return words
def word_trim(word):
# remove the front punctuation
while len(word) > 1 and word[0] in string.punctuation:
word = word[1:]
# remove the back punctuation
while len(word) > 1 and word[-1] in string.punctuation:
if word[-1] == '\'':
break
word = word[:-1]
return word
|
7eacb8f8bf513b12c445b5e6c158f48f47a5dd6f | mhrmm/csci377 | /code/resolution/cnf.py | 2,593 | 3.625 | 4 |
def l(s):
if s[0] == '!':
return Literal(s[1:], True)
else:
return Literal(s, False)
def c(s):
"""
Convenience method for constructing CNF clauses, e.g. for Exercise 7.12:
c0 = c('a || b')
c1 = c('!a || b || e')
c2 = c('a || !b')
c3 = c('b || !e')
c4 = c('d || !e')
c5 = c('!b || !c || !f')
c6 = c('a || !e')
c7 = c('!b || f')
c8 = c('!b || c')
"""
literal_strings = [x.strip() for x in s.split('||')]
return Clause([l(x) for x in literal_strings])
class Literal:
def __init__(self, symbol, neg=False):
self.symbol = symbol
self.neg = neg
def __eq__(self, other):
return self.symbol == other.symbol and self.neg == other.neg
def __hash__(self):
return hash(self.symbol) + hash(self.neg)
def __str__(self):
result = ''
if self.neg:
result = '!'
return result + self.symbol
class Clause:
def __init__(self, literals):
self.literals = literals
self.literal_values = dict()
for lit in self.literals:
self.literal_values[lit.symbol] = lit.neg
def symbol_value(self, sym):
if sym in self.literal_values:
if self.literal_values[sym] == True:
return -1
else:
return 1
else:
return 0
def size(self):
return len(self.literals)
def symbols(self):
return set([l.symbol for l in self.literals])
def is_false(self):
return len(self.literals) == 0
def disjoin(self, clause):
common_symbols = set(self.literal_values.keys()) & set(clause.literal_values.keys())
for sym in common_symbols:
if self.symbol_value(sym) * clause.symbol_value(sym) == -1:
return None
return Clause(list(set(self.literals + clause.literals)))
def remove(self, sym):
new_literals = set(self.literals) - set([Literal(sym, False), Literal(sym, True)])
return Clause(list(new_literals))
def __eq__(self, other):
return set(self.literals) == set(other.literals)
def __lt__(self, other):
return str(self) < str(other)
def __hash__(self):
return hash(tuple(sorted([str(l) for l in self.literals])))
def __str__(self):
if len(self.literals) == 0:
return 'FALSE'
else:
return ' || '.join([str(l) for l in self.literals])
|
8eee8d492361922d3ac9419421833df48a482ad7 | lindycoder/AdventOfCode | /2016/day01_2.py | 1,612 | 3.546875 | 4 | import unittest
from hamcrest import assert_that, is_
X = 0
Y = 1
def compute(input):
visited = []
pos = [0, 0]
directions = [
(0, 1),
(1, 0),
(0, -1),
(-1, 0)
]
facing = 0
commands = [(m[0], int(m[1:])) for m in input.split(", ")]
for command in commands:
direction, length = command
facing += 1 if direction == 'R' else -1
if facing < 0:
facing = len(directions) - 1
if facing >= len(directions):
facing = 0
for step in range(1, length + 1):
pos[X] += 1 * directions[facing][X]
pos[Y] += 1 * directions[facing][Y]
if tuple(pos) in visited:
return abs(pos[X]) + abs(pos[Y])
else:
visited.append(tuple(pos))
class ComputeTest(unittest.TestCase):
def test_1(self):
result = compute("R8, R4, R4, R8")
assert_that(result, is_(4))
if __name__ == '__main__':
print("Result is {}".format(compute("R4, R5, L5, L5, L3, R2, R1, R1, L5, R5, R2, L1, L3, L4, R3, L1, L1, R2, R3, R3, R1, L3, L5, R3, R1, L1, R1, R2, L1, L4, L5, R4, R2, L192, R5, L2, R53, R1, L5, R73, R5, L5, R186, L3, L2, R1, R3, L3, L3, R1, L4, L2, R3, L5, R4, R3, R1, L1, R5, R2, R1, R1, R1, R3, R2, L1, R5, R1, L5, R2, L2, L4, R3, L1, R4, L5, R4, R3, L5, L3, R4, R2, L5, L5, R2, R3, R5, R4, R2, R1, L1, L5, L2, L3, L4, L5, L4, L5, L1, R3, R4, R5, R3, L5, L4, L3, L1, L4, R2, R5, R5, R4, L2, L4, R3, R1, L2, R5, L5, R1, R1, L1, L5, L5, L2, L1, R5, R2, L4, L1, R4, R3, L3, R1, R5, L1, L4, R2, L3, R5, R3, R1, L3")))
|
36525f7587201ce39f147bdd6c7fda0f9272299c | NikhilCG26/Python-For-Everyone-Coursera | /Assign-9/9.4.py | 464 | 3.609375 | 4 | name = input('Enter Name: ')
fh = open(name)
count = dict()
for line in fh :
if line.startswith('From:') :
words = line.split()
if words[1] not in count :
count[words[1]] = 1
else :
count[words[1]] = count[words[1]] + 1
bigword = None
bignum = None
for k,v in count.items() :
if bignum is None or v > bignum :
bignum = v
bigword = k
print(bigword,bignum)
|
54de0811bb4433a500c5d18eb151c6bccf1baee9 | anjaligeda/pythonbasic-branch | /lnbcal.py | 485 | 3.9375 | 4 | '''q=[]
for i in range(2):
a=int(input('enter number = '))
q.append(a)'''
num1=int(input("Enter the first number: "))
#input value for variable num1
num2=int(input("Enter the second number: "))
#input value for variable num2
mul=num1*num2;
#perform multiplication operation
print("the product of given numbers is: ",mul)
if mul>500:
sum=num1+num2
print("the sum of given numbers is: ",sum)
else:
print('Hello LNB cod eis running fine!')
|
651b097790ee3267b88e99ee7a82525c4f8ff7ed | Kendoll10/Python-Programs | /WhileLoop.py | 792 | 4.25 | 4 | # Make sure to copy and run the codes separately on your editor to see the results
# Using while loop in our python program
i=1
while i<=6:
print(i)
i+=1
# using flag to stop looping in python
i = ""
name = "What is your name?\n"
while (i != "q"):
i = input(name) # this programme will keep on looping unless you enter the value "q"
# Using infinite loop in a programme
i = 1
while (i==1):
name = input("Enter your name: ")
print("Your name is" + " " + name) # usually not a good practice in programming
# Using break and continue with while loop
I = 1
user = ""
while (i<=5):
user = input("Insert any name: ")
print("You inserted" + " " + user)
if (user == "John"):
break
elif (user == "Mic"):
continue
I+=1
|
c7e15aa7518855691706c487514af7b61683e5b1 | dwagon/pydominion | /dominion/cards/Card_Improve.py | 1,943 | 3.640625 | 4 | #!/usr/bin/env python
import unittest
from dominion import Game, Card, Piles
import dominion.Card as Card
###############################################################################
class Card_Improve(Card.Card):
def __init__(self):
Card.Card.__init__(self)
self.cardtype = Card.CardType.ACTION
self.base = Card.CardExpansion.RENAISSANCE
self.desc = """+2 Coin; At the start of Clean-up, you may trash an Action
card you would discard from play this turn, to gain a card costing exactly
1 more than it."""
self.name = "Improve"
self.cost = 3
self.coin = 2
def hook_cleanup(self, game, player):
acts = [_ for _ in player.piles[Piles.HAND] + player.piles[Piles.DISCARD] if _.isAction()]
if not acts:
return
tt = player.plr_trash_card(cardsrc=acts, prompt="Trash a card through Improve")
if not tt:
return
cost = tt[0].cost
player.plr_gain_card(cost + 1, modifier="equal")
###############################################################################
class Test_Improve(unittest.TestCase):
def setUp(self):
self.g = Game.TestGame(numplayers=1, initcards=["Improve", "Moat", "Guide"])
self.g.start_game()
self.plr = self.g.player_list(0)
self.card = self.g["Improve"].remove()
self.card.player = self.plr
def test_play(self):
self.plr.piles[Piles.HAND].set("Moat")
self.plr.add_card(self.card, Piles.HAND)
self.plr.play_card(self.card)
self.plr.test_input = ["End phase", "End phase", "Trash Moat", "Get Guide"]
self.plr.turn()
self.assertIn("Moat", self.g.trashpile)
self.assertIn("Guide", self.plr.piles[Piles.DISCARD])
###############################################################################
if __name__ == "__main__": # pragma: no cover
unittest.main()
# EOF
|
0e4479668874a84b0dd8cdc570e1c5285acb67e0 | Qhupe/Python-ornekleri | /Döngü Yapıları/ForDöngüsü.py | 829 | 3.71875 | 4 | toplam=0
sayac=0
liste =[1,2,3,4,5,6,7,8]
s = "Python"
for eleman in liste:#burada ise in parametresi listede gezinmemize yardımcı oluyo
toplam = toplam+eleman
sayac=sayac+1
if (eleman%2==0):#burada ise gezindiğimiz elemanın 2 ile bölümünden kalanı kontrol
#edip çift mi tek mi ekrana yazdırıyoruz
print(eleman," Sayısı Çift Sayı")
else:
print(eleman,"Saysı Tek Sayı")
print("Toplam {} Eleman {}".format(toplam,eleman))
print(toplam)
for i in s:#burada ise bir string içinde karakter karakter gezebileceğimizi gördük
print(i)
liste1=[(1,2),(3,4),(5,6),(7,8)]
for i in liste1:
print(i)
|
12d015280733393147ee1f62fb7acd9f653512e7 | ivoryli/myproject | /class/phase2/MySql/read_db.py | 555 | 3.5 | 4 | '''
数据库读操作演示
select
'''
import pymysql
#创建连接
db = pymysql.connect(host='localhost',user='root',passwd='123456',database='stu',charset='utf8')
# 创建游标
cur = db.cursor()
sql = "select * from myclass where age = 20"
#执行语句 cur拥有查询结果
cur.execute(sql)
#获取从查找结果第一个
one_row = cur.fetchone()
print(one_row)
# 游标指向下一个,不重复
# 获取从查找结果前两个
many_row = cur.fetchmany(2)
print(many_row)
all_row = cur.fetchall()
print(all_row)
cur.close()
db.close() |
faf8184e2a28b7fd22c8d6c592b91347d9553e81 | amiraliakbari/sharif-mabani-python | /by-session/ta-921/j11/class1.py | 251 | 3.65625 | 4 | class Circle:
def __init__(self):
self.r = 0
self.x = 0
self.y = 0
#x = 0
#a = []
#x = None
#x = 0
#x = []
c1 = Circle()
c2 = Circle()
c1.r = 1
c2.r = 3
print c1.r
print c2.r
print c1.x
|
a6d8c873c470672024a4196ee2975e11e2a4a44e | ajinmathew/Python | /reverse-string.py | 137 | 4.15625 | 4 | def reverse(s):
str=""
for i in s:
str=i+str;
return str
inp=input("Enter a String : ")
print("Op : "+reverse(inp))
|
1cc45030fc33fc1823a3e6ff319fc7f581a8e31f | 5Hanui/algorithm | /BOJ/BOJ_12904.py | 229 | 3.5625 | 4 | S = list(input())
T = list(input())
answer = 0
while T:
if T[-1] == "A":
T.pop()
elif T[-1] == "B":
T.pop()
T.reverse()
if S == T:
answer = 1
break
print(answer) |
8dfc9d9257a4ed6854ece19e2470eb89e7bd57ce | SiERic/paradigms-au-2017 | /hw5/yat/model.py | 4,378 | 3.671875 | 4 | class Scope:
def __init__(self, parent=None):
self.data = dict()
self.parent = parent
def __setitem__(self, key, value):
self.data[key] = value
def __getitem__(self, key):
if key in self.data:
return self.data[key]
if self.parent:
return self.parent[key]
raise KeyError
class Number:
def __init__(self, value):
self.value = value
self.prior = 7
def evaluate(self, scope):
return self
def __eq__(self, other):
return self.value == other.value
def accept(self, visitor):
return visitor.visit_number(self)
class Function:
def __init__(self, args, body):
self.args = args
self.body = body
def evaluate(self, scope):
return self
def accept(self, visitor):
return visitor.visit_function(self)
class FunctionDefinition:
def __init__(self, name, function):
self.name = name
self.function = function
def evaluate(self, scope):
scope[self.name] = self.function
return self.function
def accept(self, visitor):
return visitor.visit_function_definition(self)
class Conditional:
def __init__(self, condtion, if_true, if_false=None):
self.condtion = condtion
self.if_true = if_true
self.if_false = if_false
def evaluate(self, scope):
if self.condtion.evaluate(scope).value == 0:
block = self.if_false
else:
block = self.if_true
res = None
block = block or []
for expr in block:
res = expr.evaluate(scope)
return res
def accept(self, visitor):
return visitor.visit_conditional(self)
class Print:
def __init__(self, expr):
self.expr = expr
def evaluate(self, scope):
res = self.expr.evaluate(scope)
print(res.value)
return res
def accept(self, visitor):
return visitor.visit_print(self)
class Read:
def __init__(self, name):
self.name = name
def evaluate(self, scope):
value = int(input())
scope[self.name] = Number(value)
def accept(self, visitor):
return visitor.visit_read(self)
class FunctionCall:
def __init__(self, fun_expr, args):
self.fun_expr = fun_expr
self.args = args
self.prior = 7
def evaluate(self, scope):
function = self.fun_expr.evaluate(scope)
call_scope = Scope(scope)
for expr, name in zip(self.args, function.args):
call_scope[name] = expr.evaluate(scope)
res = None
for expr in function.body:
res = expr.evaluate(call_scope)
return res
def accept(self, visitor):
return visitor.visit_function_call(self)
class Reference:
def __init__(self, name):
self.name = name
self.prior = 7
def evaluate(self, scope):
return scope[self.name]
def __eq__(self, other):
return self.name == other.name
def accept(self, visitor):
return visitor.visit_reference(self)
class BinaryOperation:
priority = {'||': 0,
'&&': 1,
'==': 2, '!=': 2,
'<': 3, '<=': 3, '>': 3, '>=': 3,
'-': 4, '+': 4,
'*': 5, '/': 5, '%': 5}
def __init__(self, lhs, op, rhs):
self.lhs = lhs
self.rhs = rhs
self.op = op
self.prior = self.priority[op]
def evaluate(self, scope):
l = self.lhs.evaluate(scope).value
r = self.rhs.evaluate(scope).value
op = self.op
if op == "&&":
op = "and"
elif op == "||":
op = "or"
elif op == "/":
op = "//"
return Number(int(eval(str(l) + ' ' + op + ' ' + str(r))))
def accept(self, visitor):
return visitor.visit_binary_operation(self)
class UnaryOperation:
def __init__(self, op, expr):
self.op = op
self.expr = expr
self.prior = 6
def evaluate(self, scope):
v = self.expr.evaluate(scope).value
if self.op == "-":
return Number(-v)
else:
return Number(int(not bool(v)))
def accept(self, visitor):
return visitor.visit_unary_operation(self)
if __name__ == '__main__':
pass
|
31f6ceb9736dc10647aaeda029fadd85473b5694 | abrosen/classroom | /itp/spring2020/interloops.py | 1,242 | 3.703125 | 4 | def numVowel(text):
count = 0
text = text.lower()
vowels ="aeiou"
for letter in text:
if letter in vowels:
count = count + 1
return count
def numEvens(num):
if num == 0:
return 1
count = 0
#num = str(num)
#for digit in num:
# digit = int(digit)
while num > 0:
digit = num % 10
if digit % 2 == 0:
count += 1
num = num // 10
return count
def isArmstrong(num):
total = 0
orig = num
while num > 0:
digit = num % 10
total = total + (digit ** 3)
num = num // 10
if total == orig:
return True
else:
return False
def riddler():
for num in range(1001,10000,2):
thou = num // 1000
# 1234
hund = (num // 100) % 10 # (num % 1000) // 100
tens = (num // 10) % 10
ones = num % 10
if thou + hund + tens + ones == 27:
if thou == 3 * tens :
if thou != hund and thou != tens and thou != ones and hund != tens and hund != ones and tens != ones:
return num
print(numVowel("hello world"))
print(numEvens(0))
print(isArmstrong(370))
print(riddler()) |
218b48490de7d74e8f7de996f2746ce19f4d914a | jtquisenberry/PythonExamples | /Interview_Cake/dynamic_programming/fibonacci_recusion_memoization.py | 1,368 | 3.734375 | 4 | import unittest
import pytest
# https://www.interviewcake.com/question/python/nth-fibonacci?section=dynamic-programming-recursion&course=fc1
# Includes recursion and memoization.
# The memo should be a dictionary where the key is the
# being passed to the first argument of fib and the value
# is the result of the computation.
def fib(n):
# Calculate the nth Fibonacci number with recursion
pass
# Tests
class Test(unittest.TestCase):
def test_zeroth_fibonacci(self):
actual = fib(0)
expected = 0
self.assertEqual(actual, expected)
def test_first_fibonacci(self):
actual = fib(1)
expected = 1
self.assertEqual(actual, expected)
def test_second_fibonacci(self):
actual = fib(2)
expected = 1
self.assertEqual(actual, expected)
def test_third_fibonacci(self):
actual = fib(3)
expected = 2
self.assertEqual(actual, expected)
def test_fifth_fibonacci(self):
actual = fib(5)
expected = 5
self.assertEqual(actual, expected)
def test_tenth_fibonacci(self):
actual = fib(10)
expected = 55
self.assertEqual(actual, expected)
def test_negative_fibonacci(self):
with self.assertRaises(Exception):
fib(-1)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
c81a722d29f4dda2dc18d96780fc5ba750884e6c | Krit-NameWalker/6230401848-oop-labs | /Krit-623040184-8-lab4/prob3_debug_correct.py | 493 | 4.09375 | 4 | import sys
import pdb
def divide(dividend, divisor):
return dividend / divisor
#pdb.set_trace()
while True:
dividend = int(input("Please enter the dividend:"))
if dividend < 0:
break
divisor = int(input("Please enter the divisor:"))
if divisor < 0:
break
try:
answer = divide(dividend, divisor)
except ZeroDivisionError:
print("division by zero")
else:
print('The answer is: {}'.format(answer))
|
e1f7204178de396ba407999e1f8380ccd0cb3d76 | RajavelJeyabalan/Practicing-Code | /Aug 03 Task.py | 1,720 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
#the function table(n) prints the table of n
def table(n):
return lambda a:a*n # a will contain the iteration variable i and a multiple of n is returned at each function call
n = int(input("Enter the number:"))
b = table(n) #the entered number is passed into the function table. b will contain a lambda function which is called again and again with the iteration variable i
for i in range(1,11):
print(n,"X",i,"=",b(i)) #the lambda function b is called with the iteration variable i
# In[4]:
class Rocket:
def __init__(self, name, distance):
self.name = name
self.distance = distance
def launch(self):
return "%s has reached %s" % (self.name, self.distance)
class MarsRover(Rocket): # inheriting from the base class
def __init__(self, name, distance, maker):
Rocket.__init__(self, name, distance)
self.maker = maker
def get_maker(self):
return "%s Launched by %s" % (self.name, self.maker)
if __name__ == "__main__":
x = Rocket("simple rocket", "till stratosphere")
y = MarsRover("mars_rover", "till Mars", "ISRO")
print(x.launch())
print(y.launch())
print(y.get_maker())
# In[5]:
def reverse(str):
if len(str) == 0: # Checking the lenght of string
return str
else:
return reverse(str[1:]) + str[0]
str = "Devansh Sharma"
print ("The original string is : ", str)
print ("The reversed string(using recursion) is : ", reverse(str))
# In[6]:
str = "Devansh Sharma"
print ("The original string is : ", str)
print ("The reversed string(using recursion) is : ", reverse(str))
# In[ ]:
|
3811af30bf4b0505d03cc2003c0d616e150beb76 | jedzej/tietopythontraining-basic | /students/nartowska_karina/lesson_01_basics/first_digit_after_decimal_point.py | 81 | 3.5625 | 4 | # Read an integer:
a = float(input())
# Print a value:
print(int((a-int(a))*10))
|
2f920a6c4279b1ec5ac66e2fb959cea08fcc5c8f | artreven/fca | /fca/algorithms/factors.py | 9,573 | 3.578125 | 4 | """
Holds functions for finding optimal factors for decomposition of context.
Created on Jan 8, 2014
@author: artreven
"""
import itertools
import collections
import random
from typing import Tuple, Set
import fca
def make_factor_cxts(factors=None):
"""
Make two contexts: objects-factors and factors-attributes out of tuple of
given concepts.
@param factors: tuple of *fca.Concept*s (or anything that has *extent* and
*intent* instance variables).
"""
def el_ind(el, el_dict):
try:
return el_dict[el]
except KeyError:
num_els = len(el_dict)
el_dict[el] = num_els
return num_els
if factors is None:
factors = []
objs_dict = dict()
atts_dict = dict()
table_objs_fcts = []
table_fcts_atts = []
for c in factors:
table_objs_fcts.append(set(el_ind(obj, objs_dict) for obj in c.extent))
table_fcts_atts.append(set(el_ind(att, atts_dict) for att in c.intent))
# sort objs and atts in order of appearance to get correct factor ex/intents
attributes = sorted(list(atts_dict.keys()), key=atts_dict.__getitem__)
objects = sorted(list(objs_dict.keys()), key=objs_dict.__getitem__)
num_atts = len(attributes)
num_objs = len(objects)
names_fcts = ['f{}'.format(x) for x in range(len(factors))]
table_objs_fcts = list(zip(*[[(x in row) for x in range(num_objs)]
for row in table_objs_fcts]))
table_fcts_atts = [[(x in row) for x in range(num_atts)]
for row in table_fcts_atts]
return (fca.Context(table_objs_fcts, objects, names_fcts),
fca.Context(table_fcts_atts, names_fcts, attributes))
def _oplus(D_objs: Set[str], y: str,
cxt: 'fca.Context',
U: Set[Tuple[str, str]]):
yprime = cxt.get_attribute_extent(y)
Dy_prime = D_objs & yprime
Dy_primeprime = cxt.oprime(Dy_prime)
cpt = fca.Concept(extent=Dy_prime, intent=Dy_primeprime)
# result = {x for x in cpt.pairs() if x not in U}
result = set(cpt.pairs()) & U
return result
def algorithm2(cxt, fidelity=1):
"""
Algorithm2 from article{
title = "Discovery of optimal factors in binary data via a novel method of matrix decomposition ",
journal = "Journal of Computer and System Sciences ",
volume = "76",
number = "1",
pages = "3 - 20",
year = "2010",
doi = "http://dx.doi.org/10.1016/j.jcss.2009.05.002",
url = "http://www.sciencedirect.com/science/article/pii/S0022000009000415",
author = "Radim Belohlavek and Vilem Vychodil"}
Extensions:
Fidelity of coverage - stop when fidelity level is covered by factors
"""
U = set(cxt.object_attribute_pairs)
len_initial = len(U)
while (len_initial - len(U)) / len_initial < fidelity:
D = set()
V = 0
to_remove = set()
while True:
D_objs = cxt.aprime(D)
ls_measures = [(len(_oplus(D_objs, j, cxt, U)), j)
for j in set(cxt.attributes) - D]
if ls_measures:
maxDj = max(ls_measures, key=lambda x: x[0])
else:
maxDj = [0,]
if maxDj[0] > V:
j = maxDj[1]
Dj = D | {j}
C = cxt.aprime(Dj)
D = cxt.oprime(C)
to_remove = set(itertools.product(C, D)) & U
V = len(to_remove)
else:
break
if len(to_remove) == 0:
print('Algorithm stuck, something went wrong, pairs left ', len(U))
assert False
U -= to_remove
yield fca.Concept(C, D), len(to_remove) / len_initial
def algorithm2_weighted(cxt, fidelity=1):
"""
Algorithm2 from article{
title = "Discovery of optimal factors in binary data via a novel method of matrix decomposition ",
journal = "Journal of Computer and System Sciences ",
volume = "76",
number = "1",
pages = "3 - 20",
year = "2010",
doi = "http://dx.doi.org/10.1016/j.jcss.2009.05.002",
url = "http://www.sciencedirect.com/science/article/pii/S0022000009000415",
author = "Radim Belohlavek and Vilem Vychodil"}
Extensions:
Fidelity of coverage - stop when fidelity level is covered by factors
"""
len_objs_initial = len(cxt.objects)
len_atts_initial = len(cxt.attributes)
def score(obj_att_pairs):
objs = {x[0] for x in obj_att_pairs}
atts = {x[1] for x in obj_att_pairs}
score = len(objs) * len(atts) / (len_objs_initial * len_atts_initial)
return score
U = set(cxt.object_attribute_pairs)
len_initial = len(U)
while (len_initial - len(U)) / len_initial < fidelity:
D = set()
V = 0
to_remove = set()
while True:
D_objs = cxt.oprime(D)
ls_measures = [(score(_oplus(D_objs, j, cxt, U)), j)
for j in set(cxt.attributes) - D]
if ls_measures:
maxDj = max(ls_measures, key=lambda x: x[0])
else:
maxDj = [0,]
if maxDj[0] > V:
j_score, j = maxDj
Dj = D | {j}
C = cxt.aprime(Dj)
D = cxt.oprime(C)
to_remove = set(itertools.product(C, D)) & U
V = len(to_remove)
else:
break
if len(to_remove) == 0:
print('Algorithm stuck, something went wrong, pairs left ', len(U))
assert False
U -= to_remove
yield fca.Concept(C, D), j_score
def algorithm2_w_condition(cxt, fidelity: float = 1,
allow_repeatitions=True,
min_atts_and_objs=3, objs_ge_atts=False):
"""
Algorithm2 from article{
title = "Discovery of optimal factors in binary data via a novel method of matrix decomposition ",
journal = "Journal of Computer and System Sciences ",
volume = "76",
number = "1",
pages = "3 - 20",
year = "2010",
doi = "http://dx.doi.org/10.1016/j.jcss.2009.05.002",
url = "http://www.sciencedirect.com/science/article/pii/S0022000009000415",
author = "Radim Belohlavek and Vilem Vychodil"}
:param objs_ge_atts: should the number of objects be greater or equal to
the number of attributes in the output factors
:param min_atts_and_objs: minimum number of attributes and objects in the
output factors
:param fidelity: stops when this fraction of crosses in the table are covered
:param allow_repeatitions: exclude attributes in already obtained factors
from further consideration - they still may appear in the closure
"""
def good_factor(cpt: 'fca.Concept'):
if objs_ge_atts:
return len(cpt.extent) >= len(cpt.intent) >= min_atts_and_objs
else:
return len(cpt.extent) >= min_atts_and_objs and \
len(cpt.intent) >= min_atts_and_objs
U = set(cxt.object_attribute_pairs)
len_initial = len(U)
removed_atts = set()
removed_objs = set()
if not len_initial:
return
while (len_initial - len(U)) / len_initial < fidelity:
D = set()
C = set(cxt.objects)
V = 0
to_remove = set()
available_atts = {x[1] for x in U} - removed_atts
while True:
Dprime = cxt.aprime(D)
ls_measures = [(len(_oplus(Dprime, j, cxt, U)), j)
for j in available_atts - D]
if not ls_measures:
# print(f'Empty ls_measures. len(U) = {len(U)}, {set(u[1] for u in U)}, len(D) = {len(D)}, len(avail_atts) = {len(available_atts)}')
return
maxDj = max(ls_measures, key=lambda x: x[0])
# print(D, Dprime, maxDj, V)
# print(cxt)
if maxDj[0] > V or not good_factor(cpt=fca.Concept(C, D)): # update the values
# D_old = D.copy()
j_score, j = maxDj
Dj = D | {j}
C = cxt.aprime(Dj)
if len(C) < min_atts_and_objs or not (available_atts - D): # early restart
U = {u for u in U if u[1] not in Dj}
removed_atts |= Dj
break
D = cxt.oprime(C)
to_remove_U = set(itertools.product(C, D)) & U
V = len(to_remove_U)
if not allow_repeatitions:
to_remove = (set(itertools.product(C, cxt.attributes)) |
set(itertools.product(cxt.objects, D))) & U
else:
to_remove = to_remove_U
elif good_factor(cpt=fca.Concept(C, D)):
if len(to_remove) == 0:
raise Exception(
f'Algorithm stuck, something went wrong, pairs left '
f'{len(U)}')
U -= to_remove
# print(f'Factor out: {len(C)}, {len(D)}')
yield fca.Concept(C, D), len(to_remove) / len_initial, (len_initial - len(U)) / len_initial
break
else:
assert False
if __name__ == '__main__':
import cProfile
import numpy.linalg as lalg
from fca import make_random_context
r_cxt = make_random_context(1200, 1000, .3)
# r_cxt = r_cxt.reduce_attributes().reduce_objects()
cProfile.run('print(lalg.svd(r_cxt.np_table))')
cProfile.run('for x in algorithm2(r_cxt, .3): print(len(x[0].extent), len(x[0].intent), x[1])')
|
9137910f100b17f4bc73a517ac3dc1641975cbdb | VaibhavRast/SLLAB | /SLLAB_FINALS/1/1a.py | 419 | 3.9375 | 4 | li=[]
n=int(input("Enter no of elements to be inserted:"))
for i in range(0,n):
li.append(int(input("Enter:")))
print(li)
print("Max:",max(li)," Min:",min(li))
ele=int(input("Enter element to be inserted:"))
li.append(ele)
print(li)
ele=int(input("Enter element to be deleted:"))
li.remove(ele)
print(li)
ele=int(input("Enter element to be searched:"))
if ele in li:
print("Found ")
else:
print("Not Found")
|
22f8acefdb525aa303583aa8e83097388761a4c4 | Umang070/Python_Programs | /set.py | 366 | 3.796875 | 4 | s = {1,2,34,34,"umang",2}
s1 = {1,2,"umang",45,47}
# print(s)
# l=[1,2,3,43,43,2,5,6]
# s=list(set(l))
print(s)
s.add(4)
# s.remove(3) #if it is not in set thenn throw error....
s.discard(4) #if it is not in set thenn do not throw error....
# print(s.clear())
# for i in s:
# print(i)
union = s | s1
print(union)
intersection = s & s1
print(intersection)
|
682b3e1d6d40f4b279052ac27df19268d227fef8 | pypi123/machine_learning_ZZH | /Unit5/Unit5_5.py | 4,609 | 3.671875 | 4 | '''引入数据,并对数据进行预处理'''
# step 1 引入数据
import pandas as pd
with open('D:\\Desktop\西瓜数据集3.0.csv', 'r', encoding='utf-8') as data_obj:
df = pd.read_csv(data_obj)
# Step 2 对数据进行预处理
# 对离散属性进行独热编码,定性转为定量,使每一个特征的取值作为一个新的特征
# 增加特征量 Catagorical Variable -> Dummy Variable
# 两种方法:Dummy Encoding VS One Hot Encoding
# 相同点:将Catagorical Variable转换为定量特征
# 不同点:Dummy Variable将Catagorical Variable转为n-1个特征变量
# One Hot Encoding 将其转换为n个特征变量,但会存在哑变量陷阱问题
# pandas自带的get_dummies()函数,可以将数据集中的所有标称变量转为哑变量
# sklearn 中的OneHotEncoder 也可以实现标称变量转为哑变量(注意要将非数字型提前通过LabelEncoder编码为数字类型,再进行转换,且只能处理单列属性)
# pybrain中的_convertToOneOfMany()可以Converts the target classes to a 1-of-k representation, retaining the old targets as a field class.
# 对target class独热编码,并且保留原target为字段类
'''
dataset = pd.get_dummies(df, columns=df.columns[:6]) # 将离散属性变为哑变量
dataset = pd.get_dummies(dataset, columns=[df.columns[8]]) # 将标签转为哑变量
# columns接受序列形式的对象,单个字符串不行
'''
dataset = pd.get_dummies(df)
pd.set_option('display.max_columns', 1000) # 把所有的列全部显示出来
X = dataset[dataset.columns[:-2]]
Y = dataset[dataset.columns[-2:]]
labels = dataset.columns._data[-2:]
# Step 3:将数据转换为SupervisedDataSet/ClassificationDtaSet对象
from pybrain.datasets import ClassificationDataSet
ds = ClassificationDataSet(19, 1, nb_classes=2, class_labels=labels)
for i in range(len(Y)):
y = 0
if Y['好瓜_是'][i] == 1:
y = 1
ds.appendLinked(X.ix[i], y)
ds.calculateStatistics() # 返回一个类直方图?搞不懂在做什么
# Step 4: 分开测试集和训练集
testdata = ClassificationDataSet(19, 1, nb_classes=2, class_labels=labels)
testdata_temp, traindata_temp = ds.splitWithProportion(0.25)
for n in range(testdata_temp.getLength()):
testdata.appendLinked(testdata_temp.getSample(n)[0],testdata_temp.getSample(n)[1])
print(testdata)
testdata._convertToOneOfMany()
print(testdata)
traindata = ClassificationDataSet(19, 1, nb_classes=2, class_labels=labels)
for n in range(traindata_temp.getLength()):
traindata.appendLinked(traindata_temp.getSample(n)[0], traindata_temp.getSample(n)[1])
traindata._convertToOneOfMany()
'''
# 使用sklean的OneHotEncoder
# 缺点是只能单列进行操作,最后再复合,麻烦
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelEncoder
a = LabelEncoder().fit_transform(df[df.columns[0]])
# dataset_One = OneHotEncoder.fit(df.values[])
# print(df['色泽']) # 单独的Series?
print(a)
aaa = OneHotEncoder(sparse=False).fit_transform(a.reshape(-1, 1))
print(aaa)
# 怎么复合暂时没写
'''
'''开始整神经网络'''
# Step 1 :创建神经网络框架
from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure import SoftmaxLayer
# 输入数据是 19维,输出是两维,隐层设置为5层
# 输出层使用Softmax激活,其他:学习率(learningrate=0.01),学习率衰减(lrdecay=1.0,每次训练一步学习率乘以),
# 详细(verbose=False)动量因子(momentum=0最后时步的梯度?),权值衰减?(weightdecay=0.0)
n_h = 5
net = buildNetwork(19, n_h, 2, outclass=SoftmaxLayer)
# Step 2 : 构建前馈网络标准BP算法
from pybrain.supervised import BackpropTrainer
trainer_sd = BackpropTrainer(net, traindata)
# # 或者使用累积BP算法,训练次数50次
# trainer_ac = BackpropTrainer(net, traindata, batchlearning=True)
# trainer_ac.trainEpochs(50)
# err_train, err_valid = trainer_ac.trainUntilConvergence(maxEpochs=50)
for i in range(50): # 训练50次,每及测试结果次打印训练结果
trainer_sd.trainEpochs(1) # 训练网络一次,
# 引入训练误差和测试误差
from pybrain.utilities import percentError
trainresult = percentError(trainer_sd.testOnClassData(), traindata['class'])
testresult = percentError(trainer_sd.testOnClassData(dataset=testdata), testdata['class'])
# 打印错误率
print('Epoch: %d', trainer_sd.totalepochs, 'train error: ', trainresult, 'test error: ', testresult)
|
c043dca76223b46286fd7ad05c13e2b5d337b727 | SeelamVenkataKiran/PythonTests | /Numpy/npex2.py | 1,406 | 3.9375 | 4 | import numpy as np
#first numpy array
first_numpy_array = np.array([1,3,5,7])
print(first_numpy_array)
#array with zeroes
array_with_zeroes = np.zeros((3,3))
print(array_with_zeroes)
#array with ones
array_with_ones = np.ones((3,3))
print(array_with_ones)
array_with_ones.shape
array_with_ones.size
array_with_ones.dtype
array_with_ones.ndim
#array with empty (puts in random values)
array_with_empty = np.empty((2,3))
print(array_with_empty)
#array with arange method to create arrays of certain data length
np_arange = np.arange(12)
print(np_arange)
#reshaping 1-dimensional to 2-dimensional or say 3 rows and 4 columns (using reshape method)
np_arange.reshape(3,4)
print(np_arange.reshape(4,3))
print(np_arange.reshape(3,4))
print(np_arange.reshape(6,2))
print(np_arange.reshape(2,6))
print(np_arange.reshape(1,12))
print(np_arange.reshape(12,1))
#linspace for linearly (equal) spaced data elements
np_linspace = np.linspace(1,6,5) #first ele,last ele & total no of equidistant elements
print(np_linspace)
np_linspace = np.linspace(1,10,4)
np_linspace
x = range(1,12,5)
for i in x:
print(i,end=":")
x = range(12)
for i in x:
print(i,end=',')
#one dimensional array
oneD_array = np.arange(15)
print(oneD_array)
#2 dimensional array
twoD_array = oneD_array.reshape(3,5)
print(twoD_array)
#3 dimensional array
threeD_array = np.arange(27).reshape(3,3,3)
print(threeD_array)
|
8c5fd9db07f87e199f5759bee4009bdaba35f3fd | maurogome/platzi | /python_intermedio/lists_and_dicts.py | 830 | 3.921875 | 4 | def run():
#my_list = [1, True, "Que onda", 3.5]
#my_dict = {"first_name": "Mauricio", "last_name": "Gomez"}
super_list = [
{"first_name": "Mauricio", "last_name": "Gomez"},
{"first_name": "Maria", "last_name": "Gonzalez"},
{"first_name": "Jose", "last_name": "Arango"},
{"first_name": "Sara", "last_name": "Mejia"},
]
super_dict = {
"natural_nums": [1,2,3,4,5],
"integer_nums": [-1,1,0,2],
"floating_nums": [0.5, -0.5, 4.3, 1.8],
}
for key, value in super_dict.items():
print(key, "-", value)
for value in super_list:
print(value)
squares = []
for i in range(1,101):
if i**2 % 3:
squares.append(i**2)
print(squares)
if __name__ == "__main__":
run() |
0ba8e5d96873233de71c9a2d2fdd881531404ac7 | Gwarglemar/Python | /Exercises/Kattis/2_9_beekeeper.py | 845 | 4.21875 | 4 | #Given test cases, identify the word with the most double vowels
vowels = {'a','e','i','o','u','y'}
double_vowels = {'aa','ee','ii','oo','uu'}
while True:
num_w = int(input())
if num_w == 0:
break
words = []
for _ in range(num_w):
words.append(input())
most_doubles = -1
best_word = ''
for w in words:
index = 0
double_count = 0
while index < len(w)-1:
if w[index] in vowels:
if w[index+1] == w[index]:
double_count += 1
index += 2
else:
index += 1
else:
index += 1
if double_count > most_doubles:
most_doubles = double_count
best_word = w
print(best_word) |
8e25ee266aaebbf75455560518c9e3b4eae38c5b | CarolineXiao/AlgorithmPractice | /TopologicalSorting.py | 1,242 | 3.8125 | 4 | """
Definition for a Directed graph node
class DirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
"""
class Solution:
"""
@param: graph: A list of Directed graph node
@return: Any topological order for the given graph.
"""
def topSort(self, graph):
# write your code here
nodeinDegree = self.inDegree(graph)
start = []
for node in nodeinDegree:
if nodeinDegree[node] == 0:
start.append(node)
#bfs
queue = []
top = []
for node in start:
queue.append(node)
while queue:
my_node = queue.pop(0)
top.append(my_node)
for neighbors in my_node.neighbors:
nodeinDegree[neighbors] -= 1
if nodeinDegree[neighbors] == 0:
queue.append(neighbors)
return top
def inDegree(self, graph):
nodeinDegree = {}
for node in graph:
nodeinDegree[node] = 0
for node in graph:
for neighbors in node.neighbors:
nodeinDegree[neighbors] += 1
return nodeinDegree
|
ff0c82d1a0e1f923c2e1cf350377fdd1fdaaa297 | c00t/python_playground | /python-basics/ch14/sqlscripts.py | 319 | 3.546875 | 4 | import sqlite3
sqlscripts = """
DROP TABLE IF EXISTS People;
CREATE TABLE People(
FirstName TEXT,
LastName TEXT,
Age INT
);
INSERT INTO People VALUES (
'Rex',
'Temple',
21
);
"""
with sqlite3.connect("test_database.db") as conn:
cursor = conn.cursor()
cursor.executescript(sqlscripts)
|
1a50e002aa63808b22679152026f3b03acf2542a | fvega-tr/Python-begins | /python_code/roman_numerals.py | 952 | 3.515625 | 4 | class Roman:
def __init__(self):
self.dictionary = {"M": 1000, "CM": 900, "D": 500, "CD": 400, "C": 100, "XC": 90,
"L": 50, "XL": 40, "X": 10, "IX": 9, "V": 5, "IV": 4, "I": 1}
self.dic = {"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I": 1}
def ord_to_roman(self, num):
result = ""
for key, value in self.dictionary.items():
while num >= value:
num -= value
result = result + key
return result
def roman_to_ord(self, roman_number):
n = 0
i = 0
while i < len(roman_number):
for key, value in self.dic.items():
if key == roman_number[i]:
if (i + 1) < len(roman_number) and value < self.dic[roman_number[i + 1]]:
n += (self.dic[roman_number[i + 1]] - value)
i += 1
else:
n += value
break
i += 1
return n
test = Roman()
print(test.ord_to_roman(124))
print(test.roman_to_ord("CXXIV")) |
4b7318f8c3ed8649b40a20a17a31623faaaf5a8a | vladislavneon/style-based-plagiarism-detection | /tokenizer.py | 368 | 3.609375 | 4 | import re
def tokenize(line):
re.sub(r'. . .', '...', line)
tokens = line.split()
return tokens
def tokenize_file(filename):
text = []
with open(filename, 'r') as inf:
for line in inf:
text.append(tokenize(line))
return text
def main():
text = tokenize_file("sample_input.txt")
print(text)
|
a371865760b22b90a370348fe720d731ef57724e | caroljunq/data-structure-exercises | /dijkstra.py | 4,018 | 3.8125 | 4 | # Dijkstra algorithm
from sys import maxsize as INF
import heapq
# Return the minimal distances from start to every node in graph
def dijks_distances(graph, start):
queue = []
distances = {}
prev = {}
for v in graph:
distances[v] = INF
prev[v] = None
queue.append(v)
distances[start] = 0
while len(queue) > 0:
dicio = {x:distances[x] for x in distances if x in queue}
u = min(dicio, key=dicio.get) #select the min value
queue.pop(queue.index(u))
for v, w in graph[u]:
alt = distances[u] + w
if alt < distances[v]:
distances[v] = alt
prev[v] = u
return distances, prev
# Return the path from start to end
def djks(graph, start, end):
queue = []
distances = {}
prev = {}
#stores the path from start to end
path = [] #path is a stack
#init all nodes with infinity and put into queue
for v in graph:
distances[v] = INF
prev[v] = None
queue.append(v)
#define the start node as distance 0
distances[start] = 0
while len(queue) > 0:
# select min distance in the queue
dicio = {x:distances[x] for x in distances if x in queue}
u = min(dicio, key=dicio.get)
queue.pop(queue.index(u))
#if end is hited
if u == end:
u = end
while prev[u]:
path.insert(0,u) #insert on top of the stack
u = prev[u]
path.insert(0,u)
break #break if path is found
#if path is not found, continues in the neighborhood
for v, w in graph[u]:
alt = distances[u] + w
# the distances changes if a min value is found
if alt < distances[v]:
distances[v] = alt
prev[v] = u
# return [] is case of there is no path between start and end nodes
return path if len(path) >= 2 else []
# relax( Node u, Node v, double w[][] )
# if d[v] > d[u] + w[u,v] then
# d[v] := d[u] + w[u,v]
# pi[v] := u
# The algorithm itself is now:
# shortest_paths( Graph g, Node s )
# initialise_single_source( g, s )
# S := { 0 } /* Make S empty */
# Q := Vertices( g ) /* Put the vertices in a PQ */
# while not Empty(Q)
# u := ExtractCheapest( Q );
# AddNode( S, u ); /* Add u to S */
# for each vertex v in Adjacent( u )
# relax( u, v, w )
# Dijkstra Algorithm with Priority Queue
#Input # graph = {
# 'a': {'b': 1}
# }
def dijkstra_pq(graph, start, goal):
distances = {x: INF for x in graph.keys()}
visited = []
distances[start] = 0
pq = [(0,start)]
while pq:
d,u = heapq.heappop(pq)
visited.append(u)
for v in graph[u]:
w = graph[u][v]
if v not in visited and distances[u] + w < distances[v]:
distances[v] = distances[u] + w
heapq.heappush(pq,(distances[v],v))
return distances[goal]
# graph = {
# 'Home': [('A',3),('B',2),('C',5)],
# 'A': [('D',3),('Home',3)],
# 'B': [('D',1),('Home',2),('E',6)],
# 'C': [('E',2),('Home',5)],
# 'D': [('A',3),('B',1),('F',4)],
# 'E': [('B',6),('C',2),('School',4),('F',1)],
# 'F': [('D',4),('E',1),('School',2)],
# 'School': [('E',4),('F',2)]
# }
#
# print(djks(graph,'Home','School'))
graph = {
'a': [('b',2),('c',4)],
'b': [('a',2),('c',1),('d',4),('e',2)],
'c': [('a',4),('e',3),('b',1)],
'd': [('b',4),('e',3),('f',2)],
'e': [('d',3),('b',2),('f',2),('c',3)],
'f': [('d',2),('e',2)]
}
#
# print(dijks_distances(graph,'a'))
# se não tiver caminho, retorna só uma array com o elemento final
# graph = {
# 'a': [('b',0)],
# 'b': [],
# 'c':[]
# }
#
graph = {
'a': {'b':2,'c':4},
'b': {'a':2,'c':1,'d':4,'e':2},
'c': {'a':4,'e':3,'b':1},
'd': {'b':4,'e':3,'f':2},
'e': {'d':3,'b':2,'f':2,'c':3},
'f': {'d':2,'e':2}
}
print(dijkstra_pq(graph,'a','f'))
|
dd58f7f1fb49839df1d59771d840aabe8e1f19c4 | VamsiKrishnaRachamadugu/python_solutions | /problemset3/7.letters_in_word.py | 520 | 4.4375 | 4 | """7.Write a function named using_only() that takes a word and a string of letters, and that returns True
if the word contains only letters in the list. Can you make a sentence using only the letters acefhlo?
Other than "Hoe alfalfa?"
"""
def using_only(word, letters_string):
for char in word:
if char not in letters_string:
return False
else:
return True
in_word = input('Enter the name: ')
letter_string = input('Enter charceters: ')
print(using_only(in_word, letter_string))
|
1c6fb0b34434bca7552b7d1243a30cd014bcc478 | frclasso/revisao_Python_modulo1 | /cap04-tipos-variaveis/04_tuple_variables.py | 466 | 4.28125 | 4 | #!/usr/bin/env python3
minhatupla = ('abcd', 786, 2.23, 'john', 70.2)
tinytupla = (123, 'john')
print(minhatupla)
print(minhatupla[0])
print(minhatupla[1:3])
print(minhatupla[2:])
print(tinytupla * 2)
print(minhatupla+tinytupla)
# o codigo abaixo eh invalido para tuplas, mas funciona para listas
#minhatupla[2] = 1000 # TypeError: 'tuple' object does not support item assignment
#tinytupla[0] = 1000 # TypeError: 'tuple' object does not support item assignment |
0917bf1dd26bb0353c1238a9cc9b23f3a60b4b8b | xodud001/coding-test-study | /peacecheejecake/brute_force/12919_A와B2.py | 537 | 3.71875 | 4 | # https://www.acmicpc.net/problem/12919
#
def check(s, t, backward):
if s[0] == 'B' and t[0] == 'A':
return False
s = s[::(-1) ** backward]
start, end = 0, len(s)
is_possible = False
while end <= len(t):
u = t[start:end]
if (u == s and
t[:start].count('B') == t[end:].count('B') + backward):
is_possible = True
break
start += 1
end += 1
return is_possible
s = input()
t = input()
print(int(check(s, t, False) or check(s, t, True)))
|
80ac03ec59b5907203947d278c3ccd2144399bac | pelletier197/Sudoku-Python | /game/SudokuSolver.py | 6,311 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module contains the sudoku solver for a sudoku grid
"""
__auteur__ = "SUPEL55"
__date__ = "2016-11-21"
__coequipiers__ = "RABOU264", "ANMIG8"
class SudokuSolver:
"""
Grid solver for a sudoku grid.
"""
def solve(self, sudokugrid):
"""Returns the solved sudoku grid associated to the given sudoku grid
Solves the given sudoku grid and returns it as a new grid. The grid given in parameter is copied
and kept as it is.In case that the given grid has no solution, None type is returned instead of
the solution grid.Set shuffle parameter to true to activate the shuffle solving. May only be
used if the function is called to generate the sudoku.
"""
if self.__respect_rules(sudokugrid):
grid = sudokugrid.copy()
empty = self.find_holes(grid)
current_index = 0
# We have one list for components in lines, col and square
lines, col, sq = self.__init_possibilities(grid)
tried = [set() for i in empty]
length = len(empty)
# Sorry not sorry for the while
while current_index < length:
# The current index we test
(i, j) = empty[current_index]
current_line = lines[i]
current_col = col[j]
current_sq = sq[grid.get_square_number(i, j)]
current_try = tried[current_index]
current_possi = (current_line & current_col & current_sq) - current_try
if len(current_possi) != 0:
# Pops the first value and test it
test = current_possi.pop()
current_try.add(test)
current_line.remove(test)
current_col.remove(test)
current_sq.remove(test)
grid[i, j] = test
current_index += 1
# There is zero possibilities for this case, so we backtrack
else: # The current possibilities are reset, as we go back, so possibilities may change
tried[current_index].clear()
current_index -= 1
# No solution we backtracked behind possibilities, so None is returned
if current_index < 0:
return None
previous_index = empty[current_index]
(i, j) = previous_index
previous_item = grid[previous_index]
lines[i].add(previous_item)
col[j].add(previous_item)
sq[grid.get_square_number(i, j)].add(previous_item)
grid[previous_index] = None
else:
return None
return grid
@staticmethod
def __init_possibilities(grid):
"""Finds the possibilities for the lines, columns and squares removing the elements from
the grid that are present in them. The result are returned as a tuple containing
(possibilities for each lines, possibilities for each columns, possibilities for each square
"""
avail = set([i for i in range(1, 10)])
lines, col, sq = [], [], []
for i in range(9):
lines.append(avail - set(grid.get_line(i)))
col.append(avail - set(grid.get_column(i)))
sq.append(avail - set(grid.get_square(i)))
return lines, col, sq
def __respect_rules(self, sudoku_grid):
"""
Verifies if the given sudoku grid respects the rules of the game.
Checks if each line, column and square only contain one instance of every number.
"""
for i in range(sudoku_grid.width):
line = sudoku_grid.get_line(i)
col = sudoku_grid.get_column(i)
sq = sudoku_grid.get_square(i)
if self.__sum(line) != self.__sum(set(line)) or self.__sum(col) != self.__sum(set(col)) \
or self.__sum(sq) != self.__sum(set(sq)):
return False
return True
def get_rules_not_respected(self, grid):
"""
Returns a set containing the elements in the grid that do not respect the sudoku rules.
For instance if there is sevens in a row, the function will return the index in the grid
of the 2 sevens meaning that both of them are not correct
"""
doubles = []
for i in range(grid.width):
line = self.__check_doubles(grid.get_line(i))
col = self.__check_doubles(grid.get_column(i))
sq = self.__check_doubles(grid.get_square(i))
doubles = doubles + [(i, e) for e in line]
doubles = doubles + [(e, i) for e in col]
doubles = doubles + [(i // 3 * 3 + e // 3, (i % 3) * 3 + e % 3) for e in sq]
return set(doubles)
@staticmethod
def __check_doubles(num_list):
"""Check for doubles in a given list and return the double"""
seen = {}
indexes = set()
for i, obj in enumerate(num_list):
if obj is not None:
if obj in seen.keys():
indexes.add(i)
indexes.add(seen.get(obj))
seen[obj] = i
return indexes
@staticmethod
def __sum(it):
"""
Calculates the sum of the given iterable, considering None as a 0 value.
This function should not be called from outside this class.
"""
count = 0
for i in it:
if i is not None:
count += i
return count
@staticmethod
def find_holes(sudoku_grid):
"""
Finds empty spaces in the grid, where there are no number (None), and return them as a
List of type containing the line and the column of those spaces.
"""
result = []
for i in range(sudoku_grid.height):
for j in range(sudoku_grid.width):
if sudoku_grid[i, j] is None:
result.append((i, j))
return result
|
9eb23079d2c7c9aa894fd4f94dfc36c79855888a | SunnyLyz/image_augmentation | /image_augmentation/image/layers.py | 4,673 | 3.5 | 4 | """Pre-processing layers for few image op(s)."""
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
from tensorflow.python.keras.utils import conv_utils
from image_augmentation.image.image_ops import cutout
class RandomCutout(Layer):
"""Apply random Cutout on images as described in
https://arxiv.org/abs/1708.04552. Internally, this layer
would make use of `image_augmentation.image.cutout`.
Note: as this is a pre-processing layer, Cutout operation is
only applied at train time and this layer has no effect at
inference time.
Args:
size: the size of Cutout region / square patch.
color: Value of each pixel that is to be filled in the square
patch formed by Cutout.
name: Optional name of the layer. Defaults to 'RandomCutout'.
**kwargs: Additional arguments that is to be passed to super class.
"""
def __init__(self, size=16, color=128, name=None, **kwargs):
super(RandomCutout, self).__init__(name=name, **kwargs)
self.size = size
self.color = color
def call(self, inputs, training=True):
with tf.name_scope(self.name or "RandomCutout"):
if training is None:
training = K.learning_phase()
if training:
return tf.map_fn(lambda x: cutout(x, self.size, self.color), inputs)
else:
return inputs
def compute_output_shape(self, input_shape):
return input_shape
def get_config(self):
config = {
"size": self.size
}
base_config = super(RandomCutout, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class ReflectPadding2D(Layer):
"""Applies reflect padding to 2D inputs. This layer is very
similar to `tf.keras.layers.ZeroPadding2D` except that it makes
use of reflect padding mode instead of zeros.
Args:
padding: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.
- If int: the same symmetric padding
is applied to height and width.
- If tuple of 2 ints:
interpreted as two different
symmetric padding values for height and width:
`(symmetric_height_pad, symmetric_width_pad)`.
- If tuple of 2 tuples of 2 ints:
interpreted as
`((top_pad, bottom_pad), (left_pad, right_pad))`
name: Optional name of the layer. Defaults to 'ReflectPadding2D'.
**kwargs: Additional arguments that is to be passed to super class.
"""
def __init__(self, padding=4, name=None, **kwargs):
super(ReflectPadding2D, self).__init__(name=name, **kwargs)
if isinstance(padding, int):
self.padding = ((padding, padding), (padding, padding))
elif hasattr(padding, '__len__'):
if len(padding) != 2:
raise ValueError('`padding` should have two elements. '
'Found: ' + str(padding))
height_padding = conv_utils.normalize_tuple(padding[0], 2,
'1st entry of padding')
width_padding = conv_utils.normalize_tuple(padding[1], 2,
'2nd entry of padding')
self.padding = (height_padding, width_padding)
else:
raise ValueError('`padding` should be either an int, '
'a tuple of 2 ints '
'(symmetric_height_pad, symmetric_width_pad), '
'or a tuple of 2 tuples of 2 ints '
'((top_pad, bottom_pad), (left_pad, right_pad)). '
'Found: ' + str(padding))
def compute_output_shape(self, input_shape):
input_shape = tf.TensorShape(input_shape).as_list()
rows = input_shape[1] + self.padding[0][0] + self.padding[0][1]
cols = input_shape[2] + self.padding[1][0] + self.padding[1][1]
return tf.TensorShape([
input_shape[0], rows, cols, input_shape[3]])
def call(self, inputs, *kwargs):
# currently, only NHWC format is supported
with tf.name_scope(self.name or "ReflectPadding2D"):
pattern = [[0, 0], list(self.padding[0]), list(self.padding[1]), [0, 0]]
return tf.pad(inputs, pattern, mode='REFLECT')
def get_config(self):
config = {'padding': self.padding}
base_config = super(ReflectPadding2D, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
|
582e1f8bc603d2c797f1f588a55630584e73114b | dhrubach/python-code-recipes | /binary_tree/e_search_clone_tree.py | 1,357 | 3.703125 | 4 | ######################################################################
# LeetCode Problem Number : 700
# Difficulty Level : Easy
# URL : https://leetcode.com/problems/search-in-a-binary-search-tree/
#####################################################################
from binary_search_tree.tree_node import TreeNode
class BinaryTreeCloneSearch:
def getTargetCopy(
self, original: TreeNode, cloned: TreeNode, target: TreeNode
) -> TreeNode:
if cloned.val == target.val:
return cloned
return self.searchClonedNode(cloned, target.val)
def searchClonedNode(self, node: TreeNode, val: int) -> TreeNode:
if not node:
return None
if node.val == val:
return node
found_node = self.searchClonedNode(node.left, val)
if not found_node and node.right:
found_node = self.searchClonedNode(node.right, val)
return found_node
def getTargetCopy_stack(
self, original: TreeNode, cloned: TreeNode, target: TreeNode
) -> TreeNode:
# dfs
stack = [cloned]
while stack:
node = stack.pop()
if node.val == target.val:
return node
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
|
62487eef2cc592ff9803b1fe544d95113d5518ac | corinnejachelski/code_challenges | /recursion.py | 1,237 | 4.4375 | 4 |
def decodeVariations(S):
"""
@param S: str
@return: int
A letter can be encoded to a number in the following way:
'A' -> '1', 'B' -> '2', 'C' -> '3', ..., 'Z' -> '26'
A message is a string of uppercase letters, and it is encoded first using this scheme. For example, 'AZB' -> '1262'
Given a string of digits S from 0-9 representing an encoded message, return the number of ways to decode it.
Examples:
input: S = '1262'
output: 3
explanation: There are 3 messages that encode to '1262' : 'AZB', 'ABFB', and 'LFB'.
"""
#base case: string is 2 or less chars
if len(S) == 1:
return 1
elif len(S) == 2 and int(S) <= 26:
return 2
elif len(S) <= 2:
#chars over 26 that end in 0 are not valid bc 0 does not translate to letter
if int(S[-1]) == 0:
return 0
else:
return 1
#take 1st char in string and 1st 2 chars (check if less than 26 for valid char)
char1 = S[0]
char2 = S[0:2]
char1_remain = S[1:]
char2_remain = S[2:]
if int(char2) > 26:
return decodeVariations(char1_remain)
else:
return decodeVariations(char1_remain) + decodeVariations(char2_remain)
|
f2db6eafb673806eaec3e21ff32bab2b5e1eb103 | VictorFAL/PythonProjects | /Submarine/dataclass_version/main.py | 2,742 | 4.21875 | 4 | from Submarine import Submarine
# x validation
def x_input():
while True:
try:
x = int(input('X = '))
except:
print('X value must be a number.')
continue
break
return x
# y validation
def y_input():
while True:
try:
y = int(input('Y = '))
except:
print('Y value must be a number.')
continue
break
return y
# z validation
def z_input():
while True:
try:
z = int(input('Z = '))
assert z <= 0
except:
print('Z value must be a number and zero or less.')
continue
break
return z
# direction validation
def direction_input():
cardinal = ('NORTH', 'EAST', 'SOUTH', 'WEST')
while True:
try:
direction = input('Direction = ').upper()
assert direction == 'NORTH' or direction == 'EAST' or direction == 'SOUTH' or direction == 'WEST'
except:
print('Direction must be North, South, East, or West.')
continue
break
direction = cardinal.index(direction)
return direction
# command validation
def comm_input():
while True:
try:
comm = input('Commands: ').upper()
for letter in comm:
assert letter =='U' or letter == 'D' or letter == 'L' or letter == 'R' or letter == 'M'
except:
print('Command must contain valid orders.')
continue
break
return comm
# =============================================================================
def main():
# starting positions
print('''\nInsert the submarine's starting X, Y and Z positions as well
as the cardinal direction that its facing.\n
[NOTE: Z = 0 represents the water's surface]\n\n''')
while True:
try:
default = input('Use default values (X = 0, Y = 0, Z = 0, Direction = NORTH)? [Y/N]: ').upper()
assert default == 'Y' or default == 'N'
except:
print('Please, insert a valid response.\n')
continue
break
if(default == 'Y'):
# instancing object
sub = Submarine()
else:
x = x_input()
y = y_input()
z = z_input()
direction = direction_input()
# instancing object
sub = Submarine(x, y, z, direction)
# command
print('''\nInsert the submarine's movement orders (e.g. "LMRDDMMUU")
U = Up\n D = Down\n L = turn Left\n R = turn Right\n M = Move''')
comm = comm_input()
new_positon = sub.command(comm)
print(f'\n\nThe submarine is now on {new_positon}')
if __name__ == '__main__':
main() |
181ca89ed4ac43879baee932c1bbeb181eaa61cd | Farhana-Afrin-Maysha/chor_police_game_python | /chor_police_PREVIOUS.py | 1,305 | 3.765625 | 4 | import random
def call_police():
print('The index of Boss is: ', mylist.index(100))
print('The index of Police is: ', mylist.index(80))
y = int(input('Say the index no of thief. '))
if (y == mylist.index(00)):
print('You are correct')
else:
print('You are not correct')
msg = "Welcome to chor-police game"
print(msg)
nums = [00, 80, 60, 100]
random.shuffle(nums)
print(nums)
mylist = [n for n in nums]
player1 = mylist[0]
#
# mylist = remove.(mylist[0])
#
player2 = mylist[1]
player3 = mylist[2]
player4 = mylist[3]
#
print(player1)
# print(player2)
# print(player3)
# print(player4)
# arr = array('i', [])
x = int(input('Enter a value (from 0-3). '))
# for i in range(4):
# x = int(input('Enter the next value (from 0-3). '))
# arr.append(x)
#
# print(arr)
if (x <= 3):
if (mylist[x] == 00):
print(' You have got the "Thief = 00" card ')
print(call_police())
elif (mylist[x] == 80):
print(' You have got the "Police = 80" card')
print(call_police())
elif (mylist[x] == 60):
print(' You have got the "Robber = 60" card')
print(call_police())
elif (mylist[x] == 100):
print(' Your have got the "Boss = 100" card')
print(call_police())
else:
print('Your input is not valid')
|
8da246bb5ddd3806dbe6debfe06db7cdce4f57fc | Savely-Prokhorov/DifferentPythonSolutions | /UniLecsTasks/15. WaterVolumeInHist.py | 699 | 3.71875 | 4 | """
Задача: Дана гистограмма, она представлена числовым массивом:
[3, 6, 2, 4, 2, 3, 2, 10, 10, 4]
Нужно посчитать объем воды (1 блок в гистограмме), ктр наберется внутри нее.
"""
from matplotlib import pyplot as plt
arr = [3, 6, 2, 4, 2, 3, 2, 10, 10, 4, 5, 6, 4, 10]
plt.bar(range(len(arr)), arr)
plt.show()
water = 0
j = 0
for i in range(len(arr) - 1):
if i < j:
continue
if arr[i + 1] < arr[i]:
start = i
j = start + 1
while arr[i] > arr[j]:
water += arr[i] - arr[j]
j += 1
print(water)
|
79ce1866c7b88ea10407873aa097e08567c99de0 | chisness/aipoker | /poker_ai-master/new_python/kuhn3p/players/TE.py | 7,186 | 3.640625 | 4 | import random
from kuhn3p import betting, deck, Player
class TE(Player):
def __init__(self, rng=random.Random()):
self.rng = rng
self.betting_round = 0
# A list of where each player is seated for the round
self.agent_p1_p2_positions = []
# Checks track of the total number of a certain action each player performed
self.raises = [0,0,0]
self.calls = [0,0,0]
self.checks = [0,0,0]
self.folds = [0,0,0]
# The likelyhood a raise is a bluff (must be divided by self.raise)
self.raise_bluff = [0,0,0]
# Creates 2-D arrays; an array for each acting state
# this stores what the result of a match was given the agent's choices
self.state_results = self.two_d_array(betting.num_internal())
# A group of 2-D arrays saying what state occured in the round and its outcome
self.changed_states = []
def __str__(self):
return 'Learning Agent'
def two_d_array(self, size):
array = []
for x in range(size):
array.append([0,0])
return array
def start_hand(self, position, card):
self.betting_round += 1
self.agent_p1_p2_positions = [position, (position + 1) % 3,
(position + 2) % 3]
self.changed_states = []
def end_hand(self, position, card, state, shown_cards):
shown_cards = self.reorder(shown_cards)
actions = self.reorder(self.get_actions(state))
winner = self.winner(actions, shown_cards)
self.adjust(state, shown_cards, actions, winner)
# Always bet on Ace. Always fold on Jack
def act(self, state, card):
action = 0
num_players = 0
if betting.can_bet(state):
if self.rng.random() >= self.algo(card, state):
action = betting.BET
else:
action = betting.CALL
else:
if self.rng.random() >= 1.1 * self.algo(card, state):
action = betting.CALL
else:
action = betting.FOLD
self.changed_states.append([state, action])
return action
# Returns the likelyhood of performing action 1 (either a check or a fold)
def algo(self, card, state):
chance = self.card_odds(card, state)
return chance
# The model for the learning algorithm
def state_percent_model(self, state_result):
if state_result[0] == state_result[1]:
return 0.5
else:
m = max(state_result)
n = min(state_result)
s = m - n
if state_result[0] > state_result[1]:
return (s+1)/((s+1.0)**2)
else:
return 1.0 - (s+1)/((s+1.0)**2)
# This is where the agent updates its knowledge base after each round
def adjust(self, state, shown_hands, actions, winner):
payoff = 0
if winner == 0: # if the agent wins
payoff = -1 * betting.pot_contribution(state, self.agent_p1_p2_positions[0])
else:
payoff = betting.pot_size(state)
# record the results for those states
for x in range(len(self.changed_states)):
state_id = self.changed_states[x][0]
action_id = self.changed_states[x][1]
self.state_results[state_id][action_id] += payoff
for x in range(len(self.agent_p1_p2_positions)):
if actions[x].find("r") != -1:
self.raises[x] += 1
if shown_hands[x] != None:
self.raise_bluff[x] += self.card_odds(shown_hands[x], None, shown_hands)
if actions[x].find("k") != -1:
self.checks[x] += 1
if actions[x].find("c") != -1:
self.calls[x] += 1
if actions[x].find("f") != -1:
self.folds[x] += 1
# Determines the odds of anyone having a higher card than the agent
def card_odds(self, card, state=None, shown_hands=None):
assert state != None or shown_hands != None
odds = (deck.ACE - card) / 3.0
if state != None:
odds *= self.other_players(state)
else:
odds *= (3.0 - self.num_folds(shown_hands))
if odds >= 1.0:
return 1.0
else:
return odds
# Returns the number of other players that havent folded
def other_players(self, state):
if betting.facing_bet_fold(state):
return 1
else:
return 2
# Determines the number of folds in a given hand
def num_folds(self, shown_hands):
sum_folds = 0
for x in range(len(shown_hands)):
if shown_hands[x] == None:
sum_folds += 1
return sum_folds
# Determines the winner of this round
def winner(self, actions, shown_cards):
# If everyone folded, determine winner by who raised
if shown_cards == [None, None, None]:
return actions.index("r")
else:
return shown_cards.index(max(shown_cards))
# Reorders game arrays so that the agent is in position 0
def reorder(self, object_list):
new_list = []
for x in range(len(self.agent_p1_p2_positions)):
new_list.append(object_list[self.agent_p1_p2_positions[x]])
return new_list
# Returns what actions each agent commited as an array
def get_actions(self, state):
old_actions = betting.to_string(state)
actions = ""
is_check = True
for x in range(len(old_actions)):
if old_actions[x] == "r":
is_check = False
if is_check is True and old_actions[x] == "c":
actions += "k"
else:
actions += old_actions[x]
new_list = ["", "", ""]
for x in range(len(actions)):
new_list[x%3] += actions[x]
return new_list
|
42402da2fb1e4e09ca337de057da35a3cafc5bee | lucassaporetti/castlevania_inventory_system | /src/core/enum/item_type_enum.py | 651 | 3.578125 | 4 | from enum import Enum
class ItemType(Enum):
UNIQUE = 1
FIST_WEAPON = 2
SHORT_SWORD_WEAPON = 3
SWORD_WEAPON = 4
CLUB_WEAPON = 5
TWO_HANDED_WEAPON = 6
THROWING_SWORD_WEAPON = 7
BOMB_WEAPON = 8
PROJECTILE_WEAPON = 9
SUB_WEAPON = 10
HEAD_ARMOR_CLOTHE = 11
BODY_ARMOR_CLOTHE = 12
GAUNTLET_ARMOR_CLOTHE = 13
CLOAK_ARMOR_CLOTHE = 14
BOOT_ARMOR_CLOTHE = 15
RING_OTHER = 16
NECKLACE_OTHER = 17
BELT_OTHER = 18
BROOCH_OTHER = 19
MEDICINE_CONSUMABLE = 20
FOOD_CONSUMABLE = 21
DRINK_CONSUMABLE = 22
CARD_CONSUMABLE = 23
def __str__(self):
return self.name
|
589c3023cea1c8829193516da449ae10202fd71e | cielo-cerezo-tm/tutoring | /plantshop.py | 861 | 4.125 | 4 | class Plant:
def __init__(self, number_of_leaves, root_system, growth_in_inches):
self.number_of_leaves = number_of_leaves
self.root_system = root_system
self.growth_in_inches = growth_in_inches
def grow(self, no_inches):
self.growth_in_inches = no_inches
def wither(self, how_many_leaves_fall):
self.number_of_leaves -= how_many_leaves_fall
def propagate(self, number_of_weeks):
if (number_of_weeks > 3):
print("hurry up and propagate. this plant is now " + str(number_of_weeks) + " weeks")
elif (number_of_weeks == 3):
print("now is the best time to propagate")
else:
print("this plant is too young")
rose = Plant(7, True,10)
cactus = Plant(0, True,20)
rose.wither(5)
rose.grow(15)
cactus.propagate(5)
|
2c7310ab0e80ce9e0fb5d18556f596a07d23c535 | ggozlo/Python_training | /section10.py | 3,426 | 3.71875 | 4 | #파이썬 예외처리의 이해
# 예외 종류
# 문법적으로 에러가 없지만, 코드 실행(런타임)프로세스 에서 발생하는 예외 처리도 중요
# linter : 코드 스타일, 문법 체크
# SyntaxError : 잘못된 문법
# print('test
# if True
# pass
# x => y
# NameError = 참조변수 없음
a = 10
b = 15
#print(c)
# ZeroDivisionError : 0 나누기 에러
# print(10/0)
# IndexError : 인덱스 범위 오버
x = [10,20,30]
print(x)
# print(x[3])
# KeyError
dic = {'name': 'kim', 'age' : 33, 'City':'Seoul'}
#print(dic['hobby'])
print(dic.get('hobby'))
# AttributeError : 모듈 , 클래스에 있는 잘못된 속성 사용시에 예외
import time
print(time.time())
#print(time.month())
# ValuError : 참조 값이 없을 떄 발생
x = [ 1, 5, 9]
# x.remove(10)
# x.index(10)
# FileNotFiundError
# f = open('test.txt', 'r')
# TypeError
x = [1,2]
y = (1,2)
z = 'test'
# print(x+y)
# print(x+z)
# print(x + list(y)) # 캐스팅
# 항상 예외가 발생하지 않을 것으로 가정하고 먼저 코딩
# 런타임 예외 발생시 예외 처리 코딩 권장 ( EAFP 코딩 스타일 )
# 예외 처리 기본
# try : 에러가 발생할 가능성이 있는 코드 실행
# except : 에러명 1
# except : 에러명 2
# else : 에러가 발생하지 않았을 경우 실행
# finall : 항상 실행
# 예제 1번
name = ['kim', 'lee' , 'park']
# try:
# z = 'Kim'
# x = name.index(z)
# print('{} found if! in name'.format(z,x+1))
# except ValueError :
# print('not found it! - occurred valueError!')
# else: # try 문이정상 실행되었을떄 ( except 문이 작동하지 않았을때 실행 )
# print('OK! else!')
#예제 2
# try:
# z = 'kim'
# x = name.index(z)
# print('{} found if! in name'.format(z,x+1))
# except : # 에러유형을 미지정시 모든 에러 포착
# print('not found it! - occurred Error!')
# else: # try 문이정상 실행되었을떄 ( except 문이 작동하지 않았을때 실행 )
# print('OK! else!')
# 예제 3
# try:
# z = 'Cho'
# x = name.index(z)
# print('{} found if! in name'.format(z,x+1))
# except :
# print('not found it! - occurred valueError!')
# else: # try 문이정상 실행되었을떄 ( except 문이 작동하지 않았을때 실행 )
# print('OK! else!')
# finally : # 에러 발생 유무에 관계 없이 실행
# print('finall ok!')
# 예제 4
# 예외 처리는 하지 않지만 무조건 수행되는 코딩 패턴
try :
print("try")
finally:
print("ok Finally!")
# 예제 5
try:
z = 'jim'
x = name.index(z)
print('{} found if! in name'.format(z))
except ValueError as l : # 오류 출력 내용을 allias 를 이용하여 변수에 저장도 가능함
print(l)
except IndexError :
print("Error")
except Exception : # 모든 에러에 대해서 발생, 여러 종류의 except 문을 사용한다면 가장 하단에 위치해야함
pass
else: # try 문이정상 실행되었을떄 ( except 문이 작동하지 않았을때 실행 )
print('OK! else!')
# 예제6
# 예외 발생 : raise
# raise 키워드로 예외 직접 발생
try :
a = 'kim'
if a == 'kim':
print('허가')
else :
raise ValueError # 허가된 사용자가 아니라면 오류를 발생시킴
except ValueError:
print('문제 발생!')
except Exception as f:
print(f)
else:
print('ok!') |
4f9e1e66b133e2e5b52f9fde0470d41f386b4638 | collins-m/comparative_programming_languages_2 | /object_oriented/src/classes/Node.py | 2,547 | 3.984375 | 4 | class Node:
def __init__(self, data):
""" initialize with a data value and left/right links
"""
self._data = data
self._left = None
self._right = None
def data(self, param=None):
""" getter/setter for data
"""
if param == None:
return self._data
else:
self._data = param
def left(self, param=None):
""" getter/setter for left traversal
"""
if param == None:
return self._left
else:
self._left = param
def right(self, param=None):
""" getter/setter for right traversal
"""
if param == None:
return self._right
else:
self._right = param
def insert(self, data):
""" insert data onto node
"""
if self.data():
if data < self.data():
if self.left() is None:
self.left(Node(data))
else:
self.left().insert(data)
elif data > self.data():
if self.right() is None:
self.right(Node(data))
else:
self.right().insert(data)
else:
print("Integer {} already present in tree".format(data))
else:
self.data(data)
def search(self, data):
""" search for data in tree
"""
if data < self.data():
if self.left() is None:
return False
return self.left().search(data)
elif data > self.data():
if self.right() is None:
return False
return self.right().search(data)
else:
return True
def preorder(self):
""" list nodes using preorder
"""
print(self.data())
if self.left():
self.left().preorder()
if self.right():
self.right().preorder()
def inorder(self):
""" list nodes using inorder
"""
if self.left():
self.left().inorder()
print(self.data())
if self.right():
self.right().inorder()
def postorder(self):
""" list nodes using postorder
"""
if self.left():
self.left().postorder()
if self.right():
self.right().postorder()
print(self.data())
def ___str___(self):
""" string method returns data
"""
return str(self._data)
|
cf0e44ee58df6369796469f3643233e12e7e3d39 | WillyNathan2/Python-Dasar | /T02_2072037/T02A_2072037.py | 1,922 | 3.78125 | 4 | # File : T02A_2072037
# Penulis : Willy Natanael Sijabat
# Deskripsi : Mencari karakter dalam string yang sudah diberi value integer
# Kamus : NamaDepan = string
# : NamaBelakang = string
# : Words = integer
# : FineWords = code (string)
def main ():
#program
NamaDepan = str(input("Nama Depan :"))
Namabelakang = str(input("Nama Belakang :"))
Words = int(input("Kode huruf yang ingin dicari :"))
NamaLengkap = NamaDepan+" "+Namabelakang
if(Words == 1):
Code = "a"
elif(Words == 2):
Code = "b"
elif(Words == 3):
Code = "c"
elif(Words == 4):
Code = "d"
elif(Words == 5):
Code = "e"
elif(Words == 6):
Code = "f"
elif(Words == 7):
Code = "g"
elif(Words == 8):
Code = "h"
elif(Words == 9):
Code = "i"
elif(Words == 10):
Code = "j"
elif(Words == 11):
Code = "k"
elif(Words == 12):
Code = "l"
elif(Words == 13):
Code = "m"
elif(Words == 14):
Code = "n"
elif(Words == 15):
Code = "o"
elif(Words == 16):
Code = "p"
elif(Words == 17):
Code = "q"
elif(Words == 18):
Code = "r"
elif(Words == 19 ):
Code = "s"
elif(Words == 20 ):
Code = "t"
elif(Words == 21 ):
Code = "u"
elif(Words == 22 ):
Code = "v"
elif(Words == 23 ):
Code = "w"
elif(Words == 24 ):
Code = "x"
elif(Words == 25 ):
Code = "y"
elif(Words == 26 ):
Code = "z"
FindWords = Code in NamaLengkap
print("Nama Lengkap :",NamaLengkap)
if (FindWords == True):
print(Code,"ditemukan dalam nama", NamaLengkap)
else:
print(Code,"tidak ditemukan dalam",NamaLengkap)
if __name__ == '__main__':
main()
|
c2f362a31e0748dd8c2a7ab128131286ae505da4 | lxh1997zj/Note | /廖雪峰python3教程/廖雪峰python3基础部分/test.py | 86 | 3.65625 | 4 | #!/usr/bin/python
#-*-coding:utf-8-*
num=input("please input your name:")
print(num) |
f08569394e820e6e3ef087e925d7d5606757a3f8 | Wondrous/web | /wondrous/utilities/rank_utilities.py | 1,638 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Company: WONDROUS
# Created by: John Zimmerman
#
# RANK_UTILITIES.PY
#
import operator
class RankUtilities(object):
@staticmethod
def rank_score(up_votes, down_votes):
"""
***
NOT IN USE, BUT KEPT SO IF WE WANT TO ALGORITHMICALLY
RANK ITEMS, WE CAN.
***
PURPOSE: The algorithm to rank items
USE: Call like: RankUtilities.rank_score(<int>, <int>)
PARAMS: 2 params, int up_votes and int down_votes
RETURNS: A integer that is the "score" of a particular item
"""
return 1
@staticmethod
def rank_items(item_list):
"""
***
NOT IN USE, BUT KEPT SO IF WE WANT TO ALGORITHMICALLY
RANK ITEMS, WE CAN.
***
PURPOSE: Rank a list of items, given their some
set of data on which to rank
USE: Call like: RankUtilities.rank_items(<list>)
PARAMS: 1 param, list of dictionaries, item_list
RETURNS: A list of the original item_list,
with each value's dictionary containing a
new key 'rank_score', whose value is used
to sort the list.
"""
ranked_items = []
for item in item_list:
item['rank_score'] = RankUtilities.rank_score()
ranked_items.append([item['rank_score'], item])
ranked_items.sort(key=operator.itemgetter(0), reverse=True)
return [item[1] for item in ranked_items]
|
fdc7ca61b9b54708df311ab62759cdb4fc643fda | arminAnderson/CodingChallenges | /ProjectEuler/Python/LargestPalindrome.py | 368 | 3.59375 | 4 | def IsPalindrome(num):
flip = 0
og = num
while num > 0:
flip *= 10
flip += num % 10
num //= 10
return og == flip
i = 999
j = 999
largest = 0
while i > 99:
while j > 99:
if IsPalindrome(i * j):
if largest < i * j:
largest = i * j
j -= 1
i -= 1
j = i
print(largest)
|
1ebde6854e10d2ba935f33a180b92eefe83c897a | Vladooha/Python_Labs | /Lab2/Zad2/Zad2.py | 745 | 3.53125 | 4 | import csv
with open('items.csv', 'r+', newline="", encoding="utf8") as items_file:
items = csv.DictReader(items_file, delimiter=';')
columns = items.fieldnames
min_price_item = None
max_price_item = None
for item in items:
price = item["Цена"]
if min_price_item is None or min_price_item["Цена"] > price:
min_price_item = item
if max_price_item is None or max_price_item["Цена"] < price:
max_price_item = item
with open('result.csv', 'w+', newline="", encoding="utf8") as result_file:
item_writer = csv.DictWriter(result_file, fieldnames = columns)
item_writer.writeheader()
item_writer.writerows([min_price_item, max_price_item]) |
70a050f9a71292b511f869b10cb72ceb5682b40e | Kaustubh05334/defang_ip | /defang_ip.py | 158 | 3.703125 | 4 | def defang_ip(ip):
d_ip = ip.split(".")
defanged_ip= "[.]".join(d_ip)
return defanged_ip
x= input("Enter a ip address: ")
print(defang_ip(x)) |
942c9b149cbff794c6e57ec7c4045ea49d1b5f18 | HarikaSabbella/EulerServer | /Euler/euler-project/src2/EulerDAG/aaa.py | 1,752 | 3.5625 | 4 | import itertools
#remove the duplicate tuples in list
def remove_dup_tuples_in_list(l):
l.sort()
return list(l for l,_ in itertools.groupby(l))
def tuple_not_in_list(t,li):
for aTuple in li:
if t == aTuple:
return False
return True
o_list = [("B","C"),("A","B"),("C","D"),("D","E"),("A","E")]
transi_tuple = ()
transi_list = []
update_transi_list = [("","")]
drop_list = []
# remove the transitive reductions in original_list in first round
for i in range(len(o_list)-1):
for j in range(i+1,len(o_list)):
if o_list[i][1] == o_list[j][0]:
transi_list.append((o_list[i][0], o_list[j][1]))
elif o_list[i][0] == o_list[j][1]:
transi_list.append((o_list[j][0],o_list[i][1]))
transi_list = remove_dup_tuples_in_list(transi_list)
for member in transi_list:
if tuple_not_in_list(member, o_list) == False:
drop_list.append(member)
# remove the transitive reductions in original_list and transi_list for following rounds
while len(update_transi_list) != 0:
update_transi_list = []
for member1 in o_list:
for member2 in transi_list:
if member1[1] == member2[0]:
update_transi_list.append((member1[0], member2[1]))
elif member1[0] == member2[1]:
update_transi_list.append((member2[0],member1[1]))
update_transi_list = remove_dup_tuples_in_list(update_transi_list)
for member in update_transi_list:
if tuple_not_in_list(member, o_list) == False:
drop_list.append(member)
transi_list = update_transi_list
drop_list = remove_dup_tuples_in_list(drop_list)
print "o_list = ", o_list
print "transi_list = ", transi_list
print "drop_list = ", drop_list
|
c4975c4fe9ae111c151e6aba8755b6476eb657bf | alangm7/Learn_Python_MIT_course_EdX | /Palindrome.py | 510 | 4.1875 | 4 | """Write a Python function that returns True if aString is a palindrome (reads the same forwards or reversed) and False otherwise. Do not use Python's built-in reverse function or aString[::-1] to reverse strings.
This function takes in a string and returns a boolean."""
def isPalidrome(word):
result = {}
x = len(word) - 1
for i in range(len(word)):
result[i] = word[(i - x) * (-1)]
final = "".join(result.values())
if final == word:
print (True)
else:
print (False)
isPalidrome('ana')
|
adec3acd2ec46bbec6f4413de4d1d486b2962a2e | gg4race/projecteuler | /problem41/problem41.py | 936 | 4.15625 | 4 | def main():
import itertools
def isPrime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n ** 0.5) + 1, 2):
if n % x == 0:
return False
return True
pandigitals = itertools.permutations('7654321')
# pandigs = [int(x) for x in pandigitals]
for pandigital in pandigitals:
num = ''.join(str(dig) for dig in pandigital)
if isPrime(int(num)):
print(num)
if __name__ == '__main__':
main()
|
6b18cfe8f5fad25069031b76cc2c13c1c20774f7 | ogradybj/tangent_rev00 | /tangentgame.py | 12,634 | 3.890625 | 4 | import pygame
import random
import math
import numpy
#colors defined
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 220, 0)
RED = (220, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (235, 235, 35)
GAMEOVER = False
class Block(pygame.sprite.Sprite):
"""
This class represents the blocks at either end of the game
It derives from the "Sprite" class in Pygame
"""
def __init__(self, color, width, height):
""" Constructor. Pass in the color of the block,
and its x and y position. """
# Call the parent class (Sprite) constructor
#used to be listed as, but is incorrect: super(pygame.sprite.Sprite, self).__init__()
pygame.sprite.Sprite.__init__(self)
# Create an image of the block, fill it with color and create variable for color.
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.color = color
# Fetch the rectangle object that has the dimensions of the image
# image.
self.rect = self.image.get_rect()
def update(self):
""" as it is hit, it will turn from black to green to yellow to red, once red and is hit the game ends"""
if self.color == BLACK:
self.image.fill(GREEN)
self.color = GREEN
elif self.color == GREEN:
self.image.fill(YELLOW)
self.color = YELLOW
elif self.color == YELLOW:
self.image.fill(RED)
self.color = RED
elif self.color == RED:
#print("GAME OVER")
GAMEOVER = True
return GAMEOVER
class Ball(pygame.sprite.Sprite):
"""
This class is for the balls that fall across the screen.
It extends the Sprite class in pygame
"""
def __init__(self, diameter, speed):
"""
initialize balls
"""
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([diameter, diameter])
self.image.fill(WHITE)
pygame.draw.circle(self.image, (BLACK), (diameter/2, diameter/2), diameter/2, 6)
self.rect = self.image.get_rect()
self.dx = speed
def reset_pos(self):
""" Reset position to the right edge of the screen of the screen"""
self.rect.y = random.randrange(330/65)*65
self.rect.x = 800
def update(self, speed):
""" called each frame to update balls """
self.dx = speed
self.rect.x -= self.dx
self.rect.y = self.rect.y + random.randrange(-2, 3)
if self.rect.y < 10:
self.rect.y = self.rect.y + 2
if self.rect.y > 390:
self.rect.y = self.rect.y - 2
if self.rect.x < -80:
self.reset_pos()
class Player(pygame.sprite.Sprite):
"""This class is the player/character that shows up on the screen
and is controlled by the user. """
def __init__(self, diameter, speed):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([diameter, diameter])
self.image.fill(WHITE)
self.on = False
pygame.draw.circle(self.image, (BLUE), (diameter/2, diameter/2), diameter/2, 5)
self.rect = self.image.get_rect()
self.rect.x = 400
self.rect.y = 200
self.xdir = -.707
self.ydir = .707
self.ii=0
self.theta = 0
self.rotdir = 1
self.thetad = self.theta+self.rotdir*3.14159/2
self.dirmag = math.sqrt(self.xdir**2+self.ydir**2)
self.thetavect = numpy.array([math.cos(self.theta), math.sin(self.theta)])
self.playervect = numpy.array([(self.xdir/self.dirmag),(self.ydir/self.dirmag)])
self.colangle = 3.14159/2
self.theta = 0
self.rotdir = 1
self.thetad = self.theta+self.rotdir*3.14159/2
self.dx = speed*2*self.xdir
self.dy = speed*2*self.ydir
def calcdir(self):
self.thetavect = numpy.array([math.cos(self.theta), math.sin(self.theta)])
self.playervect = numpy.array([(self.xdir/self.dirmag),(self.ydir/self.dirmag)])
self.colangle = math.acos(numpy.dot(self.playervect, self.thetavect))
def click(self, click):
ii = 0
def update(self, speed, zball=None, cluck=False):
"""ISSUES IN THIS SECTION
cannot get the orbit to work correctly"""
if cluck == True:
ii = self.ii
if ii ==0:
ii +=1
else:
self.theta = speed + 0.1
self.thetad = self.theta+self.rotdir*3.14159/2
self.xdir = speed*1*math.cos(self.thetad)
self.ydir = speed*1*math.sin(self.thetad)
self.dirmag = math.sqrt(self.xdir**2+self.ydir**2)
# self.thetavect = numpy.array([math.cos(self.theta), math.sin(self.theta)])
# self.playervect = numpy.array([(self.xdir/self.dirmag),(self.ydir/self.dirmag)])
print(self.colangle)
if self.colangle <= 2:
self.rotdir = -1
else:
self.rotdir = 1
self.rect.x = zball.rect.center[0]+41*math.cos(self.theta+(0.12*speed))-10
self.rect.y = zball.rect.center[1]+41*math.sin(self.theta+(0.12*speed))-10
self.theta = self.theta+(self.rotdir*.09)
elif cluck == False:
if self.rect.x >= 770:
self.xdir = self.xdir*(-1)
elif self.rect.x <= 10:
self.xdir = self.xdir*(-1)
if self.rect.y >= 390:
self.ydir = self.ydir*(-1)
elif self.rect.y <= 5:
self.ydir = self.ydir*(-1)
self.rect.y = 6
self.dirmag = math.sqrt(self.xdir**2+self.ydir**2)
self.dx = speed*2*self.xdir
self.dy = speed*2*self.ydir
self.rect.x = self.rect.x+self.dx
self.rect.y = self.rect.y+self.dy
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
def gameover(screen, score):
largeText = pygame.font.SysFont("cmr10",115)
TextSurf, TextRect = text_objects("GAME OVER", largeText)
TextRect.center = ((400),(100))
screen.blit(TextSurf, TextRect)
finalString = "SCORE: %s" %score
largeText = pygame.font.SysFont("cmr10",115)
TextSurf, TextRect = text_objects(finalString, largeText)
TextRect.center = ((400),(200))
screen.blit(TextSurf, TextRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
pause = True
main()
#gameDisplay.fill(white)
#button("Continue",150,450,100,50,green,bright_green,unpause)
#button("Quit",550,450,100,50,red,bright_red,quitgame)
pygame.display.update()
#clock.tick(15)
def paused(screen):
largeText = pygame.font.SysFont("cmr10",115)
TextSurf, TextRect = text_objects("PAUSE", largeText)
TextRect.center = ((400),(100))
screen.blit(TextSurf, TextRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
pause = True
main()
#gameDisplay.fill(white)
#button("Continue",150,450,100,50,green,bright_green,unpause)
#button("Quit",550,450,100,50,red,bright_red,quitgame)
pygame.display.update()
#clock.tick(15)
def main():
#initialize Pygame
pygame.init()
#set screen size
screen_width = 800
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
#intro screen, attempted, text not showing up
# screen.fill(WHITE)
# largeText = pygame.font.SysFont("cmr10",115)
# TextSurf, TextRect = text_objects("Tangent Arcade Game", largeText)
# TextRect.center = ((400),(100))
# screen.blit(TextSurf, TextRect)
# intro = True
# while intro:
# largeText = pygame.font.SysFont("cmr10",115)
# TextSurf, TextRect = text_objects("Tangent Arcade Game", largeText)
# TextRect.center = ((400),(100))
# screen.blit(TextSurf, TextRect)
# for event in pygame.event.get():
# if event.type == pygame.QUIT:
# pygame.quit()
# quit()
# if event.type == pygame.KEYDOWN:
# if event.key == pygame.K_g:
# intro = False
time = 0
score = 0
speed = 2
diameter = 55
# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'Group.'
ball_list = pygame.sprite.Group()
block_list = pygame.sprite.Group()
# This is a list of every sprite. All blocks and the player block as well.
all_sprites_list = pygame.sprite.Group()
end1 = Block(BLACK, 10, 400)
end1.rect.x = 0
end1.rect.y = 0
block_list.add(end1)
end2 = Block(BLACK, 10, 400)
end2.rect.x = 790
end2.rect.y = 0
block_list.add(end2)
#creating all the balls, randomly distributed
for i in range(9):
# This represents a blall
ball = Ball(diameter, speed)
# Set a random location for the block
ball.rect.x = i*98+screen_width
ball.rect.y = random.randrange(330/65)*65
# Add the ball to the list of objects
ball_list.add(ball)
all_sprites_list.add(ball)
# Create a blue ball for the player
player = Player(20, speed)
playerGroup = pygame.sprite.Group()
#making player group, so that we can simply call
#playerGroup.draw(screen) otherwise if we add player to
#the ball sprite group, it will draw underneath the balls
playerGroup.add(player)
all_sprites_list.add(player)
# possibly use these later, still trying to work out orbit
done = False
onball = None
colball = False
off = False
ii = 0
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONUP:
onball = None
colball = False
off = True
click = True
player.click(click)
#player.update(speed, onball, colball)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
pause = True
paused(screen)
# Clear the screen
screen.fill(WHITE)
#periodically increase the speed to make the game more difficult
time += 1
if time % 400 == 0:
speed +=.25
#check to see if player collides with any balls
for ball in ball_list:
#if there is a collision start orbiting the ball by
#calling player.orbit method
if math.sqrt((player.rect.center[0]-ball.rect.center[0])**2+(player.rect.center[1]-ball.rect.center[1])**2) <=(diameter/2)+7.5:#pygame.sprite.collide_rect(player, ball):
onball = ball
colball = True
player.theta = math.atan2((player.rect.center[1]-ball.rect.center[1]),(player.rect.center[0]-ball.rect.center[0]))
player.calcdir()
for block in block_list:
if pygame.sprite.collide_rect(player, block):
GAMEOVER = block.update()
if GAMEOVER == True:
gameover(screen, score)
# Calls update() method on every ball in the list
ball_list.update(speed)
player.update(speed, onball, colball)
#if no collision keep updating like normal
# else:
# onball = None
# colball = False
# player.update(speed, onball, colball)
score = time
print(score)
ball_list.draw(screen)
block_list.draw(screen)
playerGroup.draw(screen)
clock.tick(24)
pygame.display.flip()
if __name__=='__main__': main()
pygame.quit()
|
c9be14e5b9a621183a37e6178cfad9de3250f693 | claytonchagas/ML-arules-noW | /teste2.py | 136 | 3.921875 | 4 | print("hello world!")
x = ["d", "a", "c", "b", ]
print(x)
x.sort()
print(x)
string = "ola_mundo"
pos = string.find("_")
print(pos) |
f18653289b09af6a5ab6fd3f073d0e4b9058d26a | Abdur15/100-Days-of-Code | /Day_018/Challenge 32 - Draw different shapes.py | 1,510 | 4.03125 | 4 | from turtle import Turtle,Screen
screen = Screen()
screen.screensize(2000,1500)
my_turtle = Turtle()
my_turtle.shape("turtle")
def triangle():
m = 0
while m < 3:
my_turtle.pencolor("red")
my_turtle.forward(100)
my_turtle.right(120)
m+=1
def square():
m = 0
while m < 4:
my_turtle.pencolor("blue")
my_turtle.forward(100)
my_turtle.right(90)
m += 1
def pentagon():
m = 0
while m < 5:
my_turtle.pencolor("yellow")
my_turtle.forward(100)
my_turtle.right(72)
m += 1
def hexagon():
m = 0
while m < 6:
my_turtle.pencolor("green")
my_turtle.forward(100)
my_turtle.right(60)
m += 1
def heptagon():
m = 0
while m < 7:
my_turtle.pencolor("violet")
my_turtle.forward(100)
my_turtle.right(51.42)
m += 1
def octagon():
m = 0
while m < 8:
my_turtle.pencolor("orange")
my_turtle.forward(100)
my_turtle.right(45)
m += 1
def nanogon():
m = 0
while m < 9:
my_turtle.pencolor("brown")
my_turtle.forward(100)
my_turtle.right(40)
m += 1
def decagon():
m = 0
while m < 10:
my_turtle.pencolor("pink")
my_turtle.forward(100)
my_turtle.right(36)
m += 1
n=0
while n<1:
triangle()
square()
pentagon()
hexagon()
heptagon()
octagon()
nanogon()
decagon()
n=+1
screen.exitonclick()
|
dec46f857ef2ad6c4a896bc5aaa609f184e8bf79 | MohamedNagyMostafa/Facial-Keypoints-Detection | /recognize facial over many faces/main.py | 413 | 3.71875 | 4 | import numpy as np
from utils import *
#read an image
image = readImage('obamas.jpg',3)
#display image
show(image)
#detect faces in image
faces = cascadeFaces(image)
#display image with cascaded faces
image_detected_Faces = np.copy(image)
image_faces = showFacesCascade(image, faces)
#using the trained model to get facial for each face
output = feedFacialModel(image_faces)
#display result
show_ky(output)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.