blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
dd1ab026e6a6ef01f05685a1d7527d45174859ad | jc486487/Assignment_1 | /songs_list.py | 7,634 | 4.375 | 4 | """Name: Sherin Sarah Varghese
Date: 20 April 2018
Brief program details: This program tracks the song file- songs.csv,
the user wishes to learn and songs they have learned.
It also allows the user to add songs to the file indicating
the title, artist, year, whether it is required (y) or learned (n).
Link to the project on GitHub: https://github.com/jc486487/Assignment_1"""
import csv
"""Function to list the songs:
variables l, r to count the number of songs learned and those that are yet to be learned
serial # = 0
for loop to take each row from the list - 'lines'
if the 3rd element in the row is y- character is '*'
if not- character is just space
prints each row in the format - serial #. character title - artist (year) --> proper spacing to appear in columns
increase count of serial #
return l, r"""
def list_songs(lines):
r = 0
l = 0
sl_no = 0
for x in lines:
if x[3] == 'y':
character = "*"
r += 1
else:
character = " "
l += 1
print("{0:2}. {1} {2:30} - {3:<30} ({4})".format(sl_no, character, x[0], x[1], x[2]))
sl_no += 1
return l, r
"""Function to add songs to the list:
input title
if title entered is empty - alert and ask for input again
input artist
if artist entered is empty - alert and ask for input again
input year
error checking for - string entered, if its less than 0, if it exceeds the current year(2018)
converts year to string to save in the list"""
def add_songs():
t = str(input("Title: "))
while t == "":
print("Input cannot be blank")
t = str(input("Title: "))
art = str(input("Artist: "))
while art == "":
print("Input cannot be blank")
art = str(input("Artist: "))
y = input("Year: ")
success = False
while not success:
if y.isalpha():
print("Invalid input; enter a valid number")
y = input("Year: ")
elif int(y) not in range(0, 2019):
print("Invalid input; enter a valid number")
y = input("Year: ")
elif int(y) <= 0:
print("Number must be > 0")
y = input("Year: ")
else:
success = True
y = str(y)
return t, art, y
"""Function to change the unlearned songs to learned:
ask the user to enter the number of the song they wish to change
error checking to ensure they dont enter a string, space, number less than 0, number greater than total songs
convert the song # entered to integer
if the 3rd element in the song # the user entered is already 'n':
display - you have already learned title
if not:
change the 3rd element in that song to 'n'
display the song has learned
reduce the number of songs to be learned (req) by 1
return req"""
def complete_song(count_songs, lines, req):
print("Enter the number of the song to mark as learned")
song_no = input(">>> ")
flag = False
while not flag:
if song_no.isalpha():
print("Invalid input; enter a valid number")
song_no = input(">>> ")
elif song_no.isspace():
print("Input cannot be blank; enter a valid number")
song_no = input(">>> ")
elif int(song_no) < 0:
print("Number must be >= 0")
song_no = input(">>> ")
elif int(song_no) >= count_songs:
print("Invalid song number")
song_no = input(">>> ")
else:
flag = True
song_no = int(song_no)
if lines[song_no][3] == 'n':
print("You have already learned {}".format(lines[song_no][0]))
else:
lines[song_no][3] = 'n'
print("{} by {} learned".format(lines[song_no][0], lines[song_no][1]))
req -= 1
return req
"""Main function"""
#opens songs.csv file as 'f' in the read and write mood and indicate newline after each song is not needed
with open("songs.csv", 'r+', newline='') as f:
#reads the songs.csv file
reader = csv.reader(f)
#convert songs in the songs.csv file into a list - 'lines'
lines = list(reader)
#initial message
print("Songs to learn 1.0 - by Sherin Sarah Varghese")
count_songs = len(lines) # counts the number of songs in the list
print(count_songs, "songs loaded")
# displays the menu options the user can choose from
MENU = """MENU:
L - List songs
A - Add a new song
C - Complete a song
Q - Quit"""
print(MENU)
choice = input(">>> ").upper() #inputs user's choice
#variables to count the number of songs learned and those that are yet to be learned
learn = 0
require = 0
# access to this when the user doesn't want to quit the program
while choice != 'Q':
if choice == 'L':
#calls function - list_songs(); parameters - learn, require, access to list of songs ('lines')
learn, require = list_songs(lines)
#displays the number of songs learned and the songs yet to be learned
print("{} songs learned, {} songs still to learn".format(learn, require))
print(MENU) # allows the user to choose anything from the menu again, until he quits
choice = input(">>> ").upper()
elif choice == 'A':
#calls function add_songs() which contains the title, artist and year of the new song entered by user
title, artist, year = add_songs()
#displays that the song by artist has been added to the list
print("{0} by {1} ({2}) added to song list".format(title, artist, year))
#title, artist, year inputed is converted into a list to add to the list of songs- 'lines'
new_song = [title, artist, year, "y"]
lines.append(new_song)
#increases the count of songs to be learned and the total songs in the list 'lines'
require += 1
count_songs += 1
print(MENU) # allows the user to choose anything from the menu again, until he quits
choice = input(">>> ").upper()
elif choice == 'C':
#if there aren't any songs to be learned, it displays "No more songs to learn
if require == 0:
print("No more songs to learn!")
#if there are songs to be learned:
else:
#calls the function - complete_song; parameters - count of songs in the list, access to list 'lines' and number of songs to be learned
require = complete_song(count_songs, lines, require)
print(MENU) # allows the user to choose anything from the menu again, until he quits
choice = input(">>> ").upper()
#programs displays the message in this case, if their input is not 'L', 'A', 'C' or 'Q'
else:
print("Invalid option. Enter again")
print(MENU) # displays and allows the user to enter again for wrong entry
choice = input(">>> ").upper()
#when the user decides to quit, and enters 'Q', this code is executed
# clears content in the songs.csv file to add the new edited list of songs
f.truncate(0)
# enables the songs.csv file writable
writer = csv.writer(f)
# write the new edited list of songs into the songs.csv file
writer.writerows(lines)
#displays the number of songs saved to songs.csv file before ending the program
print("{} songs saved to songs.csv \nHave a nice day :)".format(count_songs))
#close songs.csv file opened as f
f.close() |
bd12b15525f046c666930b62e4e548a9e569c18e | RobertSimion/SPN_encryption_and_decryption | /main.py | 1,940 | 3.609375 | 4 | import SPN
import random
def main():
# Getting clear-text from console ,consists in 4 bytes.
clearText = input("Enter cleartext made of 4 bytes:").split()
# Transforming it in a list of 4 bytes.
clearText = SPN.prepareClearText(clearText)
print("The clear-text is:",clearText)
# We have independent keys for each round.
allKeys = []
# Generate sBox-256 bytes used for substitution block.
sBox = SPN.prepareSBox()
print("The sBox is:",sBox)
# Generate permutation structure for permutation block .
permutation = SPN.preparePermutation()
print(permutation)
# I choose 10 Rounds for SPN algorithm.
nrRounds = 10
# Iterate Encryption phase of Algth. each round from 0 to 9
# Print output of each Round for testing purpose only
# Generate independent,random key each Round and
# stack them into a list for decryption phase of Algth.
for i in range(nrRounds):
key = SPN.prepareKey()
allKeys.append(key)
encryptedText = SPN.encryptSPN(clearText,key,sBox,
permutation)
print("Encryption Output of round " + str(i) ,encryptedText)
clearText = encryptedText
# Verify each key generated during each Round.
print("The generated keys are:",allKeys)
# Generating inverse XOR operation, inverse Permutation
# structure and invers sBox operation
# for decrypting using the keys in reverse order
# Print output of each Decryption Round for testing purpose
# only.
for i in range(nrRounds):
decryptedText = SPN.decryptSPN(encryptedText,
allKeys[nrRounds - i - 1],
sBox,
permutation)
print("Decryption Output from round " + str(i),
decryptedText)
encryptedText = decryptedText
main()
|
4675094b0f6f4147c46c32617b6140560eec04ae | zerohk/python | /10_10count_the.py | 449 | 3.71875 | 4 | # -*- coding: GBK -*
def read_file(filename):
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = "Բļ" + filename + "ڣ"
print(msg)
else:
num = contents.lower().count("the")
print("ļ" + filename + "Уthe " + str(num) + "")
read_file("Alice in Wonderland.txt")
|
cff49db583f1a259ae6a639d30a1bf1c0430fd7c | leiurus17/tp_python | /functions/function_var_length_args.py | 423 | 4.25 | 4 | #Function definition is here
def printinfo(arg1, *vartuple):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var + 1
return
# Now you can call printinfo function
first = 10
print first
printinfo(first)
second = (10, 20, 30, 40, 50)
print second
printinfo(second)
# Now direct to the function
printinfo(10, 20, 30, 40, 50) |
4c4979d1c1aa9d6a67e287ce292e6c4fe261dcec | zhangruochi/leetcode | /CXY_01_05/Solution.py | 1,456 | 3.71875 | 4 | """
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入:
first = "pale"
second = "ple"
输出: True
示例 2:
输入:
first = "pales"
second = "pal"
输出: False
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/one-away-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def oneEditAway(self, first: str, second: str) -> bool:
if len(first) < len(second):
first, second = second , first
m,n = len(first), len(second)
diff = m - n
flag = 0
if diff > 1:
return False
elif diff == 1:
i , j = 0, 0
while j < n:
if first[i] != second[j]:
i+= 1
flag += 1
if flag > 1:
return False
else:
i += 1; j += 1
return True
else:
i, j = 0, 0
while j < n:
if first[i] != second[j]:
flag += 1
if flag > 1:
return False
i+= 1; j+= 1
return True
|
cbb2f2430afec075b6de53d7a53975dde82a6e9d | thiagodnog/projects-and-training | /Curso Python Coursera/Semana 4/Lista de Exercícios Adicionais 3/Adicional3Exercicio1-primalidade.py | 706 | 4.40625 | 4 | '''
Curso de Introdução à Ciência da Computação com Python Parte 1
Exercício Adicional 1
Escreva um programa que receba um número inteiro positivo na entrada e verifique se é primo. Se o número for primo, imprima "primo". Caso contrário, imprima "não primo".
Exemplos:
Digite um numero inteiro: 13
primo
Digite um numero inteiro: 12
não primo
'''
n = int(input("Digite um numro inteiro: "))
def primalidade(numero):
if (numero % 2 == 0) or (numero % 3 == 0) or (numero % 5 == 0) or (numero % 7 == 0):
if numero == 5 or numero == 7:
return print("primo")
else:
return print("não primo")
else:
return print("primo")
primalidade(n) |
62380439edcf4799d49dd471d65013bf7b7e86d2 | jnsong/Leetcode | /26. Remove Duplicates from Sorted Array.py | 239 | 3.578125 | 4 |
def removeDuplicates(nums):
if len(nums)==0:
return 0
s = 0
for j in range(1,len(nums)):
if nums[s]!=nums[j]:
s+=1
nums[s] = nums[j]
return s+1
result = removeDuplicates([1,1,2])
|
7a267e01f371947a1614dc34704e44d7dfe167b9 | vivek-gour/Python-Design-Patterns | /Patterns/Behavioral/memento.py | 1,249 | 3.5625 | 4 | __author__ = 'Vivek Gour'
__copyright__ = 'Copyright 2018, Vivek Gour'
__version__ = '1.0.0'
__maintainer__ = 'Vivek Gour'
__email__ = 'Viv30ek@gmail.com'
__status__ = 'Learning'
class Memento:
def __init__(self, file, content):
self.file = file
self.content = content
class FileWriterUtil:
def __init__(self, file):
self.file = file
self.content = ""
def write(self, str):
self.content += str
def save(self):
return Memento(self.file, self.content)
def undo(self, memento):
self.file = memento.file
self.content = memento.content
class FileWriterCaretaker:
def save(self, writer):
self.obj = writer.save()
def undo(self, writer):
writer.undo(self.obj)
if __name__ == '__main__':
caretaker = FileWriterCaretaker()
writer = FileWriterUtil("data.txt")
writer.write("First Set of Data\n")
print(writer.content + "\n\n")
# lets save the file
caretaker.save(writer)
# now write something else
writer.write("Second Set of Data\n")
# checking file contents
print(writer.content + "\n\n")
# lets undo to last save
caretaker.undo(writer)
# checking file content again
print(writer.content + "\n\n")
|
ce2421a85ec76764c622c3353ae1a689f4185d8a | mariasilviamorlino/python_practice | /w3resource/integers_romans.py | 1,448 | 4 | 4 | """
from https://www.w3resource.com/python-exercises/class-exercises/
'write a Python class to convert an integer to a roman numeral'
strategy (integer to roman): left-pad the given integer (<3999) so it has 4 digits
transform every digit into its roman number equivalent"""
def left_pad(num):
num = str(num)
pad = '0'*(4-len(num))
num = pad+num
return num
def digit_to_roman(num, magnitude):
magnitude_mapping = [['I', 'V', 'X'],
['X', 'L', 'C'],
['C', 'D', 'M'],
['M', 'n', 'o']]
digit_mapping = ['', 'W', 'WW', 'WWW',
'WY', 'Y', 'YW',
'YWW', 'YWWW', 'WZ']
digit = digit_mapping[num]
magnitude_chars = magnitude_mapping[magnitude]
digit = digit.replace('W', magnitude_chars[0])
digit = digit.replace('Y', magnitude_chars[1])
digit = digit.replace('Z', magnitude_chars[2])
return digit
def int_to_roman(num):
if num > 3999:
print("sorry, can't transform this integer to roman!")
return
num = left_pad(num)
roman = ''
mag = 3
for i in num:
roman += digit_to_roman(int(i), mag)
mag -= 1
return roman
if __name__ == '__main__':
print(int_to_roman(1))
print(int_to_roman(3999))
print(int_to_roman(27))
# notes (after peeking solutions)
# failed to think about modular arithmetics
# still think my implementation is not horrible
|
34cfa198e488cb143351955d706d8a2e5c4666fa | hexycat/advent-of-code | /2022/python/11/main.py | 5,229 | 3.953125 | 4 | """Day 11: https://adventofcode.com/2022/day/11"""
from typing import Callable
class Monkey:
def __init__(
self,
items: list[int],
operation: Callable[[int], int],
test: Callable[[int], int],
divisor: int = 1,
) -> None:
self.items = items
self.operation = operation
self.test = test
self.divisor = divisor
self.worry_level_reduction: Callable[[int], int] = lambda wr: int(wr / 3)
self.total_inspects = 0
def inpect_item(self) -> tuple[int | None, int | None]:
"""Inspect next item and return (worry level, next monkey id)"""
if not self.items:
return None, None
item = self.items.pop()
worry_level = self.worry_level_reduction(self.operation(item))
monkey_id = self.test(worry_level)
self.total_inspects += 1
return worry_level, monkey_id
def parse_starting_items(line: str) -> list[int]:
"""Parse starting items line"""
items_str = line.split(":")[-1].strip()
return [int(item) for item in items_str.split(",")]
def parse_operation(line: str) -> Callable[[int], int]:
"""Parse operation line"""
element = line.split(" ")[-1].strip()
if element == "old":
return lambda old: old * old
if "*" in line:
return lambda old: old * int(element)
return lambda old: old + int(element)
def parse_test(lines: list[str]) -> tuple[Callable[[int], int], int]:
"""Parse test line and return test function and divisor"""
for line in lines:
number = int(line.split()[-1].strip())
if "Test" in line:
divisor = number
continue
if "true" in line:
next_monkey_positive = number
continue
if "false" in line:
next_monkey_negative = number
return (
lambda value: next_monkey_positive
if value % divisor == 0
else next_monkey_negative
), divisor
def load_input(filepath: str) -> list[Monkey]:
"""Load input and return list of monkeys"""
monkeys = []
with open(filepath, "r") as file:
while True:
line = file.readline()
if not line: # EOF case
break
if not line.strip() or line.startswith("Monkey"):
continue
start_items = parse_starting_items(line)
operation = parse_operation(file.readline())
test, divisor = parse_test([file.readline() for _ in range(3)])
monkeys.append(
Monkey(
items=start_items, operation=operation, test=test, divisor=divisor
)
)
return monkeys
def play_round(monkeys: list[Monkey]) -> None:
"""Play round: all monkeys inspect all items at begining of their turn"""
for monkey in monkeys:
item, next_monkey = monkey.inpect_item()
while item is not None and next_monkey is not None:
monkeys[next_monkey].items.append(item)
item, next_monkey = monkey.inpect_item()
def play(monkeys: list[Monkey], n_rounds: int = 1) -> int:
"""Play N rounds and calculate the level of monkey business.
Round - all monkeys inspect all items that are available at
the begining of their turn. Monkey business - multiplication
of total interactions of two monkeys with the most total interactions"""
for _ in range(n_rounds):
play_round(monkeys=monkeys)
inspects = [monkey.total_inspects for monkey in monkeys]
inspects.sort(reverse=True)
return inspects[0] * inspects[1]
def part_one(monkeys: list[Monkey]) -> int:
"""Play 20 rounds and calculate the level of monkey business.
Monkey business - multiplication of total interactions of
two monkeys with the most total interactions"""
return play(monkeys=monkeys, n_rounds=20)
def update_worry_level_reduction(
monkeys: list[Monkey], divisor: int = 1
) -> list[Monkey]:
"""Update worry level reduction for all monkeys to remainder of
total product of divisors"""
product = get_divisor_product(monkeys)
monkeys_updated = []
for monkey in monkeys:
monkey.worry_level_reduction = lambda wr: int(wr % product)
monkeys_updated.append(monkey)
return monkeys_updated
def get_divisor_product(monkeys: list[Monkey]) -> int:
"""Calculate product of all divisors"""
product = 1
for monkey in monkeys:
product *= monkey.divisor
return product
def part_two(monkeys: list[Monkey]) -> int:
"""Play 10000 rounds with updated worry level reduction and calculate
the level of monkey business. Monkey business - multiplication
of total interactions of two monkeys with the most total interactions"""
monkeys = update_worry_level_reduction(monkeys)
return play(monkeys=monkeys, n_rounds=10000)
if __name__ == "__main__":
monkeys = load_input("input")
msg = "Part one: The level of monkey business after 20 rounds:"
print(f"{msg} {part_one(monkeys)}")
monkeys = load_input("input")
print(
"Part two: The level of monkey business after 10000 rounds "
+ f"and updated worry level reduction: {part_two(monkeys)}"
)
|
33f5c7938cc8b0b3f1de8f10474adbf35220ba55 | ANASinfad/LP-python-Polygons | /polygons.py | 14,600 | 3.6875 | 4 | import math
from decimal import Decimal
from PIL import Image, ImageDraw
class ConvexPolygon:
# Constructora por defecto.
def __init__(self):
self.vertices = []
self.color = [0, 0, 0]
# Funcion Para imprimir los vértices del polígono
def printPolygon(self):
n = len(self.vertices)
result = ""
for i in range(0, n):
x = self.vertices[i][0]
y = self.vertices[i][1]
if i != n - 1:
result += (str(x) + ' ' + str(y) + ' ')
else:
result += (str(x) + ' ' + str(y))
#print(result)
return result
# Método para definir el color del polígono
def assignColor(self, rgb):
r = int(rgb[0] * 255)
g = int(rgb[1] * 255)
b = int(rgb[2] * 255)
self.color = [r, g, b]
# Entrada: Una Lista de vértices. Como precondición la lista de vértices como mínimo debe tener un punto.
# Salida: Contsruye un Convex hull a partir de una lista de vértices.
def contsructWithPoints(self, points):
hull = []
left = 0
n = len(points)
for i in range(1, n):
if points[i][0] < points[left][0] or (points[i][0] == points[left][0] and points[i][1] < points[left][1]):
left = i
p = left
# Primera iteración para simular el do while.
hull.append(points[p])
q = (p + 1) % n
for j in range(0, n):
if orientation(points[p], points[q], points[j]) == 2:
q = j
p = q
# Resta de iteraciones
while p != left:
hull.append(points[p])
q = (p + 1) % n
for j in range(0, n):
if orientation(points[p], points[q], points[j]) == 2:
q = j
p = q
self.vertices = hull
# Método que recibe un vértice como parámetro y comprueba se está dentro del polígono
def pointIsInsidePolygon(self, point):
n = len(self.vertices)
# La lista de vértices tiene que tener como mínimo 3 vértices
if n < 3:
return False
# Creamos un punto extremo. no le ponemos un valor mayor que 10000 para evitar un overflow.(por las multiplicaciones)
extreme = (10000, point[1])
count = i = 0
while True:
next = (i + 1) % n
# Comprobamos si el segmento (point, extreme) se cruza con el segmento (self.vertices[i], self.vertices[next])
if doIntersect(self.vertices[i], self.vertices[next], point, extreme):
# Si el point es colineal con el segmento (self.vertices[i],self.vertices[next]). Se comprueba
# que point se encuentra en el segmento (self.vertices[i],self.vertices[next])
if orientation(self.vertices[i], point, self.vertices[next]) == 0:
return onSegment(self.vertices[i], point, self.vertices[next])
count += 1
i = next
if i == 0:
break
return count % 2 == 1
# Método que devuelve el número de vértices del Polígono que también es el número de aristas.
def numberOfVertices_edges(self):
return len(self.vertices)
# Función que comprueba que polygon2 está dentro del polígono self
# Esta función utiliza el método pointIsInsidePolygon por cada vértice del polygon2
def polygonIsInsidePolygon(self, polygon2):
n = len(polygon2.vertices)
for i in range(0, n):
if not self.pointIsInsidePolygon(polygon2.vertices[i]):
return False
return True
# El método definido abajo calcula la área de un polígono usando la formula shoelace (Gauss)
def area(self):
n = len(self.vertices)
j = n - 1
area = Decimal(0.000)
for i in range(0, n):
area += (self.vertices[j][0] + self.vertices[i][0]) * (self.vertices[j][1] - self.vertices[i][1])
j = i
result = abs(area / Decimal(2.0))
return round(result, 3)
# Función que calcula el perímetro de un polígono convexo.
def perimeter(self):
perimeter = Decimal(0.0)
n = len(self.vertices)
for i in range(0, n):
j = (i + 1) % n
perimeter += distance(self.vertices[i], self.vertices[j])
return round(perimeter, 3)
# Método que nos permite saber si el Polígono es regular o no.
def isRegular(self):
n = len(self.vertices)
j = n - 1
d = distance(self.vertices[j], self.vertices[0])
for i in range(0, n):
if d != distance(self.vertices[i], self.vertices[j]):
return False
j = i
return True
# Método que devuelve el Centroide de un Polígono en forma de tupla (coordenadas).
def getCentroid(self):
n = len(self.vertices)
if n == 0:
return ()
det = x = y = 0
for i in range(0, n):
j = (i + 1) % n
# Calculamos el determinante
aux = (self.vertices[i][0] * self.vertices[j][1]) - (self.vertices[j][0] * self.vertices[i][1])
# Se acumula la suma de los determinantes.
det += aux
x += (self.vertices[i][0] + self.vertices[j][0]) * aux
y += (self.vertices[i][1] + self.vertices[j][1]) * aux
x /= (3 * det)
y /= (3 * det)
centroid = (round(Decimal(x), 3), round(Decimal(y), 3))
return centroid
# Método que devuelve la unión de dos polígonos. Que resulta ser un convex hull, y por eso se usa la constructora de la clase.
def unionOfPolygons(self, polygon2):
# En points vamos a tener la concatenación de los vértices de self y los vértices de polygon2 sin repeticiones.
points = list(set(self.vertices) | set(polygon2.vertices))
union = ConvexPolygon()
union.contsructWithPoints(points)
return union
# Método que devuelve la lista de vértices del polígono
def getVertices(self):
return self.vertices
# Método que devuelve el color de un polígono
def getColor(self):
result = '#%02x%02x%02x' % (self.color[0], self.color[1], self.color[2])
return result
# Método que devuelve la lista de puntos de intersección entre un polígono y un segmento
def intersectionofALineAndPolygon(self, A, B):
result = []
n = len(self.vertices)
for i in range(0, n):
j = (i + 1) % n
intersectionPoint = intesectionOfTwoLines(self.vertices[i], self.vertices[j], A, B)
if len(intersectionPoint) != 0:
result.append(intersectionPoint)
return result
# Método que devuelve una lista que contiene los vértices del polígono que es la intersección de los dos polígonos de entrada, si la lista está vacía, eso implica que los polígonos no se cruzan.
# El método que se utilizó es el que usa el halfplane de cada arista del primer polígono para comprobar la orientación de los vértices que forman las aristas del segundo polígono
def intersectionOfPolygons(self, polygon2):
result = []
n = len(self.vertices)
m = len(polygon2.vertices)
if m == 0 or n == 0:
intersection = ConvexPolygon()
return intersection
for i in range(0, n):
if polygon2.pointIsInsidePolygon(self.vertices[i]):
addPointWithoutRepetitions(result, self.vertices[i])
for i in range(0, m):
if self.pointIsInsidePolygon(polygon2.vertices[i]):
addPointWithoutRepetitions(result, polygon2.vertices[i])
for i in range(0, n):
j = (i + 1) % n
x = polygon2.intersectionofALineAndPolygon(self.vertices[i], self.vertices[j])
for element in x:
addPointWithoutRepetitions(result, element)
intersection = ConvexPolygon()
intersection.contsructWithPoints(result)
return intersection
# Método que devuelve si dos polígonos son iguales o no.
def areEqual(self, polygon2):
return self.vertices == polygon2.vertices
# Método que define la escala de los vértices de un polígono y devuelve la lista de vértices escalada
def setScale(self, scaleX, scaleY):
verticesScaled = []
for v in self.vertices:
verticesScaled.append((v[0] * Decimal(scaleX), v[1] * Decimal(scaleY)))
return verticesScaled
# Método que nos permite añadir puntos a una lista sin repetirlos
def addPointWithoutRepetitions(vertices, point):
found = False
for vertex in vertices:
if vertex == point:
found = True
break
if not found:
vertices.append(point)
# Función que calcula la distancia entre los puntos p1 y p2
def distance(p1, p2):
result = math.sqrt((p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]))
return Decimal(result)
# Dado tres puntos p1, p2, p3. La función comprueba si p2 se encuentra en el segmento (p1 , p3).
def onSegment(p1, p2, p3):
if ((p2[0] <= max(p1[0], p3[0])) & (p2[0] >= min(p1[0], p3[0])) & (p2[1] <= max(p1[1], p3[1])) & (
p2[1] >= min(p1[1], p3[1]))):
return True
return False
# Función que nos permite averiguar la orientación que tienen 3 puntos
# Valor 0 => colinear
# Valor 1 => Clockwise
# Valor 2 => Counterclockwise
def orientation(p1, p2, p3):
value = (((p2[1] - p1[1]) * (p3[0] - p2[0])) - ((p2[0] - p1[0]) * (p3[1] - p2[1])))
if value == 0:
return 0 # colinear
if value > 0:
return 1 # Clockwise
else:
return 2 # Counterclockwise
# Método que comprueba los casos de intersección de los puntos p3 con p1 y p2 / p3 con p1 y p2 / p1 con p3 y p4 / p2 con p3 y p4
def doIntersect(p1, p2, p3, p4):
orient1 = orientation(p1, p2, p3)
orient2 = orientation(p1, p2, p4)
orient3 = orientation(p3, p4, p1)
orient4 = orientation(p3, p4, p2)
# Caso general
if (orient1 != orient2) and (orient3 != orient4):
return True
# Casos especiales
# p1, p2, p3 son colineales y p3 se encuentra en el segmento (p1, p2)
if (orient1 == 0) and (onSegment(p1, p3, p2)):
return True
# p1, p2, p3 son colineales y p4 se encuentra en el segmento (p1, p2)
if (orient2 == 0) and (onSegment(p1, p4, p2)):
return True
# p3, p4, p1 son colineales y p1 se encuentra en el segmento (p3, p4)
if (orient3 == 0) and (onSegment(p3, p1, p4)):
return True
# p3, p4, p2 son colineales y p2 se encuentra en el segmento (p3, p4)
if (orient4 == 0) and (onSegment(p3, p2, p4)):
return True
# otherwise
return False
# Método que devuelve una lista de vértices que forman el bounding box de polygonsList
def getBoundigBox(polygonsList):
n = len(polygonsList)
# La lista finalList tendrá los vértices de todos los polígonos sin repetición
finalList = []
# Nos encargamos de eliminar los vértices repetidos en este bucle.
for i in range(0, n):
finalList = list(set(polygonsList[i].getVertices()) | set(finalList))
if len(finalList) == 0:
return []
xmax, xmin, ymax, ymin = getMaxAndMinPoints(finalList)
bottomLeft = (round(Decimal(xmin), 3), round(Decimal(ymin), 3))
topRight = (round(Decimal(xmax), 3), round(Decimal(ymax), 3))
topLeft = (bottomLeft[0], topRight[1])
bottomRight = (topRight[0], bottomLeft[1])
return [bottomLeft, topRight, topLeft, bottomRight]
# Método que calcula los puntos máximo y mínimo de una lista de vértices
def getMaxAndMinPoints(finalList):
xmax = finalList[0][0]
xmin = finalList[0][0]
ymax = finalList[0][1]
ymin = finalList[0][1]
for j in range(1, len(finalList)):
cordX = finalList[j][0]
cordY = finalList[j][1]
if cordX > xmax:
xmax = cordX
if cordX < xmin:
xmin = cordX
if cordY > ymax:
ymax = cordY
if cordY < ymin:
ymin = cordY
return xmax, xmin, ymax, ymin
# Método que dibuja los polígonos que hay en la lista polygonsList y lo guarda en el fichero output.png. El bounding box se usa para generar una escala.
def drawPolygons(polygonsList, outputFile):
img = Image.new('RGB', (400, 400), 'White')
dib = ImageDraw.Draw(img)
box = getBoundigBox(polygonsList)
if len(box) == 0:
raise NameError('You cannot draw empty polygons')
elif box[0] == box[1]:
raise NameError('You cannot draw polygons with 1 vertex')
topRight = box[1]
bottomLeft = box[0]
width = topRight[0] - bottomLeft[0]
height = topRight[1] - bottomLeft[1]
if width != 0:
scaleX = Decimal(398 / width)
else:
scaleX = 1
if height != 0:
scaleY = Decimal(398 / height)
else:
scaleY = 1
for polygon in polygonsList:
if polygon.numberOfVertices_edges() > 1:
color = polygon.getColor()
dib.polygon(polygon.setScale(scaleX, scaleY), 'White', color)
img.save(outputFile)
# Este Método recibe como entrada cuatro vértices A, B, C, D y devuelve el punto de intersección en las línea AB y CD,
# si y solo si, el punto de intersección esta incluido en el segmento (AB) y (CD)
# Si la intercección es vacía se devuelve una tupla vacía
def intesectionOfTwoLines(A, B, C, D):
# Línea AB representada como a1x + b1y = c1
a1 = B[1] - A[1]
b1 = A[0] - B[0]
c1 = a1 * (A[0]) + b1 * (A[1])
# Línea CD representada como a2x + b2y = c2
a2 = D[1] - C[1]
b2 = C[0] - D[0]
c2 = a2 * (C[0]) + b2 * (C[1])
# Calculamos el determinante
determinant = a1 * b2 - a2 * b1
if determinant == 0:
return ()
else:
x = (b2 * c1 - b1 * c2) / determinant
y = (a1 * c2 - a2 * c1) / determinant
onLine1 = onSameLine(x, y, A, B)
onLine2 = onSameLine(x, y, C, D)
if onLine1 and onLine2:
return x, y
return ()
# Método que comprueba si un punto (x, y) está en el segmento (AB)
def onSameLine(x, y, A, B):
condition1 = (min(A[0], B[0]) < x or min(A[0], B[0]) == x)
condition2 = (max(A[0], B[0]) > x or max(A[0], B[0]) == x)
condition3 = (min(A[1], B[1]) < y or min(A[1], B[1]) == y)
condition4 = (max(A[1], B[1]) > y or max(A[1], B[1]) == y)
result = condition1 and condition2 and condition3 and condition4
return result
|
81e5fbead11e13e118d165217e03276cdabfb341 | roger6blog/LeetCode | /SourceCode/Python/Problem/00219.Contains Duplicate II.py | 1,076 | 3.65625 | 4 | '''
Level: Easy Tag: [Array]
Given an integer array nums and an integer k,
return true if there are two distinct indices i and j in the array such that
nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
0 <= k <= 10^5
'''
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
hash_map = {}
for i, n in enumerate(nums):
if n in hash_map and i - hash_map[n] <= k:
return True
hash_map[n] = i
return False
nums = [1,2,3,1,2,3]
k = 2
assert False == Solution().containsNearbyDuplicate(nums, k)
nums = [1,0,1,1]
k = 1
assert True == Solution().containsNearbyDuplicate(nums, k)
nums = [1,2,3,1]
k = 3
assert True == Solution().containsNearbyDuplicate(nums, k) |
62ab7c3a23cd760df76e84d3caadd34e90b451f7 | upasanapradhan/IW-Python-Assignment | /IW-PythonAssignment/22.py | 231 | 3.921875 | 4 | def remove_duplicates(my_list):
result = []
for i in my_list:
if i not in result:
result.append(i)
return result
list1 = [1, 2, 3, 4, 2, 1, 10, 15, 4, 10]
print(remove_duplicates(list1)) |
ba9442e4570a4c21b4add889048256a4a3ebe63d | Dombrauskas/Resources | /Python/Geradores/yield01.py | 875 | 4.5 | 4 | """
"
" Maurício Freire
" Geradores são funções que retornam um objeto por vez, de forma a ser possível
" iterá-los. Usar yield no lugar de return faz com que o método returne sem que
" ele seja encerrado.
" Generators are functions that return an object per time, thus it is possible
" to iterate them. Using yield instead of return does the method return without
" finalizing it.
"""
def func(s):
x = s // 2
print("Primeiro returno. O método continuará no próximo loop.")
print("First return. The method will continue in the next loop.")
x *= 3
yield 3 * s
print("Segundo returno.")
print("Second return.")
s -= x
yield s
print("Terceiro returno.")
print("Third return.")
yield s ** 2
n = int(input("Informe um número: "))
for i in func(n):
print(i)
d = input("\ntype ENTER to continue ")
|
93f070cc548d5f4f7dea8e1f1eb629350e4d76f4 | shivamnegi1705/Competitive-Programming | /Codeforces/Educational Round 102/B. String LCM.py | 333 | 3.921875 | 4 | # Question Link:- https://codeforces.com/contest/1473/problem/B
from math import gcd
def lcm(x,y):
return (x*y)//gcd(x,y)
for _ in range(int(input())):
a = input()
n = len(a)
b = input()
m = len(b)
l = lcm(n,m)
t1 = l//n
t2 = l//m
if a*t1 == b*t2:
print(a*t1)
else:
print(-1)
|
a0a775b98ef711307e06580302ec834ed31d34e1 | wduan1025/python-intro | /lecture7/search_demo.py | 167 | 3.53125 | 4 | import re
s = "My name is John,I'm a software_engineer with 4.5 yrs exp,\nI have 112 projects on www.github.com"
pattern = r"I'm"
m = re.search(pattern, s)
print(m) |
cd4069b94c2ce3c78416412d4a70bec65da47735 | feliciahsieh/holbertonschool-webstack_basics | /0x01-python_basics/102-infinite_add.py | 411 | 3.640625 | 4 | #!/usr/bin/python3
""" 102-infinite_add.py - adds infinite-sized integers together """
import sys
if __name__ == "__main__":
# stuff only to run when not called via 'import' here
if len(sys.argv) < 2:
print("0")
elif len(sys.argv) == 2:
print(sys.argv[1])
else:
sum = 0
for i in range(1, len(sys.argv)):
sum += int(sys.argv[i])
print(sum)
|
861850f7810812f12ce821c0687d62a38125dcab | AP-MI-2021/lab-2-ZarnescuBogdan | /main.py | 2,092 | 3.78125 | 4 | import math
def get_leap_years(start: int, end: int) -> list[int]:
list = []
for i in range(start, end + 1):
if i % 4 == 0:
list.append(i)
return list
def test_get_leap_years():
assert get_leap_years(2000, 2008) == [2000, 2004, 2008]
assert get_leap_years(2000, 2009) == [2000, 2004, 2008]
assert get_leap_years(2015, 2025) == [2016, 2020, 2024]
def get_perfect_squares(start: int, end: int) -> list[int]:
list = []
for i in range(start, end + 1):
x = math.sqrt(i)
if int(x + 0.5) ** 2 == i:
list.append(i)
return list
def test_get_perfect_squares():
assert get_perfect_squares(5, 16) == [9, 16]
assert get_perfect_squares(23, 55) == [25, 36, 49]
assert get_perfect_squares(62, 90) == [64, 81]
def is_palindrome(n) -> bool:
n1 = 0
n2 = n
while n2:
n1 = n1 * 10 + n2 % 10
n2 = n2 // 10
if n1 == n:
return True
return False
def test_is_palindrome():
assert is_palindrome(12) is False
assert is_palindrome(121) is True
assert is_palindrome(5) is True
def main():
while True:
print('5. Determină dacă un număr dat este palindrom.')
print('11. Afișează toți anii bisecți între doi ani dați (inclusiv anii dați).')
print('12. Afișează toate pătratele perfecte dintr-un interval închis dat.')
print('x. Iesire din program - exit.')
optiune = input('Alege optiunea: ')
if optiune == '5':
n = int(input("Cititi numarul: "))
print(is_palindrome(n))
elif optiune == '11':
start = int(input('Inceput: '))
end = int(input('Sfarsit: '))
print(get_leap_years(start, end))
elif optiune == '12':
start = int(input('Inceput: '))
end = int(input('Sfarsit: '))
print(get_perfect_squares(start, end))
elif optiune == 'x':
break
else:
print('Optiune invalida.')
test_get_leap_years()
test_get_perfect_squares()
test_is_palindrome()
main() |
dff3c4bb5cedf4954e42c6434e3a50afaf89e377 | sahana-s16/File-structures-mini-project-on-indexing | /add.py | 853 | 3.578125 | 4 | import indexingg
def add1():
ID1=input("Enter ID: \n")
with open(r"C:\Users\Aishu\Desktop\FS\NewCSv.csv", 'r') as myfile:
if ID1 in myfile.read():
print("Primary key already present!!")
else:
#name1=input("Enter ID: \n")
age1=input("Enter Casenumber: \n")
weight1=input("Enter Description: \n")
district1=input("Enter District: \n")
ward1=input("Enter Ward: \n")
fbiCode1=input("Enter FBI code: \n")
year1=input("Enter Year: \n")
with open(r"C:\Users\Aishu\Desktop\FS\NewCSv.csv", 'a') as file:
str=ID1+","+age1+","+weight1+","+district1+","+ward1+","+fbiCode1+","+year1
file.write(str)
file.write("\n")
indexingg.indi()
#add1()
|
6ef91a3e6c75d787b869bda2b92b3689774ce09a | AbhinavPelapudi/coding_challenges | /missingnums.py | 654 | 4.125 | 4 | def missing_number(lst, max_num):
"""Find the missing number in a list
Example::
>>> missing_number([2, 1, 4, 3, 6, 5, 7, 10, 9], 10)
8
"""
sorted_set = sorted(lst)
if sorted_set[0] != 1:
return 1
if sorted_set[-1] != max_num:
return max_num
missing_num = None
idx = 0
while idx < len(sorted_set) - 1:
if sorted_set[idx] != sorted_set[idx + 1] - 1:
missing_num = sorted_set[idx] + 1
idx += 1
return missing_num
#####################################################################
if __name__ == "__main__":
print
import doctest
if doctest.testmod().failed == 0:
print "*** ALL TESTS PASSED ***"
|
11a84809ac9c3479f9fb4aab5b95bab17e12bc17 | group4BCS1/BCS-2021 | /src/Chapter3/exercise2.py | 364 | 3.96875 | 4 | # Determining the pay using try and except
try:
hours = int(input("Enter Hours: \n "))
rate = int(input("Enter Rate: \n "))
if hours > 40 :
hours = hours - 40
pay = 40 * 10
pay = pay + ((hours * rate) * 1.5)
print(pay)
else:
pay = hours * rate
print(pay)
except:
print('Kindly input a number!')
|
6dc073ce027fd41249b1e313b9d11ad1f436e90d | alexrogeriodj/Caixa-Eletronico-em-Python | /capitulo 09/capitulo 09/capitulo 09/exercicio-09-03.py | 2,063 | 4.25 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - Novembro/2012
# Terceira reimpressão - Agosto/2013
# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3
# Primeira reimpressão - Segunda edição - Maio/2015
# Segunda reimpressão - Segunda edição - Janeiro/2016
# Terceira reimpressão - Segunda edição - Junho/2016
# Quarta reimpressão - Segunda edição - Março/2017
#
# Site: http://python.nilo.pro.br/
#
# Arquivo: exercicios\capitulo 09\exercicio-09-03.py
##############################################################################
# Assume que pares e ímpares contém apenas números inteiros
# Assume que os valores em cada arquivo estão ordenados
# Os valores não precisam ser sequenciais
# Tolera linhas em branco
# Pares e ímpares podem ter número de linhas diferentes
def lê_número(arquivo):
while True:
número = arquivo.readline()
# Verifica se conseguiu ler algo
if número == "":
return None
# Ignora linhas em branco
if número.strip()!="":
return int(número)
def escreve_número(arquivo,n):
arquivo.write("%d\n" % n);
pares = open("pares.txt","r")
ímpares = open("ímpares.txt","r")
pares_ímpares = open("pareseimpares.txt","w")
npar = lê_número(pares)
nímpar = lê_número(ímpares)
while True:
if npar == None and nímpar == None: # Termina se ambos forem None
break
if npar != None and (nímpar==None or npar<=nímpar):
escreve_número(pares_ímpares, npar)
npar = lê_número(pares)
if nímpar != None and (npar==None or nímpar<=npar):
escreve_número(pares_ímpares, nímpar)
nímpar = lê_número(ímpares)
pares_ímpares.close()
pares.close()
ímpares.close()
|
a2e324bc31236c5363021e78b6605c4982d1b29c | PythonCHB/PythonIntroClass | /week-09/code/timing.py | 734 | 4.15625 | 4 | #!/usr/bin/env python
"""
timing example
"""
def primes_stupid(N):
"""
a really simple way to compute the first N prime numbers
"""
primes = [2]
i = 3
while len(primes) < N:
for j in range(2, i/2): # the "/2" is an optimization -- no point in checking even numbers
if not i % j: # it's not prime
break
else:
primes.append(i)
i += 1
return primes
if __name__ == "__main__":
import timeit
print "running the timer:"
run_time = timeit.timeit("primes_stupid(5)",
setup="from __main__ import primes_stupid",
number=100000) # default: 1000000
print "it took:", run_time |
9f51e668e9c5cafcda05c7175bc6a77942ceda8d | taariksiers/udemy-complete-python-bootcamp | /Lectures/Section3_Lecture15.py | 711 | 4.28125 | 4 | print("String Indexes")
print("---------------")
mystring = "Hello World"
print("Original: " + mystring)
print("Indices 0:" + mystring[0] + " | 6:" + mystring[6] + " | 9:" + mystring[9] + " | -3:" + mystring[-3])
print("\nString Slicing")
print("---------------")
mystring = "abcdefghijk"
# start index, stop index, step size(default 1)
print("Original: " + mystring)
print("Slicing [2:] " + mystring[2:])
print("Slicing [:3] " + mystring[:3])
print("Slicing [3:6] " + mystring[3:6])
print("Slicing [1:3] " + mystring[1:3])
print("Slicing + step sizing | [::2] " + mystring[::2])
print("Slicing + step sizing | [::3] " + mystring[::3])
print("Slicing + step sizing: Reverse a string | [::-1] " + mystring[::-1])
|
5b0af1246b41298a3ccaaddb4c136001c747654b | lilitkhamalyan/loops | /loops.py | 296 | 4 | 4 | i = 0
# Get the number from the user
number = int(input("Enter a number from 1 to 20: "))
# Number should be [1, 20]
while not number in range (1, 21):
number = int(input("Error! Enter a number from 1 to 20: "))
# i < number, print i^2
while (i < number):
print(i ** 2)
i = i + 1
|
d4eff84cf57706405b20ca64395eb96f9e28e42b | hadismhd/PythonExercise | /Day1/greeting.py | 347 | 4.03125 | 4 | # Set the variable called greeting to some greeting, e.g. "hello".
# Set the variable called name to some name, e.g. "Heisenberg".
# Then set the variable called greet_name that that concatenates greeting , name , and a space " " between them.
greeting = "Hello"
name = "Hadis"
greet_name = (greeting + " " + name + ".")
print(greet_name) |
9bc9df29c1f08aff1deecd159f2f287c8fc8d2ca | subham73/fcc-P-Q-A | /CH-06.py | 470 | 4.3125 | 4 | #Exercise 5:
#Take the following Python code that stores a string:
#str = 'X-DSPAM-Confidence:0.8475'
#Use find and string slicing to extract the portion of the string after the
#colon character and then use the float function to convert the extracted
#string into a floating point number
##############
#solution:-
str='X-DSPAM-Confidence:0.8475'
start=str.find(':')
num=float(str[start+1:]) # '+1' will locate to the first numeric one
print(num)
################
|
2e149ed04060ee1c9f3f9e3cba20c23a267faa0f | kanisan007/testgame_kanisan007 | /kiekie.py | 1,473 | 3.5 | 4 | def printsquaresstatus(squarestatus: list):
squareinfo = []
for i in range(9):
if squarestatus[i] == 0:
squareinfo.append(' ')
elif squarestatus[i] == 1:
squareinfo.append('〇')
elif squarestatus[i] == 2:
squareinfo.append('×')
else:
raise SyntaxError('kiekie')
return squareinfo
def nokorihantei(squarestatus: list):
nokori = []
for i in range(9):
if squarestatus[i] == 0:
nokori.append(i+1)
else:
pass
return nokori
def winhantei(squarestatus: list, syurui: int):
kie = []
for i in range(9):
if squarestatus[i] == syurui:
kie.append(i+1)
else:
pass
kekka = 0
if 1 in kie:
if 2 in kie:
if 3 in kie:
kekka = 1
elif 4 in kie:
if 7 in kie:
kekka = 1
elif 5 in kie:
if 9 in kie:
kekka = 1
elif 2 in kie:
if 8 in kie:
kekka = 1
elif 3 in kie:
if 5 in kie:
if 7 in kie:
kekka = 1
elif 6 in kie:
if 9 in kie:
kekka = 1
elif 4 in kie:
if 5 in kie:
if 6in kie:
kekka = 1
elif 7 in kie:
if 8 in kie:
if 9 in kie:
kekka = 1
if kekka == 1:
kekka = syurui
return kekka
|
2e31f289de983664d0788d14960d9ed73a8b5e71 | RetamalVictor/Data_Structures_and_algorithms | /Array_based_sequences/arrays_based.py | 2,072 | 3.71875 | 4 |
class Dynamic_Array():
def __init__(self):
self._number_of_items = 0
self._data = [None]
def __len__(self):
return self._number_of_items
def is_valid_index(self, index):
if not 0 <= index < self._number_of_items:
raise IndexError
def __getitem__(self, index):
self.is_valid_index(index)
return self._data[index]
def append(self, item):
self._resize()
self._data[self._number_of_items] = item
self._number_of_items += 1
def _resize(self):
if self._number_of_items == len(self._data):
new_data = [None] *len(self._data) *2
for index in range(len(self._data)):
new_data[index] = self._data[index]
self._data = new_data
def index(self,item):
for index in range(self._number_of_items):
if self._data[index] == item:
return index
raise ValueError(f'{item} not found in array')
def count(self, item):
occurrences = 0
for index in range(self._number_of_items):
if self._data[index] == item:
occurrences +=1
return occurrences
def insert(self,index, item):
self.is_valid_index(index)
self._resize()
for index in range(self._number_of_items, index, -1):
self._data[index] = self._data[index-1]
self._data[index] = item
self._number_of_items += 1
def remove(self, item):
for index in range(self._number_of_items):
if self._data[index] == item:
for index_to_replace in range(index, self._number_of_items):
self._data[index_to_replace] = self._data[index_to_replace + 1]
self._number_of_items -= 1
self._data[self._number_of_items] = None
return
raise ValueError('Value not found')
test = Dynamic_Array()
for number in range(10):
test.append(number)
for index in range(len(test)):
print(test[index]) |
1225ff6ddddc54a2879954c65c562d89c5e1bcfd | Pedromoisescamacho/python-mega-course | /lesson 1-5/ageplus50.py | 482 | 4.125 | 4 | #this is the way that we integrate user input into a function
#creating the function
def age_plus_50():
while True:
try:
age = int(input("please enter a age: "))
if 0 < age <= 150:
print(age + 50)
break
else:
print("please enter a realistic age, i.e. more than 0 and equal or below 150")
except:
print("please enter an integer")
continue
age_plus_50()
|
b955651e8321c877eff492ea6d546ee0211f99a6 | briworkman/Graphs | /projects/ancestor/ancestor.py | 2,355 | 3.78125 | 4 | # class Stack():
# def __init__(self):
# self.stack = []
# def push(self, value):
# self.stack.append(value)
# def pop(self):
# if self.size() > 0:
# return self.stack.pop()
# else:
# return None
# def size(self):
# return len(self.stack)
# def earliest_ancestor(ancestors, starting_node):
# # Create a q/stack and enqueue starting vertex
# stack = Stack()
# visited = set()
# stack.push(starting_node)
# first = -1
# # While stack has ancestors and queue is not empty:
# while stack.size() > 0:
# # pop the first vertex/ancestor
# vertex = stack.pop()
# # if ancestor not visited
# if vertex not in visited:
# # mark as visited
# visited.add(vertex)
# print(visited)
# for ancestor in ancestors:
# if ancestor[1] == vertex:
# stack.push(ancestor[0])
# if first == -1:
# first = ancestor[0]
# parents = []
# for anc in ancestors:
# if anc[1] == vertex:
# parents.append(anc[0])
# if len(parents) == 1:
# first = anc[0]
# else:
# if first > anc[0]:
# first = anc[0]
# return first
def earliest_ancestor(ancestors, starting_node):
parents = []
for relationship in ancestors:
# if the relationship is equal to the starting node, add it to the parents array
if relationship[1] == starting_node:
parents.append(relationship)
# while the parents array is not empty
while len(parents) > 0:
# pop/dequeue the ancestor in the parents array
ancestor = parents.pop()
earlier_ancestor = earliest_ancestor(ancestors, ancestor[0])
# if the earlier ancester is greater than -1, add it to the parents array
if earlier_ancestor > -1:
parents.append((earlier_ancestor, ancestor[0]))
# if the length of the parents array is empty, return the current ancestor
elif len(parents) == 0:
return ancestor[0]
return -1
|
e1d775146fbf51104f8467794eb09da75b298b36 | jlaframboise/Calculator | /Calc10.py | 8,813 | 4.0625 | 4 | #Calculator10.py
#Jacob Laframboise March 6, 2017
#A calculator which can take an expression involving addition, subtraction, multiplication, division, exponents, and brackets with positive and negative numbers
#Code to quickly run program with a constant input instead of getting user input
#input1='(-17)+(44/6*11^2)-999'
#input1='44/6*11^2'
#inputList=list(input1)
#print('Original input: ', inputList)
def itemsToString(list1): #A function to make every item in a list a string
list2=[]
for i in list1:
list2.append(str(i))
return list2
def isNum(s): #function to determine whether an item is a number
try:
float(s)
return True
except ValueError:
return False
except IndexError:
return False
#operation funtions:
def doExponents(inpList):
for i in inpList:
place=inpList.index(i)
if i == '^':
inpList[inpList.index(i)] = float((inpList[inpList.index(i)-1]))**(float(inpList[inpList.index(i)+1])) #multiplies two items on either side of a '*' symbol
inpList.pop(place+1)#removes item after '*'
inpList.pop(place-1)#removes item before '*'
#print(' = ',''.join(itemsToString(inpList))) #shows work
return inpList
def doMultiply(inpList):
for i in inpList:
place=inpList.index(i)
if i == '*':
inpList[inpList.index(i)] = float(inpList[inpList.index(i)-1])*(float(inpList[inpList.index(i)+1]))
inpList.pop(place+1)
inpList.pop(place-1)
#print(' = ',''.join(itemsToString(inpList))) #shows work
return inpList
def doDivide(inpList):
try:
for i in inpList:
place=inpList.index(i)
if i == '/':
inpList[inpList.index(i)] = float((inpList[inpList.index(i)-1]))/(float(inpList[inpList.index(i)+1]))
inpList.pop(place+1)
inpList.pop(place-1)
#print(' = ',''.join(itemsToString(inpList))) #shows work
return inpList
except ZeroDivisionError:
print('Cannot divide by zero, your answer is undefined.')
inpList=[]
def doAdd(inpList):
for i in inpList:
place=inpList.index(i)
if i == '+':
inpList[inpList.index(i)] = float(inpList[inpList.index(i)-1])+(float(inpList[inpList.index(i)+1]))
inpList.pop(place+1)
inpList.pop(place-1)
#print(' = ',''.join(itemsToString(inpList))) #shows work
return inpList
def doSubtract(inpList):
for i in inpList:
place=inpList.index(i)
if i == '-':
inpList[inpList.index(i)] = float(inpList[inpList.index(i)-1])-(float(inpList[inpList.index(i)+1]))
inpList.pop(place+1)
inpList.pop(place-1)
#print(' = ',''.join(itemsToString(inpList))) #shows work
return inpList
#A function to run through order of operations on a selected list
def compute(expressionList):
computedList = doExponents(expressionList)
computedList = doMultiply(expressionList)
computedList = doDivide(expressionList)
computedList = doAdd(expressionList)
computedList = doSubtract(expressionList)
return computedList
#A function to group multidigit numbers together into one item
def digitGroup(inpList):
reLoop=True
while reLoop:
reLoop=False #has to be false, will be set true if something is done
posiCount=0
for i in inpList:
#double digit combine:
place=inpList.index(i)
try:
if i != inpList[-1] or inpList[-1]==inpList[-2]: #guarantees it wont check the one after the last item in the string
if i=='-' and inpList[posiCount-1]=='(' : #code to deal with negative numbers, comments in this if statement were for debugging
#print('combining: ',inpList[posiCount], ' and ', inpList[posiCount+1])
inpList[posiCount]=str(inpList[posiCount]) + inpList[posiCount+1]
#print('inpList after combining: ', inpList)
#print('Going to pop ', inpList[posiCount+1])
inpList.pop(posiCount+1)
#print('inpList after popping: ', inpList)
reLoop=True
if isNum(i) and isNum(inpList[place+1]): #checks for see if the next two items are digits
inpList[place]=inpList[place]+inpList[place+1] #combines digits into place of first digit
inpList.pop(place+1) #removes sole second digit item
#print(inpList) #shows multidigit number grouping steps
reLoop=True
except IndexError: #prevents break apon just one numerical input
print("Your number is still ", input1, ", try giving me some actual expressions :)")
posiCount+=1
return(inpList)
#The main function, will call all other functions
def solve(inputList):
inStringOrg=inputList#save original input
print('Original input: ', inputList) #print original input
inputList=list(inputList)
#print('Original input: ', inputList) #print original input as string
inputList=digitGroup(inputList) #group digits and merge negative signs
reScan=True
currentAnswer=7777777 #initializing
while reScan==True:
#print(' = ',''.join(itemsToString(inputList))) #shows each step of calculation, can be commented out for cleanliness
reScan=False
oBrackets=[] #store positions of open brackets
smallestDiff=823745619 #initializing
cBrackets=[]
posiCount=0 #to zero index and initialize, variable stores current position in list
for i in inputList: #scans for brackets and makes lists of positions
if i=='(':
#print('Found: ',i, ' as: ( in position: ', posiCount)
oBrackets.append(posiCount)
#reScan=True #disabled to prevent infinite loop potential, done on close bracket only
elif i ==')':
#print('Found: ',i, ' as: ) in position: ', posiCount)
cBrackets.append(posiCount)
reScan=True
posiCount+=1 #increase position
for i in oBrackets: #function determines which open bracket is closest to the first close bracket, and the far it is to get the correct slice inside the bracket set
if (smallestDiff==823745619 and oBrackets!=[] and cBrackets!=[]) or (cBrackets[0]-i < smallestDiff and cBrackets[0]-i > 0):
smallestDiff=cBrackets[0]-i
#print(smallestDiff)
if smallestDiff != 823745619: #if it has been set something else because it found a bracket set
toSolveList = inputList[cBrackets[0]-smallestDiff+1:cBrackets[0]]
else:
toSolveList=inputList
'''
#following 5 lines just print out to the user what the calculator is doing, can be commented out for cleaniness
print('Going to solve: ', toSolveList)
if smallestDiff != 823745619:
print('Replacing: ',inputList[cBrackets[0]-smallestDiff:cBrackets[0]+1],' with: ', compute(toSolveList))
else:
print('Replacing: ',inputList,' with: ', compute(toSolveList))
'''
#calls the compute function on either the slice between the brackets or the whole list when brackets are not present
if smallestDiff != 823745619:
inputList[cBrackets[0]-smallestDiff:cBrackets[0]+1]=compute(toSolveList)
else:
inputList=compute(toSolveList)
if currentAnswer==inputList: #checks to see if anything was done on last loop
finalAnswer=currentAnswer
#reScan=False
currentAnswer=inputList
#make a nice final answer to output
finalAnswer=''.join(itemsToString(inputList))
return(finalAnswer)
#print(solve(inputList))
#loop to get input from user and return an answer, then ask again until the user exits
cont=True #keep loop going
while cont==True:
expression=input("Input your expression here: ")
if expression=='exit':
cont=False
else:
print(' = ',solve(expression))
|
009f18767ac8789ff537b98f0795114f7e98504c | srlm89/portfolio | /python/meta-circular-lisp/meta_circular_lisp/parser.py | 2,311 | 3.53125 | 4 | def atom(token):
try: return int(token)
except ValueError:
try: return float(token)
except ValueError:
return str(token)
def tokenize(line):
pairs = 0
opens = []
line = line.strip()
tokens = line.replace('(', ' ( ').replace(')', ' ) ').split()
for i in range(len(tokens)):
token = tokens[i]
if token == '(':
opens.append('$')
pairs += 1
elif token == ')':
if len(opens) == 0:
raise SyntaxError("Unbalanced closing parentheses ')'")
opens.pop()
if token == ')' and tokens[i-1] == '.' or token == '.' and (i == 0 or tokens[i-1] == '('):
raise SyntaxError("Illegal use of dot notation")
else:
tokens[i] = atom(token)
if len(opens) > 0:
raise SyntaxError('There are %d unclosed parentheses' % len(opens))
if (pairs == 0 and len(tokens) != 1) or pairs > 0 and (line[0] != '(' or line[-1] != ')'):
raise SyntaxError('Not a LISP expression (missing surrounding parentheses?)')
return tokens
def mexpr(line):
tokens = tokenize(line)
stack = [None]
for token in reversed(tokens):
if token == ')':
push = []
elif token == '(':
car = stack.pop(0)
cdr = stack.pop(0)
push = [car, cdr]
elif token == '.':
push = stack.pop(0)[0]
else:
cdr = stack.pop(0)
push = [token, cdr]
stack.insert(0, push)
return stack.pop()[0]
def sexpr(mexpr):
is_list = lambda e: isinstance(e, (tuple, list))
stack = [[ mexpr, [] ]]
pieces = []
while len(stack) > 0:
e = stack.pop()
if is_list(e):
if is_list(e[0]) and is_list(e[1]):
push = ['(', e[0], ')', e[1]]
if is_list(e[0]) and not is_list(e[1]):
push = ['(', '(', e[0], ')', '.', e[1], ')']
if not is_list(e[0]) and is_list(e[1]):
push = [e[0], e[1]]
if not is_list(e[0]) and not is_list(e[1]):
push = [e[0], '.', e[1]]
for c in push:
if c != []:
stack.append(c)
else:
pieces.insert(0, str(e))
return ' '.join(pieces) |
2d5752f02d782c75f66e30531185a83690448cae | danielhac/python_practice_epi | /string/is_planindromic.py | 543 | 4.03125 | 4 | # A palindromic string is one which reads the same when it is reversed.
# Checks if string is palindromic
# s[~i] is s[-(i + 1)], which is the the opposite elem as s[i]
# all(): returns true if all is true
def is_palindromic(s):
return all(s[i] == s[~i] for i in range(len(s) // 2))
# Longer version, but same as above
def is_palindromic_extended(s):
for i in range(len(s) // 2):
if s[i] != s[-(i + 1)]:
return False
return True
s = "lol"
# s = "nope"
# s = "holloh"
print(is_palindromic_extended(s)) |
2286187b77335399bc0304c4312898b404d809bc | akonon/pbhw | /06/hw5_solution.py | 959 | 4 | 4 | # -*- coding: utf-8 -*-
class Person(object):
"""Represents an entry in a contact list"""
def __init__(self, surname, first_name, birth_date, nickname=None):
from datetime import datetime
self.surname = surname
self.first_name = first_name
self.birth_date = datetime.strptime(birth_date, '%Y-%m-%d').date()
if nickname:
self.nickname = nickname
def get_age(self):
"""Return person's age in years"""
import datetime
today = datetime.date.today()
years_difference = today.year - self.birth_date.year
is_before_birthday = (today.month, today.day) < (self.birth_date.month,
self.birth_date.day)
age = years_difference - int(is_before_birthday)
return str(age)
def get_fullname(self):
"""Return person's full name"""
return self.surname + ' ' + self.first_name
|
9ed57079e1b9196f62dedde9b64564c04ddf4d17 | MadSkittles/leetcode | /23.py | 811 | 3.75 | 4 | from common import ListNode
class Solution:
def mergeKLists(self, lists):
head = tail = None
while True:
min_, index = float('inf'), -1
for i, p in enumerate(lists):
if p and p.val < min_:
index, min_ = i, p.val
if index < 0:
break
min_node = lists[index]
if head is None:
head = tail = min_node
else:
tail.next = min_node
tail = min_node
lists[index] = min_node.next
min_node.next = None
return head
if __name__ == '__main__':
solution = Solution()
print(solution.mergeKLists([ListNode.list2ListNode([]), ListNode.list2ListNode([1, 3, 4]), ListNode.list2ListNode([2, 6])]))
|
649a1d32b5ea68f68e86a1edc2dac9f67282fcb7 | vivekm56/CodeSnippets | /Object-Oriented/Class-Static-Methods/oop.py | 1,601 | 3.78125 | 4 | class Employee:
numOfEmployees = 0
raiseAmount = 1.04
def __init__(self, firstName, lastName, salary):
self.firstName = firstName
self.lastName = lastName
self.salary = salary
self.mailId = (firstName + lastName + '@company.com').lower()
Employee.numOfEmployees += 1 #knit method
def increment(self):
self.salary = int(self.salary * self.raiseAmount)
@classmethod #It can be used as an alternative constructor
def set_raise_amt(cls, amount): #It can be called a class instead of an Instance
cls.raiseAmount = amount
@classmethod
def from_string(cls, emp_str):
firstName, lastName, salary = emp_str_1.split('-')
return (firstName, lastName, salary)
@staticmethod #Normal Method or function
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6 :
return False
return True
emp_1 = Employee('Mark', 'Bucher', 50000)
emp_2 = Employee('Eddiee', 'Paul', 60000)
Employee.set_raise_amt(1.05)
print(emp_1.raiseAmount)
print(emp_2.raiseAmount)
print(Employee.raiseAmount)
# Employee.set_raise_amt(1.06)
emp_str_1 = 'John-Doe-70000'
emp_str_2 = 'Steve-Smith-30000'
emp_str_3 = 'Jane-Doe-90000'
# new_emp_1 = Employee(firstName, lastName, salary)
new_emp_1 = Employee.from_string(emp)
print(new_emp_1.mailId)
print(new_emp_1.salary)
import datetime
my_date = datetime.date(2020,6,17)
print(Employee.is_workday(my_date))
|
16d8d80f2cf806246e52845ff052f643569ebd15 | pdhhiep/Computation_using_Python | /fem1d_heat_explicit/basis_function.py | 1,564 | 3.859375 | 4 | #! /usr/bin/env python
def basis_function ( index, element, node_x, point_x ):
#*****************************************************************************80
#
## BASIS_FUNCTION evaluates a basis function.
#
# Discussion:
#
# Piecewise linear basis functions are used.
#
# Basis functions are associated with NODES, and are numbered 1 to NODE_NUM.
#
# Elements are associated with intervals, having nodes as endpoints.
# Element I begins at node I and ends at node I+1.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 07 November 2014
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer INDEX, the index of the basis function to be evaluated.
#
# Input, integer ELEMENT, the index of the element in which the points lie.
#
# Input, real NODE_X(NODE_NUM), the coordinates of nodes.
#
# Input, integer POINT_NUM, the number of evaluation points.
#
# Input, real POINT_X, the evaluation points.
#
# Output, real B, DBDX, the basis function and its derivative, evaluated
# at the evaluation points.
#
import numpy as np
b = 0.0
dbdx = 0.0
if ( index == element ):
b = ( node_x[element+1] - point_x ) / ( node_x[element+1] - node_x[element] )
dbdx = - 1.0 / ( node_x[element+1] - node_x[element] )
elif ( index == element + 1 ):
b = ( point_x - node_x[element] ) / ( node_x[element+1] - node_x[element] )
dbdx = + 1.0 / ( node_x[element+1] - node_x[element] )
return b, dbdx
|
80e78ca00e83ed75247aa1817143b351fbf0b527 | BauerJustin/Elements-of-Programming-Interviews-in-Python | /Ch.7 Linked Lists/7.4 Overlap/overlap.py | 735 | 3.9375 | 4 | #code
def is_overlap(L1, L2):
temp = []
while L1:
temp.append(L1)
L1 = L1.next
while L2:
if L2 in temp:
return L2
L2 = L2.next
return None
# Linked list classes and base code
class ListNode:
def __init__(self,data=0,next_node=None):
self.data = data
self.next = next_node
def __str__(self):
return str(self.data)
LL1 = ListNode(11, ListNode(23))
LL2 = ListNode(11, ListNode(3, ListNode(5, ListNode(7, ListNode(2, ListNode(28))))))
LL3 = ListNode(124, ListNode(35, ListNode(3, ListNode(315, ListNode(25, ListNode(58))))))
LL4 = ListNode(55, ListNode(2, LL3.next.next.next))
# Test
print(is_overlap(LL1, LL2))
print(is_overlap(LL3, LL4)) |
46b3cf3016b30bcc4e3d8c0a0ff1b11930d64b96 | IEEE-CS-TXST/checkers | /checkers.py | 3,250 | 3.765625 | 4 |
class Board:
def __init__(self):
#initialize 2d array populated by 'None' in all fields
self.board = [[None for i in range(8)] for j in range(8)]
#spots where red pieces start
self.startRed = [(0,1), (0,3), (0,5), (0,7), (1,0),
(1,2), (1,4), (1,6), (2,1), (2,3) , (2,5) , (2,7)]
#spots where black pieces start
self.startblack = [(7,0), (7,2), (7,4), (7,6), (6,1),
(6,3), (6,5), (6,7), (5,0), (5,2), (5,4), (5,6)]
self.pieces = {
}
def populateboard(self):
#'element[index] - 1' to keep inside bounds of 8x8
for element in (self.startblack):
self.pieces[element] = {
'team' : 'black',
'position' : element,#black,
'king' : False,
'valid': True #if piece is still in play or not
}
self.board[element[0]][element[1]] = self.pieces[element] #black
for element in (self.startRed):
self.pieces[element] = {
'team' : 'red',
'position' : element, #red,
'king' : False,
'valid': True #if piece is still in play or not
}
self.board[element[0]][element[1]] = self.pieces[element] #red
def printboard(self):
print("-"*40)
for col in range(0,8):
for row in range(0,8):
if (self.board[col][row] == None):
print(" | ", ' ' , end='')
else:
print(" | ", self.board[col][row]['team'], end='')
print(" |",'\n')
print("-"*42)
def movement(board, pieces, currCoordinate, newCoordinate):
assert checkEdge(newCoordinate)
assert checkOccupied(board, newCoordinate)
board[newCoordinate[0]][newCoordinate[1]] = pieces[currCoordinate]
board[currCoordinate[0]][currCoordinate[1]] = None
def capture(board, pieces, currCoordinate, newCoordinate):
assert checkEdge(newCoordinate)
assert checkOccupied(board, newCoordinate)
pass
def checkEdge(newCoordinate):
#returns true if going out of bounds
return ((newCoordinate[0] < 8) and (newCoordinate[1] > 0))
#returns true if new coordinate is already populated
def checkOccupied(board, newCoordinate):
try:
return (board[newCoordinate[0]][newCoordinate[1]] == None)
except:
return False
def checkPossibleMoves(board, pieces):
moves = {}
for i in pieces:
if pieces[i]['team'] == 'red' and pieces[i]['valid'] == True:
coordinate = pieces[i]['position']
#check down left
coordinateCheck = (coordinate[0] - 1,coordinate[1] - 1)
if checkEdge(coordinateCheck) and checkOccupied(board, coordinateCheck):
moves[i] = {
'team' : 'red',
'old-position' : coordinate,
'new-position' : (coordinate[0] + 1 , coordinate[1] - 1)
}
print ("red")
#check down right
coordinateCheck = (coordinate[0] - 1,coordinate[1] + 1)
if checkEdge(coordinateCheck) and checkOccupied(board, coordinateCheck):
moves[i] = {
'team' : 'red',
'old-position' : coordinate,
'new-position' : (coordinate[0] + 1 , coordinate[1] + 1)
}
print ("red")
elif pieces[i]['team'] == 'black' and pieces[i]['valid'] == True:
#print ("black")
#check up left
#check up right
print(moves)
return moves
if __name__ == "__main__":
b = Board()
b.populateboard()
b.printboard()
checkPossibleMoves(b.board, b.pieces)
movement(b.board, b.pieces, (5,4), (4,5))
b.printboard()
# test = input("write something: ")
# print(test)
|
180f7b619063edfaf300c214f3788d0d724725ee | aitiwa/pythonTraining | /m3_3_whileBreakTest_001.py | 989 | 3.890625 | 4 | print("Section001 알고리즘-1에서 100까지중 입력받은 수까지 합계")
print("m3_3_whileLoopIfBreakTest_001.py")
print()
print("1. count, sum, limit 변수 선언과 초기화: ")
print(" count = 0 ")
print(" sum = 0 ")
count = 0
sum = 0
print("2. 사용자로부터 limit 변수의 input값을 받는다.")
print(' limit = int(input("어디까지 더할까요? :"))')
limit = int(input(" 어디까지 더할까요? : "))
print()
print("3. 반복문 내 조건문을 실행하는 반복 조건문: ")
print(" while count <= 100: ")
print(" sum = sum + count ")
print(" if count == limit : ")
print(" break ")
print(" count = count + 1 ")
print()
while count <= 100:
sum = sum + count
if count == limit :
break
count = count + 1
print("4. 결과값->")
print(" 1부터 %d까지의 합은: %d"% (count,sum))
print()
print('5. 프로그램 종료')
print(' print("Program End")')
print(" Program End") |
61b252d3fa9e86a83230b3e371f1b8a8df686065 | Jenychen1996/Basic-Python-FishC.com | /Living_example/Narcissus.py | 754 | 3.8125 | 4 | # -*- coding:utf-8 -*-
def Narcissus1():
'小甲鱼方法'
for each in range(100, 1000):
temp = each
sum = 0
while temp:
# 第一次sum = 0 + 个位数 ** 3 ; temp = 除个位数
# 第二次sum = 个位数 ** 3 + 十位数 ** 3 ; temp = 百位数
# 第三次sum = 个位数 ** 3 + 十位数 ** 3 + 百位数 ** 3 ; temp
sum = sum + (temp % 10) ** 3
temp = temp // 10
if sum == each:
print(each)
def Narcissus2():
for sum2 in range(100, 1000):
if sum2 == ((sum2 // 100) ** 3 + (sum2 // 10 % 10) ** 3 + (sum2 % 10) ** 3):
print("%d 为水仙花数。" % sum2)
print("水仙花数为:")
Narcissus1()
Narcissus2()
|
732052be15e3b19cd6593a91ae40ee331890385d | murali-kotakonda/PythonProgs | /PythonBasics1/functions/Ex3.py | 431 | 3.796875 | 4 | """
write a function that performs sum of two nums.
"""
def sum(x,y):
res = x+y
print("sum = ", res)
#call the function
sum(10,20)
sum(80,20)
sum(180,220)
sum(12.1313,131313.2424)
n1 = 90
n2= 30
sum(n1,n2)
"""
local variable:
variable created inside the function
global variable:
variable created outside the function or in global area
local variables : x , y , res
global variables : n1 , n2
""" |
68fbf8108a9879a7119844ab8af0f42cf0209d26 | sgenduso/python-practice | /src/datetime_methods.py | 418 | 3.65625 | 4 | # import datetime library
from datetime import datetime
now = datetime.now()
print now # 2016-04-25 18:27:59.145463
print now.year # 2016
print now.month # 4
print now.day # 25
print '%s/%s/%s' % (now.month, now.day, now.year) # 4/25/2016
print '%s:%s:%s' % (now.hour, now.minute, now.second) # 18:27:59
print '%s/%s/%s %s:%s:%s' % (now.month, now.day, now.year, now.hour, now.minute, now.second) # 4/25/2016 18:27:59
|
521e2470eaf8e33dd3bc12d59df06569dfc1cc61 | colephalen/SP_2019_210A_classroom | /students/GKim/lesson04/mailroom2.py | 6,185 | 3.5 | 4 | #!/usr/bin/env python
from textwrap import dedent
import sys, os
main_donors = [
{"name": "Luke Skywalker", "donations": [100.25, 200.55, 50]},
{"name": "Han Solo", "donations": [100.80, 50.99, 600]},
{"name": "Yoda", "donations": [1000.01, 50, 600.55, 200.47]},
{"name": "Ben Kenobe", "donations": [101.32, 500, 60.34]},
]
def clear_screen():
"""
clears the command screen
"""
os.system("cls" if os.name == "nt" else "clear")
def show_list():
"""
shows the donors in the list with donation amounts
\n"""
print("#" * 25, "The Current Donor List", "#" * 25)
index = 1
for row in main_donors:
print("{:<1}: {:>15}{:>10}: {:<20}".format(index, row["name"], "Amt", str(row["donations"]).replace("[","").replace("]","")))
index += 1
print("#" * 75 + "\n")
return show_list
def main_menu():
"""
Main menu options
"""
prompt = input("\n".join(("\nWelcome to the Mailroom!",
"Please choose from one of the options below:\n",
"1: Send a Thank You",
"2: Create a Report",
"3: Send to All",
"4: Quit",
">>> ")))
return prompt
def menu_thank_you():
"""
Menu to user to enter options for thank you
"""
print("""\nTo whom would you like to send a Thank You?
Please enter full name""")
thanks_answer = input("""
Enter 'LIST' to see Donor list or 'MENU' to return to Main Menu.
>>> """)
return thanks_answer
def send_email(name, amount):
"""
This functions sends a letter to an individual donor
"""
print("""\n
Dear {n},
Thank you for your generous donation of ${a}! This will help our cause
immensely in our battle against the darkside. You, {n} , have made a big
difference in our efforts and we greatly appreciate you!!! Your ${a} will be
put to great use to our forces against evil!
Thank you,
The FORCE
\n""".format(n = name, a = amount))
def send_letter(name, amount):
"""
This function can send a letter to all but mainly to write to file
"""
return dedent('''
Dear {},
Thank you for your very kind donation of ${:,.2f}.
It will be put to very good use.
Sincerely,
-The Force
'''.format(name, amount))
def send_thank_you():
"""
Either adds to list or adds a new donor to the list and a
new donation amount
"""
clear_screen()
while True:
thanks_answer = menu_thank_you().strip()
if thanks_answer.upper() == "LIST":
clear_screen()
show_list()
elif thanks_answer.upper() == "MENU":
clear_screen()
break
else:
idx = len(main_donors)-1
in_main_donors = False
for x in range(len(main_donors)-1, -1, -1):
if main_donors[x].get("name").lower() == thanks_answer.lower():
in_main_donors = True
print("\nThe Donor you have selected is {}".format(thanks_answer))
donation_amount = float(input("\nPlease enter the amount that {} kindly donated: ".format(thanks_answer)))
main_donors[idx]["donations"].append(donation_amount)
print("{}: ${:.2f}".format(thanks_answer, donation_amount))
idx -= 1
if in_main_donors == False:
donation_amount = float(input("\nPlease enter {}'s donated amount: ".format(thanks_answer)))
add_new_donors = {"name": thanks_answer, "donations": [donation_amount]}
main_donors.append(add_new_donors)
print("{} was added with a donation of ${:.2f}".format(thanks_answer,float(donation_amount)))
send_email(thanks_answer, donation_amount)
def report_menu():
"""
Menu for Create a Report and to give the user an option to exit
"""
report_menu_answer = input("""
Welcome to the 'Create a Report option'!
Enter 'MENU' to exit and return to the Main Menu
Press Enter to continue
>>> """)
return report_menu_answer
def gen_stats(lst):
donor_stats = []
for donor in lst:
donations = donor["donations"]
total = sum(donations)
num = len(donations)
avg = round(total / num, 2)
stats = [donor["name"], total, num, avg]
donor_stats.append(stats)
return donor_stats
def create_report():
"""
Generates the report of donors by donation amount from greatest to least
"""
while True:
response = report_menu().strip()
if response.upper() == "MENU":
break
else:
clear_screen()
stats_list = gen_stats(main_donors)
stats_list.sort(key=lambda stats_list: stats_list[1],reverse=True)
print("{:<20}|{:^15}|{:^15}|{:>15}".format("Donor Name", "Total Given", "Num Gifts", "Average Gifts"))
print("-" * 68)
for donor in stats_list:
print("{:<20}${:>15} {:>15} ${:>15}".format(donor[0], donor[1], donor[2], donor[3]))
print("\nEnd of Report\n")
def save_letters():
"""
Saves letters to disk of all donors in data base
"""
for donor in main_donors:
file_name = donor["name"].replace(" ", "_") + ".txt"
letter = send_letter(donor["name"], donor["donations"][-1])
with open(file_name, "w") as text_file:
text_file.write(letter)
print("\nSaving {} file to disk".format(donor["name"]))
print("\nSAVING COMPLETE\n")
def quit():
print("You are leaving the Mailroom!")
sys.exit()
def mailroom_main():
"""
Main mailroom script
"""
while True:
answer = main_menu().strip()
if answer == "1":
send_thank_you()
elif answer == "2":
create_report()
elif answer == "3":
save_letters()
elif answer == "4":
quit()
else:
print("Please choose a number 1-4")
def main():
mailroom_main()
if __name__ == "__main__": main() |
7e10f9f91560ebcc5ab920e9f0eb4f84dc3cf9cb | ankitk2109/LeetCode | /12. AddTwoNumbers(linkedlist).py | 1,804 | 3.65625 | 4 | #Problem Statement available at: https://leetcode.com/problems/add-two-numbers
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def createNode(self, val, current, carry):
if(val>9):
r = val % 10
q = val // 10
temp = ListNode(r)
carry = q
current.next = temp
else:
temp = ListNode(val)
current.next = temp
return current,carry
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if (l1==None and l2==None):
return
elif(l1==None):
return l2
elif(l2 == None):
return l1
else:
carry = 0
head = ListNode(None)
current = head
while(l1 and l2):
val = l1.val + l2.val + carry
carry = 0
current,carry = self.createNode(val,current,carry)
l1 = l1.next
l2 = l2.next
current = current.next
if l1:
while(l1):
val = l1.val + carry
carry = 0
current,carry = self.createNode(val,current,carry)
l1 = l1.next
current = current.next
if l2:
while(l2):
val = l2.val + carry
carry = 0
current,carry = self.createNode(val,current,carry)
l2 = l2.next
current = current.next
if(carry):
temp = ListNode(carry)
current.next = temp
head = head.next
return(head) |
df7fc5374c7df10b93058a0b39736ee5ee127687 | St3h/Exercicios-Python | /Semana4/fatorial.py | 160 | 3.90625 | 4 | num = int(input('Digite o valor de n: '))
multiplier = 1
result = 1
while multiplier <= num:
result = result * multiplier
multiplier += 1
print(result) |
68b2acf05cbba703ca1ae9534442f658eca4c4ef | wanghaoListening/python-study-demo | /day-exe/day07-8.py | 949 | 4 | 4 | """
子类在继承了父类的方法后,可以对父类已有的方法给出新的实现版本,这个动作称之为方法重写(override)。通过方法重写我们可以让父类的同
一个行为在子类中拥有不同的实现版本,当我们调用这个经过子类重写的方法时,不同的子类对象会表现出不同的行为,这个就是多态(poly-morphism)。
"""
from abc import ABCMeta,abstractmethod
class Pet(object,metaclass=ABCMeta):
def __init__(self,nickname):
self._nickname = nickname
@abstractmethod
def make_voice(self):
pass
class Dog(Pet):
def make_voice(self):
print('%s 汪汪叫' %self._nickname)
class Cat(Pet):
def make_voice(self):
print('%s 喵喵叫' %self._nickname)
def main():
pets = [Dog('大黑'),Cat('花火'),Dog('阿黄')]
for pet in pets:
pet.make_voice()
if __name__ == '__main__':
main()
|
83655259168152059dba174b75ea8f6f61ae7260 | preetgur/python | /Oop9.py | 1,580 | 4.09375 | 4 | # super() and overriding
# class varible is override by "instance varible "
class A:
classvar1 = "I am a class variable in class A"
def __init__(self):
self.var1 ="I am inside class A's constructor"
self.special ="This is special instance variable used with the help of super().__init__"
self.classvar1 = "Instance var in class A" # instance variable
# if we remove the instance varibale 'classvari' then it would use the class variable which comes first
class B(A):
classvar2 ="I am in class B" # class variabel
classvar1 = "class B varible "
# overriding constructor : if instance variabel is not present in constructor then it would not use the constructor of Base class then it will look for class varible if present
# But if you wana to use base class construtor then use "super().__init__()"
def __init__(self):
super().__init__() # accessing instance variable of base class
# overrides the instance varible of base class
self.var1 ="I am inside class A's constructor"
self.classvar1 = "Instance var in class A"
super().__init__() # overrides the above instance variable this class
print("super : ",super().classvar1) # accessing class variable of : class variable
a = A()
b = B()
print("############### Attribute override ##############")
print(b.classvar1) # instance variable
print(b.classvar2) # class variable
print(b.var1) # instance variable
print(b.special)
print("############### Method override ##############")
|
4fac2c14a49b47449fc69dc9a007050e73c005c6 | htg30599/SS1 | /HW/w3/bubble_sort.py | 331 | 3.59375 | 4 | def bubbleSort(nlist):
for passnum in range(len(nlist) - 1, 0, -1):
for i in range(passnum):
if nlist[i] > nlist[i + 1]:
temp = nlist[i]
nlist[i] = nlist[i + 1]
nlist[i + 1] = temp
nlist = [14, 46, 43, 27, 57, 41, 45, 21, 70]
bubbleSort(nlist)
print(nlist)
|
f515ad7fa11571f9bff156893b4a7a0d9b442d2e | syurskyi/Algorithms_and_Data_Structure | /Python for Data Structures Algorithms/src/12 Array Sequences/Array Sequences Interview Questions/PRACTICE/Largest Continuous Sum .py | 1,180 | 3.953125 | 4 | # %%
'''
# Largest Continuous Sum
## Problem
Given an array of integers (positive and negative) find the largest continuous sum.
## Solution
Fill out your solution below:
'''
# %%
def large_cont_sum(arr):
if len(arr) == 0:
return 0
max_num = sum = arr[0]# max=sum=arr[0] bug: TypeError: 'int' object is not callable. (Do not use the keyword!)
for n in arr[1:]:
sum = max(sum+n, n)
max_num = max(sum, max_num)
return max_num
pass
# %%
large_cont_sum([1,2,-1,3,4,10,10,-10,-1])
# %%
'''
____
Many times in an interview setting the question also requires you to report back the start and end points of the sum.
Keep this in mind and see if you can solve that problem, we'll see it in the mock interview section of the course!
'''
# %%
'''
# Test Your Solution
'''
# %%
from nose.tools import assert_equal
class LargeContTest(object):
def test(self,sol):
assert_equal(sol([1,2,-1,3,4,-1]),9)
assert_equal(sol([1,2,-1,3,4,10,10,-10,-1]),29)
assert_equal(sol([-1,1]),1)
print ('ALL TEST CASES PASSED')
#Run Test
t = LargeContTest()
t.test(large_cont_sum)
# %%
'''
## Good Job!
''' |
d3f93cde28a6d571a4553bf8134c77286a03c180 | skk4/python_study | /src/network/ex40submit_get.py | 983 | 3.515625 | 4 | '''
Created on 2017.7.21
@author: Administrator
'''
import sys, urllib2, urllib
def addgetdata(url, data):
'''Adds data to url. Data should be a list or tuple consisting of 2-item
lists or tuples of the form :(key, value)
Items that have no key should key set to None.
A given key may occur more than once.'''
return url + '?' + urllib.urlencode(data, doseq = 0)
zipcode = raw_input(">")
#words = 'python'
#max = 25
#source = 'www'
url = addgetdata('http://www.wunderground.com/cgi-bin/findweather/getForecast', [('query', zipcode)])
#url = addgetdata('http://www.freebsd.org/cgi/search.cgi', [('words', zipcode)])
#url = addgetdata('http://www.freebsd.org/cgi/search.cgi', [('words', words), ('max', max), ('source',source)])
print "Using URL", url
req = urllib2.Request(url)
fd = urllib2.urlopen(req)
while 1:
data = fd.read(1024)
if not len(data):
break
sys.stdout.write(data) |
f8550fa835a9b68cef0b12cface5dd6694791230 | hlywp8/PythonDemo | /dataStructure.py | 702 | 3.59375 | 4 | shoplist=['mango','banana','apple']
for i in shoplist:
print(i,end=',')
shoplist.append('rice')
shoplist.sort()
print(shoplist)
del shoplist[0]
print(shoplist)
zoo=('wolf','elephant','penguin')
new_zoo=('monkey','dolphin',zoo)
print('%s is last'%new_zoo[2][2])
ab={'tom':'tom1','jerry':'jerry1','lily':'lily1'}
ab['tom']='tom2'
ab['larry']='larry1';
del ab['jerry']
for k,v in ab.items():
print('key is %s,value is %s'%(k,v))
if 'tom' in ab or ab.has_key('tom'):
print('has!')
name='swaroop'
print(name[1:3])
if name.startswith('swa'):
print('swa')
if 'a' in name:
print('a')
if name.find('oop')!=-1:
print('oop')
limiter='_'
list0=['a','b','c']
print(limiter.join(list0))
|
fb8809bbb36ae61f46a3bf30c25e67da1c7e7666 | shesan/Python-Projects | /CodingQuestions/1021.py | 507 | 3.65625 | 4 | # 1021. Remove Outermost Parentheses
class Solution(object):
def removeOuterParentheses(self, S):
"""
:type S: str
:rtype: str
"""
pos = 0
result = ""
for c in S:
if c == ")":
pos -= 1
if pos:
result += c
if c == "(":
pos += 1
return result
test = Solution()
S = "(()())(())"
print(S)
print(test.removeOuterParentheses(S))
|
9b18821a8179f08cd68549de348b22bc7be87e07 | st2013hk/pylab | /chatbot/chat1.py | 1,190 | 3.609375 | 4 | from chatterbot import ChatBot
chatbot = ChatBot("hellochatbot")
# from chatterbot.trainers import ListTrainer
# conversation = [
# "Hello",
# "Hi there!",
# "How are you doing?",
# "I'm doing great.",
# "That is good to hear",
# "Thank you.",
# "You're welcome."
# ]
#
# chatbot.set_trainer(ListTrainer)
# chatbot.train(conversation)
# response = chatbot.get_response("what is your name")
# print(response)
bot = ChatBot(
'hellochatbot',
storage_adapter='chatterbot.storage.SQLStorageAdapter',
input_adapter='chatterbot.input.TerminalAdapter',
output_adapter='chatterbot.output.TerminalAdapter',
logic_adapters=[
'chatterbot.logic.MathematicalEvaluation',
'chatterbot.logic.TimeLogicAdapter'
],
database='./mischat.db'
)
print("Type something to begin...")
# The following loop will execute each time the user enters input
while True:
try:
# We pass None to this method because the parameter
# is not used by the TerminalAdapter
bot_input = bot.get_response(None)
# Press ctrl-c or ctrl-d on the keyboard to exit
except (KeyboardInterrupt, EOFError, SystemExit):
break |
1189038656cea30682826e72d6e33cf5c7f31718 | uu64/project-euler | /problem035.py | 840 | 3.5625 | 4 | #!/usr/bin/env python3
def sieve(limit):
is_prime = [True for _ in range(limit)]
# primes = []
is_prime[0] = is_prime[1] = False
for i in range(2, len(is_prime)):
if is_prime[i]:
# primes.append(i)
for j in range(i*2, len(is_prime), i):
is_prime[j] = False
# remove not circular primes
circular_primes = set()
for i in range(2, len(is_prime)):
if is_prime[i]:
s_prime = str(i)
for j in range(1, len(s_prime)):
tmp = int(f"{s_prime[j:]}{s_prime[:j]}")
if not is_prime[tmp]:
is_prime[i] = False
break
if is_prime[i]:
circular_primes.add(i)
return circular_primes
ans = sieve(1000000)
# ans = sieve(100)
print(ans)
print(len(ans))
|
d911232e91dc886d7f33f07e3ab2d1b73cd9c76a | eterne92/COMP9021 | /assignment/assignment_1/quiz_4.py | 3,317 | 3.828125 | 4 | from random import randint
import sys
poker2dice = {
'Ace':0,'King':1,'Queen':2,'Jack':3,'10':4,'9':5
}
dice2poker = ['Ace','King','Queen','Jack','10','9']
def check_hand(dices):
check = [0] * 6
for dice in dices:
check[dice] += 1
if max(check) == 5:
return 'Five of a kind'
elif max(check) == 4:
return 'Four of a kind'
elif max(check) == 3:
if 2 in check:
return 'Full house'
else:
return 'Three of a kind'
elif max(check) == 2:
if check.count(2) == 1:
return 'One pair'
else:
return 'Two pair'
else:
if check[0] == 0 or check[-1] == 0:
return 'Straight'
else:
return 'Bust'
def print_dice(dices):
dices.sort()
print('The roll is:', end = '')
for dice in dices:
print(f' {dice2poker[dice]}',end = '')
print('\n',end = '')
print(f'It is a {check_hand(dices)}')
def reroll(orginal_dices,round):
dices = orginal_dices[:]
while(True):
input_pokers = input(f'Which dice do you want to keep for the {round} roll? ')
pokers = input_pokers.split()
if len(pokers) == 1 and pokers[0].upper() == 'ALL':
return -1
else:
flag = 1
for poker in pokers:
if poker not in poker2dice:
flag = 0
break
elif poker2dice[poker] not in dices:
flag = 0
break
else:
index = dices.index(poker2dice[poker])
dices[index] = -1
if flag == 0:
print('That is not possible, try again!')
dices = orginal_dices[:]
continue
else:
break
# print(dices)
rolls = [1] * 5
for i in range(5):
if dices[i] == -1:
rolls[i] = 0
if not 1 in rolls:
return -1
else:
return rolls
def roll_the_dice(rolls,dices):
for i in range(5):
if rolls[i] == 1:
dices[i] = randint(0,5)
return dices
def play():
rolls = [1] * 5
i2word = ['first','second','third']
for i in range(3):
if not i:
dices = [0] * 5
dices = roll_the_dice(rolls,dices)
print_dice(dices)
else:
rolls = reroll(dices,i2word[i])
if rolls == -1:
print('Ok, done.')
break
else:
roll_the_dice(rolls,dices)
print_dice(dices)
return
def simulate(n):
rolls = [1] * 5
dices = [0] * 5
hands = {
'Five of a kind' : 0,
'Four of a kind' : 0,
'Full house' : 0,
'Straight' : 0,
'Three of a kind': 0,
'Two pair' : 0,
'One pair' : 0,
'Bust' : 0}
hands_names = [
'Five of a kind',
'Four of a kind',
'Full house',
'Straight',
'Three of a kind',
'Two pair',
'One pair',
'Bust']
for i in range(n):
dices = roll_the_dice(rolls,dices)
hands[check_hand(dices)] += 1
for i in range(7):
print(f"{hands_names[i]:15}: {hands[hands_names[i]]/n*100:.2f}%")
|
c08eedbb71547315df10e2b27a17e2083dbf728a | cosmicTabulator/python_code | /Graham - Week 3 HW.py | 1,043 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 30 11:03:54 2016
@author: Graham Cooke
"""
#Website to be anaylyzed
website = "example.site.domain/main/home"
#stores the location of the most recently found slash
#-1 is a placholder to indicate that no slash has been found
slash = -1
#main loop
#sets the range of index to length of website(minus 1 due to starting at 0)
#to the end(-1), and to interate backwards through the range
for index in range(len(website)-1, -1, -1):
#print(index)
#look for the last slash from the left and stores the location
if website[index] == "/":
slash = index
#looks for the last period from the left
if website[index] == ".":
#if there was a slash, print from the last period to the next slash
if slash != -1:
print(website[index:slash])
break
#if therewas no slash, print from the period to the end
else:
print(website[index:])
break
print("End") |
973995e9258f0053c96a8ec8447a4cf8a65d5d9c | vemanand/pythonprograms | /general/sets1.py | 738 | 4.3125 | 4 | '''
Sample program to demonstrate different SET operations
Python offers a datatype called set whose elements must be unique. Set must be declared using curly/flower brackets
It can be used to perform different set operations like union, intersection, difference and symmetric difference.
'''
# define two sample sets
SET1 = {0, 2, 4, 6, 8, 10}
SET2 = {1, 2, 3, 4, 5, 6}
# set union
print("Union of two sets is", SET1 | SET2)
# set intersection
print("Intersection of sets is", SET1 & SET2)
# set difference. First set minus second set = Unique elements of set1
print("Difference of sets is", SET1 - SET2)
# set symmetric difference. Unmatched/Uncommon entries from both the sets
print("Symmetric difference of sets is", SET1 ^ SET2) |
d59acab76690ed543c5d9a775f3621c5433fca08 | namratarane20/python | /algorithm/insertionword.py | 510 | 4.21875 | 4 | #this program is used to load the file and read the values and perform insertion sorting of the values
from data import main
try:
file = open('wordlist','r') # opening the file
str_ = file.read() # read the text and storing in object
split_array = str_.split() # splitting the array to list
main.insertion(split_array) # calling the method
except FileNotFoundError:
print("FILE NOT FOUND") |
68d5535267725c58a26271957f4569859c93a968 | Danieltech99/CS-222-Final-Project | /helpers/fiedler.py | 2,116 | 3.625 | 4 | import numpy as np
# return the Fiedler value to show strong connection of the array
def fiedler(adj_mat):
'''
Return the fiedler value, the second smallest
eigenvalue of the Laplacian.
Done by constructing a degree matrix from the
adjacency matrix and calculating the Laplacian
and its eigenvalues.
'''
# Calculate the row sum of the adjacency matrix
# ... the row sum is the (out) degree of the node
rowsum = adj_mat.sum(axis=1)
# Construct a degree matrix
# ... the degree matrix is a diagnal matrix of node degree
# ... (D = diag(d))
degree_matrix = np.diag(np.array(rowsum))
# The Laplacian is defined as
# ... the degree matrix minus the adjacency matrix
# ... (L = D - M)
laplacian = degree_matrix - adj_mat
# Calculate the eigenvalues of the Laplacian
e_values, _ = np.linalg.eig(laplacian)
# Sort the eigenvalues
sorted_e_values = sorted(e_values)
# The Fiedler value is the second smallest eigenvalue of the Laplacian
return sorted_e_values[1]
def normalized_fiedler(adj_mat):
'''
Extends above
... but does so with the normalized adj and Laplacian
A_n = D^(-1/2) * A * D^(-1/2)
L = I - A_n
'''
# Calculate the row sum of the adjacency matrix
# ... the row sum is the (out) degree of the node
rowsum = adj_mat.sum(axis=1)
# Construct a degree matrix to the power (-1/2)
# ... the degree matrix is a diagnal matrix of node degree
# ... (D = diag(d))
handle_zeros = [0 if e == 0 else e ** (-1/2) for e in rowsum]
degree_matrix_neg_1_2 = np.diag(np.array(handle_zeros))
# A_n = D^(-1/2) * A * D^(-1/2)
norm_adj_mat = np.matmul(degree_matrix_neg_1_2, np.matmul(adj_mat, degree_matrix_neg_1_2))
# L = I - A_n
norm_laplacian = np.identity(len(adj_mat)) - norm_adj_mat
# Calculate the eigenvalues of the Laplacian
e_values, _ = np.linalg.eig(norm_laplacian)
# Sort the eigenvalues
sorted_e_values = sorted(e_values)
# The Fiedler value is the second smallest eigenvalue of the Laplacian
return sorted_e_values[1] |
2b5a05626c732d22186e1e45d69cfbce8138af15 | citatricahayas/Cita-Tri-Cahaya-Sakti_I0320020_Aditya-Mahendra_Tugas4 | /I0320020_exercise4.1.py | 253 | 3.75 | 4 | x = 28
y = 2
#Output x+y = 30
print("x+y = ", x+y)
#Output x-y = 26
print("x-y = ", x-y)
#Output x*y = 56
print("x*y = ", x*y)
#Output x/y = 14
print("x/y = ", x/y)
#Output x//y = 14
print("x//y = ", x//y)
#Output x**y = 784
print("x**y = ", x**y) |
da3f5536bf1f9d127019ccb1835ca41ad4a1fc90 | zarbod/Python-labs | /fourth.py | 101 | 4.25 | 4 | radius = float(input("Enter radius: "))
print("Area of the Circle is: " + str(3.14*radius*radius)) |
eb09354142758498019b15b7b8dca5c217cb8b72 | BorjaCuevas/PuzzleSolver | /Core/piece.py | 369 | 3.53125 | 4 | """ Piece class """
class Piece:
def __init__(self, key, sideA, sideB, sideC, sideD):
self.key = key
self.sideA = sideA
self.sideB = sideB
self.sideC = sideC
self.sideD = sideD
def rotate(self):
"""
Rotate the piece to make easy to look for restrictions
@return: none
"""
pass
|
9acb21fdedec85175de70604ea0de7f5b0c23cc9 | narennandi/interview-cake | /sorting_searching_logarithms.py | 1,242 | 3.96875 | 4 | def binary_search(nums, target):
low = 0
high = len(nums) -1
while low <= high:
mid = (high + low) // 2
if nums[mid] == target:
return mid
elif target > nums[mid]:
low = mid + 1
else:
high = mid - 1
return "Target not in array"
def merge_ranges(meetings):
# Sort by start time
sorted_meetings = sorted(meetings)
# Initialize merged_meetings with the earliest meeting
merged_meetings = [sorted_meetings[0]]
for current_meeting_start, current_meeting_end in sorted_meetings[1:]:
last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1]
# If the current meeting overlaps with the last merged meeting, use the
# later end time of the two
if (current_meeting_start <= last_merged_meeting_end):
merged_meetings[-1] = (last_merged_meeting_start,
max(last_merged_meeting_end,
current_meeting_end))
else:
# Add the current meeting since it doesn't overlap
merged_meetings.append((current_meeting_start, current_meeting_end))
return merged_meetings
|
bee39ef20702db94f7bb22922067051ed702fccc | BAFurtado/Python4ABMIpea2019 | /for_loop.py | 198 | 4.0625 | 4 |
# for i in 'hello':
# print(i)
#
# for i in range(5):
# # print(i)
#
# a = 'hi, my name is Bernardo'
# for i in a.split(' '):
# print('pa' + i)
for i in range(5):
print(i.upper()) |
3f2d5148f6c94b76897b654959805ab382364def | zefaradi/Coding-Challenges-from-codewars.com | /Human Readable Time.py | 790 | 4.03125 | 4 | # Human Readable Time
# Description:
# Write a function, which takes a non-negative integer (seconds) as input and
# returns the time in a human-readable format (HH:MM:SS)
# HH = hours, padded to 2 digits, range: 00 - 99
# MM = minutes, padded to 2 digits, range: 00 - 59
# SS = seconds, padded to 2 digits, range: 00 - 59
# The maximum time never exceeds 359999 (99:59:59)
#
# You can find some examples in the test fixtures.
def make_readable(seconds):
hours = seconds/3600
hours2 = int(hours)
minutes = hours - hours2
minutes2 = minutes * 60
minutes3 = int(minutes2)
seconds = minutes2 - minutes3
seconds2 = round(seconds * 60)
return ("%02d:%02d:%02d" % (hours2, minutes3, seconds2))
test = make_readable(3600)
print(test)
|
b8eab53f165858c45015f5103bfc6af109e8f43a | AdamZhouSE/pythonHomework | /Code/CodeRecords/2662/60898/317192.py | 359 | 3.765625 | 4 | def intToBi(x):
temp=""
while(x>1):
temp=str(x%2)+temp
x=x//2
temp=str(x)+temp
return temp
t=eval(input())
for i in range(0,t):
x=eval(input())
str1=intToBi(x)
cnt=0
for j in range(0,len(str1)):
if str1[j]=='1':
cnt+=1
if(cnt%2!=0):
print("odd")
else:
print("even")
|
2b3985a018d793cc3c12022250313a8904d8d9f7 | alinbabu2010/Python-programs | /calculator.py | 770 | 3.734375 | 4 | import math
def add():
a,b=map(int,raw_input("Enter the two numbers\n").split())
c=a+b
print("Sum is {}").format(c)
def sub():
a,b=map(int,raw_input("Enter the two numbers\n").split())
c=a-b
print("Difference is {}").format(c)
def pro():
a,b=map(int,raw_input("Enter the two numbers\n").split())
c=a*b
print("Product is {}").format(c)
def div():
a,b=map(int,raw_input("Enter the two numbers\n").split())
c=a/b
print("Quotient is {}").format(c)
def squt():
a=input("Enter the number\n")
c=math.sqrt(a)
print("Square root of {0} is {1}").format(a,c)
def pwr():
a,b=map(int,raw_input("Enter the number and power\n").split())
c=pow(a,b)
print("Power is {0}").format(c)
|
f829ac02ab839a3e48575e60b4bae0b6ae5342fa | ChinaChenp/Knowledge | /learncode/python/tuple.py | 229 | 3.53125 | 4 | dimensions = (200, 50, 200, 300, 412)
for dimension in dimensions:
print(dimension)
dimensions = (1, 2, 5, 1, 7, 8)
print(dimensions)
#可以是不同类型
tuples = ("a", 1, 5, "fdjs", "9", 6)
for v in tuples:
print(v) |
df3e432546842bd21ad5206438785d9d7d6a857a | ProgmanZ/Modul-15.5-Tasks--HW- | /Task-07.py | 1,179 | 3.65625 | 4 | # Задача 7. Контейнеры
def weight_input(dialog):
while True:
print(dialog, end='')
weight_container = int(input())
if 200 >= weight_container > 0:
break
else:
print("Ошибка. Вес контейнера не может превышать 200 кг.")
return weight_container
def search_place(weight_new_container, container_list):
count = 0
for numb_cont in range(len(container_list)):
if weight_new_container > container_list[numb_cont] and weight_new_container != container_list[numb_cont]:
count += 1
break
count += 1
return count
containers = int(input("Кол-во контейнеров: "))
data_containers = []
old_dialog = 'Введите вес контейнера (кг): '
new_dialog = '\nВведите вес нового контейнера (кг): '
for container in range(containers):
data_containers.append(weight_input(old_dialog))
new_container = weight_input(new_dialog)
numb = search_place(new_container, data_containers)
print('\nНомер, куда встанет новый контейнер: ', numb)
|
38d5fee05736012c35f4ea576bb94a32186b5ebd | aaronrambhajan/sunshine-list-analyzer | /main.py | 1,653 | 3.90625 | 4 | import functions
print('This program calculates the average salary increase of all UofT \
employees on the Sunshine List who were employed between two given years, \
ranging 2006 to 2016. The Sunshine List includes public sector employees \
with salaries in excess of $100k.')
answer = 'yes'
while answer.lower() == 'yes' or answer.lower() == 'yeah' \
or answer.lower() == 'ye' or answer.lower() == 'y' \
or answer.lower() == 'ya':
# Prompt for first input.
one = input('\nEnter the starting year: ')
# Checks that input is numeric.
while one.isnumeric() == False:
one = input('Year information must be a number between 2006 and \
2016, please! Enter the starting year: ')
# Checks that input is within valid year range.
while int(one) < 2006 or int(one) > 2016:
one = int(input('Year information must be between 2006 and 2016, \
please! Re-enter the starting year: '))
# Prompt for second input.
two = input('\nEnter the ending year: ')
# Checks that input is numeric.
while two.isnumeric() == False:
two = input('Year information must be a number between 2006 and \
2016, please! Enter the ending year: ')
# Checks that input is within valid year range.
while int(two) < 2006 or int(two) > 2016 or int(one) == int(two):
two = int(input('Year information must be between 2006 and 2016, \
please! Re-enter the ending year: '))
# Run program according to input.
functions.main_program(one, two)
# Reprompt, and conclude.
answer = input('\nAny more requests? ')
print("\nHope you found what you're looking for! Developed in 2017 by Aaron \
Rambhajan.\n")
|
576ed152dc496c6c604581873157a17e518f6d40 | ridvanaltun/project-euler-solutions | /040/040.py | 790 | 3.859375 | 4 | """
While döngüsü kurup kontrol ifadesi koyabilirdim ancak her seferinde
kontrol ifadesi programı ~2 kat yavaşlatacaktır.
Bu yüzden aşağıdaki hesabı yaptım.
(9 * 1) + (99 * 2) + (999 * 3) +
(9999 * 4) + (99999 * 5) + (76135 * 6) = 1000005
Yani döngü toplamda 9 + 99 + 999 + 9999 + 99999 + 76135 kez döndüğünde
1000005 basamak üretiyor.
"""
import time
start = time.time()
num = ""
# Basamakları oluştur
for i in range(1, 9 + 99 + 999 + 9999 + 99999 + 76135 + 1):
num = num + str(i)
# Sonucu yazdır
print(int(num[0]) * int(num[9]) * int(num[99]) * int(num[999]) *
int(num[9999]) * int(num[99999]) * int(num[999999]))
elapsed = (time.time() - start)
print("This code took: " + str(elapsed) + " seconds")
# This code took: 0.09795546531677246 seconds
|
cc65c69b2cabb47eaef5079fa600dd6e2ed00b47 | Iftakharpy/Data-Structures-Algorithms | /section 10 implementaion_of_Binary_Tree_with_Node.py | 1,738 | 3.890625 | 4 | class Node:
def __init__(self,value):
self.value = value
self.high = None
self.low = None
def __repr__(self):
return f'[value:{self.value},\nhigh:{self.high},low:{self.low}]'
class Binary_Tree:
def __init__(self,value=None):
if value==None:
self.root = None
self.length=0
else:
self.root = Node(value)
self.length=1
def __repr__(self):
return f"root:{self.root}\nlength:{self.length}"
def insert(self,value):
new_node = Node(value)
if self.root==None:
self.root = new_node
return
current_node = self.root
while True:
if value<=current_node.value:
if current_node.low==None:
current_node.low=new_node
self.length+=1
return
current_node=current_node.low
else:
if current_node.high==None:
current_node.high=new_node
self.length+=1
return
current_node=current_node.high
def lookup(self,value):
current_node = self.root
while True:
if value==current_node.value:
return True
if value>current_node.value:
current_node=current_node.high
continue
current_node = current_node.low
if current_node.value==value:
return True
if current_node.high == None and current_node.low==None:
return False
a=Binary_Tree()
vals = [9,20,4,1,6,21,19]
for i in vals:
a.insert(i)
print(a)
a.remove(1)
print(a) |
7c5b7266b8cbc35f27dd7ef69f98624a9e7b23a2 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3985/codes/1592_2425.py | 67 | 3.546875 | 4 | a= float(input())
b= float(input())
c= a/b
print(round(c,3),"km/l") |
66a47167c2401ff04917df9ba595062b587a6643 | kih1024/codingStudy | /(삼성,시뮬)주사위굴리기.py | 1,350 | 3.546875 | 4 | def move(li):
temp = li[-1]
li[1:] = li[0:3]
li[0] = temp
def rotate(d):
# 오른쪽으로 돌릴때
if d == 0:
li = [dice[0], dice[2], dice[5], dice[3]]
move(li)
dice[0], dice[2], dice[5], dice[3] = [i for i in li]
# 왼쪽으로 돌릴때
elif d == 1:
li = [dice[0], dice[3], dice[5], dice[2]]
move(li)
dice[0], dice[3], dice[5], dice[2] = [i for i in li]
# 위로 돌릴때
elif d == 2:
li = [dice[0], dice[1], dice[5], dice[4]]
move(li)
dice[0], dice[1], dice[5], dice[4] = [i for i in li]
# 아래로 돌릴때
else:
li = [dice[0], dice[4], dice[5], dice[1]]
move(li)
dice[0], dice[4], dice[5], dice[1] = [i for i in li]
if arr[y][x] == 0:
arr[y][x] = dice[-1]
else:
dice[-1] = arr[y][x]
arr[y][x] = 0
n, m, y, x, k = map(int, input().split())
arr = [list(map(int, input().split())) for i in range(n)]
order = [i - 1 for i in list(map(int, input().split()))]
dy, dx = [0, 0, -1, 1], [1, -1, 0, 0]
# 위 앞 오른쪽 왼쪽 뒤 아래
dice = [0] * 6
for i in order:
# d : 0 동,1 서,2 북,3 남
if y + dy[i] > n - 1 or y + dy[i] < 0 or x + dx[i] > m - 1 or x + dx[i] < 0:
continue
y = y + dy[i]
x = x + dx[i]
rotate(i)
print(dice[0])
|
81ce564bb048503047157725590a9fa8fcd75ce2 | j2sdk408/misc | /mooc/algorithms_II/graph_process.py | 1,146 | 3.90625 | 4 | """
implementation of graph algorithms
"""
from graph import Graph
class GraphProcess(object):
"""class for graph processing"""
@staticmethod
def degree(G, v):
"""compute the degree of v"""
return len(G.adj(v))
@staticmethod
def max_degree(G):
"""compute maximum degree"""
return max([GraphProcess.degree(G, x) for x in xrange(G.V())])
@staticmethod
def average_degree(G):
"""compute average degree"""
return 2. * G.E() / G.V()
@staticmethod
def number_of_self_loops(G):
"""count self-loops"""
count = 0
for v in xrange(G.V()):
if v in G.item_dict[v]:
count += 1
return count
@staticmethod
def print_info(G):
"""print graph info"""
print "max. degree: %d" % GraphProcess.max_degree(G)
print "avg. degree: %d" % GraphProcess.average_degree(G)
print "#self-loops: %d" % GraphProcess.number_of_self_loops(G)
if __name__ == "__main__":
import sys
file_name = sys.argv[1]
G = Graph.from_file(file_name)
GraphProcess.print_info(G)
|
99bc910a9d1b6ed412b05b73da75f01af01ec92c | baloooo/coding_practice | /top_k_frequent.py | 1,261 | 4.03125 | 4 | '''
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
'''
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
from heapq import heapify, heappop
import collections
freq_map = collections.defaultdict(int)
for num in nums:
freq_map[num] += 1
max_heap = [(-freq, num) for num, freq in freq_map.items()]
heapify(max_heap)
most_frequent = []
for _ in xrange(k):
most_frequent.append(heappop(max_heap)[1])
return most_frequent
if __name__ == '__main__':
test_cases = [
([1, 1, 1, 2, 2, 3], [1, 2]),
]
for test_case in test_cases:
res = Solution().topKFrequent(test_case[0], 2)
if res == test_case[1]:
print "Passed"
else:
print "Failed: Test case: {0} Got {1} Expected {2}".format(
test_case[0], res, test_case[1])
|
4a94e296f7ffce5292df94946a0f6605f779e5ac | wkddngus5/data-structure-python | /sorting/bubble-sort/index.py | 2,373 | 4.65625 | 5 | import unittest
# Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in form of an array with n number of elements.
# Bubble Sort compares all the element one by one and sort them based on their values.
# If the given array has to be sorted in ascending order,
# then bubble sort will start by comparing the first element of the array with the second element,
# if the first element is greater than the second element, it will swap both the elements,
# and then move on to compare the second and the third element, and so on.
# If we have total n elements, then we need to repeat this process for n-1 times.
# It is known as bubble sort, because with every complete iteration the largest element in the given array,
# bubbles up towards the last place or the highest index, just like a water bubble rises up to the water surface.
# Sorting takes place by stepping through all the elements one-by-one and comparing it with the adjacent element and swapping them if required.
# Following are the steps involved in bubble sort(for sorting a given array in ascending order):
# 1. Starting with the first element(index = 0), compare the current element with the next element of the array.
# 2. If the current element is greater than the next element of the array, swap them.
# 3. If the current element is less than the next element, move to the next element. Repeat Step 1.
# Worst Case Time Complexity [ Big-O ]: O(n2)
def bubble_sort(list):
for index2 in range(len(list) - 1):
for index in range(len(list) - index2 - 1):
if list[index] > list[index + 1]:
temp = list[index + 1]
list[index + 1] = list[index]
list[index] = temp
def optimized_bubble_sort(list):
flag = False
for index2 in range(len(list) - 1):
for index in range(len(list) - index2 - 1):
if list[index] > list[index + 1]:
flag = True
temp = list[index + 1]
list[index + 1] = list[index]
list[index] = temp
if flag == False:
break
class Test(unittest.TestCase):
def test1(self):
list = [5, 1, 6, 2, 4, 3]
copy_list = list[:]
bubble_sort(list)
copy_list.sort()
self.assertEqual(list, copy_list)
def test2(self):
list = [5, 1, 6, 2, 4, 3]
copy_list = list[:]
optimized_bubble_sort(list)
copy_list.sort()
self.assertEqual(list, copy_list)
if __name__ == '__main__':
unittest.main() |
844e7f340d023a46706da4b951bc531fb5c4ec80 | Alf0nso/NN-Games | /NN/nn_tic_tac_toe.py | 1,533 | 3.921875 | 4 | # Training of Tic tac toe
#
# @Author: Afonso Rafael & Renata
#
# Train the neural network on
# tic tac toe games and observe how it
# performs!
import neural_net as nn
import numpy as np
import utils as ut
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
# libraries both for making the MLP and
# for testing it.
print()
print(50*"-")
print("Generating Neural Net")
MLP = np.array(nn.MLP(9, [25, 20], 3), dtype='object')
p = ut.nn_construct_input("tic_games", 3, 3)
targets = []
for target in p[1]:
x = [0, 0, 0]
x[int(target) - 1] = 1.0
targets.append(x)
targets = np.array(targets)
inputs = np.array(p[0])
# Spliting the data for training and testing
X_train, X_test, y_train, y_test = train_test_split(inputs, targets, test_size=0.2, random_state=42, stratify=targets)
print()
print(50*"-")
print("Training The Neural Neural Network")
nn.train(MLP, X_train, y_train, 25, 0.1)
print(50*"-")
print("Testing the Neural Network")
outputs = nn.forward_propagate(X_test, MLP[0], MLP[1])
print()
print()
pred_y = []
for output in outputs:
output = list(output)
pred_labels = [0, 0, 0]
pred_labels[output.index(max(output))] = 1.0
pred_y.append(pred_labels)
print('Accuracy for Testing Set: ',
accuracy_score(y_test, np.array(pred_y)))
print('F1 Score for Testing Set: ',
f1_score(y_test, np.array(pred_y), average='weighted'))
# file = open("Neural_Network_2", "wb")
# np.save(file, MLP)
# file.close
|
56037bd446e10089f8fb2ffb7b804c0dde08599c | Hamza-Ejaz/Python | /Assignment 3/max_no._of_list.py | 80 | 3.5 | 4 | list1 = [9,7,6,4,16,29,13,20,43,36,11,52,47,19,]
list1.sort()
print(list1[-1]) |
140d1ece0346562e78b8c5aab70004f94da21316 | Dorrro/PythonPlayground | /PythonPlayground/zaj2/4.py | 620 | 3.78125 | 4 | import random
words = ["jeden", "dwa", "dom", "test"]
word = random.choice(words)
step = 1
guess = ""
print("W słowie znajduje się " + str(len(word)) + " liter")
while step <= 5 and guess != word:
letter = input("Podaj literę, która może istnieć w słowie: ")
if len(letter) != 1:
print("Litera ma tylko jeden znak :)")
continue
if letter in word:
print("TAK!")
else:
print("NIE!")
guess = input("Odgadnij słowo: ")
step = step + 1
if guess == word:
print("Gratulacje!")
else:
print("Niestety, nie udało Ci się odgadnąć słowa: " + word) |
6e352f8b76bc17768bbc6227fc03cbe594cd7f22 | marlonsd/FerrIA-Robots | /player.py | 10,950 | 3.65625 | 4 | """
Based on Paul Vincent Craven code
http://simpson.edu/author/pcraven-2/
"""
import pygame, abc, sys
import numpy as np
from objects import Base, Mine, Wall
# Colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
BLUE = ( 0, 0, 255)
RED = ( 255, 0, 0)
GREEN = ( 0, 255, 0)
YELLOW = ( 255, 255, 0)
# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# This class represents the bar at the bottom that the player controls
class Player(pygame.sprite.Sprite):
""" This class represents the bar at the bottom that the player controls. """
# Constructor function
def __init__(self, id, x, y, capacity=1):
# Set speed vector
self.change_x = 0
self.change_y = 0
self.walls = None
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Set height, width
self.image = pygame.Surface([15, 15])
self.image.fill(WHITE)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
self.gold = 0
self.capacity = capacity
self.id = id
def changespeed(self, x, y):
""" Change the speed of the player. """
self.change_x += x
self.change_y += y
def update(self):
""" Update the player position. """
# Move left/right
self.rect.x += self.change_x
if self.rect.x >= SCREEN_WIDTH:
self.rect.x -= self.change_x
# Did this update cause us to hit a wall?
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
# If we are moving right, set our right side to the left side of the item we hit
if self.change_x > 0:
self.rect.right = block.rect.left
else:
# Otherwise if we are moving left, do the opposite.
self.rect.left = block.rect.right
# Move up/down
self.rect.y += self.change_y
if self.rect.y >= SCREEN_HEIGHT:
self.rect.y -= self.change_y
# Check and see if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, self.walls, False)
for block in block_hit_list:
# Reset our position based on the top/bottom of the object.
if self.change_y > 0:
self.rect.bottom = block.rect.top
else:
self.rect.top = block.rect.bottom
def storeGold(self, mine):
capacity = self.capacity - self.gold
if capacity > 0:
gold = mine.toMine(capacity)
if gold > 0:
self.gold += gold
print 'Got', gold, 'gold from mine', mine.id
if mine.gold == 0:
mine.kill()
def releaseGold(self):
gold = self.gold
self.gold = 0
return gold
def inside(self, obj):
inside_x = (obj.rect.x <= self.rect.x and obj.rect.x+obj.rect.width >= self.rect.x)
inside_y = (obj.rect.y <= self.rect.y and obj.rect.y+obj.rect.height >= self.rect.y)
return (inside_x and inside_y)
def _isIn(self,vector, point):
try:
index = vector[point]
return True
except:
return False
@abc.abstractmethod
def moviment(self, player_pos, gradient):
possibility = [(-1,-1),(0,-1),(1,-1),(-1,0),(0,0),(1,0),(-1,1),(0,1),(1,1)]
if (self.rect.x <= 10 or self.rect.x < 0):
try:
possibility.remove((-1,-1))
except:
pass
try:
possibility.remove((-1,0))
except:
pass
try:
possibility.remove((-1,1))
except:
pass
elif (self.rect.x >= SCREEN_WIDTH-30):
try:
possibility.remove((1,-1))
except:
pass
try:
possibility.remove((1,0))
except:
pass
try:
possibility.remove((1,1))
except:
pass
if (self.rect.y <= 10 or self.rect.y < 0):
try:
possibility.remove((-1,-1))
except:
pass
try:
possibility.remove((0,-1))
except:
pass
try:
possibility.remove((1,-1))
except:
pass
elif (self.rect.y >= SCREEN_HEIGHT-30):
try:
possibility.remove((-1,1))
except:
pass
try:
possibility.remove((0,1))
except:
pass
try:
possibility.remove((1,1))
except:
pass
mov_x, mov_y = possibility[np.random.randint(len(possibility))]
new_pos = (player_pos[self.id][0]+mov_x, player_pos[self.id][1]+mov_y)
while self._isIn(player_pos, new_pos):
try:
possibility.remove((mov_x, mov_y))
except:
pass
mov_x, mov_y = possibility[np.random.randint(len(possibility))]
new_pos = (player_pos[self.id][0]+mov_x, player_pos[self.id][1]+mov_y)
Player.changespeed(self, mov_x,mov_y)
player_pos[self.id] = (new_pos)
class Player1(Player):
def __init__(self, id, x, y, capacity=1):
Player.__init__(self, id, x, y, capacity=1)
class Player2(Player):
def __init__(self, id, x, y, capacity=1):
Player.__init__(self, id, x, y, capacity)
def changespeed(self, x, y):
self.change_x = x
self.change_y = y
def moviment(self, player_pos, gradient):
if self.gold:
possibility = [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
for x, y in possibility:
try:
aux = gradient[self.rect.x+x][self.rect.y+y]['base']
except:
possibility.remove((x,y))
poss = []
for x, y in possibility:
poss.append(gradient[self.rect.x+x][self.rect.y+y]['base'])
pos = np.argsort(poss)[0]
mov_x, mov_y = possibility[pos]
new_pos = (self.rect.x+mov_x, self.rect.y+mov_y)
Player2.changespeed(self,mov_x,mov_y)
player_pos[self.id] = (new_pos)
else:
Player.moviment(self,player_pos, gradient)
class Player3(Player2):
def __init__(self, id, x, y, capacity=1):
Player2.__init__(self, id, x, y, capacity)
self.xixi = 1
self.mark = False
def storeGold(self, mine):
self.xixi = 1
Player.storeGold(self, mine)
def releaseGold(self):
self.mark = False
self.xixi = 1
return Player.releaseGold(self)
def moviment(self, player_pos, gradient):
if self.gold:
if (gradient[self.rect.x][self.rect.y]['base'] != 100):
gradient[self.rect.x][self.rect.y]['mine'] += self.xixi
self.xixi += 1
Player2.moviment(self, player_pos, gradient)
else:
possible_neighbor = [(-1,-1),(0,-1),(1,-1),(0,0),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
for x, y in possible_neighbor:
try:
aux = gradient[self.rect.x+x][self.rect.y+y]['base']
except:
possible_neighbor.remove((x,y))
possibility = []
for pos, neighbor in enumerate(possible_neighbor):
if gradient[self.rect.x+neighbor[0]][self.rect.y+neighbor[1]]['mine']:
possibility.append([gradient[self.rect.x+neighbor[0]][self.rect.y+neighbor[1]]['mine'], pos])
if len(possibility):
pos = np.argsort(possibility, axis=0)[0][0]
mov_x, mov_y = possible_neighbor[possibility[pos][1]]
if mov_x == 0 and mov_y == 0:
Player.moviment(self,player_pos, gradient)
else:
new_pos = (self.rect.x+mov_x, self.rect.y+mov_y)
while self._isIn(player_pos, new_pos):
try:
possibility.remove((mov_x, mov_y))
except:
pass
mov_x, mov_y = possibility[np.random.randint(len(possibility))]
new_pos = (self.rect.x+mov_x, self.rect.y+mov_y)
Player2.changespeed(self, mov_x,mov_y)
player_pos[self.id] = (new_pos)
else:
Player.moviment(self,player_pos, gradient)
class Player4(Player3):
def __init__(self, id, x, y, capacity=1):
Player3.__init__(self, id, x, y, capacity=1)
# self.gold = 1
def moviment(self, player_pos, gradient):
if self.gold:
if (gradient[self.rect.x][self.rect.y]['base'] != 100):
gradient[self.rect.x][self.rect.y]['mine'] += self.xixi
self.xixi += 1
Player2.moviment(self, player_pos, gradient)
else:
possible_neighbor = [(-1,-1),(0,-1),(1,-1),(0,0),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
for x, y in possible_neighbor:
try:
aux = gradient[self.rect.x+x][self.rect.y+y]['base']
except:
possible_neighbor.remove((x,y))
possibility = []
for pos, neighbor in enumerate(possible_neighbor):
if gradient[self.rect.x+neighbor[0]][self.rect.y+neighbor[1]]['mine']:
possibility.append([gradient[self.rect.x+neighbor[0]][self.rect.y+neighbor[1]]['mine'], pos])
if len(possibility):
pos = np.argsort(possibility, axis=0)[0][0]
mov_x, mov_y = possible_neighbor[possibility[pos][1]]
if mov_x == 0 and mov_y == 0:
gradient[self.rect.x][self.rect.y]['mine'] = 0
Player.moviment(self,player_pos,gradient)
else:
new_pos = (self.rect.x+mov_x, self.rect.y+mov_y)
while self._isIn(player_pos, new_pos):
try:
possibility.remove((mov_x, mov_y))
except:
pass
mov_x, mov_y = possibility[np.random.randint(len(possibility))]
new_pos = (self.rect.x+mov_x, self.rect.y+mov_y)
gradient[new_pos[0]][new_pos[1]]['mine'] = 0
Player2.changespeed(self, mov_x,mov_y)
player_pos[self.id] = (new_pos)
else:
Player.moviment(self,player_pos, gradient)
|
eff5f158a3bf7b335b257b2322f1b1f94b4bb2d4 | amarschn/VOT_2014_Tracking_Challenge | /utilities.py | 2,333 | 3.640625 | 4 | #!/usr/bin/env python
"""
Utilities
===========
This module contains multiple utility functions:
get_jpeg => will load jpeg images and return them as an array.
plot_pixel_position => will plot pixel location given an array.
rect_resize => will resize a rectangle given an array of points.
"""
import cv2
import os
import matplotlib.pyplot as plt
import numpy as np
def get_jpeg(path):
"""
Returns all JPEG files given a path
:param path:
"""
image_names = []
for f in os.listdir(path):
if f.endswith(".jpg"):
image_names.append(path + f)
return image_names
def plot_pixel_position(pos):
"""
:param pos:
:return:
"""
pos = np.array(pos)
plt.plot(pos[:, 0])
plt.plot(pos[:, 1])
plt.legend(['X pixel location', 'Y pixel location'])
plt.show()
def rect_resize(rect, car_points, buffer=40):
"""
Resizes a rectangle based on given points, will grow the rectangle by a buffered amount given the max and min values
of the point array
:param rect: rectangle containing
:param points:
:param buffer:
:return:
"""
# Define the max and min of x and y to be added or subtracted the buffer, respectively
[min_x, min_y] = np.min(car_points,1) - buffer
[max_x, max_y] = np.max(car_points,1) + buffer
# Grow the rectangle by the mean of the rectangles current position and the mean of the min and max x and y
# positions. This keeps the rectangle from re-sizing drastically every frame due to changing feature points
rect[0] = np.mean([rect[0], min_x])
rect[1] = np.mean([rect[1], min_y])
rect[2] = np.mean([rect[2], max_x])
rect[3] = np.mean([rect[3], max_y])
# Return the new rectangle
return np.int32(rect)
if __name__ == '__main__':
# Load images into array
imgs = get_jpeg('C:/Users/Drew/Dropbox/Uber_Assignment/uber_cv_car_exercise/car/')
# Begin video capture of images
cap = cv2.VideoCapture(imgs[0])
idx = 0
# Loop through images, end once at the end of the image array
while idx < len(imgs):
ret, frame = cap.read()
cv2.imshow('Frame', frame)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
# Update the index
idx += 1
# Close all windows
cv2.destroyAllWindows()
|
4f4aefd5d67caec1e912f9fb806a282114e74335 | Sk0uF/Algorithms | /py_algo/arrays_strings/string_manipulation/terrible_chandu.py | 579 | 3.671875 | 4 | """
Codemonk link: https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-manipulation/practice-problems/algorithm/terrible-chandu/
Reverse the given string.
Input - Output:
The first contains the number of test cases.
Each of the next T lines contains a single string S.
Sample input:
2
ab
aba
Sample Output:
ba
aba
"""
"""
The problem is straight forward.
Final complexity: O(N)
"""
inp_len = int(input())
for _ in range(inp_len):
s = input()
# The general case is a[begin:end:step].
print(s[::-1])
|
7cc059a69d5719d3909cf0d98f98e5e6d07d5d3d | namanj401/A-Z-ML | /Regression/Polynomial Regression/polynomial regression.py | 884 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset= pd.read_csv('Regression\Polynomial Regression\Position_Salaries.csv')
X=dataset.iloc[:,1:-1].values
y=dataset.iloc[:,-1].values
from sklearn.linear_model import LinearRegression
lin_reg=LinearRegression()
lin_reg.fit(X,y)
from sklearn.preprocessing import PolynomialFeatures
poly_reg= PolynomialFeatures(degree=4)
X_poly=poly_reg.fit_transform(X)
lin_reg_2=LinearRegression()
lin_reg_2.fit(X_poly,y)
plt.scatter(X,y,color='red')
plt.plot(X,lin_reg.predict(X),color='blue')
plt.title('Level vs Salary')
plt.xlabel('Level')
plt.ylabel('Salary')
plt.show()
plt.scatter(X,y,color='red')
plt.plot(X,lin_reg_2.predict(X_poly),color='blue')
plt.title('Level vs Salary')
plt.xlabel('Level')
plt.ylabel('Salary')
plt.show()
lin_reg.predict([[6.5]])
print(lin_reg_2.predict(poly_reg.fit_transform([[6.5]]))) |
6a4603a0cbf46fec268bcb2f6b25fb6577ae7296 | Escartin85/scriptsPy | /calculation_marks_university/final_average_RISK.py | 1,154 | 3.609375 | 4 |
def conversionLetterToScore(subMark_letter):
if (subMark_letter == "F3"): return 0
if (subMark_letter == "F2"): return 23
if (subMark_letter == "F1"): return 37
if (subMark_letter == "D"): return 43
if (subMark_letter == "D+"): return 47
if (subMark_letter == "C"): return 53
if (subMark_letter == "C+"): return 57
if (subMark_letter == "B"): return 63
if (subMark_letter == "B+"): return 67
if (subMark_letter == "A-"): return 75
if (subMark_letter == "A"): return 85
if (subMark_letter == "A+"): return 95
subMark1_letter = "A-"
subMark2_letter = "C"
subMark1_portion = 50.0
subMark2_portion = 50.0
subMark1 = conversionLetterToScore(subMark1_letter)
subMark2 = conversionLetterToScore(subMark2_letter)
scoreMark1 = subMark1 * (subMark1_portion / 100.0)
scoreMark2 = subMark2 * (subMark2_portion / 100.0)
print("1.CW " + "\t\t\t" + str(int(subMark1_portion)) + "%" + " " + subMark1_letter + "\t" + str(scoreMark1))
print("2.Test" + "\t\t\t\t\t" + str(int(subMark2_portion)) + "%" + " " + subMark2_letter + "\t" + str(scoreMark2))
total_marks = scoreMark1 + scoreMark2
print(total_marks)
|
80b24bada743deccd58825714e1cda753547eb0d | Sriram-Reddyy/Leetcode_solutions | /787.Cheapest Flights Within K Stops.py | 1,307 | 3.578125 | 4 | """
787. Cheapest Flights Within K Stops
Medium
There are n cities connected by m flights. Each flight starts from city u
and arrives at v with a price w. Now given all the cities and flights, together
with starting city src and the destination dst, your task is to find the cheapest
price from src to dst with up to k stops. If there is no such route, output -1.
Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
The cheapest price from city 0 to city 2 with at most 1 stop costs 200,
as marked red in the picture.
"""
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
if src == dst:
return 0
if not flights:
return -1
flights_graph = defaultdict(list)
for s, d, p in flights:
flights_graph[s].append((d,p))
max_stop = K + 1
cost_heap = [(0,src,0)]
while cost_heap:
cur_p, cur, stop = heapq.heappop(cost_heap)
if cur == dst:
return cur_p
for nxt, nxt_p in flights_graph[cur]:
if stop < max_stop:
heapq.heappush(cost_heap, (cur_p+nxt_p, nxt, stop+1))
return -1
|
8544cabefdb473d9b80b5db7ff68d041652a0cf4 | wlsdhr477/OpenCollegePythonWebProject | /OC_1112/whlieroof.py | 898 | 3.703125 | 4 | sum=0
n=0
while n<11:
sum=sum+n
n=n+1
print(sum)
print(n)
#break 여기까지 처리하겠다./continue이번 처리는 Skip하고 그 다음 처리 반복
n=0
while n<10:
n = n + 1
if n==3:
continue
print("현재 n은" + str(n) + "입니다.")
if n==5:
break
print("현재 n은 " + str(n) + "입니다.")
#List Comprehension
#특정 List에 대한 조작을 심플한 for문으로 표현할 수 있다!
names=["신봉건", "고유빈", "김진옥", "이광우"]
nimNames = []
for name in names:
nimNames.append(name+"님")
for nimName in nimNames:
print(nimName)
print("+++++++++++++++++++++++++++++++++++")
nimNames2 = [ name + "님" for name in names]
for nimName4 in nimNames2:
print(nimName4)
#min/max
print("+++++++++++++++++++++++++++++++++++")
numbers = [1, 100, -1, 30, 5, 99, 45, 30, -2, -10]
for i in numbers:
|
c589edbbd471915928918ae3b7aaa4d27a2028e4 | PCA1610/Smartninja | /Uebung07/variables.py | 316 | 3.921875 | 4 | a = int(input("Gib eine Zahl ein: "))
b = int(input("Gib eine zweite Zahl ein: "))
o = input("Choose your opperator: + - / *: ")
c = True
if o == "+":
if c:
print(a + b)
elif o == "-":
print(a - b)
elif o == "/":
print(a / b)
elif o == "*":
print(a * b)
else:
print("Falscher Operator") |
c9d619c34324b198ef83213af5585eb361f93fbb | gauraviitp/python-programs | /Threading.py | 502 | 3.640625 | 4 | import threading
# Below code simulates printing in tandem.
#
semA = threading.Semaphore()
semB = threading.Semaphore()
semB.acquire()
def fooA():
count = 20
while count >= 0:
semA.acquire()
print('A')
semB.release()
count -= 1
def fooB():
count = 20
while count >= 0:
semB.acquire()
print('B')
semA.release()
count -= 1
t = threading.Thread(target=fooA)
t.start()
t2 = threading.Thread(target=fooB)
t2.start()
|
fde879c8ff95b2a3890e0a4d6b75bdae24620bf8 | GuilleCulebras/X-Serv-13.6-Calculadora | /calc.py | 609 | 3.59375 | 4 | #!/usr/bin/python3
import sys
NUM_VALORES= 4 #constantes definirlas con mayusculas
if len(sys.argv) != NUM_VALORES:
sys.exit("Usage: python3 calc.py operacion operando1 operando2")
funcion= sys.argv[1]
try:
op1 = float(sys.argv[2])
op2 = float(sys.argv[3])
except ValueError:
sys.exit("Los operandos han de ser floats. Gracias")
if funcion == 'suma':
print(op1 + op2)
elif funcion == 'resta':
print(op1 - op2)
elif funcion == 'div':
try:
print(op1/op2)
except ZeroDivisionError:
sys.exit("No se dividir por 0")
elif funcion == 'mult':
print(op1 * op2)
else:
print("Operador incorrecto")
|
fd75f53549a2753003423152a4d4d9cfd92eb4b6 | taraszubachyk/homework | /Task2.py | 438 | 4.3125 | 4 | #Task2
#Output question “What is your name?“, “How old are you?“, Where do you live?“.
# Read the answer of user and output next information: “Hello, (answer(name))“, “Your age is (answer(age))“, “You live in (answer(city))“
name = input("What is your name: ")
age = int(input("How old are you: "))
location =input("Where do you live: ")
print(f"Hello, {name}. Your age is {age}. You live in {location}.")
|
1bff468db3cc6e58e79b2cbe70f7c6fce9bf66d3 | hyc121110/LeetCodeProblems | /String/lengthOfLongestSubstring.py | 832 | 3.984375 | 4 | '''
Given a string, find the length of the longest substring without repeating characters.
'''
def lengthOfLongestSubstring(s):
# 2 pointers: pointer scan from left to right, pointer record first
# character
if len(s) == 0: return 0
# stores index of char's first occurence
dict = {}
start = max_length = 0
for i in range(len(s)):
if s[i] in dict and start <= dict[s[i]]:
# if character in dict, update pointer
# second check make sure don't enter just because we seen it before
start = dict[s[i]] + 1
else:
# compare current max and new max
max_length = max(max_length, i - start + 1)
# update key's value
dict[s[i]] = i
return max_length
print(lengthOfLongestSubstring(s="abcabcbb")) # ans = 3 |
7381be9f357956721ce144b1d311532dc4b50dbe | Mishakaveli1994/Python_Fundamentals_Jan | /Lists_Basic_Excercises/1_Invert_Values.py | 320 | 3.734375 | 4 | number = input()
number_sep = number.split(' ')
for i in range(len(number_sep)):
if int(number_sep[i]) < 0:
number_sep[i] = abs(int(number_sep[i]))
elif int(number_sep[i]) > 0:
number_sep[i] = int(number_sep[i]) * -1
elif int(number_sep[i]) == 0:
number_sep[i] = 0
print(number_sep)
|
5262e7f48d3f369d974226932fb92a68d73c0b98 | Ozyman/LearnPython | /5/lesson5-reading.py | 1,522 | 4.40625 | 4 | # Read this code, and try to understand what will happen when you run it, then run the code and see if you were correct.
# If you didn't predict it correctly, review the code to identify your misunderstanding.
correct_guess = 42
guess = input("Guess a number between 1 and 100: ")
# The input() function always returns a string. Even if you enter a number, it's stored as a series of characters.
# Python can't compare a string to an integer (e.g. correct_guess), so you first need to convert the guess to an integer.
# The int() function converts a string to an integer
guess_int = int(guess)
while guess_int != correct_guess:
if guess_int < correct_guess:
print("You guessed too low.")
if guess_int > correct_guess:
print("You guessed too high.")
print("Try again!")
guess = input("Guess a number between 1 and 100: ")
guess_int = int(guess)
# Similarly, if we want to combine two strings, they both have to be strings. It won't work if one is an integer.
# So we convert correct_guess to a string before combining it with another string
correct_guess_str = str(correct_guess)
print("You guessed it! My number was " + correct_guess_str)
# We didn't have to use a variable 'correct_guess' to store the value 42. Instead, everywhere we put 'correct_guess' we could put 42 instead, and it would work exactly the same.
# The advantage to using a variable is that if we want to change the correct guess, we only have to change it in one place, instead of 4 different places.
|
eb2bed84b6577dae54c07a2fedb6eadf0e3939e3 | Diniz-G/Minicurso_Python | /minicurso_python/strings2.py | 499 | 3.9375 | 4 | a = "Gabriel"
b = "Diniz"
concat = a + " " + b + "\n"
print(concat)
print(concat.lower())
print(concat.upper())
print(concat.strip()) #remove o "\n"
#######################################
my_string = "O rato roeu a roupa..."
my_list = my_string.split() #separa em strings a cada " "
#ou passa-se como argumento em qual caractere deve quebrar a string
print(my_list)
busca = my_string.find("roeu")
print(busca)
print(my_string[busca:])
calça = my_string.replace("roupa", "calça")
print(calça) |
667a78368e07842ecd89fa33e8ad8501b8e7f3b0 | Usherwood/usherwood_ds | /usherwood_ds/tools/topic_wordclouds.py | 2,692 | 3.9375 | 4 | #!/usr/bin/env python
"""Creating wordclouds for pandas series of text records"""
import pandas as pd
from wordcloud import WordCloud
import matplotlib.pyplot as plt
__author__ = "Peter J Usherwood"
__python_version__ = "3.5"
class Visualizer:
"""
Creates a class to wrap around WordCloud
"""
def __init__(self):
self.textstring = None
self.word_frequency = None
self.wordcloud_obj = None
self.image = None
def wordcloud_from_series(self, series, stopwords=[], bg_colour='white', width=1200, height=1000):
"""
Generates the wordcloud from a series of text.
:param series: Pandas series of text records to become a wordcloud
:param stopwords: Set of stopwords to remove, use utils>preprocessing>stopwords>create_stopwords_set
:param bg_colour: Background colour background colour
:param width: Int pixel width of image
:param height: Int pixel height of image
:return: Wordcloud image
"""
self.textstring = " ".join(series.tolist())
wordcloud = WordCloud(stopwords=stopwords,
background_color=bg_colour,
width=width,
height=height
).generate(self.textstring)
self.wordcloud_obj = wordcloud
self.word_frequency = pd.DataFrame({'Word': list(self.wordcloud_obj.words_.keys()),
'Score': list(self.wordcloud_obj.words_.values())})
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
self.image = wordcloud
return True
def wordcloud_from_frequencies(self, frequencies, stopwords=[], bg_colour='white', width=1200, height=1000):
"""
Generates the wordcloud from a series of text.
:param frequencies: A pandas df of words to frequencies, columns Word and Score
:param stopwords: Set of stopwords to remove, use utils>preprocessing>stopwords>create_stopwords_set
:param bg_colour: Background colour background colour
:param width: Int pixel width of image
:param height: Int pixel height of image
:return: Wordcloud image
"""
self.word_frequency = frequencies
wordcloud = WordCloud(stopwords=stopwords,
background_color=bg_colour,
width=width,
height=height
).generate(self.textstring)
self.wordcloud_obj = wordcloud
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
return True
|
17a966127b416fa167c405a5740c843a4f804c80 | Matt41531/Chuck_A_Luck_Dice_Game | /program3.py | 7,474 | 4.0625 | 4 | from graphics import *
from random import *
def draw_dice(x,y,dienum,win):
'''
Purpose: draw a dice image on the screen at the location given, using
the corresponding gif file
Pre-conditions: (int) x and y of location, (int) number of the die,
(GraphWin) graphics window
Post-condition: (Image) returns the Image object created
'''
point = Point(x,y)
dice = ''.join([str(dienum), '.gif'])
die = (Image(point, dice))
die.draw(win)
return die
def getbet(pot, win):
'''
Purpose: get the amount of the bet from the user
while not letting the user bet less than 1 dollar and not more
than they have in the pot
Pre-conditions: (int) the amount of the pot and the graphics window
Post-conditions: (int) the validated user's input (from 1 to amount of pot)
'''
inputs = "Enter a bet from 1 - " + str(pot) +"$"
input_txt = Text(Point(400,400), inputs)
input_txt.draw(win)
bet_box = Entry(Point(400, 450), 5)
bet_box.draw(win)
bet_box.setText(1) #To prevent misclicks from crashing program with '' <1 in while loop
win.getMouse()
bet = bet_box.getText()
bet = int(bet)
while bet<1 or bet>pot:
if bet <1:
feedback_txt = Text(Point(400,500), 'That bet is too low!')
else:
feedback_txt = Text(Point(400,500), 'You don\'t have that much money!')
feedback_txt.draw(win)
bet_box.setText(1)
win.getMouse()
bet = int(bet_box.getText())
feedback_txt.undraw()
input_txt.undraw()
bet_box.undraw()
return bet
def getnumber(win):
'''
Purpose: get the die number the user wants to bet on (1-6)
Pre-conditions: graphics window
Post-conditions: validated user's input (1-6)
'''
number_txt = Text(Point(400,350), "Enter a die number to bet on 1-6")
number_txt.draw(win)
number_box = Entry(Point(400,400), 5)
number_box.draw(win)
number_box.setText('1')
win.getMouse()
user_roll = number_box.getText() #To avoid crash, do not convert to int until anwser validated as 1-6
while user_roll not in "123456":
feedback = Text(Point(400,600), "That's not a valid bet!")
feedback.draw(win)
number_box.setText('1')
win.getMouse()
user_roll = number_box.getText()
feedback.undraw()
user_roll = int(user_roll)
number_box.undraw()
number_txt.undraw()
return user_roll
def check_matches(roll1, roll2, roll3, user_roll):
'''
Purpose: compare the user's roll to the three rolls
and find out if there are 0, 1, 2, or 3 matches
Pre-conditions: three rolls and user's roll
Post-conditions: 0-3, number of matches
'''
num_matches = 0
if user_roll == roll1:
num_matches += 1
if user_roll == roll2:
num_matches += 1
if user_roll == roll3:
num_matches += 1
return num_matches
def in_box(point1, point2, clickpoint):
'''
Purpose: to test a point to see if it is in a box defined by
two other points (upper right and lower left)
Pre-conditions: two points that define the box, a third point
Post-conditions: True if point3 is inside the box,
False if not
Design:
initialize flag
if the point's X is inside the other points' X's and
the point's Y is inside the other points' Y's
flag is set True
return the flag
'''
flag = False
clickpointX = clickpoint.getX()
clickpointY = clickpoint.getY()
point1X = point1.getX()
point1Y = point1.getY()
point2X = point2.getX()
point2Y = point2.getY()
if (clickpointX >=point1X and clickpointX <= point2X) and (clickpointY >=point1Y and clickpointY <= point2Y):
flag = True
return flag
def playagain(win):
'''
Purpose: ask the user if they want to play again, get their
Yes or No response, validated by ignoring any clicks
anywhere on the screen except in the Yes and No boxes
Pre-conditions: the graphics window
Post-conditions: a bool value, True means the user chose Yes,
False otherwise
'''
play_txt = Text(Point(400, 100), "Do you wanna play another game?")
play_txt.draw(win)
yes_box = Rectangle(Point(100,400), Point(200,550))
yes_box.draw(win)
no_box = Rectangle(Point(600,400), Point(700,550))
no_box.draw(win)
yes_txt = Text(Point(150, 475), "Yes?")
yes_txt.draw(win)
no_txt = Text(Point(650, 475), "No?")
no_txt.draw(win)
response = win.getMouse()
while (in_box(Point(100,400), Point(200,550), response) == False) and (in_box(Point(600,400), Point(700,550), response) == False):
error = Text(Point(400, 175), "That is not a valid response")
error.draw(win)
response = win.getMouse()
error.undraw()
play_txt.undraw()
if (in_box(Point(100,400), Point(200,550), response)):
yes_box.undraw()
no_box.undraw()
yes_txt.undraw()
no_txt.undraw()
return True
else:
yes_box.undraw()
no_box.undraw()
yes_txt.undraw()
no_txt.undraw()
return False
def main():
win = GraphWin('Chuck-a-Luck', 800,800)
playagain_flag = True
pot = 100
chuckaluck = Text(Point(400,50), 'Chuck-a-Luck!')
chuckaluck.draw(win)
while (playagain_flag) and (pot >0):
bet = getbet(pot,win)
user_roll = getnumber(win)
roll1 = randrange(1,7)
roll2 = randrange(1,7)
roll3 = randrange(1,7)
die1 = draw_dice(100,175,roll1,win)
die2 = draw_dice(400,175,roll2,win)
die3 = draw_dice(700,175,roll3,win)
matches = check_matches(roll1,roll2,roll3, user_roll)
matches_str = "You had " + str(matches) + " matches."
matches_txt = Text(Point(400,700), matches_str)
matches_txt.draw(win)
winnings = 0
if matches == 1:
winnings = bet
elif matches == 2:
winnings = bet * 5
elif matches == 3:
winnings = bet * 10
else:
winnings = -bet
pot = pot + winnings
if winnings >0:
feedback = "You won " + str(winnings) + "$"
else:
feedback = "You lost " + str(bet)
feedback_txt = Text(Point(400, 755), feedback)
feedback_txt.draw(win)
num_pot = "The pot is now " + str(pot) + "$"
pot_txt = Text(Point(400, 775), num_pot)
pot_txt.draw(win)
win.getMouse()
die1.undraw()
die2.undraw()
die3.undraw()
pot_txt.undraw()
feedback_txt.undraw()
matches_txt.undraw()
if pot > 0:
playagain_flag = playagain(win)
else:
playagain_flag = False
pot_txt.undraw()
feedback_txt.undraw()
if pot >0:
results = "You left with " + str(pot) +"$"
else:
results = "You lost!"
results_txt = Text(Point(400,400), results)
results_txt.draw(win)
win.getMouse()
win.close()
main()
|
01f143333a0157925a9dd77a4029cbf3fc68838c | yaoguoliang92/demo | /WebContent/python/xiao-jia-yu/20han-shu-quanju-bianliang.py | 382 | 3.59375 | 4 | def func():
global count #变为全局
count =10
print(10)
def fun1():
print('func1')
def fun2():
print('func2')
fun2()
fun1()
#fun2访问不到
#----------------
#闭包
def FunX(x):
def FunY(y):
return x*y
return FunY
print(FunX(8)(5))
def func1():
x=5
def func2():
nonlocal x #用list[]也可以
x*=x
return x
return func2()
func1()
print(x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.