blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
234a8bc6f168afac7ab18c566b0a783e5e9080fd | prabalbhandari04/python_ | /labexercise2.py | 312 | 4.28125 | 4 | #Write a program that reads the length of the base and the height of a right-angled triangle and prints the area. Every number is given on a separate line.#
length_of_base = int(input("Enter the lenght of base:"))
height = int(input("Enter the height:"))
area = (1/2)*(length_of_base*height)
print(area) |
f9d3c49fda6f4419d84f23f8275bcb20e55b9489 | prabalbhandari04/python_ | /labexercise_12.py | 105 | 4.34375 | 4 | #Given x = 5, what will be the value of x after we run x+=3?
x=5
x+=3
print(x)
#It's value will be 8. |
defc112609510a6b38eeaa5bc84eef640cb62fd7 | elikir/algorithms | /sort/insertionsort.py | 772 | 3.578125 | 4 | import time
import random
def sort(lis):
for x in range(1,len(lis)):
curVal = lis[x]
pos = x
while 0 < pos and lis[pos-1] > curVal:
lis[pos] = lis[pos-1]
pos -= 1
lis[pos] = curVal
return lis
#run #1 on list of length 100 - 0.000652874565125 seconds
#run #2 on list of length 100 - 0.00066021232605 seconds
if __name__ == "__main__":
outside_average = 0
for x in range(100):
inside_average = 0
for y in range(100):
lis = range(100)
random.shuffle(lis)
start = time.time()
sort(lis)
end = time.time()
inside_average += end-start
outside_average += inside_average/100
print outside_average/100 |
06fe1661b93a940e28adb9c5fab488df85e19eb8 | ankush-phulia/Lift-MDP-Model | /simulator/Elevator.py | 2,956 | 4.25 | 4 | class Elevator(object):
"""
- state representation of the elevator
"""
def __init__(self, N, K):
self.N = N # number of floors
self.K = K # number of elevators
# initial positions of all elevators
self.pos = [0]*K
# button up on each floor (always 0 for top floor)
self.BU = [0]*N
# button down on each floor (always 0 for first floor)
self.BD = [0]*N
# floor buttons pressed inside elevator, for each elevator
self.BF = [[0]*N for i in range(K)]
# light up indicator for each lift for its current floor (always 0 for top floor)
self.LU = [0]*K
# light down indicator for each lift for its current floor (always 0 for first floor)
self.LD = [0]*K
def __str__(self):
"""
- returns a string expression of the current state of the elevator
"""
state = ''
state += ' '.join([str(x) for x in self.pos]) + ' '
state += ''.join([str(x) + ' ' + str(y) + ' ' for x,
y in zip(self.BU, self.BD)])
for e in self.BF:
state += ' '.join([str(x) for x in e])
state += ' '
state += ' '.join([str(x) for x in self.LU]) + ' '
state += ' '.join([str(x) for x in self.LD]) + ' '
return state
# state modifiers
def modify_pos(self, k, delta):
"""
- change position of kth lift by delta (+/- 1)
- validity checks in Simulator
"""
self.pos[k] += delta
def modify_floor_button(self, n, direction, status):
"""
- n : floor number
- direction : 'U' for up button and 'D' for down button
- status : 0 to clear and 1 to press
- returns if status was toggled
"""
toggled = True
if direction == 'U':
if self.BU[n] == status:
toggled = False
self.BU[n] = status
if direction == 'D':
if self.BD[n] == status:
toggled = False
self.BD[n] = status
return toggled
def modify_elevator_button(self, k, n, status):
"""
- k : elevator number
- n : floor number
- status : 0 to clear and 1 to press
- returns if status was toggled
"""
toggled = True
if self.BF[k][n] == status:
toggled = False
self.BF[k][n] = status
return toggled
def reset_lights(self):
self.LU = [0] * self.K
self.LD = [0] * self.K
def modify_lights(self, k, direction, status):
"""
- k : lift number
- direction : 'U' for up button and 'D' for down button
- status : 0 to clear and 1 to press
"""
if direction == 'U':
self.LU[k] = status
if direction == 'D':
self.LD[k] = status
|
09b7ed3aac44b5ec2840d972df3ce8b6ad68d9b3 | jonstod/DS-Portfolio-Project | /d_graph.py | 11,785 | 3.90625 | 4 | # Course: CS261 - Data Structures
# Author: Jonathon Stoddart
# Assignment: 6
# Description: Part 2 - Directed Graph (via Adjacency Matrix)
import heapq as heap
class DirectedGraph:
"""
Class to implement directed weighted graph
- duplicate edges not allowed
- loops not allowed
- only positive edge weights
- vertex names are integers
"""
def __init__(self, start_edges=None):
"""
Store graph info as adjacency matrix
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self.v_count = 0
self.adj_matrix = []
# populate graph with initial vertices and edges (if provided)
# before using, implement add_vertex() and add_edge() methods
if start_edges is not None:
v_count = 0
for u, v, _ in start_edges:
v_count = max(v_count, u, v)
for _ in range(v_count + 1):
self.add_vertex()
for u, v, weight in start_edges:
self.add_edge(u, v, weight)
def __str__(self):
"""
Return content of the graph in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
if self.v_count == 0:
return 'EMPTY GRAPH\n'
out = ' |'
out += ' '.join(['{:2}'.format(i) for i in range(self.v_count)]) + '\n'
out += '-' * (self.v_count * 3 + 3) + '\n'
for i in range(self.v_count):
row = self.adj_matrix[i]
out += '{:2} |'.format(i)
out += ' '.join(['{:2}'.format(w) for w in row]) + '\n'
out = f"GRAPH ({self.v_count} vertices):\n{out}"
return out
# ------------------------------------------------------------------ #
def add_vertex(self) -> int:
"""
Adds a new vertex to the graph. Returns an integer number of vertices in the graph after the addition.
"""
self.v_count += 1 # update vertex count
for row in self.adj_matrix: # add new column to existing rows
row.append(0)
self.adj_matrix.append([0]*self.v_count) # add new row
return self.v_count
def add_edge(self, src: int, dst: int, weight=1) -> None:
"""
Adds a new edge to the graph, connecting vertex src to vertex dst. If either vertex does not exist, weight is
not a positive integer, or if src and dst refer to the same vertex, method does nothing. If the edge already
exists, the method will update its weight.
"""
if 0 <= src < self.v_count and 0 <= dst < self.v_count and weight > 0 and src != dst:
self.adj_matrix[src][dst] = weight # set/update weight
def remove_edge(self, src: int, dst: int) -> None:
"""
Removes an edge between vertex src and vertex dst. If either vertex does not exist, or there is no edge
between them, the method does nothing.
"""
if 0 <= src < self.v_count and 0 <= dst < self.v_count:
self.adj_matrix[src][dst] = 0
def get_vertices(self) -> []:
"""
Returns a list of vertices in the graph.
"""
vertices = []
for i in range(self.v_count):
vertices.append(i)
return vertices
def get_edges(self) -> []:
"""
Returns a list of edges in the graph.
Each edge is returned as a tuple: (source vertex, destination vertex, weight)
"""
edges = []
for src in range(self.v_count): # source vertices
for dst in range(self.v_count): # destination vertices
if self.adj_matrix[src][dst] != 0: # edge weight
edges.append((src, dst, self.adj_matrix[src][dst]))
return edges
def is_valid_path(self, path: []) -> bool:
"""
Takes a list of vertex indices and returns True if the sequence of vertices represents a valid path in the
graph (from first to last vertex, at each step traversing over an edge in the graph).
An empty path is considered valid.
"""
if len(path) == 0:
return True
for i in range(len(path)-1):
# check source and destination exist
if path[i] < 0 or path[i] >= self.v_count or path[i+1] < 0 or path[i+1] >= self.v_count:
return False
# check edge exists
if self.adj_matrix[path[i]][path[i+1]] == 0:
return False
return True
def dfs(self, v_start, v_end=None) -> []:
"""
Return list of vertices visited during DFS search
Vertices are picked in ascending order
"""
if v_start not in range(0, self.v_count): # start vertex not in graph
return []
visited = [] # stack of visited vertices
stack = [] # stack of neighbors to visit
stack.append(v_start)
while len(stack) != 0:
src = stack.pop()
if src == v_end: # we have reached the end. add to visited and return
visited.append(src)
return visited
elif src not in visited: # avoid duplicates
visited.append(src)
for dst in range(self.v_count-1, -1, -1): # all vertices in descending order (due to stack nature)
if self.adj_matrix[src][dst] != 0: # check edge exists
stack.append(dst)
return visited
def bfs(self, v_start, v_end=None) -> []:
"""
Return list of vertices visited during BFS search
Vertices are picked in ascending order
"""
if v_start not in range(0, self.v_count):
return []
visited = []
queue = []
queue.append(v_start)
while len(queue) != 0:
src = queue.pop(0) # pop first element since list is a queue and not a stack
if src == v_end:
visited.append(src)
return visited
elif src not in visited:
visited.append(src)
for dst in range(self.v_count): # vertices in ascending order (queue)
if self.adj_matrix[src][dst] != 0 and dst not in visited:
queue.append(dst)
return visited
def has_cycle(self):
"""
Return True if graph contains a cycle, False otherwise
"""
if 0 <= self.v_count <= 1 : # 0 or 1 vertices - no cycle
return False
white = [] # unvisited list
grey = [] # visiting list (if we encounter one of these, there is a cycle)
black = [] # visited list (all its neighbors have also been visited)
for i in range(self.v_count): # fill unvisited list
white.append(i)
while len(white) > 0:
src = white[0] # arbitrary starting point for DFS
if self.rec_cycle(src, white, grey, black):
return True
return False
def rec_cycle(self, src, white, grey, black):
"""
DFS search helper method for has_cycle. Takes a source vertex - if we have visited but not fully explored one
of its neighbors, we found a cycle and the method returns True. If we have not visited a neighbor, method
recurses, visiting and exploring that neighbor. If no cycles are found, returns False.
"""
white.remove(src)
grey.append(src)
for dst in range(self.v_count):
if self.adj_matrix[src][dst] != 0:
if dst in black: # already fully explored
continue
if dst in grey: # found a cycle
return True
if self.rec_cycle(dst, white, grey, black): # must be in white - recurse
return True
grey.remove(src) # src has been fully explored (all neighbors explored) - return False
black.append(src)
return False
def dijkstra(self, src: int) -> []:
"""
Implements the Dijkstra algorithm to compute the length of the shortest path from a given vertex src to
all other vertices in the graph. Returns a list with one value per each vertex in the graph, where the value
at index 0 is the length of the shortest path from vertex src to vertex 0, etc. If a vertex is not reachable
from src, the respective value in the list is INFINITY. Assumes src is a valid vertex.
"""
min_paths = [] # list of shortest distances to each vertex
pq = [(0, src)] # priority queue - [priority, vertex] where priority is distance
for i in range(self.v_count):
min_paths.append(float('inf')) # initialize all min paths as infinity (unreachable)
while len(pq) > 0:
d, v = heap.heappop(pq)
if d < min_paths[v]: # new shortest path
min_paths[v] = d
for vi in range(self.v_count): # find direct successors and enqueue them with their current path distance to priority queue
if self.adj_matrix[v][vi] != 0:
di = self.adj_matrix[v][vi]
pq.append((d + di, vi))
return min_paths
if __name__ == '__main__':
print("\nPDF - method add_vertex() / add_edge example 1")
print("----------------------------------------------")
g = DirectedGraph()
print(g)
for _ in range(5):
g.add_vertex()
print(g)
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
for src, dst, weight in edges:
g.add_edge(src, dst, weight)
print(g)
print("\nPDF - method get_edges() example 1")
print("----------------------------------")
g = DirectedGraph()
print(g.get_edges(), g.get_vertices(), sep='\n')
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
print(g.get_edges(), g.get_vertices(), sep='\n')
print("\nPDF - method is_valid_path() example 1")
print("--------------------------------------")
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
test_cases = [[0, 1, 4, 3], [1, 3, 2, 1], [0, 4], [4, 0], [], [2]]
for path in test_cases:
print(path, g.is_valid_path(path))
print("\nPDF - method dfs() and bfs() example 1")
print("--------------------------------------")
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
for start in range(5):
print(f'{start} DFS:{g.dfs(start)} BFS:{g.bfs(start)}')
print("\nPDF - method has_cycle() example 1")
print("----------------------------------")
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
edges_to_remove = [(3, 1), (4, 0), (3, 2)]
for src, dst in edges_to_remove:
g.remove_edge(src, dst)
print(g.get_edges(), g.has_cycle(), sep='\n')
edges_to_add = [(4, 3), (2, 3), (1, 3), (4, 0)]
for src, dst in edges_to_add:
g.add_edge(src, dst)
print(g.get_edges(), g.has_cycle(), sep='\n')
print('\n', g)
print("\nPDF - dijkstra() example 1")
print("--------------------------")
edges = [(0, 1, 10), (4, 0, 12), (1, 4, 15), (4, 3, 3),
(3, 1, 5), (2, 1, 23), (3, 2, 7)]
g = DirectedGraph(edges)
for i in range(5):
print(f'DIJKSTRA {i} {g.dijkstra(i)}')
g.remove_edge(4, 3)
print('\n', g)
for i in range(5):
print(f'DIJKSTRA {i} {g.dijkstra(i)}')
|
7e74f5268702ceb4707281805581384dc59d0080 | Anshikaverma24/meraki-function-questions | /meraki functions ques/inner function ques/q3.py | 528 | 4.0625 | 4 | # Question 3
# Ek function banaiye jo 3 numbers ka sum aur average print kare.Hum user se 3 number
# input karwayenge aur fir unn 3 numbers ka sum aur average print karwayenge
def sum():
num1=int(input("enter 1st no."))
num2=int(input("enter 2nd no."))
num3=int(input("enter 3rd no."))
add=num1+num2+num3
print (add)
sum()
def average():
num1=int(input("enter 1st no."))
num2=int(input("enter 2nd no."))
num3=int(input("enter 3rd no."))
avg=num1+num2+num3/3
print(avg)
average() |
bc0c4a64a9f71c3a9ae77b1123eeffe48b98d3c5 | FefAzvdo/Python-Training | /Exercicios/Aula 10/030.py | 506 | 3.90625 | 4 | # Ano bissexto
# Divisível por 4. Sendo assim, a divisão é exata com o resto igual a zero;
# Não pode ser divisível por 100. Com isso, a divisão não é exata, ou seja, deixa resto diferente de zero;
# Pode ser que seja divisível por 400. Caso seja divisível por 400, a divisão deve ser exata, deixando o resto igual a zero.
ano = int(input("Digite o ano: "))
if ano % 4 == 0:
if ano % 100 != 0:
print("É bissexto")
else:
if ano % 400 != 0:
print("Não é bissexto")
|
2af1e2e3ac726d51a31c371483abd2e6d1b6d5b9 | FefAzvdo/Python-Training | /Exercicios/Aula 13/051.py | 287 | 4 | 4 | # socorram me subi no onibus em marrocos
frase = input("Digite uma frase: ")
formatada = frase.replace(" ", "")
print("Frase =>", formatada)
print("Ao contrário =>", formatada[::-1])
if formatada == formatada[::-1]:
print("É PALÍNDROMO")
else:
print("NÃO É PALÍNDROMO")
|
f501d353de483ac071efcd002afb39410d8a1a5f | FefAzvdo/Python-Training | /Exercicios/Aula 12/036.py | 230 | 3.953125 | 4 | n1 = int(input("Digite um número :"))
n2 = int(input("Digite outro número :"))
if n1 > n2:
print(f"{n1} é maior do que {n2}")
elif n1 == n2:
print(f"{n1} é igual a {n2}")
else:
print(f"{n2} é maior do que {n1}")
|
608c925a7bb0d43f25cbb24431020093dd0617c4 | FefAzvdo/Python-Training | /Aulas/013.py | 431 | 4.21875 | 4 | # Estruturas de Repetição
# Output: 1, 2, 3, 4, 5
for count in range(1, 6):
print(count)
# Executa 3x
# Output: * * *
for count in range(0, 3):
print("*")
for count in range(0, 11):
if(count % 2 == 0):
print(f"{count} é PAR")
else:
print(f"{count} é ÍMPAR")
for count in range(6, 0, -1):
print(count)
n = int(input("Digite um número: "))
for count in range(0, n+1):
print(count)
|
cf1d9c20518ca86804c83ffee8fd439b587ee8f3 | FefAzvdo/Python-Training | /Exercicios/Aula 09/023.py | 84 | 3.65625 | 4 | nome = input("Digite seu nome completo: ")
print(nome.upper().find("SILVA") != -1)
|
1218eb2a6ac77aecfdef4846500dc1623c58c418 | FefAzvdo/Python-Training | /Exercicios/Aula 10/033.py | 738 | 4.25 | 4 | # Condição de existência de um triângulo
# Para construir um triângulo não podemos utilizar qualquer medida, tem que seguir a condição de existência:
# Para construir um triângulo é necessário que a medida de qualquer um dos lados seja menor que a soma das medidas dos outros dois e maior que o valor absoluto da diferença entre essas medidas.
# | b - c | < a < b + c
# | a - c | < b < a + c
# | a - b | < c < a + b
a = float(input("Digite o tamanho da primeira medida: "))
b = float(input("Digite o tamanho da segunda medida: "))
c = float(input("Digite o tamanho da terceira medida: "))
isTriangle = abs(b - c) < a < (b + c)
if isTriangle:
print("Forma um triângulo")
else:
print("Não forma um triângulo")
|
1d8df8f0fd6996602088725eaef8fb63429cdf99 | mileshill/HackerRank | /AI/Bot_Building/Bot_Saves_Princess/princess.py | 2,127 | 4.125 | 4 | #!/usr/bin/env python2
"""
Bot Saves Princess:
Mario is located at the center of the grid. Princess Peach is located at one of the four corners. Peach is denoted by 'p' and Mario by 'm'. The goal is to make the proper moves to reach the princess
Input:
First line contains an ODD integer (3<=N<=99) denoting the size of the grid. The is followed by an NxN grid.
Output:
Print out the steps required to reach the princess. Each move will have the format "MOVE\n"
Valid Moves:
LEFT, RIGHT, UP, DOWN
"""
from sys import stdin, stdout
r = stdin.readline
def find_princess_position( grid_size ):
""" Read the array to find princess """
assert type( grid_size ) is int
for i in range( grid_size ):
line = list(r().strip())
if 'p' in line:
j = line.index('p')
location = (j,i)
return location
def get_directions( x_peach, y_peach, x_mario, y_mario):
""" Determine L/R U/D directions mario will travel """
horizontal_dir =''
vertical_dir = ''
# horizontal direction
if x_peach > x_mario:
horizontal_dir = "RIGHT"
else:
horizontal_dir = "LEFT"
# vertical direction
if y_peach > y_mario:
vertical_dir = "DOWN"
else:
vertical_dir = "UP"
return (horizontal_dir, vertical_dir)
def generate_marios_path( grid_size, location_of_princess ):
""" Generate the steps to move to the princess """
grid_center = (grid_size -1)/2 + 1
distance_to_wall = grid_center -1
xp, yp = location_of_princess
x_dir, y_dir = get_directions( xp, yp, xm, ym )
horizontal = [ x_dir for x in range(distance_to_wall)]
vertical = [ y_dir for y in range(distance_to_wall) ]
return horizontal + vertical
def main():
grid_size = int( r().strip() )
location_of_princess = find_princess_position( grid_size )
marios_path = generate_marios_path( grid_size, location_of_princess )
assert type( marios_path ) is list
for move in marios_path:
stdout.write( move + '\n' )
if __name__ == '__main__':
main()
|
d4b4d700b8b95d23069a2d8e5f3276854aa77432 | rahulkumar1m/exercism-python-track | /darts/darts.py | 230 | 3.953125 | 4 | import math
def score(x : int, y : int) -> int:
circle = math.sqrt(x**2 + y**2)
if circle <= 1:
return 10
elif circle <= 5:
return 5
elif circle <= 10:
return 1
else:
return 0
|
f1d0eed5c88aff33508a9b32e9aaec1a3f962de3 | rahulkumar1m/exercism-python-track | /isogram/isogram.py | 528 | 4.3125 | 4 | def is_isogram(string) -> bool:
# Tokenizing the characters in the string
string = [char for char in string.lower()]
# initializing an empty list of characters present in the string
characters = []
# if a character from string is already present in our list of characters, we return False
for char in string:
if (char == " ") or (char == "-"):
continue
elif char in characters:
return False
else:
characters.append(char)
return True
|
083dff2e186c84f0c113fb4c11b69222102e754e | rahulkumar1m/exercism-python-track | /yacht/yacht.py | 1,502 | 3.984375 | 4 | """
This exercise stub and the test suite contain several enumerated constants.
Since Python 2 does not have the enum module, the idiomatic way to write
enumerated constants has traditionally been a NAME assigned to an arbitrary,
but unique value. An integer is traditionally used because it’s memory
efficient.
It is a common practice to export both constants and functions that work with
those constants (ex. the constants in the os, subprocess and re modules).
You can learn more here: https://en.wikipedia.org/wiki/Enumerated_type
"""
# Score categories.
# Change the values as you see fit.
YACHT = 50
ONES = 1
TWOS = 2
THREES = 3
FOURS = 4
FIVES = 5
SIXES = 6
FULL_HOUSE = None
FOUR_OF_A_KIND = None
LITTLE_STRAIGHT = 30
BIG_STRAIGHT = 30
CHOICE = None
def score(dice, category):
num_counts = [(i, dice.count(i)) for i in set(dice)]
sort_counts = sorted([y for x, y in num_counts])
if category == YACHT and all(x == dice[0] for x in dice):
score = YACHT
elif category == FOUR_OF_A_KIND:
score = sum([x*4 for x, y in num_counts if y >= 4])
elif category == CHOICE:
score = sum(dice)
elif category == BIG_STRAIGHT and dice == [2,3,4,5,6]:
score = BIG_STRAIGHT
elif category == LITTLE_STRAIGHT and dice == [1,2,3,4,5]:
score = LITTLE_STRAIGHT
elif category == FULL_HOUSE and sort_counts == [2,3]:
score = sum([x*y for x, y in num_counts])
else:
score = dice.count(category)*category
return score |
ca4a19062fac62c815d2c4a2cafb654f0c7db6a7 | jc345932/programming | /task1.py | 264 | 4 | 4 | def main():
x = int(input("Enter x:"))
y = int(input("Enter y:"))
doMath(x, y)
def doMath (x, y):
sum = x + y
diff = x - y
product = x * y
quotient = x / y
print(sum)
print(diff)
print(product)
print(quotient)
main() |
423f9c7f03e804adaff03a5936d426b99931c1ac | ammarlam10/evolutionary-Algorithm | /evo.py | 13,664 | 3.859375 | 4 | # Created By: Muhammad Ammar Ahmed 09389
# Running this program will output 12 graphs, 1st 6 will contain avg_avg fitness and avg_best fitness of Function 1
# and last 6 will produce for function 2.
# ------------------------------------------
# The values printed on the console are average average fitness of 40 generations and average best fitness of
# of 40 generations
# ------------------------------------------
# I have used the following nested structure to store values: A dictionary containing a list of 3 elements against every
# key. The elements of the list are [x,y,fitness] for each chromosome
# -----------------------------------------
from random import randint
import matplotlib.pyplot as plt
# import csv
import random
def initialPopulation(size,f):
# initializes population as per
list={}
if(f==1):
for a in range(0,size,1):
list[a]=[float(randint(-5,5)),float(randint(-5,5))]
else:
for a in range(0,size,1):
list[a]=[float(randint(-2,2)),float(randint(-1,3))]
return list
def computeFitness(pop,f):
if(f==1):
for k in pop:
if(len(pop[k])==2):
pop[k].append((pop[k][0]**2)+ (pop[k][1]**2))
# pop[k].append((100*((pop[k][0]**2)-(pop[k][1]))**2) + (1-(pop[k][0])**2))
else:
pop[k][2]= (pop[k][0]**2)+ (pop[k][1]**2)
else:
for k in pop:
if(len(pop[k])==2):
# pop[k].append((pop[k][0]**2)+ (pop[k][1])**2)
pop[k].append((100*((pop[k][0]**2)-(pop[k][1]))**2) + (1-(pop[k][0])**2))
else:
# pop[k][2]= (pop[k][0]*pop[k][0])+ (pop[k][1])*(pop[k][1])
pop[k][2]= (100*((pop[k][0]**2)-(pop[k][1]))**2) + (1-(pop[k][0])**2)
return pop
def offspring(pop,xu,yu,xl,yl):
iter = len(pop)
i=0
while i<iter:
# pri/nt i
prob=randint(0,10) # print i
if(prob>=9):
if(pop[i][0]<xu)and(pop[i][0]>xl):
# print "mutate x"
temp=pop[i][0]
pop[i]=[pop[i+1][0]+random.uniform(-.25, .25),pop[i][1],pop[i][2]]
pop[i+1]=[temp,pop[i+1][1],pop[i+1][2]]
# print pop[i]
else:
temp=pop[i][0]
pop[i]=[pop[i+1][0],pop[i][1],pop[i][2]]
pop[i+1]=[temp,pop[i+1][1],pop[i+1][2]]
elif(prob>=7):
if(pop[i][1]<yu)and(pop[i][1]>yl):
# print "mutate y"
temp=pop[i][0]
pop[i]=[pop[i+1][0],pop[i][1],pop[i][2]]
pop[i+1]=[temp,pop[i+1][1]+random.uniform(-.25, .25),pop[i+1][2]]
# print pop[i]
else:
temp=pop[i][0]
pop[i]=[pop[i+1][0],pop[i][1],pop[i][2]]
pop[i+1]=[temp,pop[i+1][1],pop[i+1][2]]
i+=2
# print pop
return pop
def rbs(pop, num):
# print pop
for i in range(len(pop)):
for j in range(len(pop)-1-i):
if pop[j][2] > pop[j+1][2]:
pop[j], pop[j+1] = pop[j+1], pop[j]
total=0
# print pop
for i in pop:
total+=i+1
# print total
rel_rank = [(f+1)/float(total) for f in pop]
probs = [sum(rel_rank[:i+1]) for i in range(len(rel_rank))]
# print rel_rank
# print probs
new_pop={}
for n in range(num):
r=random.random()
for p in pop:
if(r<=probs[p]):
new_pop.update({n:pop[p]})
break
return new_pop
def roulette_select(pop, num):
total=0
for i in pop:
total+=pop[i][2]
rel_fitness = [pop[f][2]/float(total) for f in pop]
probs = [sum(rel_fitness[:i+1]) for i in range(len(rel_fitness))]
new_pop = {}
for n in range(num):
r=random.random()
for p in pop:
if(r<=probs[p]):
new_pop.update({n:pop[p]})
break
return new_pop
def binarytour(pop,num):
new_pop={}
count=0
for i in range(num):
r1=randint(0,len(pop)-1)
r2=randint(0,len(pop)-1)
if(pop[r1][2]>=pop[r2][2]):
new_pop.update({(i):pop[r1]})
else:
new_pop.update({(i):pop[r2]})
# print new_pop
return new_pop
def truncation(pop,percent,size):
for i in range(len(pop)):
for j in range(10-1-i):
if pop[j][2] < pop[j+1][2]:
pop[j], pop[j+1] = pop[j+1], pop[j]
prop=percent*len(pop)/100 # 10*20/100
# print prop
repeat=size/prop
# print repeat
new_pop={}
k=0
for i in range(repeat):
for j in range(prop):
new_pop[k]=pop[j]
k+=1
# print new_pop
return new_pop
def combine(pop,ofs):
new={}
# print ofs
# print pop
for i in range(len(ofs)):
new[i]=ofs[i]
j=0
for i in range(len(ofs),len(pop)+len(ofs)):
# print j
# print pop[j]
new[i]=pop[j]
j+=1
return new
def average(pop):
fitness = [pop[f][2] for f in pop]
return sum(fitness)/len(fitness)
def best(pop):
fitness = [pop[f][2] for f in pop]
return max(fitness)
# def avg_plot(plot):
# plot[][]
#
# STEP 1
def rbs_trunc(run,xu,yu,xl,yl,f):
p=initialPopulation(10,f)
p=computeFitness(p,f)
t_plot=[]
for i in range(10):
plot={}
p=initialPopulation(10,f)
p=computeFitness(p,f)
for i in range(run):
select = rbs(p,10)
select=computeFitness(select,f)
ofs=offspring(select,xu,yu,xl,yl)
ofs=computeFitness(ofs,f)
# print ofs
# ofs=computeFitness(ofs)
total=combine(ofs,p)
p=truncation(total,20,10)
plot[i]=[average(p),best(p)]
if(i==39):
print "------------------------"
print plot
print "-------------------------"
t_plot.append(plot)
# print t_plot
avg_plot=[]
best_plot=[]
for i in range(len(t_plot[0])):
atemp=[]
btemp=[]
for j in range(len(t_plot)):
atemp.append(t_plot[j][i][0])
btemp.append(t_plot[j][i][1])
avg_plot.append(sum(atemp)/len(atemp))
best_plot.append(sum(btemp)/len(atemp))
print "average average fitness"
print avg_plot
print "average best fitness"
print best_plot
line_up, = plt.plot(best_plot, label='Best')
line_down, = plt.plot(avg_plot, label='Average')
plt.legend([line_up, line_down], ['Best', 'Average'])
plt.title("RBS with Truncation")
plt.show() # plt.show()
def fps_trunc(run,xu,yu,xl,yl,f):
p=initialPopulation(10,f)
p=computeFitness(p,f)
t_plot=[]
for i in range(10):
plot={}
p=initialPopulation(10,f)
p=computeFitness(p,f)
for i in range(run):
select = roulette_select(p,10)
select=computeFitness(select,f)
ofs=offspring(select,xu,yu,xl,yl)
ofs=computeFitness(ofs,f)
total=combine(ofs,p)
p=truncation(total,20,10)
plot[i]=[average(p),best(p)]
t_plot.append(plot)
# print t_plot
avg_plot=[]
best_plot=[]
for i in range(len(t_plot[0])):
atemp=[]
btemp=[]
for j in range(len(t_plot)):
atemp.append(t_plot[j][i][0])
btemp.append(t_plot[j][i][1])
avg_plot.append(sum(atemp)/len(atemp))
best_plot.append(sum(btemp)/len(atemp))
print "average average fitness"
print avg_plot
print "average best fitness"
print best_plot
line_up, = plt.plot(best_plot, label='Best')
line_down, = plt.plot(avg_plot, label='Average')
plt.legend([line_up, line_down], ['Best', 'Average'])
# plt.show()
plt.title("FPS with Truncation")
plt.show()
def bin_trunc(run,xu,yu,xl,yl,f):
p=initialPopulation(10,f)
p=computeFitness(p,f)
t_plot=[]
for i in range(run):
plot={}
p=initialPopulation(10,f)
p=computeFitness(p,f)
for i in range(40):
select = binarytour(p,10)
select=computeFitness(select,f)
ofs=offspring(select,xu,yu,xl,yl)
ofs=computeFitness(ofs,f)
total=combine(ofs,p)
p=truncation(total,20,10)
plot[i]=[average(p),best(p)]
t_plot.append(plot)
# print t_plot
avg_plot=[]
best_plot=[]
for i in range(len(t_plot[0])):
atemp=[]
btemp=[]
for j in range(len(t_plot)):
atemp.append(t_plot[j][i][0])
btemp.append(t_plot[j][i][1])
avg_plot.append(sum(atemp)/len(atemp))
best_plot.append(sum(btemp)/len(atemp))
print "average average fitness"
print avg_plot
print "average best fitness"
print best_plot
line_up, = plt.plot(best_plot, label='Best')
line_down, = plt.plot(avg_plot, label='Average')
plt.legend([line_up, line_down], ['Best', 'Average'])
# plt.show()
plt.title("Binary Tournament with Truncation")
plt.show()
def fps_bin(run,xu,yu,xl,yl,f):
p=initialPopulation(10,f)
p=computeFitness(p,f)
t_plot=[]
for i in range(10):
plot={}
p=initialPopulation(10,f)
p=computeFitness(p,f)
for i in range(run):
select = roulette_select(p,10)
select=computeFitness(select,f)
ofs=offspring(select,xu,yu,xl,yl)
ofs=computeFitness(ofs,f)
total=combine(ofs,p)
p=binarytour(total,10)
plot[i]=[average(p),best(p)]
t_plot.append(plot)
# print t_plot
avg_plot=[]
best_plot=[]
for i in range(len(t_plot[0])):
atemp=[]
btemp=[]
for j in range(len(t_plot)):
atemp.append(t_plot[j][i][0])
btemp.append(t_plot[j][i][1])
avg_plot.append(sum(atemp)/len(atemp))
best_plot.append(sum(btemp)/len(atemp))
print "average average fitness"
print avg_plot
print "average best fitness"
print best_plot
line_up, = plt.plot(best_plot, label='Best')
line_down, = plt.plot(avg_plot, label='Average')
plt.legend([line_up, line_down], ['Best', 'Average'])
# plt.show()
plt.title("FPS with Binary Tournament")
plt.show()
def rbs_bin(run,xu,yu,xl,yl,f):
p=initialPopulation(10,f)
p=computeFitness(p,f)
t_plot=[]
for i in range(run):
plot={}
p=initialPopulation(10,f)
p=computeFitness(p,f)
for i in range(40):
select = rbs(p,10)
select=computeFitness(select,f)
ofs=offspring(select,xu,yu,xl,yl)
ofs=computeFitness(ofs,f)
total=combine(ofs,p)
p=binarytour(total,10)
plot[i]=[average(p),best(p)]
t_plot.append(plot)
# print t_plot
avg_plot=[]
best_plot=[]
for i in range(len(t_plot[0])):
atemp=[]
btemp=[]
for j in range(len(t_plot)):
atemp.append(t_plot[j][i][0])
btemp.append(t_plot[j][i][1])
avg_plot.append(sum(atemp)/len(atemp))
best_plot.append(sum(btemp)/len(atemp))
print "average average fitness"
print avg_plot
print "average bset fitness"
print best_plot
line_up, = plt.plot(best_plot, label='Best')
line_down, = plt.plot(avg_plot, label='Average')
plt.legend([line_up, line_down], ['Best', 'Average'])
# plt.show()
plt.title("RBS with Binary Tournament")
plt.show()
def bin_bin(run,xu,yu,xl,yl,f):
# p=initialPopulation(10)
# p=computeFitness(p)
t_plot=[]
for i in range(10):
plot={}
p=initialPopulation(10,f)
p=computeFitness(p,f)
for i in range(run):
select = binarytour(p,10)
select=computeFitness(select,f)
ofs=offspring(select,xu,yu,xl,yl)
ofs=computeFitness(ofs,f)
total=combine(ofs,p)
p=binarytour(total,10)
plot[i]=[average(p),best(p)]
t_plot.append(plot)
# print t_plot
avg_plot=[]
best_plot=[]
for i in range(len(t_plot[0])):
atemp=[]
btemp=[]
for j in range(len(t_plot)):
atemp.append(t_plot[j][i][0])
btemp.append(t_plot[j][i][1])
avg_plot.append(sum(atemp)/len(atemp))
best_plot.append(sum(btemp)/len(atemp))
print "average average fitness"
print avg_plot
print "average best fitness"
print best_plot
line_up, = plt.plot(best_plot, label='Best')
line_down, = plt.plot(avg_plot, label='Average')
plt.legend([line_up, line_down], ['Best', 'Average'])
plt.title("Binary Tournament with Binary Tournament")
plt.show()
# 1st FUNCTION
rbs_trunc(40,5,5,-5,-5,1) # arguments are (total runs, x upperboud, y upperbound,x lower bound, y lower bound, function)
fps_trunc(40,5,5,-5,-5,1)
bin_trunc(40,5,5,-5,-5,1)
fps_bin(40,5,5,-5,-5,1)
rbs_bin(400,5,5,-5,-5,1)
bin_bin(40,5,5,-5,-5,1)
# 2nd FUNCTION
rbs_trunc(40,2,3,-2,-1,2) # arguments are (total runs, x upperboud, y upperbound,x lower bound, y lower bound, function)
fps_trunc(40,2,3,-2,-1,2)
bin_trunc(40,2,3,-2,-1,2)
fps_bin(40,2,3,-2,-1,2)
rbs_bin(40,2,3,-2,-1,2)
bin_bin(40,2,3,-2,-1,2)
|
5d77e9ffd0d437c0d98567cdbd80277f5cbd47af | mrinalmayank7/python-programming | /CLASSES & OBJECTS/M_Overriding.py | 326 | 3.546875 | 4 | class India:
def __init__(self):
self.value="INSIDE COUNTRY"
def globe(self):
print(self.value)
class Punjab(India):
def __init__(self):
self.value="INSIDE STATE"
def globe(self):
print(self.value)
o1=India()
o2=Punjab()
o1.globe()
o2.globe()
|
38bb9777c09a1ac702330eccca23e21a270dad2e | mrinalmayank7/python-programming | /FILE HANDLING/File_Handling.py | 658 | 3.8125 | 4 | #MODES
#''r' is for read, ti is the default mode
#'w' is for write from the first line
#'a' write from the end of file , if file doest not exist it will create a new file
#'x' is for create a file , if file exist then it will return error
#'t' is text
#'b' is for binary
f= open('file1.txt','w+') #w+ is for both read write
f1=open('file1.txt','a')
for i in range(3):
f.write('New Line %d\n'% (i+1))
f1.write('Append Line %d\n'% (i+2))
f.close()
f1.close()
f2= open('file1.txt','r')
print(f2.readline()) #readline reads one line
if f2.mode=='r':
readfile=f2.read() #read all lines
print(readfile)
f2.close()
|
ee7621808654eae021fdfbe36d3bb796695a032e | mrinalmayank7/python-programming | /PRACTICE WORKSHEETS/worksheet3.2.py | 1,452 | 3.8125 | 4 |
print("Name :Mrinal Mayank")
print("UID :19BCS1605")
class MAGIC:
def __init__(self,o):
self.o = o
def __ge__(self,operator1): #for greater than and equal to
return self.o > operator1.o
def __mul__(self,operator1): #for multiplication
return self.o * operator1.o
def __lt__(self,operator1): #for less than
return self.o < operator1.o
object1 = MAGIC(11)
object2 = MAGIC(10)
print (object1 >=object2) #magic method __ge__
print (object1 * object2) #magic method __mul__
print (object1 < object2) #magic method __lt__
class CU_STUDENT:
def __init__(self,name ,UID):
self.name = name
self.UID = UID
def view(self ,dept ,sec , group):
print("NAME :", self.name)
print("UID :", self.UID)
print("DEPARTMENT :", dept)
print("CLASS :", sec)
print("GROUP :", group)
def Age(self,age) :
print("AGE :", age)
def Mark(self):
sum= 0
n=int(input("ENTER TOTAL NUMBER OF SUBJECTS :"))
marks=[]
for i in range(n):
item = int(input("ENTER MARKS : "))
marks.append(item)
for i in range(0, len(marks)):
sum = sum + marks[i]
print("TOTAL MARKS :", sum)
o1 = CU_STUDENT("MRINAL MAYANK" , "19BCS1605")
o1.view("CSE","CSE 8","C")
o1.Age(20)
o1.Mark()
|
7912b115e12d200e6981cdbe55ca8c3175eba085 | fangbz1986/python_study | /函数式编程/03filter.py | 1,222 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Python内建的filter()函数用于过滤序列。
和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
filter()的作用是从一个序列中筛出符合条件的元素。由于filter()使用了惰性计算,所以只有在取filter()结果的时候,才会真正筛选并每次返回下一个筛出的元素。
'''
# 例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n % 2 == 1
a = filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
print(type(a)) # filter
print(list(a)) # filter
# 把一个序列中的空字符串删掉,可以这么写:
def not_empty(s):
return s and s.strip()
a = list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
print(a)
'''
可见用filter()这个高阶函数,关键在于正确实现一个“筛选”函数。
注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list
'''
|
8a3d11386042b7c7c67c110f2e255005d8879556 | fangbz1986/python_study | /03高级特性/05生成器.py | 4,412 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
生成器
通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator
'''
# 列表生成式
L = [x * x for x in range(10)]
print(L)
# 生成器 要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
# 如果要一个一个打印出来,可以通过next()函数获得generator的下一个返回值:
g = (x * x for x in range(10))
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
# 使用next()有点变态,正确的方法是使用for循环,因为generator也是可迭代对象
g = (x * x for x in range(10))
for n in g:
print(n)
'''
著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:
a, b = b, a + b
t = (b, a + b) # t是一个tuple
a = t[0]
b = t[1]
但不必显式写出临时变量t就可以赋值。
'''
def fib(max):
n,a,b=0,0,1
while n<max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
fib(6)
# 也就是说,上面的函数和generator仅一步之遥。要把fib函数变成generator,只需要把print(b)改为yield b就可以了:
# 定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator:
# 这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。
# 而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
def fib(max):
n,a,b=0,0,1
while n<max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
f=fib(10)
print(f)
# 举个简单的例子,定义一个generator,依次返回数字1,3,5:
# odd不是普通函数,而是generator,在执行过程中,遇到yield就中断,下次又继续执行。执行3次yield后,已经没有yield可以执行了,所以,第4次调用next(o)就报错
def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5)
o = odd()
next(o)
next(o)
next(o)
# next(o)
'''
回到fib的例子,我们在循环过程中不断调用yield,就会不断中断。当然要给循环设置一个条件来退出循环,不然就会产生一个无限数列出来。
同样的,把函数改成generator后,我们基本上从来不会用next()来获取下一个返回值,而是直接使用for循环来迭代:
'''
for n in fib(6):
print(n)
'''
但是用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中:
'''
g = fib(6)
while True:
try:
x=next(g)
print("g:",x)
except StopIteration as e:
print('Generator return value:', e.value)
break
'''
总结
generator是非常强大的工具,在Python中,可以简单地把列表生成式改成generator,也可以通过函数实现复杂逻辑的generator。
要理解generator的工作原理,它是在for循环的过程中不断计算出下一个元素,并在适当的条件结束for循环。对于函数改成的generator来说,遇到return语句或者执行到函数体最后一行语句,就是结束generator的指令,for循环随之结束。
'''
|
3135ff685de3e016c265c88484827ec95bccea97 | projectcollection/Intro-Python-II | /src/adv.py | 3,698 | 3.5 | 4 | import textwrap
from player import Player
from room import Room
from items import *
#Make some items
samurai = Weapon('samurai', 10, 500, 100)
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons", [samurai]),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east.""", [samurai]),
'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm.""", [samurai]),
'narrow': Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air.""", [samurai]),
'treasure': Room("Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south.""", [samurai]),
}
# Link rooms together
room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']
#
# Main
#
# Make a new player object that is currently in the 'outside' room.
player1 = Player('player1', room['outside'])
# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
#
# If the user enters "q", quit the game.
def tut():
return (
'm(move) direction(N,E,S,W)\n'
'i(item) command(inv->"inventory", ir->"in room", get, drop)\n'
'i get(or)drop item_name all(optional)\n'
)
def item_action(player, action, item = '', get_all = False):
if(get_all == 'all'):
get_all = True
if(action == 'inv'):
print([i.name for i in player.items])
elif(action == 'ir'):
print([i.name for i in player.current_loc.items])
elif(action == 'drop'):
items = player.get_item(item, get_all)
if(len(items) > 0):
player.current_loc.add_item(items)
print('ITEM DROPPED IN ROOM')
else:
print('Item not in inventory')
elif(action == 'get'):
items = player.current_loc.get_item(item, get_all)
if(len(items) > 0):
player.add_item(items)
print('ITEM ADDED TO INVENTORY')
else:
print('Item not found in room')
while True:
print('\n')
print(f'Current Location: {player1.current_loc.name}')
print(textwrap.fill(player1.current_loc.desc, 25))
print(('-----\n'
f'{textwrap.dedent(player1.current_loc.rooms_around())}\n'
'-----\n'))
print('\n')
user_cmd = input('what\'s the move? write "tut" for tutorial\n>>> ').split()
if user_cmd[0] == 'q':
break
elif(user_cmd[0] == 'm' and len(user_cmd) >= 2 and user_cmd[1].upper() in ('N', 'E', 'S', 'W')):
player1.move(user_cmd[1])
elif(user_cmd[0] == 'i'):
if len(user_cmd) == 2:
item_action(player1, user_cmd[1])
elif len(user_cmd) > 3:
item_action(player1, user_cmd[1], user_cmd[2], user_cmd[3])
else:
item_action(player1, user_cmd[1], user_cmd[2])
elif(user_cmd[0] == 'tut'):
print(tut())
else:
print('Unknown Command') |
cabe3b1323ec56f099fb7d22bd2dc5d966455b91 | ryancey1/Rosalind | /Algorithmic-Heights/08-heapsort.py | 364 | 3.734375 | 4 | #! /usr/bin/env python3
'''
'''
import sys, os
import algorithmic_heights as algs
## METHODS GO HERE ##
def main():
file = sys.argv[1]
with open(file) as _:
line = [lines.strip() for lines in _]
arr, n = [int(x) for x in line[1].split()], int(line[0])
print(*algs.heapsort(arr, n))
if __name__ == '__main__':
main()
|
a3e8aefe45bce23e73caa3bcae8e4054e9b4668b | ryancey1/Rosalind | /Bioinformatics-Stronghold/17-mortal-fibonacci.py | 375 | 3.921875 | 4 | #! /usr/bin/env python3
'''
Given: Positive integers n≤100 and m≤20.
Return: The total number of pairs of rabbits that will remain after the n-th month if all rabbits live for m months.
'''
import sys
memo = {}
def mortal_fibonacci(n, m, memo):
pass
if __name__ == '__main__':
n, m = 6, 3
if n > 100 or m > 20:
exit("Values are too large")
|
1997d7b74abb8a6ab5706bfdffb6009da2084891 | ryancey1/Rosalind | /Algorithmic-Heights/03-insertion-sort.py | 413 | 3.53125 | 4 | #! /usr/bin/env python3
import sys, os
import algorithmic_heights as algs
def main():
file = sys.argv[1]
# file = os.getcwd() + '/Algorithmic-Heights/rosalind_ins.txt'
with open(file) as f:
line = [lines.strip() for lines in f.readlines()]
n, arr = int(line[0]), [int(x) for x in line[1].split()]
print(algs.insertion_sort(arr, n))
if __name__ == '__main__':
main() |
122a3f71dd406d2cea9d838e3fe1260cd0e3adcf | hardlyHacking/cs1 | /static/solutions/labs/gravity/solution/system.py | 2,283 | 4.21875 | 4 | # system.py
# Solution for CS 1 Lab Assignment 3.
# Definition of the System class for gravity simulation.
# A System represents several Body objects.
# Based on code written by Aaron Watanabe and Devin Balkcom.
UNIVERSAL_GRAVITATIONAL_CONSTANT = 6.67384e-11
from math import sqrt
from body import Body
class System:
# To initialize a System, just save the body list.
def __init__(self, body_list):
self.body_list = body_list
# Draw a System by drawing each body in the body list.
def draw(self, cx, cy, pixels_per_meter):
for body in self.body_list:
body.draw(cx, cy, pixels_per_meter)
# Compute the distance between bodies n1 and n2.
def dist(self, n1, n2):
dx = self.body_list[n2].get_x() - self.body_list[n1].get_x()
dy = self.body_list[n2].get_y() - self.body_list[n1].get_y()
return sqrt(dx * dx + dy * dy)
# Compute the acceleration of all other bodies on body n.
def compute_acceleration(self, n):
total_ax = 0
total_ay = 0
n_x = self.body_list[n].get_x()
n_y = self.body_list[n].get_y()
for i in range(len(self.body_list)):
if i != n: # don't compute the acceleration of body n on itself!
r = self.dist(i, n)
a = UNIVERSAL_GRAVITATIONAL_CONSTANT * self.body_list[i].get_mass() / (r * r)
# a is the magnitude of the acceleration.
# Break it into its x and y components ax and ay,
# and add them into the running sums total_ax and total_ay.
dx = self.body_list[i].get_x() - n_x
ax = a * dx / r
total_ax += ax
dy = self.body_list[i].get_y() - n_y
ay = a * dy / r
total_ay += ay
# To return two values, use a tuple.
return (total_ax, total_ay)
# Compute the acceleration on each body, and use the acceleration
# to update the velocity and then the position of each body.
def update(self, timestep):
for n in range(len(self.body_list)):
(ax, ay) = self.compute_acceleration(n)
self.body_list[n].update_velocity(ax, ay, timestep)
self.body_list[n].update_position(timestep)
|
b3c3e255cbffa0ddf0cab275f72643915f39e018 | hardlyHacking/cs1 | /static/solutions/labs/gravity/solution/body.py | 1,498 | 3.96875 | 4 | # body.py
# Solution for CS 1 Lab Assignment 2.
# Definition of the Body class for gravity simulation.
# Based on code written by Aaron Watanabe and Devin Balkcom.
from cs1lib import *
class Body:
# Initialize a Body object.
def __init__(self, mass, x, y, vx, vy, pixel_radius, r, g, b):
self.mass = mass
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.pixel_radius = pixel_radius
self.r = r
self.g = g
self.b = b
# Return the mass of a Body object.
def get_mass(self):
return self.mass
# Return the x position of a Body object.
def get_x(self):
return self.x
# Return the y position of a Body object.
def get_y(self):
return self.y
# Update the position of a Body object for a given timestep.
def update_position(self, timestep):
self.x += self.vx * timestep
self.y += self.vy * timestep
# Update the velocity of a Body object for a given timestep by
# given accelerations ax in x and ay in y.
def update_velocity(self, ax, ay, timestep):
self.vx += ax * timestep
self.vy += ay * timestep
# Have a Body object draw itself.
def draw(self, cx, cy, pixels_per_meter):
set_fill_color(self.r, self.g, self.b)
disable_stroke()
enable_fill()
draw_circle(cx + self.x * pixels_per_meter,
cy + self.y * pixels_per_meter,
self.pixel_radius)
|
d45482664ec4e67e88942b98ba6f5eb5a91fa165 | hardlyHacking/cs1 | /static/solutions/shortassign/rich/solution/portia.py | 1,382 | 3.921875 | 4 | # portia.py
# Solution to CS 1 Short Assignment #3, Problem 2 by THC.
# Computes the balances of two bank accounts:
# Brutus's account starts with $1 in year 0, compounded at 5% annually.
# Portia's account starts with $100,000 in year 0, compounded at 4% annually.
# Computes the first year in which Brutus's balance exceeds Portia's balance.
BRUTUS_INITIAL_BALANCE = 1.0 # how much Brutus's account starts with
BRUTUS_INTEREST_RATE = 5.0 # Brutus's interest rate, as a percent
PORTIA_INITIAL_BALANCE = 100000.0 # how much Portia's account starts with
PORTIA_INTEREST_RATE = 4.0 # Portia's interest rate, as a percent
brutus_balance = BRUTUS_INITIAL_BALANCE # Brutus's balance, will be updated annually
portia_balance = PORTIA_INITIAL_BALANCE # Portia's balance, will be updated annually
year = 0 # which year
# Update the balance once per year, until Brutus's balance exceeds Portia's.
while brutus_balance <= portia_balance:
year = year + 1
brutus_balance = brutus_balance + (BRUTUS_INTEREST_RATE / 100.0) * brutus_balance
portia_balance = portia_balance + (PORTIA_INTEREST_RATE / 100.0) * portia_balance
# All done. Print the result, nicely formatted.
print "At year " + str(year) + ", Brutus's balance of " + str(brutus_balance) + \
" exceeds Portia's balance of " + str(portia_balance) + "."
|
b33d2944d9bad1577ec4c248fb2c48ddb8cdd1f1 | hardlyHacking/cs1 | /static/solutions/labs/quicksort/solution/lab3_checkpoint.py | 1,807 | 3.9375 | 4 | # lab4_checkpoint.py
# CS 1 Lab Assignment #3 checkpoint by THC.
# Reads in a file of information about world cities, stores each line
# into a City object, and then writes out the string representation of
# each City object into a file.
# Each line of the input file has the following fields, separated by commas:
# 1. A two-letter country code.
# 2. The name of the city.
# 3. A two-character region code. The characters might be numeric,
# alphabetical, or a combination.
# 4. The city's population, an integer.
# 5. The city's latitude, in degrees, a float.
# 6. The city's longitude, in degrees, a float.
# The format of the output file has the following fields, separated by commas:
# 1. The name of the city.
# 2. The city's population, an integer.
# 3. The city's latitude, in degrees, a float.
# 4. The city's longitude, in degrees, a float.
from city import City
from string import lower
# Load a csv file and return a list of City objects.
def load_cities(filename):
cities = [] # start with an empty list
f = open(filename, 'r') # get ready to read
for line in f: # read each line
fields = line.strip().split(',') # separate its contents
cities.append(City(fields[0], fields[1], fields[2], int(fields[3]),
float(fields[4]), float(fields[5])))
f.close() # done with the file
return cities
# Write information about City objects to a file.
def write_cities(cities, filename):
outfile = open(filename, "w") # get ready to write
i = 0
while i < len(cities):
outfile.write(str(cities[i]) + "\n") # write the next City object
i += 1
outfile.close() # done writing
cities = load_cities("world_cities.txt")
write_cities(cities, "cities_out.txt")
|
7eed2e54b2fbabb3ef286b12f6595ffb5b47d339 | acecpt/PyGames | /runner.py | 4,662 | 3.890625 | 4 | # https://youtube/watch?v=-8n91btt5d8
import random # library for generating random numbers
import sys # python window controls
import pygame # https://www.pygame.org/docs
pygame.init()
print(pygame.get_init())
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
myFont = pygame.font.SysFont("monospace", 30)
BLACK = (0,0,0)
RED = (255, 0, 0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
PLAYER_SIZE = 50
PLAYER_MOVE = 50
PLAYER_POS = [WIDTH/2, HEIGHT- 2 * PLAYER_SIZE] # half way x, two players up from the bottom
ENEMY_SIZE = 50
ENEMY_POS = [random.randint(0,WIDTH - ENEMY_SIZE), 0] # create enemy inside width of screen
ENEMY_LIST = [ENEMY_POS] # List to handle multiple enemies
ENEMY_COUNT = 10
SPEED = ENEMY_SIZE / 5
GAME_OVER = False
SCORE = 0
CLOCK = pygame.time.Clock()
def set_level(SCORE, SPEED):
if SCORE < 20:
SPEED = 5
elif SCORE < 40:
SPEED = 8
elif SCORE < 60:
SPEED = 11
else:
SPEED = 15
return SPEED
def drop_enemies(ENEMY_LIST): # Send Enemies in waves, drop at the bottom of the window
delay = random.random()
if len(ENEMY_LIST) < ENEMY_COUNT and delay < 0.1: # Populate the list at a delay
x_pos = random.randint(0,WIDTH-ENEMY_SIZE)
y_pos = 0
ENEMY_LIST.append([x_pos, y_pos])
def draw_enemies(ENEMY_LIST): # Draw Enemies in the generated list
for ENEMY_POS in ENEMY_LIST:
pygame.draw.rect(screen, BLUE, (ENEMY_POS[0], ENEMY_POS[1], ENEMY_SIZE, ENEMY_SIZE))
def update_enemy_pos(ENEMY_LIST, SCORE):
for idx, ENEMY_POS in enumerate(ENEMY_LIST): #while loop trick to index list
if ENEMY_POS[1] >= 0 and ENEMY_POS[1] < HEIGHT: # On the screen
ENEMY_POS[1] += SPEED # Move it down
else:
ENEMY_LIST.pop(idx) # pop / drop off list when at bottom 0
SCORE += 1
return SCORE
def collision_check(ENEMY_LIST, PLAYER_POS):
for ENEMY_POS in ENEMY_LIST:
if detect_collision(PLAYER_POS, ENEMY_POS):
return True
return False
def detect_collision(PLAYER_POS, ENEMY_POS): # Both positions are upper left of the drawn square
p_x = PLAYER_POS[0] # ranges left to right from player_pos[0] to player_pos[0] + player_size
p_y = PLAYER_POS[1] # ranges top to bottom from player_pos[1] to player_pos[1] + player_size
e_x = ENEMY_POS[0] # ranges left to right from enemy_pos[0] to enemy_pos[0] + enemy_size
e_y = ENEMY_POS[1] # ranges top to bottom from enemy_pos[1] to enemy_pos[1] + enemy_size
if (e_x >= p_x and e_x < (p_x + PLAYER_SIZE)) or (p_x >= e_x and p_x < (e_x + ENEMY_SIZE)): # Check X overlap
if (e_y >= p_y and e_y < (p_y + PLAYER_SIZE)) or (p_y >= e_y and p_y < (e_y + ENEMY_SIZE)): # Check Y overlap
return True # only return after checking both X and Y
return False
while not GAME_OVER:
for event in pygame.event.get():
print(event) # watch events in console
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
X = PLAYER_POS[0]
Y = PLAYER_POS[1]
if event.key == pygame.K_LEFT:
X -= PLAYER_MOVE
elif event.key == pygame.K_RIGHT:
X += PLAYER_MOVE
elif event.key == pygame.K_UP:
Y -= PLAYER_MOVE
elif event.key == pygame.K_DOWN:
Y += PLAYER_MOVE
PLAYER_POS = [X,Y] # use modified position for draw
screen.fill(BLACK) # Background color
# Update the position of the enemy #Commented out upon multiple enemies: def update_enemy_pos
# if ENEMY_POS[1] >= 0 and ENEMY_POS[1] < HEIGHT: # On the screen
# ENEMY_POS[1] += SPEED # move it down
# else:
# ENEMY_POS[0] = random.randint(0, WIDTH-ENEMY_SIZE) # New Rand x at top
# ENEMY_POS[1] = 0
# if detect_collision(PLAYER_POS, ENEMY_POS): #Commented out since: def collision_check
# GAME_OVER = True
# break # breaks out before overlap redraw
drop_enemies(ENEMY_LIST)
SCORE = update_enemy_pos(ENEMY_LIST, SCORE)
SPEED = set_level(SCORE, SPEED)
text = "Score: " + str(SCORE)
label = myFont.render(text, 1, YELLOW)
screen.blit(label, (WIDTH - 200, HEIGHT - 40))
if collision_check(ENEMY_LIST, PLAYER_POS):
GAME_OVER = True
break
draw_enemies(ENEMY_LIST)
pygame.draw.rect(screen, RED, (PLAYER_POS[0], PLAYER_POS[1], PLAYER_SIZE, PLAYER_SIZE))
CLOCK.tick(30)
pygame.display.update()
|
beabf3189c86e0e8d2604ef7b6e7bc1c0d6715c1 | jpmghyston/advent-of-code-2019 | /3/3_part2.py | 1,661 | 3.6875 | 4 | input_file = open("input.txt", "r")
path_directions_1 = input_file.readline().strip().split(',')
path_directions_2 = input_file.readline().strip().split(',')
def coords_for_path(path):
_x = 0
_y = 0
path_coords_visited = []
for instruction in path:
direction = instruction[0]
distance = int(instruction[1:])
if direction == "R":
path_coords_visited += [(new_x, _y) for new_x in range(_x, _x + distance)]
_x += abs(distance)
elif direction == "L":
path_coords_visited += [(new_x, _y) for new_x in range(_x, _x - distance, -1)]
_x -= abs(distance)
elif direction == "U":
path_coords_visited += [(_x, new_y) for new_y in range(_y, _y + distance)]
_y += abs(distance)
elif direction == "D":
path_coords_visited += [(_x, new_y) for new_y in range(_y, _y - distance, -1)]
_y -= abs(distance)
return path_coords_visited
def distance_to_point(path, point):
distance = 1
for i in range(1, len(path)):
new_location = path[i]
if new_location == point:
return distance
x, y = new_location
old_x, old_y = path[i - 1]
distance += abs(x - old_x) + abs(y - old_y)
path_1 = coords_for_path(path_directions_1)
path_2 = coords_for_path(path_directions_2)
crosses = set(path_1).intersection(set(path_2))
crosses.remove((0, 0))
distances_to_crosses = [distance_to_point(path_1, cross) + distance_to_point(path_2, cross) for cross in crosses]
distances_to_crosses.sort()
print distances_to_crosses
|
b9e31fcc8653fb44cb7b98216001542f8dff3f85 | terenceshin/modularized-ml-code | /model.py | 1,846 | 3.703125 | 4 | import pandas as pd
import xgboost as xgb
def xgb_classifier(X_train, y_train, params):
"""
Creates XGBoost Classifier
Inputs:
X_train (df): the feature training data
y_train (df): the target training data
params (dict): the parameters of XGBoost
Returns:
XGB Classifier
"""
model = xgb.XGBClassifier(**params)
return model.fit(X_train, y_train)
def make_predictions(model, X_test):
"""
Makes predictions on validate/test data
Inputs:
model (object): the model to be used for the new data
X_test (df): the data to feed through the model
Returns:
Model predictions
"""
return model.predict(X_test)
def plot_feat_importance(model, feature_names, size=10):
"""
plots feature importance of a model
Inputs:
model (object): the model which its features will be plotted
feature_names (list): the list of feature names
size (int): the number of features to plot
Returns:
Plot of feature importance for a given model
"""
feat_importances = pd.Series(model.feature_importances_, index=feature_names)
feature_importances.nlargest(size).plot(kind='barh', figsize=(20,20))
def feat_imp_to_df(model, feature_names):
"""
Writes feature importance to a DataFrame
Inputs:
model (object): the model that we want the feature importance
feature_names (list): the list of feature names
Returns:
DataFrame of feature importance
"""
df = pd.DataFrame(model.feature_importances_, feature_names) \
. reset_index() \
.rename(columns={'index': 'feature', 0: 'feat_importance'}) \
.sort_values(by='feat_importance', ascending=False)
return df
|
483d4305953b5bda4c9b7b60a4144068e5d08f46 | nikhilkhera/algorithmic_toolbox_assignment | /algorithmic toolbox/week3/fuel.py | 714 | 3.765625 | 4 | # python3
import sys
def compute_min_refills(distance, tank,no_stops, stops):
# write your code here
numrefils=0
stops.append(distance)
stops.insert(0,0)
current_refill=0
while current_refill <= no_stops:
last_Refill = current_refill
while(current_refill<=no_stops) and stops[current_refill+1]-stops[last_Refill]<=tank:
current_refill=current_refill+1
if current_refill==last_Refill:
return -1
if current_refill<=no_stops:
numrefils=numrefils+1
return numrefils
if __name__ == '__main__':
d, m, _, *stops = map(int, sys.stdin.read().split())
print(compute_min_refills(d, m,_, stops))
|
3666bb73d265cf9eda5b649eb26297551a20e6d9 | nikhilkhera/algorithmic_toolbox_assignment | /algorithmic toolbox/week4/majority_element_3.py | 445 | 3.71875 | 4 | def majority(elements):
thisdict = {}
for i in elements:
if i not in thisdict:
thisdict[i]=1
else:
thisdict[i]+=1
for i in thisdict.values():
if i > len(elements)/2:
return 1
return 0
def main():
num_elements = int(input())
elemets = [int(x) for x in input().split()]
assert len(elemets) == num_elements
print(majority(elemets))
main() |
8c1bfdd62dc1552d2fb5b5533a0dd01ebd22d7fd | nikhilkhera/algorithmic_toolbox_assignment | /algorithmic toolbox/week5/primitive_calculator.py | 894 | 3.5625 | 4 | def primitivecalculator(n):
if n==1:
return [0,0]
steps=[0,0]
div=[2,3]
for i in range(2,n+1):
minstep=9999999
if steps[i-1]+1<minstep:
minstep=steps[i-1]+1
for j in div:
if i% j==0:
if steps[i//j]+1<minstep:
minstep=steps[i//j]+1
steps.append(minstep)
return steps
def backtrack(steps,n):
if n==1:
return
if n%2==0 and steps[n]==steps[n//2]+1:
backtrack(steps,n//2)
print(n//2,end=" ")
elif n%3==0 and steps[n]==steps[n//3]+1:
backtrack(steps,n//3)
print(n//3,end=" ")
else:
backtrack(steps,n-1)
print (n-1,end=" ")
return
def main():
n=int(input())
steps =primitivecalculator(n)
print(steps[n])
backtrack(steps,n)
print(n)
main() |
4594c093fb80bcffec0b301ffaa0bc3c8b7704c8 | nikhilkhera/algorithmic_toolbox_assignment | /algorithmic toolbox/week4/lottery.py | 2,949 | 3.78125 | 4 | # Uses python3
import sys
import random
def merge(A,B):
c=[]
while(len(A)!=0 and len(B)!=0):
if(A[0][0])<=B[0][0]:
c.append(A.pop(0))
else:
c.append(B.pop(0))
if(len(A)==0):
c.extend(B)
else :
c.extend(A)
return c
def mergeSort(elements):
n=len(elements)
if n==1:
return elements
m=int(n/2)
A=mergeSort(elements[:m])
B=mergeSort(elements[m:])
return merge(A,B)
def fast_count_segments(starts, ends, points):
count={}
for i in points:
count[i]=0
#creating a new array consisting of points starts and ends values combined
arr = []
for i in range(len(starts)): #the order has to be this while entering into the new array
arr.append((starts[i],'l'))
for i in points:
arr.append((i,'p'))
for i in range(len(starts)):
arr.append((ends[i],'r'))
newarr=mergeSort(arr)
#counting the no. of segments
stage=0
i=0
while i< (len(points)+(2*len(starts))):
if newarr[i][1]=='l':
stage+=1
elif newarr[i][1]=='r':
stage-=1
else :
count[newarr[i][0]]=stage
i=i+1
cnt=[]
for i in points:
cnt.append(count[i])
return cnt
'''
def naive_count_segments(starts, ends, points):
cnt = [0] * len(points)
for i in range(len(points)):
for j in range(len(starts)):
if starts[j] <= points[i] <= ends[j]:
cnt[i] += 1
return cnt
'''
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
m = data[1]
starts = data[2:2 * n + 2:2]
ends = data[3:2 * n + 2:2]
points = data[2 * n + 2:]
count=fast_count_segments(starts,ends,points)
for i in count:
print(i,end=' ')
#use fast_count_segments
#cnt = naive_count_segments(starts, ends, points)
#for x in cnt:
# print(x, end=' ')
'''
def test():
while 1:
points=[]
for i in range(random.randint(1,50)):
points.append(random.randint(0,10))
segment_rng = random.randint(1,50)
starts=[]
ends=[0]*segment_rng
for i in range(segment_rng):
starts.append(random.randint(0,100))
while ends[i]<=starts[i]:
ends[i]=random.randint(0,150)
print("POINTS:",points)
print("SEGEMENT START:",starts)
print("SEGMENT END:",ends)
cnt1= fast_count_segments(starts,ends,points)
cnt2= naive_count_segments(starts, ends, points)
if cnt1!=cnt2:
print("------SLOW:{}----FAST:{}----".format(cnt2,cnt1))
print("-----ERROR-----")
break
print("ok")
test()
''' |
30b26711fedc988ada22838725fe87edf0a2874b | testuserhehexd/uw-projects | /Movies Project/Top 5 Movies made by Country/top_countries.py | 3,078 | 3.703125 | 4 | """
Nalu Zou, Yuming Tsang, Jerome Orille
CSE 163
This file will identify the top five movies with the highest average
rating per country.
"""
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
def average_ratings_per_country(df, countries):
"""
This function analyzes the data based on the average movie ratings per
country.
Returns top 5 average movie ratings
"""
# find mean ratings per country
df = df.groupby('country')['score'].mean()
top_5 = df.nlargest(5)
# plot average ratings by country
fig, ax = plt.subplots(1)
countries.plot(ax=ax, color='#EEEEEE')
scores = countries.merge(df, left_on='NAME', right_on='country',
how='outer')
scores = scores.dropna()
scores.plot(ax=ax, column='score', legend=True, vmin=0, vmax=10)
plt.title('Average IMDb Movie Ratings Per Country')
plt.savefig('top-ratings.png', bbox_inches='tight')
return top_5
def top_five_per_country(df, countries):
"""
This function analyzes the data based on the top movie per country.
Gives good overview of how top hits from each country compare.
Returns top 5 highest ratings
"""
# find top rating per country
df = df.groupby('country')['score'].max()
top_5 = df.nlargest(5)
# plot top ratings by country
fig, ax = plt.subplots(1)
countries.plot(ax=ax, color='#EEEEEE')
scores = countries.merge(df, left_on='NAME', right_on='country',
how='outer')
scores = scores.dropna()
scores.plot(ax=ax, column='score', legend=True, vmin=0, vmax=10)
plt.title('Top IMDb Movie Rating Per Country')
plt.savefig('top-movie.png', bbox_inches='tight')
return top_5
def sort_movies(df):
"""
Returns dataframe sorted by country and score
"""
df = df.sort_values(['country'], ascending=True) \
.groupby(['country'], sort=False) \
.apply(lambda x: x.sort_values(['score'], ascending=False)) \
.reset_index(drop=True)
return df
def main():
"""
Main method reads in and filters movie data, turns it into a
geopandas dataframe, and produces plots based on ratings
in different countries.
"""
# read in csv file
df = pd.read_csv('movies.csv', encoding="ISO-8859-1")
# filter data
columns = ['country', 'name', 'score']
df = df.loc[:, columns]
# sort movies by country
df = sort_movies(df)
# filter geopandas dataframe to be merged with cvs data
countries = gpd.read_file('ne_50m_admin_0_countries.shp')
countries = countries[['NAME', 'geometry']]
countries.loc[countries['NAME'] == 'United Kingdom', 'NAME'] = 'UK'
countries.loc[countries['NAME'] == 'United States of America',
'NAME'] = 'USA'
# produce plots and print top 5 average and highest ratings
print("Top 5 Average Movie Ratings:")
print(average_ratings_per_country(df, countries))
print("Top 5 Highest Ratings")
print(top_five_per_country(df, countries))
if __name__ == '__main__':
main() |
490389021ee556bb98c72ae687389445ebb6dcb7 | Andras00P/Python_Exercise_solutions | /31 - Guess_Game.py | 855 | 4.46875 | 4 | ''' Build a simple guessing game where it will continuously ask the user to enter a number between 1 and 10.
If the user's guesses matched, the user will score 10 points, and display the score.
If the user's guess doesn't match, display the generated number.
Also, if the user enters "q" stop the game. '''
import random
print("Welcome to the Guessing Game! \n\n")
print("Enter the letter q, to quit.\n")
score = 0
while True:
npc = random.randint(0, 10)
print("Guess a number between 0 and 10.")
n = input("What's your guess? \n")
if n == "q":
print("\nGame Over!")
break
num = int(n)
if num is npc:
score += 10
print("Your guess was correct!\n")
print(f"You currently have {score} points\n")
else:
print(f"The number was {npc}\n")
|
1312a36aee5ceebbb32beedfef010210a5bb19bb | Andras00P/Python_Exercise_solutions | /18 - Calculate_Grades.py | 871 | 4.21875 | 4 | ''' Calculate final grade from five subjects '''
def grades(a, b, c, d, e):
avg_grade = int((a + b + c + d + e) / 5)
f_grade = ""
if avg_grade >= 90:
f_grade = "Grade A"
elif avg_grade >= 80:
f_grade = "Grade B"
elif avg_grade >= 70:
f_grade = "Grade C"
elif avg_grade >= 60:
f_grade = "Grade D"
else:
f_grade = "Grade F"
return f_grade, avg_grade
grade_a = int(input("Enter the subject a grade: \n\n"))
grade_b = int(input("Enter the subject b grade: \n\n"))
grade_c = int(input("Enter the subject c grade: \n\n"))
grade_d = int(input("Enter the subject d grade: \n\n"))
grade_e = int(input("Enter the subject e grade: \n\n"))
final_grade, final_score = grades(grade_a, grade_b, grade_c, grade_d, grade_e)
print(f"Your Final grade is: {final_grade}, {final_score}")
|
3607e93c5431e03789f3f980fd2220c4a8dc9b10 | Andras00P/Python_Exercise_solutions | /24 - Reverse_String.py | 443 | 4.375 | 4 | """ Reverse a string.
If the input is: Hello World.
The output should be: .dlroW olleH """
def reverse_string(text):
result = ""
for char in text:
result = char + result
return result
# Shortcut
def reverse_string2(text):
return text[::-1]
usr_text = input("Write the text, you want to reverse: \n")
print("Reversed: \n", reverse_string(usr_text) + "\n", reverse_string2(usr_text))
|
a5fd62036f3dd8a6ec226ffae14b48c6c5ab06ca | Andras00P/Python_Exercise_solutions | /21 - Check_Prime.py | 357 | 4.21875 | 4 | ''' For a given number, check whether the number is a prime number or not '''
def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
usr_num = int(input("Enter number: \n"))
if is_prime(usr_num):
print("The number is a Prime")
else:
print("The number is not a Prime")
|
a063feb62e0fa07e815315aa7f0cead126dabb19 | amalathomas3/python | /lab11.1.py | 247 | 3.609375 | 4 | import calendar as c
from datetime import *
print(c.month(2021,1))
d=datetime.today()
print("year; ",d.year)
print("month; ",d.month)
print("hour; ",d.hour)
print("minute; ",d.minute)
print("second; ",d.second)
print("datetime format:",d)
|
cbdbb88e82583228c93a75da235a6a4a0baca435 | venkat58/basic | /exapmles/basicexamples.py | 1,246 | 3.78125 | 4 | # decorator example
def outer_div(func):
def inner(x,y):
if(x<y):
x,y = y,x
return func(x,y)
return inner
@outer_div
def divide(x,y):
print(x/y)
def logo():
thickness = 9 #int(input()) #This must be an odd number ex: 5
c = 'H'
#Top Cone
for i in range(thickness):
print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1))
#Top Pillars
for i in range(thickness+1):
print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))
#Middle Belt
for i in range((thickness+1)//2):
print((c*thickness*5).center(thickness*6))
#Bottom Pillars
for i in range(thickness+1):
print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))
#Bottom Cone
for i in range(thickness):
print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6))
def welcome_mat_design():
n, m = map(int,input().split())
pattern = [('.|.'*(2*i + 1)).center(m, '-') for i in range(n//2)]
print('\n'.join(pattern + ['WELCOME'.center(m, '-')] + pattern[::-1]))
if __name__ == "__main__":
#divide(2,4)
#logo()
welcome_mat_design() |
ac899cc4fe64b3c746a3af49bfe6570695440786 | minhbang/vi_gec_bert_transformer | /gen/rules/search_replace/rule.py | 2,347 | 3.53125 | 4 | class Rule(object):
""" Rule Base class
Một luật Tìm/Thay thế, ví dụ D/GI/V thay thế lẫn nhau
"""
@staticmethod
def get_all_patterns():
return []
def __init__(self, pattern: str = None) -> None:
self.search_replace = []
if pattern is not None:
ps = pattern.split('/')
if len(ps) > 1:
self.add_pair(ps[0], ps[1])
if len(ps) > 2:
# Chỉ xử lý đến trường hợp A/B/C
self.add_pair(ps[1], ps[2])
self.add_pair(ps[0], ps[2])
else:
raise Exception('Error: Pattern like "A/B"')
def add_pair(self, p1: str, p2: str):
c1 = self.preprocess_search_str(p1)
c2 = self.preprocess_search_str(p2)
self.search_replace.append((c1, c2))
self.search_replace.append((c2, c1))
def preprocess_search_str(self, c: str):
return c
def before_replace(self, word: str):
return word
def after_replace(self, word: str):
return word
def replace(self, old: str, new: str, word: str):
""" Tìm/Thay thế old bằng new trong từ word,
tự động phát hiện lower, upper hay capitalize để biến đổi phù hợp trước khi thay vào
Parameters
----------
old
new
word
Returns
-------
str
"""
sr = [
(old.upper(), new.upper()),
(old.capitalize(), new.capitalize()),
(old.lower(), new.lower())
]
new_word = word = self.before_replace(word)
for s, r in sr:
new_word = word.replace(s, r)
if new_word != word:
break
new_word = self.after_replace(new_word)
return new_word
def apply(self, word: str) -> list:
""" Áp dụng rule này cho từ word duy nhất 1 lần random
Parameters
----------
word:str
Returns
-------
list
Danh sách từ đã bị thay đổi
"""
result = []
for sr in self.search_replace:
new_word = self.replace(sr[0], sr[1], word)
if new_word != word:
result.append(new_word)
return result
|
fb8c5dd6ffd12d82b2629ee0b742bc437bf5e8d8 | SuiMingYang/leecodeWS | /14.py | 550 | 3.703125 | 4 | class Solution:
def longestCommonPrefix(self, strs) -> str:
if len(strs)==0:
return ""
if len(strs)==1:
return strs[0]
mn=min(len(strs[0]),len(strs[1]),len(strs[2]))
k=-1
for i in range(mn):
if strs[0][i]==strs[1][i] and strs[2][i]==strs[1][i]:
k=i
else:
break
if k!=-1:
return strs[0][0:k+1]
else:
return ""
obj=Solution()
print(obj.longestCommonPrefix(["flower","flow","flight"]))
|
cf4f0f430612a88914f6344346318778bdabb691 | dyehuty/recipe-app-api | /app/app/old_calc.py | 148 | 4 | 4 | def add(x,y):
"""Add two numer together"""
return x + y
def substract(x,y):
"""Substract x from y and return value """
return y - x |
06afe217a85fc98b1689ac6e6119a118fe91f9b5 | garciacastano09/pycourse | /intermediate/exercises/mod_05_iterators_generators_coroutines/exercise.py | 2,627 | 4.125 | 4 | #-*- coding: utf-8 -*-
u'''
MOD 05: Iterators, generators and coroutines
'''
def repeat_items(sequence, num_times=2):
'''Iterate the sequence returning each element repeated several times
>>> list(repeat_items([1, 2, 3]))
[1, 1, 2, 2, 3, 3]
>>> list(repeat_items([1, 2, 3], 3))
[1, 1, 1, 2, 2, 2, 3, 3, 3]
>>> list(repeat_items([1, 2, 3], 0))
[]
>>> list(repeat_items([1, 2, 3], 1))
[1, 2, 3]
:param sequence: sequence or iterable to iterate over
:param num_times: number of times to repeat each item
:returns: generator with each element of the sequence repeated
'''
for i in sequence:
rep=num_times
while rep>0:
yield i
rep-=1
continue
def izip(*sequences):
'''Return tuples with one element of each sequence
It returns as many pairs as the shortest sequence
The same than std lib zip function
>>> list(izip([1, 2, 3], ['a', 'b', 'c']))
[[1, 'a'], [2, 'b'], [3, 'c']]
>>> list(izip([1, 2, 3], ['a', 'b', 'c', 'd']))
[[1, 'a'], [2, 'b'], [3, 'c']]
:param sequences: two or more sequences to loop over
:returns: generator returning tuples with the n-th item of input sequences
'''
if len(sequences) > 0:
tuples_len = min(int(i) for i in map(lambda x: len(x), sequences))
else:
yield []
return
for index in range(0, tuples_len):
result_element = []
for sequence in sequences:
result_element.append(sequence[index])
yield result_element
def merge(*sequences):
'''Iterate over all sequences returning each time one item of one of them
Always loop sequences in the same order
>>> list(merge([None, True, False], ['a', 'e', 'i', 'o', 'u']))
[None, 'a', True, 'e', False, 'i', 'o', 'u']
>>> list(merge(['a', 'e', 'i', 'o', 'u'], [None, True, False]))
['a', None, 'e', True, 'i', False, 'o', 'u']
>>> list(merge(['a', 'e', 'i', 'o', 'u'], [None, True, False], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
['a', None, 0, 'e', True, 1, 'i', False, 2, 'o', 3, 'u', 4, 5, 6, 7, 8, 9]
:param sequences: two or more sequences to loop over
:returns: generator returning one item of each
'''
iterators = map(iter, sequences)
while sequences:
yield map(iter)
def flatten(L):
'''flatten the input list of lists to a flattened list
>>>list(flatten([1, 2, [3]])
[1, 2, 3]
>>>list(flatten([1, 2, [3, 4], [[5]])
[1, 2, ,3 ,4 ,5]
:param L: list of lists
:returns: generator with flattened list
'''
yield None
|
014e36604daf04ec73c663fe223cd445fcd01ca5 | garciacastano09/pycourse | /advanced/exercises/mod_05_functools/exercise_mod_05.py | 585 | 4.25 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
u"""
Created on Oct 5, 2013
@author: pablito56
@license: MIT
@contact: pablito56@gmail.com
Module 05 functools exercise
>>> it = power_of(2)
>>> it.next()
1
>>> it.next()
2
>>> it.next()
4
>>> it.next()
8
>>> it.next()
16
>>> it = power_of(3)
>>> it.next()
1
>>> it.next()
3
>>> it.next()
9
"""
from itertools import imap, count
def power_of(x):
"""Generator returning powers of the provided number
"""
# Try to use imap and count (from itertools module)
# You MUST use pow function in this exercise
return count(1)
|
e506aecc46760fd380700bdfc47ee96ab95e193a | garciacastano09/pycourse | /modules/mod_07_multiprocessing/mod_mp_fibonacci.py | 1,058 | 3.609375 | 4 | #-*- coding: utf-8 -*-
u"""
MOD: Multiprocessing with requests
"""
import multiprocessing
import requests
import threading
def fibonacci(n):
"""Return the nth fibonacci number"""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def get_fibonacci(num):
fib = fibonacci(30 + num)
print "GET FIBONACCI", num, fib
def get_fibonacci_3x_mp():
p = multiprocessing.Pool(3)
p.map(get_fibonacci, range(3))
def get_fibonacci_3x_th():
threads = []
for i in range(3):
t = threading.Thread(target=get_fibonacci, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
if __name__ == "__main__":
import time
start_th = time.time()
get_fibonacci_3x_th()
end_th = time.time()
start_mp = time.time()
p = multiprocessing.Pool(3)
p.map(get_fibonacci, range(3))
end_mp = time.time()
print "ELAPSED THREADING: {:.5f} seconds".format(end_th - start_th)
print "ELAPSED MULTIPROCESSING: {:.5f} seconds".format(end_mp - start_mp)
|
351bd55ea95d6cbc8180219ed9729a17bb81f3ee | test-for-coocn/test-back | /pyton/StatOneVar.py | 833 | 3.734375 | 4 | import math
def sqr(x):
return x * x
data = [66, 59, 62, 64, 63,
68, 65, 59, 68, 64,
65, 51, 67, 64, 83,
59, 61, 62, 57, 72,
65, 64, 54, 60, 53,
65, 67, 60, 53, 79,
74, 53, 61, 68, 75,
50, 57, 55, 66, 56,
55, 61, 70, 71, 49,
69, 70, 80, 73, 72]
n = len(data) # The number of scores
print("n =%d"%n)
print("Data...")
i = 1
for x in data:
print("%5d:"%i + " %f"%x)
i+=1
sum = 0.0
for x in data:
sum += x
mean = sum / n
print("Mean = %f"%mean)
ssum = 0.0
for x in data:
ssum += sqr(x - mean)
var = ssum / n
sd = math.sqrt(var)
print("Variance = %f"%var + " sd = %f"%sd)
uvar = ssum / (n - 1.0)
sd_uvar = math.sqrt(uvar)
print("Unbiased Var. = %f"%uvar + " sd(uvar) = %f"%sd_uvar) |
c3d462c1e5cd9bb28a67ee54f8f80c03ec14f06a | ACEinfinity7/Determinant2x2 | /deter_lib.py | 792 | 4.125 | 4 | def deter2x2(matrix):
"""
function to calculate the determinant of
the 2x2 matrix.
The determinant of a matrix is defined as
the upper-left element times the lower right element
minus
the upper-right element times the lower left element
"""
result = (matrix[0][0]*matrix[1][1])-(matrix[0][1]*matrix[1][0])
# TODO: calculate the determinant of the 2x2 matrix
return result
def deter3x3(matrix):
a = matrix[0][0]
b = matrix[0][1]
c = matrix[0][2]
d = matrix[1][0]
e = matrix[1][1]
f = matrix[1][2]
g = matrix[2][0]
h = matrix[2][1]
i = matrix[2][2]
result = (a*e*i) - (a*f*h) - (b*d*i) + (b*f*g) + (c*d*h) - (c*e*g)
return result
matrix_test = [[4,1,3],[5,3,1],[8,4,2]]
print(deter3x3(matrix_test))
|
6e090a6455cc172865ecf2d0b48110312068a0e4 | mitchellflax/lpsr-samples | /3-4FunctionsInTurtle/jennyc.py | 760 | 3.90625 | 4 | # myFractalTemplate.py
import turtle
def makeRhombus(myTurtle, side):
myTurtle.left(120)
myTurtle.forward(side)
myTurtle.left(120)
myTurtle.forward(side)
myTurtle.left(60)
myTurtle.forward(side)
myTurtle.left(120)
myTurtle.forward(side)
# make our turtle
squeak = turtle.Turtle()
squeak.color("red")
squeak.speed(8)
# squeak makes squares centered at the same point
# but going in a slightly rotated position with each loop
# and with a slightly smaller side length each time
length = 100
while length > 0:
makeRhombus(squeak, length)
# rotate and make the sides shorter
squeak.right(5)
length = length - 1
# wait to exit until I've clicked
turtle.exitonclick()
|
2cf3df6fe11dd50ef0b28adaea768e1125486be2 | mitchellflax/lpsr-samples | /Unit1-2Unordered/discounter.py | 301 | 4.09375 | 4 | # find out price from user
print("What is the price?")
price = int(input())
# calculate discount price
discount_price = .9 * price
# if user gets a discount, tell them.
# if not, tell them.
if price > 1000:
print("Your price is " + str(discount_price))
else:
print("Your price is " + str(price))
|
ef80b3131b124c9275235e8b3f2b36902d201380 | mitchellflax/lpsr-samples | /3-4FunctionsInTurtle/iris.py | 220 | 3.796875 | 4 | import turtle
t = turtle.Turtle()
turtle.colormode(255)
c = 50
while c > 0:
t.speed(10)
t.color(128,0,0)
t.forward(c * 3)
t.color(0,225,225)
t.right(135)
t.forward(c * 3)
c = c - 1
turtle.exitonclick()
|
e9ab612826132d35b03b98c46fdef6d7bfc3888e | mitchellflax/lpsr-samples | /3-8IntroToObjects/launch2.py | 235 | 3.515625 | 4 | import turtle
def drawSquare(ourTurtle):
ct = 0
while ct < 4:
ourTurtle.forward(100)
ourTurtle.left(90)
ct = ct + 1
shawn = turtle.Turtle()
shawn.backward(200)
drawSquare(shawn)
turtle.exitonclick()
|
5cab377556b008ff48dc6b8080f32f9221d9f0f8 | mitchellflax/lpsr-samples | /3-3IntroToTurle/square.py | 232 | 3.59375 | 4 | # square.py
import turtle
# make our turtle
rocky = turtle.Turtle()
# rocky makes a square
lines = 0
while lines < 4:
rocky.forward(150)
rocky.left(90)
lines = lines + 1
# wait to exit until I've clicked
turtle.exitonclick()
|
e354f576673621e8dc851bda02d495a5196f9f7d | mitchellflax/lpsr-samples | /3-6ATkinterExample/remoteControl.py | 464 | 4.28125 | 4 | import turtle
from Tkinter import *
# create the root Tkinter window and a Frame to go in it
root = Tk()
frame = Frame(root, height=100, width=100)
# create our turtle
shawn = turtle.Turtle()
# make some simple buttons
fwd = Button(frame, text='fwd', fg='red', command=lambda: shawn.forward(50))
left = Button(frame, text='left', command=lambda: shawn.left(90))
# put it all together
fwd.pack(side=LEFT)
left.pack(side=LEFT)
frame.pack()
turtle.exitonclick()
|
ed15cbf4fd067d8b9c8194d22b795cb55005797f | mitchellflax/lpsr-samples | /ProblemSets/PS5/teamManager.py | 1,525 | 4.3125 | 4 | # a Player on a team has a name, an age, and a number of goals so far this season
class Player(object):
def __init__(self, name, age, goals):
self.name = name
self.age = age
self.goals = goals
def printStats(self):
print("Name: " + self.name)
print("Age: " + str(self.age))
print("Goals: " + str(self.goals))
# default doesn't matter, we'll set it again
user_choice = 1
my_players = []
while user_choice != 0:
print("What do you want to do? Enter the # of your choice and press Enter.")
print("(1) Add a player")
print("(2) Print all players")
print("(3) Print average number of goals for all players")
print("(0) Leave the program and delete all players")
user_choice = int(raw_input())
# if the user wants to add a player, collect their data and make a Player object
if user_choice == 1:
print("Enter name:")
player_name = raw_input()
print("Enter age:")
player_age = int(raw_input())
print("Enter number of goals scored this season:")
player_goals = int(raw_input())
my_players.append(Player(player_name, player_age, player_goals))
print("Ok, player entered.")
# if the user wants to print the players, call printStats for each Player
if user_choice == 2:
print("Here are all the players...")
for player in my_players:
player.printStats()
if user_choice == 3:
# average = sum of all goals divided by count of players
sum = 0
count = 0
for player in my_players:
sum += player.goals
count += 1
avg = sum / count
print("Average goals: " + str(avg))
|
505b7944e773905bd8b1c5c8be4ce6d9a3b58730 | mitchellflax/lpsr-samples | /4-2WritingFiles/haikuGenerator2.py | 1,548 | 4.3125 | 4 | # haikuGenerator.py
import random
# Ask the user for the lines of the haiku
print('Welcome to the Haiku generator!')
print('Would you like to write your haiku from scratch or get a randomized first line?')
print('(1) I\'ll write it from scratch')
print('(2) Start me with a random line')
user_choice = int(raw_input())
# if the user wants to write from scratch, keep it simple
if user_choice == 1:
print('Provide the first line of your haiku:')
haiku_ln1 = raw_input()
# if the user is into getting a random starter, we have some work to do
else:
# open the rando file and bring in the random lines
starters_file = open('haikuStarters.txt', 'r')
starters_list = []
# get the starter lines and add them to a list
line = starters_file.readline()
while line:
starters_list.append(line)
line = starters_file.readline()
# spit the line back to the user
print('All right, here\'s your first line:')
haiku_ln1 = starters_list[random.randint(0,len(starters_list))]
print(haiku_ln1)
print('Provide the second line of your haiku:')
haiku_ln2 = raw_input()
print('Provide the third line of your haiku:')
haiku_ln3 = raw_input()
# Ask the user for the filename
print('What file would you like to write your haiku to?')
filename = raw_input()
# Write the haiku to a file
my_file = open(filename, 'w')
my_file.write(haiku_ln1 + '\n')
my_file.write(haiku_ln2 + '\n')
my_file.write(haiku_ln3 + '\n')
# Success! Close the file.
my_file.close()
print("Done! To view your haiku, type 'cat' and the name of your file at the command line.")
|
7e13745a73f6d77bbebcc267c0d4481ba6a86d3a | mitchellflax/lpsr-samples | /3-4FunctionsInTurtle/samplePatternTemplate.py | 495 | 4.25 | 4 | # samplePattern.py
import turtle
# myTurtle is a Turtle object
# side is the length of a side in points
def makeTriangle(myTurtle, side):
pass
# make our turtle
kipp = turtle.Turtle()
kipp.forward(150)
kipp.right(180)
# kipp makes triangles centered at a point that shifts
# and decreases in size with each loop
length = 100
while length > 0:
makeTriangle(kipp, length)
kipp.forward(3)
# make the sides shorter
length = length - 1
# wait to exit until I've clicked
turtle.exitonclick()
|
4a2107cbe21ebb9b44b81c31d82e40d6d309e117 | 110100100-b2/Goal-Keeping-Agent | /main.py | 2,249 | 4 | 4 | # Main Program can go here, we can load all other modules and run it in this .py file.
import turtle
# Importing Modules
import sys
sys.path.insert(0, './modules')
import functions
import ScoreBoard
start = False
wn = turtle.Screen()
wn.setup(width=839, height=1039, startx = 250, starty = 0) # dimensions and positioning of the screen
wn.title("Goal Keeping Agent")
wn.bgcolor("lightgreen")
wn.bgpic('./images/back.gif')
ScoreBoard.start_or_quit("START")
#Registering outside emoji shapes... you could think of the emojis as a way to extend the AI of the goalee, as he knows when to be happy, sad, etc
wn.register_shape('./images/emojis/sleeping.gif')
wn.register_shape('./images/emojis/happy.gif')
wn.register_shape('./images/emojis/lol.gif')
wn.register_shape('./images/emojis/sad.gif')
# Creating text file to write
functions.create_text('simulation_data.txt')
# Creating Goalie Turtle Object
goalie = turtle.Turtle()
#Creating Ball
ball = turtle.Turtle()
ball.shape('blank')
# We use this to determine the range which the Goalie can randomly appear
line = functions.draw_line(wn, goalie, 5)
#Essentially what this is doing is determining a random y value that lies along the line x = line[0], thus we can determine a random position <x, y> that will ALWAYS be along the line we've drawn
goalie.setpos(functions.setRandomPos(line))
#Setting emoji as goalie
goalie.shape('circle') #this allows the goalkeeper's face to appear above the goal line
goalie.shape('./images/emojis/sleeping.gif')
#Drawing Visualisation
graphicsTurtle = turtle.Turtle()
functions.graphics(wn, graphicsTurtle, line, 25)
def shoot():
global start
start_point = functions.getStartPoint()
if ball.position() == start_point or start == False:
start = True
functions.simulation(wn, ball, goalie, line, functions.generate_random_speed(), 1) #s = 1
def help(): #help menu
ScoreBoard.start_or_quit("START")
def quit(): #quit screen will hence be displayed with stats
ScoreBoard.start_or_quit("QUIT")
wn.bye()
def clearLines(): #clears dotted lines
ball.clear()
wn.onkey(shoot, "space")
wn.onkey(help, "i")
wn.onkey(clearLines, "c")
wn.onkey(quit, "q")
wn.listen()
wn.mainloop()
|
f9f2cbd0408139865c1cb412a80c1d60b5cc038c | Brian-Musembi/ICS3U-Unit6-04-Python | /array_average.py | 1,839 | 4.1875 | 4 | #!/usr/bin/env python3
# Created by Brian Musembi
# Created on June 2021
# This program prints a 2D array and finds the average of all the numbers
import random
def average_2D(list_2D):
# This function finds the average
total = 0
rows = len(list_2D)
columns = len(list_2D[0])
for row_value in list_2D:
for value in row_value:
total += value
average = total / (rows * columns)
return average
def main():
# This function handles input and prints a 2D array
print("This program prints a 2D array and finds the average "
"of all numbers.")
print("")
list_2D = []
# input
while True:
try:
rows_input = input("Input the number of rows you want: ")
rows = int(rows_input)
columns_input = input("Input the number of columns you want: ")
columns = int(columns_input)
print("")
# check for negative numbers
if rows > 0 and columns > 0:
for loop_counter_rows in range(0, rows):
temp_column = []
for loop_counter_columns in range(0, columns):
random_num = random.randint(0, 50)
temp_column.append(random_num)
print("{0} ".format(random_num), end="")
list_2D.append(temp_column)
print("")
average_of_array = average_2D(list_2D)
average_rounded = '{0:.5g}'.format(average_of_array)
print("")
print("The average of all the numbers is: {0}"
.format(average_rounded))
break
except Exception:
# output
print("Enter a number for both values, try again.")
if __name__ == "__main__":
main()
|
19e082e2f994b16d55ae046ac8c5baf727759888 | coreman14/Python-From-java | /CPRG251/Assignment 6/MovieManagementSystem.py | 4,716 | 3.578125 | 4 | from InputVerify import intInputCheck
from Movie import Movie
from random import shuffle
from dotenv import load_dotenv
import os
import psycopg2
from psycopg2 import OperationalError
class MovieManagementSystem():
"""Movie Management system redone in python
"""
def __init__(self):
load_dotenv()
"""Constructor that creates a blank list for movies
"""
self.movies = []
self.driver = psycopg2.connect(
database=os.getenv("DB"),
user=os.getenv("ESER"),
password=os.getenv("PASSWERD"),
host=os.getenv("HEST"),
port=5432
);
self.driver.autocommit = True
def displayMenu(self):
"""Displays menu and calls each method depending on choice
"""
option = -1
while (option != 5):
print("Movie management system")
print("1. Add new movie")
print("2. Generate list of movies released in a year")
print("3. Generate list of random movies")
print("4. Delete movie by id");
print("5. Exit")
option = intInputCheck("Enter an option: ")
if option == 1:
self.addMovie()
elif option == 2:
self.generateMovieListInYear()
elif option == 3:
self.generateRandomMovieList()
elif option == 4:
self.deleteMovieById()
elif option == 5:
self.driver.close()
print("Closing.")
else:
print("Invalid input, please try again.")
def deleteMovieById(self):
num = intInputCheck("Enter id of movie to delete:");
try:
cursor = self.driver.cursor();
cursor.execute("DELETE FROM moviemanagementdb.movies WHERE id ="+str(num)+";")
except OperationalError as e:
e.printStackTrace();
def addMovie(self):
"""Creates a new movie object from input
"""
name = ""
while name == "":
name = input("Enter title of movie: ")
year = intInputCheck("Enter year of movie: ")
mins = intInputCheck("Enter length of movie(In minutes): ")
try:
cursor = self.driver.cursor()
cursor.execute(f"INSERT INTO moviemanagementdb.movies (duration, title, year) VALUES ({mins}, '{name}', {year});")
except OperationalError as e:
e.printStackTrace()
print("\nMovie added\n")
def generateMovieListInYear(self):
"""Outputs text after finding a movie with matching input year
"""
duration = 0
year = intInputCheck("Enter year: ")
print("Movie list")
print("{:<5}{:<15s}{:<6}{}".format( "ID","Duration","Year","Title"))
try:
cursor = self.driver.cursor()
cursor.execute(f"SELECT * FROM moviemanagementdb.movies WHERE YEAR = {year};");
rs = cursor.fetchall()
for r in rs:
ids, mins, name, year = r
print("{:<5}{:<15}{:<6}{}".format( ids, mins, year, name))
duration += mins
if len(rs) == 0:
print("No movies were found with that year")
except OperationalError as e:
e.printStackTrace()
print(f"\nTotal Duration: {duration}")
print()
def generateRandomMovieList(self):
"""Outputs text after shuffling the arraylist that contains all of them,
checking if movie has already been outputted, then shuffling again if
needs to
"""
duration = 0
num = intInputCheck("Enter number of movies: ")
print("Movie list")
print("{:<5}{:<15s}{:<6}{}".format( "ID","Duration","Year","Title"))
try:
cursor = self.driver.cursor()
cursor.execute(f"SELECT * FROM moviemanagementdb.movies;");
rs = cursor.fetchall()
shuffle(rs)
shuffle(rs)
for r in rs:
ids, mins, name, year = r
print("{:<5}{:<15}{:<6}{}".format( ids, mins, year, name))
duration += mins
if num < 1:
break;
else:
num -= 1
except OperationalError as e:
e.printStackTrace()
print(f"\nTotal Duration: {duration}")
print()
|
c054b2383fd5b7d7a042d69673d2708aef9be0b1 | coreman14/Python-From-java | /CPRG251/Assignment 6/Movie.py | 2,090 | 4.40625 | 4 | class Movie():
def __init__(self, mins:int, name:str, year:int):
"""Creates an object and assign the respective args
Args:
mins (int): Length of the movie
name (str): Name of the movie
year (int): Year the movie was released
"""
self.mins = mins
self.year = year
self.name = name
def getYear(self):
"""Returns the year of the movie
Returns:
int: The year of the movie
"""
return self.year;
def setYear(self, year):
"""Sets the year of the movie
Args:
year (int): The year of the movie
"""
self.year = year;
def getMins(self):
"""Returns the length of the movie in minutes
Returns:
int: The length of the movie
"""
return self.mins;
def setMins(self,mins):
"""Sets the length of the movie in minutes
Args:
mins (int): The length of the movie
"""
self.mins = mins;
def getName(self):
"""Returns the name of the movie
Returns:
str: The name of the movie
"""
return self.name;
def setName(self, name):
"""Sets the name of the movie
Args:
name (str): The name of the movie
"""
self.name = name;
def __str__(self):
"""Returns a formatted string for output
Returns in order of (Mins,Year,Name)
Returns:
str: A string for output in a list (Mins,Year,Name)
"""
return f"{self.getMins():<15}{self.getYear():<6}{self.getName()}"
def formatForFile(self):
"""Returns the movie in a csv format
Returns in order of (Mins,Name,Year)
Returns:
str: The movie in a CSV format (Mins,Name,Year)
"""
return f"{self.getMins()},{self.getName()},{self.getYear()}\n"
|
76f4f8296437a2789453406a1dfb4335b00d818c | TomCantrell/Othello-Board-Game | /getLine.py | 1,242 | 3.59375 | 4 | """
Line of opponents pieces
"""
def getLine(board,who,pos,dir):
lst=list()
i=pos[0]
j=pos[1]
if board[i][j]!=0:
return lst
while True:
if i+dir[0]==8 or j+dir[1]==8: ######need to deal with these better
break
if i+dir[0]==-1 or j+dir[1]==-1:
break
if board[i+dir[0]][j+dir[1]]==0:
lst=list()
#print("You can't do that m8")
break
if board[i+dir[0]][j+dir[1]]==who:
break
lst.append((i+dir[0],j+dir[1]))
i+=dir[0]
j+=dir[1]
return lst
"""
############Testing
"""
board = [[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1],
[0,0,0,0,1,2,2,0],
[0,0,0,1,1,2,0,0],
[0,0,0,2,2,2,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]]
"""
print(getLine(board,1,(6,3),(-1,1)))
print(getLine(board,2,(4,2),(0,1)))
print(getLine(board,2,(3,3),(1,1)))
print(getLine(board,1,(6,6),(-1,-1)))
print(getLine(board,1,(4,6),(0,-1)))
print(getLine(board,1,(6,4),(-1,0)))
print(getLine(board,2,(2,5),(1,0)))
print(getLine(board,1,(2,6),(1,-1)))
print(getLine(board,1,(2,5),(1,0)))
print(getLine(board,1,(6,6),(0,-1)))
"""
|
46ba9a68d7ed4616cbdf597f77c9cfcca7c02132 | TomCantrell/Othello-Board-Game | /game.py | 23,523 | 4.03125 | 4 |
import othello as pf
pf.play()
"""
A Python module for the othello game.
This module comprises of many functions which all contribute to the final main
function play() which deals with the actual game flow.
Full name: Thomas Cantrell
StudentId: 10170539
Email:thomas.cantrell@student.manchester.ac.uk
"""
def newGame(player1,player2):
"""
This function takes the names of players 1 and 2, then it returns a
dictionary containing a variable who (initialsed as who=1) and a list of
lists which is the initialised board variable.
"""
game = dict()
game["player1"] = str(player1) #Black player
game["player2"] = str(player2) #White player
game["who"] = 1
game["board"] = [ [0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,2,1,0,0,0],
[0,0,0,1,2,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0]]
# TODO: Initialize dictionary for a new game
return game
#########################################################################
# TODO: All the other functions of Tasks 2-12 go here.
# USE EXACTLY THE PROVIDED FUNCTION NAMES AND VARIABLES!
def printBoard(board):
"""
This function takes a list of lists and prints out a nicely formatted
board. Columns are labelled at the top of the board and the bottom of board
with a through h, rows are labelled either side of the board with 1 through
8.
Two lists of strings are initialised, columns and row with columns
labelling the columns and row used for making the edge of the board clear.
A variable k is then initialised and a for loop goes through each list in
board initialising an empty list lst each time. If the elements in the list
are non-zero (1 or 2), the if statements then add an X or O accordingly, if
an element is zero then an empty string is simply added.
This is then printed with vertical bars in between X's, O's and empty
strings. Furthermore at the bottom of the board the letters are added to
denote the columns again much like before at the top of the board.
"""
columns = ["a","b","c","d","e","f","g","h"]
row = ["+","+","+","+","+","+","+","+","+"]
print(" "*1,"|{}|{}|{}|{}|{}|{}|{}|{}|\n".format(*columns)," {}-{}-{}-{}-{}-{}-{}-{}-{}".format(*row))
k=0
for i in range(len(board)):
lst=list()
k += 1
for j in board[i]:
if j==0:
lst.append(' ')
if j==1:
lst.append('X')
if j==2:
lst.append('O')
print(k,"|{}|{}|{}|{}|{}|{}|{}|{}|".format(*lst),k)
print(" {}-{}-{}-{}-{}-{}-{}-{}-{}\n".format(*row)," |{}|{}|{}|{}|{}|{}|{}|{}|".format(*columns))
def strToIndex(s):
"""
This function takes a string s and then returns an index in the form of a
tuple. This tuple refers to the position in the list of lists in the board
variable. The first few lines aim to deal with the various versions of a
string a user can input i.e " 4 c" returns the same thing as "c4".
Firstly a list called lst is created by taking a list of s.strip(), where
s.strip() strips the spaces (if there are any) from the beginning and end of
the string. Then the for loop removes and spaces in between so that there
is only characters left in the list and no spaces. The if statement then
checks if the first element in the list is a digit (to check whether the
user has entered "4c" or "c4" and deal with each of them accordingly), this
is done with the function .isdigit(). If it is a digit then the list is
reversed using the reverse function.
Then two lists are initialised col and row, which refer to the columns and
rows respectively. Furthermore k is initialsed at 0 and c at -1.
Then a for loop, which loops over col checks if any of the elements in col
are equal to the lower case zero-th element in lst also while the variable
k is increasing each loop. lst[0].lower is used because the user may have
entered "C4" instead of "c4", hence it means the user can enter a move
in upper/lowercase. Then the variable c=k-1 gives the indice of the
associated column position (takes a value in 0,..,7).
However if c==-1 after the for loop has covered all elements in col, then a
valueError is raised as this means the move that has been entered must not
be valid.
The variable l is then initialised as l=0, then a for loop over row checks
if any of the elements are equal to the 2nd element in lst (lst[1]). It
makes sense to take int(lst[1]) as we know this will a number otherwise a
valueError would've been raised. Similarly as with the other for loop r=l-1
gives the associated board row position.
"""
lst=list(s.strip())
for _ in s.strip():
if _==' ':
lst.remove(_)
if lst[0].isdigit()==True:
lst=list(reversed(lst))
if len(lst)!=2:
raise ValueError("Not valid")
col=["a","b","c","d","e","f","g","h"]
row=[1,2,3,4,5,6,7,8]
k=0
c=-1
for i in col:
k+=1
if i==lst[0].lower():
c=k-1
if c==-1:
raise ValueError("Not a Valid move")
r=-1
l=0
for j in row:
l+=1
if j==int(lst[1]):
r=l-1
if r==-1:
raise ValueError("Not a Valid move")
return (r,c)
def indexToStr(t):
"""
This function takes a tuple and then returns a string, which refers to a
board position on the printed board.
A list col is initialised which refers to the columns of the printed board.
The function returns a string made up of col[t[1]] (t[1] refers to the
second position in the tuple) and the row is made up from t[0] then add 1.
"""
col = ["a","b","c","d","e","f","g","h"]
return col[t[1]]+str(t[0]+1)
def loadGame():
"""
This function takes no arguments, and attempts to load a dictionary from a
.txt file. It then returns a dictionary with player1 and player2 assigned
to the first two lines of the text file. The variable who is then set equal
to the third line, and the variable board is set equal to lines 3 through
11.
Firstly the function initialises an empty dictionary called dct along with
a list lst. Then the function attempts to open a file called game.txt and
this assigned as g, it is being opened for reading. Then this file is read
line by line and since the file is in a particular format, the names of the
players, who and the board can all be obtained by simply setting the lines
of this file equal to them. For example the board variable takes lines 3 to
11, and similarly the first 2 lines will be the players names.
If the file cannot be opened because it cannot find a text file called
game.txt then an exception for FileNotFoundError prints "The file couldn't
be found".
After this three if statements check that the first two lines are indeed
string, if the board is the right type and if who is equal to an integer.
Hence the format of the text file has been checked, if it is not of the
correct form a ValueError is raised.
The function returns the dictionary dct, with player1 and player2's
names assigned along with the board and who.
"""
try:
with open("game.txt",mode="r",encoding="utf8") as g:
dct = dict()
lst=list()
for line in g:
lst.append(line.rstrip("\n").strip()) #.rstriphttps://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline-in-python
tmp=list()
for _ in range(3,11):
tmp.append(lst[_])
bd=list()
for i in tmp:
ls=list()
for _ in i.split(","):
ls.append(int(_))
bd.append(ls)
dct["player1"]=lst[0]
dct["player2"]=lst[1]
dct["who"]=int(lst[2])
dct["board"]=bd
if type("player1") and type(dct["player2"]) != str:
raise ValueError
if type(dct["board"])!=list:
raise ValueError
if type(dct["who"]) != int:
raise ValueError
return dct
except FileNotFoundError:
print("The file couldn't be found \n")
except ValueError:
print("File not of correct format \n")
def getLine(board,who,pos,dir):
"""
This function takes 4 input arguments namely board, who, pos (position) and
dir (direction) and it then returns a list of oppents pieces which form a
line. This function initialises an empty list then checks the next position
in the direction given and then checks that it is not equal to zero i.e if
that particular position is already occupied by a players piece. Then it
checks which player occupies this piece, if it is the same as the variable
who, it then stops and doesn't check the rest of line as this wouldn't be
a valid move.
However if the next piece in the given direction is indeed the opponents
piece, the position will be added to the empty list and move on to the
next piece in the given direction. It will continue to do so until it
reaches a position occupied by the value who or zero. If the line of
opponents pieces ends in a zero, the list lst is set empty and thus an
empty list is returned.
Otherwise the line of opponents pieces ends in the value of who i.e the
value of who for the current player. Thus a line of opponents pieces is
obtained and the list of positions of these pieces is returned.
"""
lst=list()
i=pos[0]
j=pos[1]
if board[i][j]!=0:
return lst
while True:
if i+dir[0]==8 or j+dir[1]==8:#
lst=list()
break
if i+dir[0]==-1 or j+dir[1]==-1:
lst=list()
break
if board[i+dir[0]][j+dir[1]]==0:
lst=list()
break
if board[i+dir[0]][j+dir[1]]==who:
break
lst.append((i+dir[0],j+dir[1]))
i+=dir[0]
j+=dir[1]
return lst
def getValidMoves(board,who):
"""
This function takes 2 input arguments namely the variable board and the
variable who.
This function goes through each board position and at each position it goes
through a list of directions making use of the getLine function above. If
the list which the getLine function returns is non empty i.e there are
valid moves with line(s) of opponents pieces to be obtained. Then the
position, at which the getLine function is being tested, is added to a list
lst.
This function then returns a list of positions on the board where the
player who could potentially go.
"""
dirs = [(0,1),(0,-1),(1,0),(-1,0),(-1,1),(1,-1),(-1,-1),(1,1)]
lst=list()
for i in range(8):
for j in range(8):
for k in dirs:
if len(getLine(board,who,(i,j),k))!=0:
lst.append((i,j))
return list(set(lst))
def makeMove(board,move,who):
"""
This function takes 3 input arguments namely board, move (a tuple
refering to a board position) and the variable who.
A list of directions is first initialsed, along with an empty list. A for
loop then goes through all the directions and checks if getLine function
produces a non empty list with each direction. If the list is indeed non
empty, then a for loop goes through the list of opponents pieces (list of
tuples from getLine) and then adds it to lst along with the position "move"
the player wishes to make.
If the list lst is non empty, a for loop then adds it to the board changing
the positions to the value of the variable who. An updated board is then
returned.
"""
dirs = [(0,1),(0,-1),(1,0),(-1,0),(-1,1),(1,-1),(-1,-1),(1,1)]
lst=list()
for i in dirs:
if len(getLine(board,who,move,i))!=0:
for j in getLine(board, who, move, i):
lst.append(j)
lst.append(move)
for k in lst:
board[k[0]][k[1]]=who
return board
def scoreBoard(board):
"""
This function takes 1 input argument board and returns an integer.
Two variables are initialsed p1score and p2score, these refer to player1's
score and player2's score respectively. Then two for loops go through the
board positions and add to the initalised p1score and p2score if a position
is occupied by a 1 or 2.
The function then returns p1score-p2score, so if scoreBoard is positive
there are more 1's than 2's (giving an adventage to player1), and if
scoreBoard is negative then there are more 2's than 1's (giving an
advantage to player2). If scoreBoard is equal to zero then there is no
advantage to either player.
"""
p1score=0
p2score=0
for i in board:
for j in i:
if j==1:
p1score+=1
if j==2:
p2score+=1
return p1score-p2score
def suggestMove1(board,who):
"""
This function takes 2 input arguments board and who. Two lists are
initialised and lst is set equal to getValidMoves(board,who), this is so
that getValidMoves function is only called once, so it is more efficient.
The modules copy and random are imported at the beginning of the function.
Then a for loop goes through the valid moves of the player who, the
board2 variable is assigned to a deepcopy of the original board. In each
loop makeMove(board2,i,who) (where i represents a valid move) is evaluated
and then the scoreBoard function evaluates the returned board from
makeMove. This score is then added to the initialised empty list t, thus
creating a list of scores from potential moves a player could make.
Then there are two if statements where one finds the maximum scoreBoard
value and then adds the position(s) at which this maximum scoreBoard value
occurs to the list l (which was initialised at the beginning). The other if
statement finds the minimum scoreBoard value and adds the position(s) where
this occurs to the list l. If there are no valid moves available then None
is returned.
After the list l is created, random.choice(l) chooses at random a move
which achieves the largest score to the advantage of player who.
Random.choice is used because there may be more than one board position
which achieves max/minimum score. Hence the function returns a tuple
chosen at random from the list l.
"""
lst=getValidMoves(board,who)
t=list()
l=list()
import copy
import random
for i in lst:
board2=copy.deepcopy(board)
t.append(scoreBoard(makeMove(board2,i,who)))
if who==1:
for j in range(len(t)):
if t[j]==max(t):
l.append(lst[j])
if who==2:
for j in range(len(t)):
if t[j]==min(t):
l.append(lst[j])
if len(l)==0:
return None
return random.choice(l)
##########################################################################
# ------------------- Main function --------------------
def play():
"""
This function is the main part of the module and takes care of the overall
operation of the game. This function takes no input arguments.
Firstly the module time is imported, then a welcome message is displayed
to the user, along with another message on what to input if the user wishes
to load a game or play the computer. A while loop is then used for asking
the user(s) names and the while loop means that the names of either player
can be repeatedly asked for if the user is entering empty strings, also c
can be typed in as either player 1 or 2. Furthermore the use of
.capitalize() means that the name of player 1 and 2 are capitalised.
Then a dictionary is initialised called dct, this is set equal to the
dictionary returned from the function newGame(player1,player2) as this
initialises the starting board and sets who equal to 1. If l is typed in as
player1 then the function loadGame() opens a game from a text file and
uses the names and board from that to jump straight into a game, this is
done by setting loadGame() equal to dct.
"""
##welcome message
import time
print("-"*55)
print("*"*55)
print("****"+" "*8+"WELCOME TO TOM'S OTHELLO GAME!"+" "*8+"****")
print("*"*55)
print("-"*55, "\n")
print("Enter the players' names, or type 'C' to play the computer or 'L' to load a game.\n")
while True:
dct=dict()
player1=input("Name of player 1: ").capitalize()
if not player1:
player1=input("Name of player 1: ").capitalize()
if player1=="L":
if loadGame() is None:
player1=""
print("Please enter a player name or attempt to load the game again")
else:
print("Entering loaded game. \n")
dct=loadGame()
break
if player1:
while True:
player2=input("Name of player 2: ").capitalize()
if not player2:
player2=input("Name of player 2: ").capitalize()
if len(player2)!=0:
dct = newGame(player1,player2)
break
print("Enter q to quit the game.\n Let's play!!!!")
break
"""
After the dictionary has been set, the game begins and the user can enter q
when it is their move to quit the game. The first player is always (X) and
the second (O) and this is shown to the user(s) at the beginning. Two
variables s and k are initialised at zero, then printBoard() prints the
starting board (it would print the board from the text file if l was
inputted as player 1).
Inside the while loop another variable d is initialised as an empty string.
Then an if and else statement checks whether s is even or odd and this
determines the variable who and ensures that it alternates players each
turn. The variable d is also set to the name of player1 or player2
depending on whether s is odd/even.
Another variable lst is set to getValidMoves(board, who), thus obtaining a
list of the valid moves of that particular player. If lst is empty then
k increases by 1 and the user is informed that there are no valid moves for
that particular player, s is also increased by 1 thus moving it on to the
next players turn. The variable k is set back to zero if the next player
can go, otherwise k will increase to 2 and thus the game will be finished
and the break statement breaks out of the while loop.
Next, if lst is non-empty then it checks the name of the player and sees if
it is the computers turn. If it is indeed the computers turn "Computer is
thinking..." is printed and time.sleep(2) represents the thinking time.
A new variable move is then set equal to suggestMove1(board,who). Otherwise
it'll be the users turn, so the user is asked to input a move, this is then
turned into a string. Here it is also checked if the move is equal to "q"
which would quit the game with the break statement.
Then it attempts to check whether or not its a valid move via the
strtoIndex function. If its not a valid move or if strtoIndex raises an
error, it raises an error and informs the user that it is not a valid move.
Otherwise it is a valid move and this move is then made via the makeMove
function and the new board is set to dct["board"], this is then displayed
to the user, k is then set to zero as a move has been made and s has
increased so that in the next loop it is the other players turn.
If the scoreBoard function returns a positive value for this new board then
player1 has the advantage so this is displayed to the user(s), a similar
thing is done if scoreBoard is negative. If scoreBoard returns zero then
there is no advantage and so "No advantage is printed".
Outside of this while loop the scores are added up and the winner is
decided, this is then displayed to the user(s).
"""
print(dct["player1"],"= X",8*" ",dct["player2"],"= O")
s=0
k=0
printBoard(dct["board"])
while True:
d=""
board=dct["board"]
if s%2==0:
who=1
d=dct["player1"]
print(dct["player1"],"'s move")
else:
who=2
d=dct["player2"]
print(dct["player2"],"'s move")
lst=getValidMoves(board, who)
if len(lst)==0:
k+=1
print("No Valid Moves for", d, ", skipping player. \n")
s+=1
if k==2:
print("--------------"+" "*8+"Game Finished!"+" "*8+"---------------\n")
break
if len(lst)!=0:
if d=="C":
print("Computer is thinking...")
time.sleep(2)
move=indexToStr(suggestMove1(board,who))
print("The Computer chose ",indexToStr(suggestMove1(board,who)))
else:
move=str(input("Please enter a move: "))#### Tom (X), C (O)
if move=="q":
print("--------------"+" "*8+"Game Stopped"+" "*8+"---------------\n")
break
try:
if strToIndex(move) not in lst:
raise IndexError
if strToIndex(move) in lst:
for i in getValidMoves(board,who):
if i==strToIndex(move):
dct["board"]=makeMove(board, strToIndex(move), who)
printBoard(dct["board"])
k=0
s+=1
except IndexError:
print("Not a valid move\n")
printBoard(dct["board"])
pass
except ValueError:
print("Not a valid move\n")
printBoard(dct["board"])
pass
if scoreBoard(board)>0:
print("Advantage", dct["player1"], "(X)")
if scoreBoard(board)<0:
print("Advantage", dct["player2"], "(O)")
if scoreBoard(board)==0:
print("No Advantage")
#p1score=0
#p2score=0
#for i in board:
# for j in i:
# if j==1:
# p1score+=1
# if j==2:
# p2score+=1
#########Scoreboard score
print(scoreBoard(board))
if scoreBoard(board)>0:
print(dct["player1"], "wins!!")
#print(dct["player1"], "(X) wins! With a score of", p1score)
#print(dct["player2"], "(O) scores", p2score)
if scoreBoard(board)<0:
print(dct["player2"], "wins!!")
#print(dct["player2"], "(O) wins! With a score of", p2score)
#print(dct["player1"], "(X) scores", p1score)
if scoreBoard(board)==0:
print("No winner, it's a draw")
# the following allows your module to be run as a program
if __name__ == '__main__' or __name__ == 'builtins':
play()
|
c83e073c42b1e784ebad334a97c1399c0083a5a7 | MajidSalimi/Python-Learning | /Input/Input.py | 236 | 3.984375 | 4 | name=input('Please Enter Your Name:')
number=int(input('Please enter your age:'))
height=float(input('Please enter your age:'))
print('Name:',name.title())
print('Age:',number)
print('Height:',height)
print('Age/10=',eval('number/10')) |
e71728e73143aafec0819f03fb2cadd550c5de49 | 84omidreza/jalase8 | /complex .py | 1,056 | 4.0625 | 4 | def sum_complex(x , y ):
result_calculation={}
result_calculation['kamel'] = x["kamel"] + y["kamel"]
result_calculation['mohomi'] = x["mohomi"] + y["mohomi"]
return result_calculation
def sub_complex(x , y):
result_calculation={}
result_calculation["kamel"] = x ["kamel"] - y ["kamel"]
result_calculation["mohomi"] = x ["mohomi"] - y ["mohomi"]
return result_calculation
def mult_complex(x , y):
result_calculation={}
result_calculation["kamel"] = x["kamel"] * y["kamel"]
result_calculation["mohomi"] = x["mohomi"] * y ["mohomi"]
return result_calculation
def show_menu():
print("1- sum number complex: ")
print("2- sub number complex: ")
print("3- mult number complex: ")
print("4- exit: ")
choice= int(input("enter one choice for calculation : "))
if choice == 1:
sum=sum_complex(a,m)
print (sum)
elif choice == 2 :
sub=sub_complex(a,m)
print (sub)
elif choice == 3:
mul=mult_complex(a,m)
print (mul )
elif choice == 4:
exit() |
34d705727c44475ce5c1411558760a01969ef75b | Syvacus/python_programming_project | /Session number 2.py | 2,246 | 4.1875 | 4 | # Question 1
# Problem: '15151515' is printed because the chairs variable is text instead of a number
# Solution: Convert the chairs variable from text to number
chairs = '15' # <- this is a string (text) rather than an int (number)
nails = 4
total_nails = int(chairs) * nails # <- convert string to int by wrapping it in the int() function
message = 'I need to buy {} nails'.format(total_nails)
print(message)
#my solution
nails = 4
chairs = 15
total_nails = nails * chairs
message = "I _need _to _buy" + str (total_nails) +"nails"
print(message)
# Question 2
# Problem: When the code is run, we get a error: 'NameError: name 'Penelope' is not defined'
# this is because Python is interpreting Penelope as a variable, rather than a string
# Solution: To store text, it needs to be enclosed in either '{text}' or "{text}"
my_name = 'Penelope' # <- store the name as text by enclosing in single or double quotes
my_age = 29
message = 'My name is {} and I am {} years old'.format(my_name, my_age)
print(message)
#my solution
my_name = "Penelope"
my_age = 29
message = (my_name, my_age)
print(message)
# Question 3
# Task: I have a lot of boxes of eggs in my fridge and I want to calculate how many omelettes I can make.
# Write a program to calculate this.
# Assume that a box of eggs contains six eggs and I need four eggs for each omelette, but I should be
# able to easily change these values if I want. The output should say something like "You can make 9
# omelettes with 6 boxes of eggs".
boxes = 7
eggs_per_box = 6
eggs_per_omelette = 4
total_number_of_eggs = boxes * eggs_per_box
# Calculate whole number of omelettes
number_of_whole_omelettes = total_number_of_eggs // eggs_per_omelette
left_over_eggs = total_number_of_eggs % eggs_per_omelette
message = 'Using {} boxes of eggs, you can make {} whole omelettes, with {} eggs left over.'
print(message.format(boxes, number_of_whole_omelettes, left_over_eggs))
# Calculate number of omelettes (as a decimal)
number_of_decimal_omelettes = total_number_of_eggs / eggs_per_omelette
message = 'Using {} boxes of eggs, you can make {} omelettes.'
print(message.format(boxes, number_of_decimal_omelettes))
|
320afdfbe5f55615bdbb72e77953a8590e2c840d | NapsterZ4/python_basic_course | /excepciones.py | 1,216 | 3.890625 | 4 | def suma(n1, n2, n3) -> int:
return n1 + n2 + n3
def resta(n1, n2, n3) -> int:
return n1 - n2 - n3
def multiplicacion(n1, n2, n3) -> int:
return n1 * n2 * n3
def division(n1, n2, n3):
# Validar division entre 0
try:
return n1 / n2 / n3
except ZeroDivisionError:
print("No es divisible entre 0")
while True:
try:
a = int(input("Ingrese el primer numero: "))
b = int(input("Ingrese el segundo numero: "))
c = int(input("Ingrese el tercer numero: "))
operacion = int(input("Introduce el numero de operacion "
" 1. Suma"
" 2. Resta"
" 3. Multiplicacion"
" 4. Division: "))
break
except ValueError:
print("Ingrese datos validos")
if operacion == 1:
print("La suma es: ", suma(a, b, c))
elif operacion == 2:
print("La resta es: ", resta(a, b, c))
elif operacion == 3:
print("La multiplicacion es: ", multiplicacion(a, b, c))
elif operacion == 4:
print("La division es: ", division(a, b, c))
else:
print("La operacion no fue realizada con exito, ingrese un numero entre 1 y 4")
|
acab7dba850041e5b5283d1a661a00a76b17a8c1 | NapsterZ4/python_basic_course | /tuplas.py | 492 | 4.1875 | 4 | # listas que no pueden modificarse
a = (1, 4, 5.6, "Juan", 6, "Maria")
b = ["Jorge", 5, "Peru", 90]
tup2 = 34, "Javier", 9.6, "Murillo"
c = tuple(b) # Convirtiendo la lista en tupla
d = list(a) # Conviertiendo la tupla en una lista
print(tup2)
print(a)
print(c) # Resultado de la lista convertida en tupla
print(d) # Resultado de la tupla convertida en lista
print("Elementos de la tupla: ", len(a)) # Contar elementos de la tupla
print("Posicion de un elemento en la tupla: ", d[4])
|
648d64ce99d1259b3be83d322f56eea46af8e5c4 | kylemingwong/pytest | /pytest/some-test.py | 192 | 3.734375 | 4 | class MyClass(object):
gender = 'Male'
def __init__(self,who):
self.name = who
def sayHi(self):
print 'Hello, '+self.name
me = MyClass('Tom')
me.sayHi()
|
406ab8c99fbc44eb3d590c6b3c1646d6d0c44ee8 | labyrlnth/codeeval | /easy/word_to_digit.py | 546 | 3.84375 | 4 | import sys
dic = {'one':'1',
'two':'2',
'three':'3',
'four':'4',
'five':'5',
'six':'6',
'seven':'7',
'eight':'8',
'nine':'9',
'zero':'0'}
def word_to_digit(word):
return dic[word]
def main():
f = open(sys.argv[1], 'r')
lists = f.readlines()
for line in lists:
if line:
line = line.strip()
words = line.split(';')
print "".join(map(word_to_digit, words))
if __name__ == "__main__":
main() |
afe56fea320586725a5e430d8ae2cfafde68fa0c | dipanjank/aws-lambda-simple-forecast | /chalicelib/forecaster.py | 1,131 | 3.8125 | 4 | import pandas as pd
def average_forecast(data_dict):
"""
Take daily data and return the average of the training data as forecast from
``data_dict['start_date']`` and ``data_dict['end_date']``. Dates expected in YYYY-MM-DD
format.
:param data_dict: The train data and the predict start and end dates.
:return: The prediction result as a list of dictionaries, with keys 'date' and 'data'.
"""
train_df = pd.DataFrame(data_dict['train_data'])
if 'date' not in train_df.columns:
raise ValueError('No "date" column provided.')
if 'data' not in train_df.columns:
raise ValueError('No "data" column provided.')
avg_forecast = train_df.data.mean()
# Return the average value as the forecast for each day between start and end date
predict_dates = pd.date_range(
start=data_dict['start_date'],
end=data_dict['end_date'],
freq='D'
)
predict_df = pd.Series(index=predict_dates, name='data', data=avg_forecast)
return [
{'date': date.strftime('%Y-%m-%d'), 'data': data}
for date, data in predict_df.items()
]
|
f7e1d7c9e73023370e1a1d6c42d2f372288ab91c | krenevych/ClassWork | /Stat1/OOP4/Car.py | 780 | 3.859375 | 4 | from Mat.OOP4.Figure import Rectangle, Circle, Figure
from turtle import *
class Car(Figure):
def __init__(self, x, y, color):
super().__init__(x, y, color)
self.properties = [
Rectangle(self._x, self._y, 300, 70, "red"),
Rectangle(self._x + 50, self._y + 70, 200, 30, "red"),
Circle(self._x + 50, self._y, 20, "black"),
Circle(self._x + 250, self._y, 20, "black"),
Rectangle(self._x + 50, self._y + 75, 100, 10, "red")
]
def _draw(self, color):
for el in self.properties:
el._draw(color)
if __name__ == "__main__":
# Ініціалізація turtle
home()
delay(10)
car = Car(-100, 100, "red")
car.show()
car.hide()
mainloop() |
5bc96545ae14cf28597903acce40e1627537cb68 | krenevych/ClassWork | /Stat1/L4/l4_4.py | 146 | 3.765625 | 4 | counter = 0
while True:
n = int(input())
if n == 0:
break
if n % 2 == 0:
continue
counter += 1
print(counter)
|
d27062b7f9bc4856251ea85a713c23759f51fc06 | krenevych/ClassWork | /Stat1/OOP11/examle.py | 719 | 3.65625 | 4 | from tkinter import *
root = Tk() # створюємо головне вікно програми
def hello():
res = ent.get()
# print("Hello, %s!" % res)
lab["text"] = "Hello, %s!" % res
# Поле введення
ent = Entry(root, font="Arial 18")
ent.pack()
lab = Label(root,
font="Arial 18",
bg = "red",
text="Результат")
lab.pack()
btn = Button(root, # батьківське вікно
text="Click me", # надпис на кнопці
width=30, height=5, # ширина та висота
bg="white", fg="black", # колір фону і напису
command=hello)
btn.pack()
root.mainloop()
|
c4d001af6e3b30dcd53e358eb4f91a07a32325d7 | krenevych/ClassWork | /Mat/L13/t4.py | 2,077 | 3.578125 | 4 | def readMatrix(file_name):
try:
with open(file_name, "r") as f:
matrix = []
for line in f:
row = [float(el) for el in line.split()]
matrix.append(row)
return matrix
except FileNotFoundError:
return None
except ValueError:
print("Wrong file format")
return None
def writeMatrix(M, file_name):
with open(file_name, "w") as f:
for row in M:
print(*row, file=f)
def sumMatrix(A, B):
assert len(A) == len(B) # кількість рядків у обох матрицях однакова
assert len(A[0]) == len(B[0]) # кількість стовпчиків у обох матрицях однакова
C = []
for i in range(len(A)):
C.append([])
for j in range(len(A[i])):
C[i].append(A[i][j] + B[i][j])
return C
def mult(A, B):
assert len(A[0]) == len(B) # кількість стовпчиків лівої матриці
# дорівнює кількості рядків правої матриці
C = []
for i in range(len(A)):
row = [0] * len(B[0])
C.append(row)
n = len(C) # кількість рядків
m = len(C[0]) # кількість стовпчиків
for i in range(n):
for j in range(m):
for k in range(m):
C[i][j] += A[i][k] * B[k][j]
return C
def isMartEqual(A, B):
assert len(A) == len(B)
n = len(A) # кількість рядків
assert len(A[0]) == len(B[0])
m = len(A[0]) # кількість стовпчиків
for i in range(n):
for j in range(m):
if A[i][j] != B[i][j]:
return False
return True
A = readMatrix("t4A.txt")
B = readMatrix("t4B.txt")
# C = readMatrix("t4C.txt")
# AB = mult(A, B)
# if isMartEqual(AB, C):
# print("A * B = C")
# else:
# print("A * B != C")
C = mult(A, B)
writeMatrix(C, "t4C1.txt")
# C = sumMatrix(A, B)
# writeMatrix(C, "t4_sum_out.txt")
print(C)
|
7a231c32014c5e43a13fb12339b60197ac660660 | krenevych/ClassWork | /Mat/L3/l3_2.py | 154 | 3.671875 | 4 |
# n = 17
# 2 4 8 16
n = int(input())
res = 2 # 2^1
while res < n:
print(res, end=" ")
# print(res, end="***")
# print(res)
res *= 2
|
3f1ac1cf6059b10139c752dae2f947a297c31d29 | krenevych/ClassWork | /Mat/L8/l8_1.py | 284 | 3.59375 | 4 |
# 0! = 1
# 5! = 1 * 2 * 3 * 4 * 5 = 4! * 5
# f(n) = n!
# f(0) = 1
# f(n) = f(n-1) * n
def f(n):
if n == 0: # термінальний випадок
return 1
else: # рекурсивна гілка
prev = f(n - 1)
return prev * n
print(f(5)) |
8fe31d5e7a1371e9725898168743b71e9db08b84 | krenevych/ClassWork | /Mat/L6/l6_7.py | 80 | 3.65625 | 4 |
s = input()
lst = s.split()
for word in lst:
print(len(word), end=" ")
|
d587eb1da3a6ee2fc2d067a7824e4ac060d2ee8f | krenevych/ClassWork | /Mat/OOP11/t3.py | 1,018 | 3.5625 | 4 | from tkinter import *
from tkinter.filedialog import askopenfilename
def readFile(file_name, textbox : Text):
textbox.delete('1.0', END)
with open(file_name, encoding="UTF-8") as f:
textbox.insert('1.0', f.read())
def main():
root = Tk() # створюємо головне вікно програми
global textbox
textbox = Text(root, # батьківський віджет
font='Arial 14', # шрифт
wrap='word') # чи переносити текст по словах
textbox.pack()
btn = Button(root,
width=20, height=2,
text="Open file",
font="Перевірити",
command=dialog_open_file
)
btn.pack()
root.mainloop() # запускаємо цикл головного вікна
def dialog_open_file():
global textbox
filename = askopenfilename()
readFile(filename, textbox)
if __name__ == "__main__": main() |
4fe1ec4fae56b4a2b96ae9daa9e6a5712598707d | krenevych/ClassWork | /Stat1/L4/l4_5.py | 275 | 3.59375 | 4 | n = int(input())
# 2 * 3 * 5 = 30
# 7 , 49, 343 [1, n^0.5]
if n % 2 == 0:
print(2)
else:
flag = True
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
print(i)
flag = False
break
if flag:
print(n) |
c526d4fd974de335e8aa26447a6442bfcdbce4be | krenevych/ClassWork | /Mat/OOP11/t2.py | 662 | 4.0625 | 4 | from tkinter import *
root = Tk() # створюємо головне вікно програми
entry = Entry(
root,
width=70,
font="Arial 20",
)
listbox = Listbox(
root,
width=70,
height = 15
)
def show_words():
global entry, listbox
content : str = entry.get()
words = content.split()
listbox.delete(0, END)
for word in words:
listbox.insert(END, word)
btn = Button(
root,
width=20, height=5,
text="Hello!",
font="Перевірити",
command=show_words
)
entry.pack()
listbox.pack()
btn.pack()
root.mainloop() # запускаємо цикл головного вікна
|
65310340928ed2f77db21a4aa8eac35baf562f61 | krenevych/ClassWork | /Stat1/L9/l9_6.py | 259 | 3.796875 | 4 | a = input()
b = input()
freq_a = {el: a.count(el) for el in a}
freq_b = {el: b.count(el) for el in b}
#
# print(freq_a)
# print(freq_b)
for k in freq_b:
if k not in freq_a or freq_a[k] < freq_b[k]:
print("No")
break
else:
print("Ok") |
3c2def7535feb672ce3dd63fa2e57172c6be7e52 | krenevych/ClassWork | /Mat/L6/l6_5.py | 112 | 3.53125 | 4 |
"welcome to python"
s = input()
res = s[0]
for c in s[1:]:
if c != res[-1]:
res += c
print(res) |
794f303abeb262ed4ece4ba55bc8b21817f187ee | krenevych/ClassWork | /Mat/OOP11/canvas.py | 1,369 | 3.5625 | 4 | from tkinter import *
from tkinter.filedialog import askopenfilename
def openPicture():
global canvas
filename = askopenfilename()
photo = PhotoImage(file=filename)
id = canvas.create_image(0, 0, image=photo, anchor=NW)
pass
def main():
root = Tk() # створюємо головне вікно програми
global canvas
canvas = Canvas(root, # батьківський віджет
width=800, # ширина віджета у пікселях
height=600 # висота віджета у пікселях
)
canvas.pack() # відображення віджета у вікні
btn = Button(root,
width=20, height=2,
text="Move object",
command=onBtnClick
)
btn.pack()
photo = PhotoImage(file="cat.png")
global id_cat
id_cat = canvas.create_image(0, 0, image=photo, anchor=NW)
move(id_cat, 3, 3)
root.mainloop() # запускаємо цикл головного вікна
isMoving = False
def onBtnClick():
global isMoving
isMoving= not isMoving
def move(id, dx, dy):
global canvas, isMoving
print("Move")
if isMoving:
canvas.move(id_cat, 3, 3)
canvas.after(25, move, id, dx, dy)
if __name__ == "__main__": main() |
a23d16e55e2697a3e939126d0e067babc0249373 | marcotw2school/schoolstuff | /Geometria/Utilities/Calcolatrice.py | 4,954 | 3.546875 | 4 | # Creato da Marco Sisto - 28/11/2020
import math
# finput = FiguraInput
# minput = MainInput
def rettangolo_parallelogrammo():
finput = input('Cosa vuoi calcolare?: ')
if finput == 'Area':
base = int(input('Inserisci la Base: '))
altezza = int(input('Inserisci l''Altezza: '))
area = base * altezza
print('Area = ' + str(area))
elif finput == 'Perimetro':
base = int(input('Inserisci la Base: '))
altezza = int(input('Inserisci l''Altezza: '))
perimetro = 2*base + 2*altezza
print('Base*2 = ' + str(base*2), 'Altezza*2 = ' + str(altezza*2), 'Perimetro = ' + str(perimetro))
elif finput == 'Diagonale':
base = int(input('Inserisci la Base: '))
altezza = int(input('Inserisci l''Altezza: '))
diagonale = math.sqrt(base**2 + altezza**2)
print('Base^2 = ' + str(base**2) ,'Altezza^2 = ' + str(altezza**2),'Diagonale = ' + str(diagonale))
elif finput == 'Formule Inverse':
finput = input('Che formula inversa vuoi calcolare?: ')
if finput == 'Base':
area = int(input('Inserisci l''Area: '))
altezza = int(input('Inserisci l''Altezza: '))
base = area//altezza
print(base)
elif finput == 'Altezza':
area = int(input('Inserisci l''Area: '))
base = int(input('Inserisci la Base: '))
altezza = area//base
print(altezza)
def quadrato():
finput = input('Cosa vuoi calcolare?: ')
if finput == 'Area':
lato = int(input('Inserisci il lato: '))
area = lato**2
print('Area/Lato^2 = ' + str(area))
elif finput == 'Perimetro':
lato = int(input('Inserisci il lato: '))
perimetro = lato*4
print('Perimetro/Lato*4 = ' + str(perimetro))
elif finput == 'Diagonale':
lato = int(input('Inserisci il lato: '))
diagonale = lato * math.sqrt(2)
print('Diagonale = ' + str(diagonale))
elif finput == 'Formule Inverse':
print('Che formula inversa vuoi calcolare?:')
finput = input('LatoConArea = 1, LatoConDiagonale = 2')
if finput == '1':
area = int(input('Inserisci l''Area: '))
lato = math.sqrt(area)
print('Lato = ' + str(lato))
elif finput == '2':
diagonale = int(input('Inserisci la Diagonale: '))
lato = diagonale//math.sqrt(2)
print('Lato = ' + str(lato))
def triangolo():
finput = input('Cosa vuoi calcolare?: ')
if finput == 'Area':
base = int(input('Inserisci la Base: '))
altezza = int(input('Inserisci l''Altezza: '))
area = (base * altezza)//2
print('Area = ' + str(area))
elif finput == 'Formule Inverse':
print('Che formula inversa vuoi calcolare?:')
finput = input('Base = 1, Altezza = 2, Formula di Erone (Area) = 3: ')
if finput == '1':
area = int(input('Inserisci l''Area: '))
altezza = int(input('Inserisci l''Altezza: '))
base = (2*area)//altezza
print('Base = ' + int(base))
elif finput == '2':
area = int(input('Inserisci l''Area: '))
base = int(input('Inserisci la Base: '))
altezza = (2*area)//base
print('Altezza = ' + str(altezza))
elif finput == '3':
semiperimetro = int(input('Inserisci il semiperimetro: '))
a = int(input('Inserisci a: '))
b = int(input('Inserisci b: '))
c = int(input('Inserisci a: '))
area = math.sqrt(semiperimetro * (semiperimetro - a) * (semiperimetro - b) * (semiperimetro - c))
print('Area = ' + str(area))
def triangolo_rettangolo():
finput = input('Cosa vuoi calcolare?: ')
if finput == 'Area':
print('Che formula vuoi usare?: ')
finput = input('AreaConBase = 1, AreaConIpotenusa = 2: ')
if finput == '1':
base = int(input('Inserisci il Cateto: '))
altezza = int(input('Inserisci l''Altezza: '))
area = (base * altezza)//2
print('Area = ' + str(area))
elif finput == '2':
ipotenusa = int(input('Inserisci l''Ipotenusa: '))
latobliquo = int(input('Inserisci il Lato Obliquo: '))
area = (ipotenusa * latobliquo)//2
print('Area = ' + str(area))
elif finput == 'Perimetro':
ipotenusa = int(input('Inserisci l''Ipotenusa: '))
c1 = int(input('Inserisci il Cateto 1: '))
c2 = int(input('Inserisci il Cateto 2: '))
perimetro = ipotenusa + c1 + c2
print('Perimetro = ' + str(perimetro))
def main():
minput = input('Che figura vuoi calcolare?: ')
if minput == 'Rettangolo':
rettangolo()
elif minput == 'Quadrato':
quadrato()
elif minput == 'Triangolo':
triangolo()
elif minput == 'Triangolo Rettangolo':
triangolo_rettangolo()
main()
|
95d7dd2afe45d705d1bbb3884245e1258651f0c0 | DHANI4/NUMBER-GUESSING-GAME | /NumberGuessing.py | 443 | 4.28125 | 4 | import random
print("Number Guessing Game")
rand=random.randint(1,20)
print("Guess a Number between 1-20")
chances=0
while(chances<5):
chances=chances+1
guess=int(input("Enter Your Guess"))
if(guess==rand):
print("Congratulations You Won!!")
break
elif(guess<rand):
print("Guess a number higher")
else:
print("Guess a number lesser")
if not chances<5:
print("You Loose") |
d7494be4817349002aff937d8a33a6720e11fd8b | ArDrift/InfoPy_scripts | /9_het/8_dolgozatok.py | 824 | 4.03125 | 4 | #!/usr/bin/env python3
# A rendezéshez felhasználtam: https://docs.python.org/3/howto/sorting.html#key-functions
class Hallgato:
def __init__(self, neptun, nev, pont):
self.neptun = neptun
self.nev = nev
self.pont = pont
def __str__(self):
return "Név: {}, Neptun: {}, Pont: {}".format(self.nev, self.neptun, self.pont)
def beolvas(file):
diaklista = []
with open(file, "rt") as f:
for sor in f:
diaklista.append(Hallgato(sor.split(":")[0], sor.split(":")[1], int(sor.split(":")[2])))
return diaklista
def main():
lista1 = beolvas("8_zheredmeny.txt")
lista2 = list(lista1)
lista1[0].pont = 27
lista1 = sorted(lista1, key=lambda hallgato: hallgato.nev)
lista2 = sorted(lista2, key=lambda hallgato: hallgato.pont)
for elem in lista2:
print(elem)
main()
|
2e3362025d094d18945d069e065e709bc2209f11 | ArDrift/InfoPy_scripts | /13_het/3_Charlie.py | 560 | 3.96875 | 4 | #!/usr/bin/env python3
def main():
fagyik = {
"pisztácia": 0,
"vanília": 3,
"tutti-frutti": 8,
"karamell": 4,
"rumos dió": 5,
"kávé": 9,
}
iz = input("Fagyi? ")
while iz != "":
valasz = fagyik.get(iz, -1)
if valasz == -1:
print("{} nem is volt!".format(iz))
elif valasz == 0:
print("{} kifogyott!".format(iz))
else:
print("kösz, öcsi!")
fagyik[iz] -= 1
iz = input("Fagyi? ")
return
main()
|
70da854d8607eca02688e944098cfbd81639e291 | ArDrift/InfoPy_scripts | /2_het/11_haromszog_golyokbol.py | 208 | 3.765625 | 4 | #!/usr/bin/env python3
sorszam = int(input("Add meg a háromszög sorainak számát:"))
i = 0
while i < sorszam:
print(" " * (sorszam - i - 1), end="")
print("o" * (1 + i * 2), end="\n")
i += 1
|
cdc79f173212c6828503091bbf27589e136af03e | ArDrift/InfoPy_scripts | /7_het/6_szamtani-sorozat.py | 258 | 3.609375 | 4 | #!/usr/bin/env python3
def sorozat(elso, incr, sorszam):
if sorszam == 0:
return elso
else:
return sorozat(elso, incr, sorszam - 1) + incr
def main():
for i in range(10 + 1):
print(sorozat(0, 12, i), end=" ")
print("")
main()
|
049919709c0a7163789dd0186a4ff5210b350ecb | ArDrift/InfoPy_scripts | /10_het/8_beolvasas-adott-szamrendszerben.py | 592 | 3.609375 | 4 | #!/usr/bin/env python3
# A feladat megoldásához felhasználtam: https://docs.python.org/3/library/stdtypes.html
def tizesbe(rendszer, szamstr):
res = 0
for b in range(len(szamstr)):
if szamstr[b].isdecimal():
res += int(szamstr[b]) * rendszer ** (len(szamstr) - 1 - b)
else:
res += (ord(szamstr[b].upper())-55) * rendszer ** (len(szamstr) - 1 - b)
return res
def main():
rendszer = int(input("Add meg a számrendszert: "))
szam = input("Add meg a számot: ")
print("A megadott szám 10-es számrendszerben: {}".format(tizesbe(rendszer, szam)))
main()
|
5c86b495b677bd18b4e066d8998531bf9e860913 | ArDrift/InfoPy_scripts | /szorgalmi/2_kismutato-nagymutato.py | 2,516 | 4.03125 | 4 | #!/usr/bin/env python3
"""
A feladat felkészítéséhez felhasználtam a következő forrást:
https://docs.python.org/3/library/turtle.html
"""
import turtle
ora = int(input("Add meg az órák számát: "))
perc = int(input("Add meg a percek számát: "))
masodperc = int(input("Add meg a másodpercek számát: "))
szinmix = [255, 0, 0]
def print_clock(ora, perc, masodperc):
# kezdőállás, óra legyen középen
turtle.speed(0)
turtle.ht()
turtle.width(5)
turtle.up()
turtle.seth(-90)
turtle.fd(250)
turtle.seth(0)
turtle.down()
# számlap színezés
turtle.color("#86fc80")
turtle.begin_fill()
turtle.circle(250)
turtle.end_fill()
turtle.color("#0d83dd")
for szog in range(0, 360, 6):
# színek változtatása
turtle.colormode(255)
# zöld nő
if szog in range(0, 60) and szinmix[1] <= 255 - 21:
szinmix[1] += 21
# piros csökken
elif szog in range(60, 120) and szinmix[0] >= 0 + 21:
szinmix[0] -= 21
# kék nő
elif szog in range(120, 180) and szinmix[2] <= 255 - 21:
szinmix[2] += 21
# zöld csökken
elif szog in range(180, 240) and szinmix[1] >= 0 + 21:
szinmix[1] -= 21
# piros nő
elif szog in range(240, 300) and szinmix[0] <= 255 - 21:
szinmix[0] += 21
# kék csökken
elif szog in range(300, 360) and szinmix[2] >= 0 + 21:
szinmix[2] -= 21
turtle.color(szinmix)
# óra, perc strigulák kirajzolása, külső körvonal
turtle.seth(90 + szog)
turtle.width(4)
# óra-strigulák
if szog % 15 == 0:
turtle.width(5)
turtle.fd(20)
turtle.bk(20)
# perc-strigulák
else:
turtle.fd(10)
turtle.bk(10)
turtle.seth(szog)
turtle.width(5)
turtle.circle(250, 6)
# középre helyezés
turtle.up()
turtle.setpos(0,0)
turtle.down()
# óramutató
turtle.width(7)
turtle.color("#720ddd")
turtle.seth(90 - ora * 30 - perc * 0.5)
turtle.fd(120)
turtle.bk(120)
# percmutató
turtle.width(5)
turtle.color("#0d91dd")
turtle.seth(90 - perc * 6 - masodperc * 0.1)
turtle.fd(170)
turtle.bk(170)
# másodpercmutató
turtle.width(3)
turtle.color("#dd1e0d")
turtle.seth(90 - masodperc * 6)
turtle.fd(220)
turtle.bk(220)
# középső kör
turtle.up()
turtle.seth(-90)
turtle.fd(10)
turtle.down()
turtle.begin_fill()
turtle.color("#ddbb0d")
turtle.seth(0)
turtle.circle(10)
turtle.end_fill()
turtle.done()
print_clock(ora, perc, masodperc)
|
174f8f924bde5b23d1a2eefc1dfe94400e0848b4 | ArDrift/InfoPy_scripts | /2_het/9-1_adott_hosszusagu_szakasz_1.py | 168 | 3.96875 | 4 | #!/usr/bin/env python3
hossz = int(input("Mekkora legyen a szakasz?"))
i = 0
print("+", end="")
while i < hossz:
print("-", end="")
i += 1
print("+", end="")
|
68750d9ff369f0a41d6028c2b92d9168caea65a0 | ilya1203/SQL | /sqlwriter.py | 4,112 | 3.65625 | 4 | import sqlite3
class SQLwriter:
def __init__(self):
self.name = 'db'
self.table = ''
def create_column(self, columns):
db = sqlite3.connect(f'{self.name}.sqlite')
cursor = db.cursor()
try:
cursor.executescript(f"""
CREATE TABLE {self.table}(
pk int
);""")
db.commit()
except Exception as ex:
pass
for column in columns:
try:
cursor.executescript(f"""
ALTER TABLE {self.table}
ADD {column['name']} {column['type']};
""")
except Exception as ex:
pass
else:
db.commit()
db.close()
def get_pk(self):
if(len(SQLwriter.get_value(self=self))>0):
db = sqlite3.connect(f'{self.name}.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT pk FROM {self.__class__.__name__}")
result = cursor.fetchall()
print(str(result[-1]).split(',')[0].split('(')[-1])
db.close()
return int(str(result[-1]).split(',')[0].split('(')[-1])
else:
return 0
def get_value(self):
db = sqlite3.connect(f'{self.name}.sqlite')
cursor = db.cursor()
cursor.execute(f"SELECT * FROM {self.__class__.__name__}")
result = cursor.fetchall()
db.close()
return result
def set_value(self, values):
db = sqlite3.connect(f'{self.name}.sqlite')
cursor = db.cursor()
comand = f"INSERT INTO {self.__class__.__name__} VALUES {values};"
print(comand)
cursor.execute(comand)
db.commit()
db.close()
class ModelsSql:
def __init__(self):
self.mkdb()
self.name = 'db'
def create_obj(self, args):
name = self.__class__.__name__
print(f"created into {name} {args}")
pk = SQLwriter.get_pk(self=self) + 1
val = f'({pk}'
for v in args:
if type(v) == type(str()):
val = f'{val}, "{v}"'
else:
val = val + ',' + str(v)
else:
val = val + ')'
SQLwriter.set_value(self=self, values=val)
def view(self):
area = []
for key in self.__class__.__dict__.keys():
if key != '__module__' and key != '__doc__':
area.append(key)
to_return = []
counter = 0
for element in SQLwriter.get_value(self=self):
to_return.append({})
for i in range(len(element)):
if i == 0:
to_return[counter]['pk'] = (element[i])
else:
for ar in range(len(area)):
if i == ar+1:
to_return[counter][area[ar]] = (element[i])
else:
counter += 1
return to_return
def sord(self, by):
val = self.view()
to_return = []
for element in val:
for key in by.keys():
if element[key] == by[key]:
to_return.append(element)
return to_return
def OrmInteger(self=None):
return 'int'
def OrmFloat(self=None):
return 'real'
def OrmText(self=None,mx=255):
return f'varchar({mx})'
def mkdb(self):
nm = self.__class__.__name__
print(nm)
area=[]
for key in self.__class__.__dict__.keys():
if key != '__module__' and key != '__doc__':
print(f"{key}-{self.__class__.__dict__[key]}")
area.append({"name": key, "type": self.__class__.__dict__[key]})
else:
sc = SQLwriter()
sc.table = nm
sc.create_column(columns=area)
class TraTra(ModelsSql):
a = ModelsSql.OrmInteger()
b = ModelsSql.OrmText(mx=122)
|
fe917d7e04cc15418b25bfaba90722b1ca861632 | jgendron/boozonians | /Unit Test Scorer/scorer-testing.py | 1,752 | 3.671875 | 4 | #!/usr/bin/python -tt
# 'shroom-scorer
'''
This scoring program takes as an argument the input ...blah, blah
...finish documentation
'''
def scorer(key, predictions):
msg = False
#-----
# normalize input by ensuring all lowercase and remove whitespace
submit = [answer.lower().strip() for answer in predictions]
#-----
# compare input to answer key
correct = [e for e in range(len(key)) if key[e] == submit[e]]
accuracy = len(correct)/len(submit)
if accuracy < 1: msg = True
print(' ' + str(len(correct)) + ' correct and ' +
str((len(submit)-len(correct))) + ' wrong.')
print(' Prediction accuracy is {:.2%}'.format(accuracy))
return(msg)
# Calls the above functions with participant inputs.
def main():
import sys
#-----
# read in answer key and assign to list
f = open('alien_answer_key.txt', 'r')
truth_data = [e.strip() for e in f.readlines()] #remove \n characters
f.close
#-----
# read in participant's submission from .txt file
team_input = sys.argv[1]
t = open(team_input,'r')
submission = t.readlines()
t.close
if len(submission) != len(truth_data):
print('Ooops! Your submission should inclue 2,437 lines of data')
sys.exit()
#-----
# print preamble to console
print('\nThank you for submitting your predictions...')
print(' How well did you choose?\n')
print("Your alien-nation results:")
#-----
# call scorer function, assigning output to flag
flag = scorer(truth_data, submission)
if flag == True:
print('\n ...and one bad alien can really mess up a party!!')
else:
print("\n Congratulations!")
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.