blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
d70c1dc2f7c543be01f714f94f75d5faf1f5ac08 | yuooo/SetCover | /preprocessing.py | 2,132 | 4.15625 | 4 | import numpy as np
import setcover
import matplotlib.pyplot as plt
"""
@author: ea26425
"""
"""
This function reads a data set from a txt file and returns
- a dictionary of the elements, "list_of_elements" and
- a list of tuples, "list_of_sets", where every tuple contains the cost and the dictionary of a set
The format of the txt data files is:
number of elements, number of sets
the cost of each set c(j),j=1,...,n
for each element i (i=1,...,m): the number of sets which cover
element i followed by a list of the sets which cover element i
The data sets can be found here: http://people.brunel.ac.uk/~mastjjb/jeb/orlib/scpinfo.html
"""
def create_data_set(path_dir):
f = open(path_dir, "r")
num_of_el, num_of_sets = map(int, f.readline().split())
#print 'elements: ', num_of_el, ' sets: ', num_of_sets
# read weights
weights = []
while(len(weights) < num_of_sets):
for w in map(int, f.readline().split()):
weights.append(w)
list_of_elements = {}
for el in xrange(num_of_el):
list_of_elements.update({str(el):0})
list_of_sets = []
for s in xrange(num_of_sets):
list_of_sets.append((weights[s], {}))
frequency = np.zeros((num_of_el,))
for element in xrange(num_of_el):
frequency[element] = map(int, f.readline().split())[0]
# list of sets that include the element
sets_of_element = []
while(len(sets_of_element)<frequency[element]):
for s in map(int, f.readline().split()):
sets_of_element.append(s-1)
# update every set with the current element
for s in sets_of_element:
list_of_sets[s][1].update({str(element):0})
return list_of_elements, list_of_sets
def is_in_set(h_set1, h_set2):
return set(h_set1.keys()) <= set(h_set2.keys())
def remove_useless(l_sets):
l_sets_pruned = []
for i_1, (w_set, h_set) in enumerate(l_sets):
is_good = True
for i_2, (w_set_tocompare, h_set_tocompare) in enumerate(l_sets):
if is_in_set(h_set, h_set_tocompare) and w_set > w_set_tocompare:
is_good = False
break
if is_good:
l_sets_pruned.append((w_set, h_set))
return l_sets_pruned |
d875f870a9f5dc4e4772bdf55c9cadaec62d6229 | thaolinhnp/Python_Fundamentals | /PYBai_09a_project/main4.py | 768 | 3.796875 | 4 | # Global variable - Biến toàn cục
tenHocSinh="An"
def InThongTin1():
print(f'1-Tên HS (Global variable):{tenHocSinh}')
def InThongTin2():
# Local variable - Biến cục bộ trong function
hoHocSinh='Lê'
tenHocSinh='Bình'
print(f'2-Tên HS (Local variable):{hoHocSinh} {tenHocSinh}')
def InThongTin3():
# Global variable - Biến toàn cục
global hoHocSinh
hoHocSinh='Lê'
global tenHocSinh
tenHocSinh='Bình'
print(f'3-Tên HS (Global variable):{hoHocSinh} {tenHocSinh}')
if __name__ == "__main__":
# InThongTin1()
# InThongTin2()
# print(f'Main - Tên HS (Global variable):{tenHocSinh}')
InThongTin3()
print(f'Main-Tên HS (Global variable):{hoHocSinh} {tenHocSinh}')
print('end') |
00725ac55655abd26fee15982934dfa56dfefc53 | nicoaizen/Fundamentos_de_informatica_Aizen | /Práctica_de_introducción_a_Python_Parte2/ej9.py | 372 | 3.984375 | 4 | nombres = []
edades = []
edad_max = max(edades)
while True:
nombre = input("Nombre del alumno")
edad = input("Edad del alumno")
if nombre != "*":
nombres.append(nombre)
edades.append(edad)
if nombre == "*": break;
print("La edad maxima es ", edad_max)
print("Alumnos con edad maxima:")
for nombre, edad in (nombres, edades):
if edad == edad_max:
print(nombre) |
385c50fca3a9e41ba6b40823ef311182782dddd1 | Denki77/forPython | /src/day_02/00_hello_function.py | 420 | 3.984375 | 4 | """
Пример программы для работы с функциями
Сделать
- функцию hello, которая выводит текст приветствия клиенту
"""
def user_hello(user: str):
print(f"Hello, {user}")
clients = ['John', 'David', 'Kate', 'Alex']
for user in clients:
user_hello(user)
clients_two = ['Edward']
for user in clients_two:
user_hello(user)
|
812a663321e472e5bdc1c8965d4784ae8f0b61d7 | Remyaaadwik171017/mypythonprograms | /collections/list/list15.py | 209 | 3.5625 | 4 | lst=[1,2,3,4,5,6,7,8,9,10]
print(lst)
n=int(input("Enter any no form 1-10: "))
for i in lst:
while n>=i:
print((lst[n-2],lst[0]),(lst[1],lst[n-3]),(lst[3],lst[n-4]),(lst[4],lst[n-5]))
break |
343ee83a9d3edcd187a17fbb1564199d44d8b8d4 | hyrlamiranda/python-learn | /multiples.py | 176 | 4.03125 | 4 | #Write a program that prints a multiplication table for numbers up to
#12.
for line in range(1,12):
for table in range(1,12):
print (line * table, '\t')
print |
54e0612a6366574933cece9a443719d7745f3ae5 | WeiTang1/DailyCoding | /DailyCoding61.py | 201 | 3.75 | 4 | def solution(x,y):
if y == 0:
return 1
if y % 2 == 0:
return solution(x,y/2) * solution(x,y/2)
else:
return x* solution(x,y/2) * solution(x,y/2)
print solution(5,5) |
c6dd7ca0556c4a1a5541e4f4106532348de289d7 | robin-norwood/TIY-Python-Apr-2016 | /week1/exceptions.py | 580 | 3.984375 | 4 | # We can validate user input to ensure expected behavior:
#
# aNumber = "default"
#
# while not aNumber.isdigit():
# aNumber = input("Enter a number: ")
#
# aNumber = int(aNumber)
# print(5 + aNumber)
import sys
aNumber = None
while not aNumber:
try:
aNumber = input("Enter a number: ")
aNumber = int(aNumber)
except ValueError as e:
print(type(e))
print("Dude. No. A number. Like with digits")
aNumber = None
except EOFError:
print("Fine, be that way")
sys.exit()
print("Got a number: " + str(aNumber))
|
9984fe1d6be5fb9535faf51077db0208a6148e57 | CirXe0N/AdventOfCode | /2020/02/python/puzzle_01.py | 616 | 3.71875 | 4 | def calculate_valid_passwords(lines):
amount_valid = 0
for line in lines:
policy, password = line.split(': ')
letter = policy[-1]
min_occurrence, max_occurrence = policy[:-2].split('-')
min_occurrence = int(min_occurrence)
max_occurrence = int(max_occurrence)
counter = password.count(letter)
if min_occurrence <= counter <= max_occurrence:
amount_valid += 1
return amount_valid
with open('input.txt') as f:
lines = list(f.read().splitlines())
answer = calculate_valid_passwords(lines)
print(f'The answer is {answer}')
|
b84ca5cc474e5dab10b2abe5257c759a0a0047af | alanphys/pylinac | /pylinac/core/mask.py | 980 | 3.71875 | 4 | """Module for processing "masked" arrays, i.e. binary images."""
from typing import Tuple
import numpy as np
def bounding_box(array: np.array) -> Tuple[float, ...]:
"""Get the bounding box values of an ROI in a 2D array."""
binary_arr = np.argwhere(array)
(ymin, xmin), (ymax, xmax) = binary_arr.min(0), binary_arr.max(0) + 1
return ymin, ymax, xmin, xmax
def filled_area_ratio(array: np.array) -> float:
"""Return the ratio of filled pixels to empty pixels in the ROI bounding box.
For example a solid square would be 1.0, while a sold circle would be ~0.785.
"""
ymin, ymax, xmin, xmax = bounding_box(array)
box_area = (ymax - ymin) * (xmax - xmin)
filled_area = np.sum(array)
return float(filled_area / box_area)
def square_ratio(array: np.array) -> float:
"""Determine the width/height ratio of the ROI"""
ymin, ymax, xmin, xmax = bounding_box(array)
y = abs(ymax - ymin)
x = abs(xmax - xmin)
return y/x
|
6bb067544a3fc40c05085342289679d45e68660a | approjecthub/problem-solving-with-python | /no. of primes in prefix sum array.py | 659 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 15 10:28:36 2019
@author: Anirban
"""
## Count the number of primes in the prefix sum array of the given array
import math
arr = [1, 5, 2, 3, 7, 9]
def isprime(value):
if(value<2):
return False
for i in range(2, math.ceil(math.sqrt(value))):
if(value%i==0):
return False
return True
def prefix_sum(a = arr):
sum = 0
prime_count = 0
for i in range(len(a)):
sum += a[i]
a[i] = sum
if(isprime(a[i])==1):
prime_count += 1
return prime_count |
4d3ec582077e89ed995357783f22d5ac48b90935 | parka01/python_ex | /0219/ex1.py | 365 | 3.78125 | 4 | '''num=int(input('합계를 원하는 숫자 입력: '))
i=1
sums=0
while i<=num:
sums=sums+i
i=i+1
print('1부터 %d까지의 합은: '%num,sums)'''
#----------------모범답안---------------------
num=int(input('합계를 원하는 숫자 입력: '))
i=1
sum=0
while i<=num:
sum=sum+i
i=i+1
print("1부터 {}까지의 합:{}".format(num,sum))
|
2b7c2df76c45ebd9b3672488819a0d6f2b11fa40 | ramonaghilea/Fundamentals-of-Programming | /Stars/ui.py | 2,169 | 3.65625 | 4 | from game import Game, GameExceptionWon, GameExceptionLost
class UI:
def __init__(self, game):
self._game = game
def _printMenu(self):
res = "Commands:"
res += "exit \n"
res += "fire <coordinate> \n"
res += "cheat \n"
return res
def start(self):
cmd2 = ""
gameOn = True
while gameOn:
try:
self._printMenu()
if cmd2 != "cheat":
print(self._game.getBoard())
cmd2 = input("Enter command: ")
if cmd2 == 'exit':
return
if cmd2 == 'cheat':
print(self._game.getCheatBoard())
else:
cmd = cmd2.split()
if cmd[0] == 'fire':
result = self._game.fire(cmd[1][0], int(cmd[1][1]))
if result == 0:
print("Try again. The cell was an asteroid or was previously fired upon.")
while result == 0:
cmd = input("Enter a valid cell: ")
cmd = cmd.split()
result = self._game.fire(cmd[1][0], int(cmd[1][1]))
if result == 1:
print("Hit. You fired one alien ship.")
elif result == 2:
print("The cell was empty.")
elif result == 1:
print("Hit. You fired one alien ship.")
elif result == 2:
print("The cell was empty.")
#self._game.checkGameOver()
else:
print("Bad Command")
except GameExceptionWon as ex:
print(self._game.getCheatBoard())
print(ex)
gameOn = False
except GameExceptionLost as ex:
print(self._game.getCheatBoard())
print(ex)
gameOn = False |
75eab007ed225d86fd1c0bec70fe434062fe3e5c | NadezdaAvdanina/lesson1 | /test22.py | 344 | 3.71875 | 4 | def get_answer(quation):
quation = str(quation)
quation = quation.lower()
answer = { 'Привет': 'и тебе привет', 'как дела?': 'Лучше всех', 'пока': 'увидимся!' }
return answer.get (quation, 'Повтори, пожалуйста')
inp = input('Напиши мне')
х = get_answer(inp)
print(x)
|
3181882410c5ef3afbc1376cafa5be18f39b2231 | networkdynamics/topics | /src/topics/text_document.py | 2,697 | 3.609375 | 4 | class TextDocument:
"""
This class encapuslates the information contained in a text document such that it can be directly
used by an .... # TODO
TODO: Clarify the features of the document (in particular, types and labels)
TODO: Change all count_ methods to num_
"""
def __init__(self, text, labels=set(), **kwargs):
"""
**Args**
* ``text``: a string containing the text for this document.
* ``labels``: a set containing the labels for this document.
**Keyword args**
* ``to_lower [=False]`` (boolean): if true, convert the document's
text to lowercase
"""
to_lower = kwargs.pop("to_lower", False)
if to_lower:
text = text.lower()
# TODO: Check for extra keywords
self._words = text.split()
self._labels = labels
# A[tpe][i] is the index of the ith occurence of type tpe
self._type_occurrences = {}
for i, w in enumerate(self._words):
if w not in self._type_occurrences:
self._type_occurrences[w] = [i]
else:
self._type_occurrences[w].append(i)
def __len__(self):
"""
Return the length of the document.
"""
return len(self._words)
def __iter__(self):
"""
Iterate through words in the document.
"""
for word in self._words:
yield word
def iterlabels(self):
"""
Iterate through labels applied to the document.
TODO: rename to iter_labels
"""
return iter(self._labels)
def has_label(self, lbl):
"""
Return whether this document is labelled with ``lbl``.
"""
return lbl in self._labels
def add_label(self, lbl):
"""
Add the label ``lbl`` to this document.
"""
self._labels.add(lbl)
def count_labels(self):
"""
Return the number of labels applied to this document.
"""
return len(self._labels)
def get_type_occurrence(self, tpe, i):
"""
Obtain the token index of the ith occurrence of type ``tpe``.
"""
return self._type_occurrences[tpe][i]
def count_types(self):
"""
Return the number of unique types in this document.
"""
return len(set(self._words))
def count_type(self, tpe):
"""
Return the number of words with type ``tpe``.
"""
return reduce(lambda acc, i: acc + 1 if i == tpe else acc, self._words, 0)
def filter_type(self, excluded):
"""
Remove the word type ``excluded`` from the document.
"""
self._words = [w for w in self._words if w != excluded]
if excluded in self._type_occurrences:
del self._type_occurrences[excluded]
def filter_types(self, excluded):
"""
Remove all the word types in the iterable ``excluded`` from the document.
"""
self._words = [w for w in self._words if w not in excluded]
for tpe in excluded:
if tpe in self._type_occurrences:
del self._type_occurrences[tpe]
|
1821771de866ab285deee4415181ad96b8589512 | HeimerR/holbertonschool-higher_level_programming | /0x03-python-data_structures/3-print_reversed_list_integer.py | 226 | 4.125 | 4 | #!/usr/bin/python3
def print_reversed_list_integer(my_list=[]):
if my_list is not None:
local = my_list.copy()
local.reverse()
for i in range(len(local)):
print("{:d}".format(local[i]))
|
2abfc24d40390547c4f9ca04756e6eba7359a9fc | CRAWlab/ARLISS | /2017/Tools/equivalent_height.py | 3,587 | 3.609375 | 4 | #! /usr/bin/env python
###############################################################################
# equivalent_drop_height.py
#
# Script to plot the height from which to drop an object to reach a
# velocity by ground impact. Ignores any air resistance.
#
# NOTE: Any plotting is set up for output, not viewing on screen.
# So, it will likely be ugly on screen. The saved PDFs should look
# better.
#
# Created: 08/13/15
# - Joshua Vaughan
# - joshua.vaughan@louisiana.edu
# - http://www.ucs.louisiana.edu/~jev9637
#
# Modified:
# *
#
###############################################################################
import numpy as np
import matplotlib as plt
PLOT_SI = True # plot the curve in SI units?
PLOT_IMPERIAL = True # fplot the curve in imperial units?
g = 9.81 # accel due to gravity
# Impact velocities between 0.1 and 10m/s
impact_velocity = np.arange(0.1, 10, 0.1)
# Use conservation of energy, ignore aerodynamic effects
height = impact_velocity**2 / (2 * g)
# Plot in SI?
if PLOT_SI:
# Set the plot size - 3x2 aspect ratio is best
fig = plt.Figure(figsize=(6,4))
ax = plt.gca()
plt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96)
# Change the axis units font
plt.setp(ax.get_ymajorticklabels(),fontsize=18)
plt.setp(ax.get_xmajorticklabels(),fontsize=18)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Turn on the plot grid and set appropriate linestyle and color
ax.grid(True,linestyle=':', color='0.75')
ax.set_axisbelow(True)
# Define the X and Y axis labels
plt.xlabel('Impact Velocity (m/s)', fontsize=22, weight='bold', labelpad=5)
plt.ylabel('Drop Height (m)', fontsize=22, weight='bold', labelpad=10)
plt.plot(impact_velocity, height, linewidth=2, linestyle='-', label=r'Height (m)')
# uncomment below and set limits if needed
# plt.xlim(0,5)
# plt.ylim(0,10)
# Adjust the page layout filling the page using the new tight_layout command
plt.tight_layout(pad=0.5)
# save the figure as a high-res pdf in the current folder
plt.savefig('equivalent_drop_height_SI.pdf')
# Also plot in imperial units?
if PLOT_IMPERIAL:
# Set the plot size - 3x2 aspect ratio is best
fig = plt.figure(figsize=(6,4))
ax = plt.gca()
plt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96)
# Change the axis units font
plt.setp(ax.get_ymajorticklabels(),fontsize=18)
plt.setp(ax.get_xmajorticklabels(),fontsize=18)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Turn on the plot grid and set appropriate linestyle and color
ax.grid(True,linestyle=':', color='0.75')
ax.set_axisbelow(True)
# Define the X and Y axis labels
plt.xlabel('Impact Velocity (mph)', fontsize=22, weight='bold', labelpad=5)
plt.ylabel('Drop Height (ft)', fontsize=22, weight='bold', labelpad=10)
plt.plot(impact_velocity * 2.23694, height * 3.28084, linewidth=2, linestyle='-', label=r'Height (m)')
# uncomment below and set limits if needed
# plt.xlim(0,5)
# plt.ylim(0,10)
# Adjust the page layout filling the page using the new tight_layout command
plt.tight_layout(pad=0.5)
# save the figure as a high-res pdf in the current folder
plt.savefig('equivalent_drop_height_imperial.pdf')
# show the figures
plt.show()
|
7b5ae8b10b43d535862620bfe8010062ea544537 | JairMendoza/Python | /curso 2/ej27.py | 862 | 3.71875 | 4 | import random
import os
intentos=10
numero=random.randrange(100)
num=200
acierto=0
while num!=numero:
os.system("cls")
print(f"Vamos a generar un numero aleatorio entre 0 y 100 el cual\ntu deberas atinar\ntienes {intentos} intentos.")
num=int(input("Ingrese el numero: "))
if num==numero:
acierto=1
break
elif num>numero:
print("El numero que ingreso es mayor al que hay que adivinar.")
intentos=intentos-1
else:
print("El numero que ingreso es menor al que hay que adivinar.")
intentos=intentos-1
if intentos==0:
acierto=2
break
input()
if acierto==1:
print(f"Atinaste al numero random!\n lo hiciste en {10-intentos} intentos")
if acierto==2:
print(f"No haz logrado atinar al numero rando :c\n el numero era: {numero}")
input()
|
42802f51cc1070f212594cc1e8dabf682dd57e6d | henrystark-csu/mininet-rt | /benchmark/InterNodeTopo.py | 962 | 3.546875 | 4 | #!/usr/bin/python
"""
"""
from mininet.topo import Topo, Node
class InterNodeTopo( Topo ):
'''Topology for a group of 2host-1sw sets.'''
def __init__( self, N ):
'''Constructor'''
# Add default members to class.
super( InterNodeTopo, self ).__init__()
# Create switch and host nodes
hosts = range(1, 2*N+1)
switches = range(2*N+1, 3*N+1)
for h in hosts:
self.add_node( h, Node( is_switch=False ) )
for s in switches:
self.add_node( s, Node( is_switch=True ) )
# Wire up hosts
for i in range(0, N):
self.add_edge(hosts[2*i], switches[i])
self.add_edge(hosts[2*i + 1], switches[i])
# Consider all switches and hosts 'on'
self.enable_all()
if __name__ == '__main__':
sizes = [ 1, 10, 20 ]
for n in sizes:
print "*** Printing InterNodeTopo : size ", n
topo = InterNodeTopo(n)
print "Nodes: ", topo.nodes()
print "Switches: ", topo.switches()
print "Hosts: ", topo.hosts()
print "Edges: ", topo.edges()
|
a5d4cf11e0746a7317c53cafc5291f0cabf960ad | sebastiaanspeck/Sokoban | /sokoban.py | 4,739 | 3.96875 | 4 | from copy import deepcopy
"""
Board:
. : empty square
@ : player
# : wall
$ : box
% : empty goal
+ : player on goal
* : box on goal
Solution:
The solution is stored in the LURD format:
- where lowercase l, u, r and d represent a move in that (left, up, right, down) direction
- capital LURD represents a push.
"""
moves = []
possible_moves = ["left", "up", "right", "down"]
boards = []
board_start = []
def init(path):
global boards, board_start
data = []
with open(path, 'r') as f:
for lines in f.readlines():
lines = lines.replace('\n', '')
line = []
for character in lines:
if character == ' ':
character = '.'
line.append(character)
data.append(line)
board_start = data
boards = [[[board_start], []]]
def solution(board):
# check if the boxes ($) are on the locations of the goals (%)
return location(board, "$") == location(board_start, "%")
def result(current_board):
# print(current_board)
print("We found a solution for your problem: \n")
print_board(current_board[0][0])
print_moves(current_board[1])
print("Number of moves:", len(current_board[1]))
def print_moves(sol):
# print the solution according to the LURD-format
print(''.join(sol))
def print_board(board):
# print the board
for row in board:
print(''.join(row))
def location(board, character):
# print the location for a given character (ea. @ for player and $ for box)
locations = [[ix, iy] for ix, row in enumerate(board) for iy, i in enumerate(row) if i == character]
return locations
def direction_coordinates(x, y, move_position):
# set the following 4 variables to the correct movements
if move_position == "up":
a = x - 1
c = x - 2
b = d = y
elif move_position == "down":
a = x + 1
c = x + 2
b = d = y
elif move_position == "left":
a = c = x
b = y - 1
d = y - 2
else:
# move_position == "right"
a = c = x
b = y + 1
d = y + 2
return a, b, c, d
def move_player(x, y, move_position, board):
# TODO: Specify the deadlocks
current_board = board[0][0]
current_moves = board[1]
location_start = location(current_board, "@")
old_loc = [location_start[0][0], location_start[0][1]]
a, b, c, d = direction_coordinates(x, y, move_position)
if current_board[a][b] == "#" or current_board[a][b] == "$" and current_board[c][d] == "#" \
or current_board[a][b] == "$" and current_board[c][d] == "$" or current_board[a][b] == "%":
# if one of these conditions is true, it is an invalid move, so we pass the function
pass
elif current_board[a][b] == "$":
current_board[a][b] = "@"
current_board[c][d] = "$"
current_board[old_loc[0]][old_loc[1]] = "."
current_moves.append(str(move_position[0].upper()))
boards.append([[current_board], current_moves])
else:
current_board[a][b] = "@"
current_board[old_loc[0]][old_loc[1]] = "."
current_moves.append(str(move_position[0]))
boards.append([[current_board], current_moves])
# def test(board):
# current_board = board[0][0]
# if current_board[a][b] == "%":
# pass
# else:
# current_board[old_loc[0]][old_loc[1]] = "."
def move(direction, board):
location_player = location(board[0][0], "@")
x = location_player[0][0]
y = location_player[0][1]
move_player(x, y, direction, board)
def breadthfirst(board):
# take a direction, deepcopy board -> move(direction = possible move, board = current_board)
# save board in list boards [x][0], save solution in list boards [x][1] (this happens in move-function)
# test current_board[0][0] if current_board[0][0] is the solution -> print board, the moves and number of moves
# else, take next direction, deepcopy board ...
for possible_move in possible_moves:
current_board = deepcopy(board)
move(possible_move, current_board)
print_board(current_board[0][0])
if solution(current_board[0][0]):
result(current_board)
return True
def game():
init('boards/3x3.txt')
while boards:
board = boards.pop(0)
# check if the start board is already the solution
if solution(board[0]):
print("The start-board is already the solution")
elif breadthfirst(board):
boards.clear()
# TODO: What if no solution is found?
# print("We couldn't find a solution for your problem :(")
game()
|
d32e89f7f71aa31a3f3994ad60c7908ead91143a | babiswas/pythonlessons | /classdec.py | 465 | 3.53125 | 4 | class A:
def __init__(self,a,b):
print("Object creation function executed")
self.a=a
self.b=b
def __call__(self,func):
print("call function executed")
def wrapper(*args):
print("Wrapper executed")
return func(*args)
return wrapper
@A(2,3)
def func(*args):
for var in args:
print(var)
if __name__=="__main__":
print("Calling Wrapped functions")
func(3,4,5,6)
|
5d0ddc89bcc5d946f56ed8d0e38a1edbfec8a6ce | vishrutkmr7/DailyPracticeProblemsDIP | /2019/11 November/dp11192019.py | 1,405 | 3.6875 | 4 | # This problem was recently asked by Facebook:
# Given a list of building in the form of (left, right, height), return what the skyline should look like.
# The skyline should be in the form of a list of (x-axis, height),
# where x-axis is the next point where there is a change in height starting from 0,
# and height is the new height starting from the x-axis.
def generate_skyline(buildings):
# Fill this in.
if not buildings:
return []
if len(buildings) == 1:
l, r, h = buildings[0]
return [[l, h], [r, 0]]
mid = len(buildings) // 2
left = generate_skyline(buildings[:mid])
right = generate_skyline(buildings[mid:])
return merge(left, right)
def merge(left, right):
h1, h2 = 0, 0
i, j = 0, 0
result = [[0, 0]]
while i < len(left) and j < len(right):
x0 = left[i][0]
x1 = right[j][0]
if x0 <= x1:
h1 = left[i][1]
i += 1
if x1 <= x0:
h2 = right[j][1]
j += 1
if max(h1, h2) != result[-1][1]:
result.append([min(x0, x1), max(h1, h2)])
result.extend(right[j:])
result.extend(left[i:])
return result[1:]
# 2 2 2
# 2 2 2
# 1 1 2 2 2 1 1
# 1 1 2 2 2 1 1
# 1 1 2 2 2 1 1
# pos: 1 2 3 4 5 6 7 8 9
print(generate_skyline([(2, 8, 3), (4, 6, 5)]))
# [(2, 3), (4, 5), (7, 3), (9, 0)]
|
5bb738e4b2c4d47a0c42110cf0e65bab48b13c80 | snehasurna1875/100-days-of-code | /Day-68/array3.py | 377 | 3.9375 | 4 | '''WAP to accept a value from user and serach that value in the array and if the value is present then check whether that value is even or odd'''
import array
arr1 = array.array('i', [1, 2, 3])
n=eval(input("enter the value to be searched-"))
for i in range(len(arr1)):
if n==arr1[i]:
if n%2==0 :
print ("even")
else:
print ("odd")
|
5432908635fd6db97737e2f2ad2ccf55fb4321ca | HCTYMFF/PythonStuday | /第二章/排序.py | 325 | 3.953125 | 4 | def doubbleSort(numbers):
for j in range(len(numbers)-1,-1,-1):
for i in range(j):
if(numbers[i]>numbers[i+1]):
numbers[i],numbers[i+1]=numbers[i+1],numbers[i]
print(numbers)
def main():
numbers=[2,4,365,7,3,1]
doubbleSort(numbers)
if __name__=='__main__':
main()
|
7492dd120c3c66b28e2470a73d762b8a648694ce | maximus1115/Cellular-Automata | /CA Experimenting.py | 4,892 | 3.921875 | 4 | x = int('1101101', 5)
print (x)
##n = 18
##base = 3
##xary = ''
##while n > 1:
## xary = str(n%base) + xary
## n = n//base
##xary = str(n%base) + xary
##
##print (xary)
##print (3 ** 2 ** 2)
##
##print (3 ** 3 ** 3)
##
##print (155555555555555 > 3**3**3)
##print(len('105330488576562345234538380193503486834235634352234234234534523452345345345634855675668'))
##colors={'1': (0, 0, 0), '0': (255, 255, 255)}
##
##for color in colors:
## print (color)
##import itertools
##import sys
##def generate_rule(rule_number, number_of_neighbors=3, values=[1, 0]):
## '''Generates a rule from the number classification input and other parameters.
## `number_of_neighbors` takes an int and is how many above neighbors are inputs for each cell
## -e.g., nearest neighbor is 3, next nearest neighbor is 5, etc...
## `values` takes a list of all possible values cells can take, which must be translated into ints 0 - n.
## -fyi, the order of the items makes a difference in how the rule is implemented. Reverse order if troubleshooting.
## -Maybe there's a way to do this without using ints as values, but it seems practical for now.'''
## rules_dict = {}
##
## #Tells you if you entered an invalid rule number given the other parameters.
## if rule_number >= (len(values) ** (len(values) ** number_of_neighbors)):
## print ('rule_number too large to index to rule parameters.')
## sys.exit()
##
## #Generates a list of all possible codons.
## codons = list(itertools.product(values, repeat=number_of_neighbors)) #Gives a list of tuples.
## for index, elem in enumerate(codons): #Turns into a list of lists.
## codons[index] = list(elem)
##
## #Creates a string of a number with a base equal to the number of values and number of digits equal to the number of codons.
## n = rule_number
## base = len(values)
## xary = ''
## while n > 1:
## xary = str(n%base) + xary
## n = n//base
## xary = str(n%base) + xary
##
## while len(xary) < len(codons): #Adds extra zeros to the front of the number so all codons are matched to a value.
## xary = '0' + xary
##
## #Pairs all inputs with an output
## codons_as_strings = codons #This is meant to turn the list of lists of codons into a list of strings, which can be hashed in the dict.
## for index, triplet in enumerate(codons):
## codon_string = ''
## for elem in triplet:
## codon_string = codon_string + str(elem)
## codons_as_strings[index] = codon_string
##
## for index, triplet in enumerate(codons_as_strings):
## rules_dict[triplet] = xary[index]
##
## return rules_dict #There's probably a better way to do this.
##
##x = generate_rule(5000000000, 5, [1, 0])
##for i in x:
## print (i, x[i])
##x = 'abcd'
##y = ['1234', 2, 3, 4]
##
##print (y[1, 1])
##x = {'a': 1, 'b': 2}
##
##print (x['a'])
##import random
##
##x = [1, 2, 3]
##y = ''
##for i in x:
## y += str(i)
##
##z = ['0' * 4]
##
##x.extend(z)
##
##print (x[3])
##values = [0,1]
##x = 'abc'
##dicty = {}
##for i in x:
## dicty[i] = values[int(1)]
##
##for i in dicty:
## print (i, dicty[i])
##n = 184
##base = 2
##xary = ''
##while n > 1:
## xary = str(n%base) + xary
## n = n//base
##xary = str(n%base) + xary
##
##print (xary)
#This code works!!!:
##n = 16
##base = 3
##x = ''
##
##while n > 1:
## x = str(n%base) + x
## n = n//base
##
##x = str(n%base) + x
##
##print (x)
##x = [1,2,3]
##y = ''
##
##for i in x:
## y = y + str(i)
##
##print (y)
##import itertools
##x = ['a', 'b', 'c', 'd']
##values = [True, False]
##number_of_neighbors = 3
##codons = list(itertools.product(values, repeat=number_of_neighbors))
##
##print (codons)
##
##for index, elem in enumerate(codons):
## codons[index] = list(elem)
##
##print(codons)
##rule_number = 54
##
##z = "{0:b}".format(rule_number)
##
##print (z)
# Function to print binary number for the
# input decimal using recursion
#This one works, I just want to return the value instead of print it.
##def decimalToXary(n, base):
## '''Takes a decimal int `n` and returns it in the base representation `base`.'''
## print (n)
## if n > 1:
## # divide with integral result
## # (discard remainder)
## decimalToXary(n//base, base)
##
## print (n%base, end ='')
##
##
##x = decimalToXary(6, 2)
##def decimalToXary(n, base):
## '''Takes a decimal int `n` and returns it in the base representation `base`.'''
## if n > 1:
## # divide with integral result
## # (discard remainder)
## decimalToXary(n//base, base)
##
## return str(n%base)
##
##x = decimalToXary(8, 3)
##
##print (x)
#Driver code
##if __name__ == '__main__':
## decimalToXary(8, 3)
## print
## decimalToBinary(18)
#### print
## decimalToBinary(7)
#### print
|
0698777b3373dce8a2aa3057ee3ce83799e7ee2b | dianaevergreen/1337code | /path-sum_v3.py | 1,212 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def DFS(self, root):
if not root:
return None
if not root.left and not root.right:
return [root.val]
leftie = self.DFS(root.left)
rightie = self.DFS(root.right)
sol = []
if leftie is not None:
for l in leftie:
sol.append(root.val + l)
if rightie is not None:
for r in rightie:
sol.append(root.val + r)
return sol
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
answer = self.DFS(root)
if answer is None:
return False
for a in answer:
if a == sum:
return True
return False
|
9c1c43a06f9d5a9b1bf0e0d20a2b2a0934e9dabf | poojamalviya/ds-algo | /arr.py | 463 | 3.84375 | 4 | def removeDuplicate(arr):
for i in range(0, len(arr)-2):
if arr[i] == arr[i+1]:
arr.remove(arr[i])
return arr
arr=[1,1,3,4,5,6,6]
print(removeDuplicate(arr))
def mysterious_recursive_function(number):
"""
Mysterious recursive function
:param number:
:return: mysterious number
"""
return number * mysterious_recursive_function(number - 1)
# check output for input 5
print(mysterious_recursive_function(5)) |
9348d041b18c4cf2751f2c58af01de7cbb981326 | wanghan79/2020_Python | /徐嘉辰 2018013342/生成器.py | 1,767 | 3.609375 | 4 | import random
import string
def DataSampling(datatype, datarange, num, strlen=8):
for index in range(0,num):
if datatype is int:
it = iter(datarange)
item = random.randint(next(it),next(it))
yield item
continue
elif datatype is float:
it = iter(datarange)
item = random.uniform(next(it),next(it))
yield item
continue
elif datatype is str:
item = ''.join(random.SystemRandom().choice(datarange) for _ in range(strlen))
yield item
continue
else:
continue
def DataScreening(data,condition):
for i in data:
if type(i) is int:
if i>=condition[0] and i<=condition[1]:
yield i
if type(i) is float:
if i>=condition[0] and i<=condition[1]:
yield i
if type(i) is str:
for item in condition:
if item in i:
yield i
result_int1 = set()
result_int2 = set()
for x in DataSampling(int,[0,200],100):
result_int1.add(x)
print(result_int1)
for y in DataScreening(result_int1,(0,100)):
result_int2.add(y)
print(result_int2)
result_float1 = set()
result_float2 = set()
for x in DataSampling(float,[0,100],100):
result_float1.add(x)
print(result_float1)
for y in DataScreening(result_float1,(10,50)):
result_float2.add(y)
print(result_float2)
result_str1 = set()
result_str2 = set()
for x in DataSampling(str,string.ascii_letters+string.digits,100,20):
result_str1.add(x)
print(result_str1)
for y in DataScreening(result_str1,('in','out','1')):
result_str2.add(y)
print(result_str2)
|
475b530f09f5c753526330e52f8a478a5b001942 | WilmerLab/IPMOF | /ipmof/forcefield.py | 2,383 | 3.53125 | 4 | # IPMOF Force Field Functions
# Date: June 2016
# Author: Kutay B. Sezginel
import os
import math
import xlrd
import numpy as np
def read_ff_parameters(excel_file_path, ff_selection):
"""
Read force field parameters from an excel file according to force field selection
"""
# Read Excel File
force_field_data = xlrd.open_workbook(excel_file_path)
# Read columns to acquire force field parameters
atom_names = force_field_data.sheets()[0].col_values(0)[2:]
uff_sigma = force_field_data.sheets()[0].col_values(1)[2:]
uff_epsilon = force_field_data.sheets()[0].col_values(2)[2:]
dre_sigma = force_field_data.sheets()[0].col_values(3)[2:]
dre_epsilon = force_field_data.sheets()[0].col_values(4)[2:]
uff = {'atom': atom_names, 'sigma': uff_sigma, 'epsilon': uff_epsilon}
dre = {'atom': atom_names, 'sigma': dre_sigma, 'epsilon': dre_epsilon}
if ff_selection == 'uff':
return uff
if ff_selection == 'dre':
return dre
else:
print('No such force field')
def get_ff_parameters(atom_names, ff_parameters):
"""
Get force field parameters of the atom list and force field parameters you provide
"""
atom_ff_parameters = []
for atom in atom_names:
for ff_index, ff_atom in enumerate(ff_parameters['atom']):
if atom == ff_atom:
atom_name = atom
sigma = ff_parameters['sigma'][ff_index]
epsilon = ff_parameters['epsilon'][ff_index]
atom_ff_parameters.append([atom_name, sigma, epsilon])
return atom_ff_parameters
def lorentz_berthelot_mix(sigmaList1, sigmaList2, epsilonList1, epsilonList2):
"""
Lorentz-Berthelot mixing rules for given lists of sigma1, sigma2, epsilon1, and epsilon2
"""
sig = np.zeros([len(sigmaList1), len(sigmaList2)])
eps = np.zeros([len(epsilonList1), len(epsilonList2)])
for index1 in range(len(sigmaList1)):
for index2 in range(len(sigmaList2)):
sig[index1][index2] = (sigmaList1[index1] + sigmaList2[index2]) / 2
eps[index1][index2] = math.sqrt(epsilonList1[index1] * epsilonList2[index2])
return sig, eps
def lennard_jones(r, sig, eps):
"""
Calculate Lennard Jones potential for given distance, sigma, and epsilon values.
Energy unit: (kB)
"""
return 4 * eps * ((sig / r)**12 - (sig / r)**6)
|
9d113e03f1b7ce9b0a3683881a5a7c808ffcebdb | shrivastava-himanshu/Python-Programs | /sum_of_squares.py | 389 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 5 22:19:37 2018
@author: shrivh1
"""
def sum_of_squares():
sum_of_sq = 0
sum_of_num= 0
list1 = [1,2,3,4,5,6,7,8,9,10]
for i in list1:
sum_of_sq += int(i*i)
for j in list1:
sum_of_num += int(j)
diff = int(sum_of_squares - (sum_of_num*sum_of_num))
print(diff)
sum_of_squares() |
cf70c3017c65dc53e86909121e95ab30dc0d85a7 | ghlee0304/tensorflow-basic-and-advanced | /Basic_ver2/lec1_basic_for_ml/lec1_1_load_data.py | 1,030 | 3.5 | 4 | import numpy as np
'''
1.For Classification Problem
Data frame : (features, class)
Data format : csv
'''
iris_data = np.loadtxt("./data/iris.csv", delimiter=',')
features = iris_data[:, :-1]
labels = iris_data[:, -1]
nsamples = len(iris_data)
ndims = np.size(features, 1) #np.shape(features)[1]
nclass = len(set(labels))
print("#"*15,"Data Summary", "#"*15)
print("\n> The number of data samples : {:d}".format(nsamples))
print("> Dimensions of data : {:d}".format(ndims))
print("> The number of classes : {:d}\n".format(nclass))
'''
2.For Regression Problem
Data frame : (features, target)
Data format : csv
'''
nile_data = np.loadtxt("./data/nile.csv", delimiter=',')
features = nile_data[:, :-1]
targets = nile_data[:, -1]
nsamples = len(nile_data)
ndims = np.size(features, 1)
print("#"*15, "Data Summary", "#"*15)
print("\n> The number of data samples : {:d}".format(nsamples))
print("> Dimensions of data : {:d}".format(ndims))
print(targets)
|
1f91de7c0b564804f11d9f3466b4375a96feae36 | rafacharlie/POO2 | /python/ej6/Tiempo.py | 1,730 | 3.859375 | 4 | '''
Crea la clase Tiempo con los métodos suma y resta. Los objetos de la clase Tiempo
son intervalos de tiempo y se crean de la forma Tiempo t = new Tiempo(1, 20,
30) donde los parámetros que se le pasan al constructor son las horas, los
minutos y los segundos respectivamente. Crea el método toString para ver los
intervalos de tiempo de la forma 10h 35m 5s. Si se suman por ejemplo 30m 40s y
35m 20s el resultado debería ser 1h 6m 0s. Realiza un programa de prueba para
comprobar que la clase funciona bien.
@author: Rafael Infante
'''
class Tiempo:
'''Constructor'''
def __init__(self,horas,minutos,segundos):
self.horas=horas
self.minutos=minutos
self.segundos=segundos
'''Metodo que suma
*
* @param: objeto
* @return: objeto
'''
def suma(self,tiempo):
self.horas= self.horas+tiempo.horas
self.minutos=self.minutos+tiempo.minutos
self.segundos=self.segundos+tiempo.segundos
if self.minutos>=60:
self.horas+=1
self.minutos-=60
if self.segundos>=60:
self.minutos+=1
self.segundos-=60
'''Metodo que suma
*
* @param: objeto
* @return: objeto
'''
def resta(self,tiempo):
self.horas= self.horas-tiempo.horas
self.minutos=self.minutos-tiempo.minutos
self.segundos=self.segundos-tiempo.segundos
if self.minutos>=60:
self.horas+=1
self.minutos-=60
if self.segundos>=60:
self.minutos+=1
self.segundos-=60
#return tiempo(horas,minutos,segundos)
def __str__(self):
cadena="Tiempo [hora=" + str(self.horas) +", min=" + str(self.minutos) + ", seg=" + str(self.segundos) + "]"
return cadena
|
38eca6b7ea4e1ccf7c81495ef9cd4a74cd35c01b | CamiloCastiblanco/AYED-AYPR | /AYED/AYED 2020-1/repetidos.py | 257 | 3.703125 | 4 | def repe(lista):
x = []
for i in lista:
if int(i) not in x:
x.append(int(i))
return x
def main():
lista = input().strip().split(",")
l = repe(lista)
print(str(l).replace("[","").replace("]",""))
main()
|
060677ab59c8dfbdbe45344d815bd8f689d83eb3 | PowerLichen/pyTest | /HW7/HW1.py | 1,689 | 3.875 | 4 | """
Project: Homework 7.1
Author: 최민수
StudentID: 21511796
Date of last update: Apr. 19, 2021
Detail: Person 클래스를 생성자, 접근자, 변경자와 출력 함수를 포함하여 구현
"""
class Person:
# define initiator
def __init__(self,name,reg_id,age):
self.setName(name)
self.setRegId(reg_id)
self.setAge(age)
# define accessor
def getName(self):
return self.name
def getRegId(self):
return self.reg_id
def getAge(self):
return self.age
# define mutator
def setName(self, name):
if str(type(name)) != "<class 'str'>":
name="NoName"
self.name = name
def setRegId(self, reg_id):
if reg_id>999999:
print("*** Error in setting Reg Id (name:{}, RegId:{})".format(self.name,reg_id))
reg_id=0
self.reg_id =reg_id
def setAge(self, age):
if age<1 or age>150:
print("*** Error in setting age (name:{}, age:{})".format(self.name,age))
age=0
self.age=age
def __str__(self):
s = "Person(\"{}\",{},{})".format(self.name,self.reg_id,self.age)
return s
def printPersonList(L_persons):
for p in L_persons:
print(" ", p)
######################################################
# Application
if __name__ == "__main__":
persons = [
Person("Kim", 990101, 21),
Person("Lee", 980715, 22),
Person("Park", 101225, 20),
Person("Hong", 110315, 19),
Person("Yoon", 971005, 23),
Person("Wrong", 100000, 350)
]
print("persons : ")
printPersonList(persons) |
f8af0e29ffbb02377f36acce351254f9ca9eb1de | shamiliraghul/python | /posneg.py | 112 | 4.0625 | 4 | num=int(input())
if(num>0):
print("the num is positive")
elif(num<0):
print("the num is negative")
|
7eb53eb6fd35de13d96220b2dcb1eed0bc96b98b | GlebovAlex/2020_eve_python | /Priya_Homework/PayComputation.py | 594 | 4.28125 | 4 | # Rewrite your pay computation with time-and-a-half for overtime and create a function called compute pay which takes two parameters ( hours and rate).
# Enter Hours: 45
# Enter Rate: 10
# Pay: 475.0
def computePay(hours, rate):
pay = 0
if hours <= 40:
pay = hours * rate
elif hours > 40:
pay = (hours - 40) * (rate * 1.5) + (40 * rate)# extra hours * overtime rate plus regular pay
return pay
# userHours = float(input("Enter hours: "))
# userRate = float(input("Enter the rate of pay: "))
print("Your Pay is: " + str(computePay(45, 10))) |
95d660a700537f9a6ae5df20d7d6f1117f3e6048 | xiaoyuechen/numerical-analysis | /lab11/runge_kutta.py | 1,105 | 3.78125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def runge_kutta4(f, h, t0, y0, tn):
"""use Runge-Kutta 4th order method to solve ODE at tn
Parameters
__________
f : the right hand side of the ODE
h : resolution
t0 : the initial position
y0 : the initial value
tn : the unknown position
Returns
_______
ys : the values including the intermediate values
tn's value is at the end (returning the
intermediates are continent for plotting)
"""
n = int((tn - t0) / h) + 1
ys = np.zeros((y0.shape[0], n))
ys[:, 0] = y0
for i in range(0, n - 1):
ti = t0 + h * i
yi = ys[:, i]
k1 = h * f(ti, yi)
k2 = h * f(ti + h / 2, yi + k1 / 2)
k3 = h * f(ti + h / 2, yi + k2 / 2)
k4 = h * f(ti + h, yi + k3)
ys[:, i + 1] = yi + k1 / 6 + k2 / 3 + k3 / 3 + k4 / 6
return ys
if __name__ == "__main__":
f = lambda t, y: np.array([y[1], 3 / 2 * y[0]])
ys = runge_kutta4(f, 0.01, 0, np.array([4, -5]), 1)
xs = np.linspace(0, 1, 101)
plt.plot(xs, ys[0])
plt.show()
|
e66efbb1a0c69e8023d5c9bd093fadad5469990e | supasole9/Angry-Ball | /game.py | 4,109 | 3.828125 | 4 | import pygame
import random
# import classes necessary to create the game
from ball import Ball
from bar import Bar
from text import Text
# possible game states
STATUS_PLAYING = 1
STATUS_LOSE = 2
STATUS_WIN = 3
#
# The game contains one Ball and one Bar. It moves them
# each frame. If they collide the game is over, and stops
# allowing motion.
#
# The Ball and Bar are drawn every frame. If the game is
# over, then a Text message is also drawn.
#
class Game:
# create all of the objects necessary for the game play and display
def __init__(self, width, height):
self.mWidth = width
self.mHeight = height
self.mBall = Ball(width/3, height/2, 10, (255, 255, 0))
self.mBars = []
self.mbotBars = []
self.spawnBar()
#self.spawnbotBar()
self.mCount = 0
self.mPoints = 0
#self.mBar = Bar(width/2, height/3, 100, 10, (255, 255, 0))
#self.mBar.accelerate(20)
self.mGameOver = False
self.mGameStatus = STATUS_PLAYING
self.mWinnerMessage = Text("You Win!", self.mWidth/2, self.mHeight/2)
self.mLoserMessage = Text("Sorry, try again.", self.mWidth/2, self.mHeight/2)
return
# accelerate the ball vertically by a specified amount
def bounceBall(self, amount):
self.mBall.bounce(amount)
return
def spawnBar(self):
h = random.randrange(100, 450, 25)
color = (random.randrange(1, 256), random.randrange(1, 256), random.randrange(1, 256))
bar = Bar(550, 0, 50, h, color)
bar.accelerate(20)
self.mBars.append(bar)
color2 = (random.randrange(1, 256), random.randrange(1, 256), random.randrange(1, 256))
randy = h + 100
botbar = Bar(550, randy, 50, 500-randy, color)
botbar.accelerate(20)
self.mbotBars.append(botbar)
return
# move all of the objects, according to the physics of this world
def evolve(self):
if self.mGameOver:
# game over, nothing will move
return
self.mPointsmessage = Text("Points = "+str(self.mPoints), 400, 400)
# move the Ball and Bar
self.mBall.evolve(self.mHeight)
for botbar in self.mbotBars:
botbar.evolve(self.mWidth)
for bar in self.mBars:
bar.evolve(self.mWidth)
if self.mBars[self.mCount].getX() < 150:
self.spawnBar()
#self.spawnbotBar()
self.mCount += 1
self.mPoints +=1
# check for collisions
if self.mBall.collidesWithBarToLose(bar):
print self.mPoints
self.mGameOver = True
self.mStatus = STATUS_LOSE
elif self.mBall.collidesWithBarToLose(botbar):
print self.mPoints
self.mGameOver = True
self.mStatus = STATUS_LOSE
elif self.mBall.hitground():
print self.mPoints
self.mGameOver = True
self.mStatus = STATUS_LOSE
elif self.mBall.hitroof():
print self.mPoints
self.mGameOver = True
self.mStatus = STATUS_LOSE
return
# redraw the whole screen
def draw(self, surface):
# make the background, be drawing a solid colored rectangle
rect = pygame.Rect(0, 0, self.mWidth, self.mHeight)
pygame.draw.rect(surface, (169,169,169), rect, 0)
self.mPointsmessage.draw(surface)
# draw the Ball and Bar
self.mBall.draw(surface)
for bar in self.mBars:
bar.draw(surface)
for botbar in self.mbotBars:
botbar.draw(surface)
#botbar.draw(surface)
if self.mGameOver:
# draw end of game message
if self.mStatus == STATUS_LOSE:
self.mLoserMessage.draw(surface)
elif self.mStatus == STATUS_WIN:
self.mWinnerMessage.draw(surface)
return
|
aa2b4a859e3150ce9dc059830bfbf24eb422ea88 | samgottuso/poker_simulator | /read_hand.py | 3,106 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 8 20:01:34 2018
@author: 583185
"""
#Getting rid of our outside betting logic for testing the main play_hand script
#Checking what cards people have
def read_hand(version,hand,players):
players_list=[]
players_initial={}
if version=='players':
for x in range(0,players):
players_list.append("player{0}".format(x))
card1=vars(hand[players_list[x]][0])
card2=vars(hand[players_list[x]][1])
max_value=max(card1['value'],card2['value'])
if (card1['value'])==card2['value']:
# print("Pair of ",card1['value'])
players_initial[players_list[x]]={'hand':'pair','value':max_value,'suit':'N/A'}
# elif (card1['value']-card2['value']==abs(1)):
## print("Outside straight draw")
# players_initial[players_list[x]]={'hand':'outside straight','value':max_value,'suit':'N/A'}
#assuming that a 10 or higher is better than an outside flush draw, might have to revisit it
elif (card1['value'] >= 10 or card2['value']>=10):
# print("high card of", max_value)
players_initial[players_list[x]]={'hand':'high card','value':max_value,'suit':'N/A'}
# elif (card1['suit']==card2['suit']):
## print("Flush draw")
# players_initial[players_list[x]]={'hand':'outside flush','value':max_value,'suit':card1['suit']}
else:
# print (max(card1['value'],card2['value']))
players_initial[players_list[x]]={'hand':'high card','value':max_value,'suit':'N/A'}
elif version == 'dealer':
#find if there are any pairs or outside straight draws or flush draws
for x in range(0,players):
card1=vars(hand['dealer_hand'][0])
card2=vars(hand['dealer_hand'][1])
max_value=max(card1['value'],card2['value'])
if (card1['value'])==card2['value']:
# print("Pair of ",card1['value'])
players_initial['dealer_hand']={'hand':'pair','value':max_value,'suit':'N/A'}
# elif (card1['value']-card2['value']==abs(1)):
## print("Outside straight draw")
# players_initial['dealer_hand']={'hand':'outside straight','value':max_value,'suit':'N/A'}
#assuming that a 10 or higher is better than an outside flush draw, might have to revisit it
elif (card1['value'] >= 10 or card2['value']>=10):
# print("high card of", max_value)
players_initial['dealer_hand']={'hand':'high card','value':max_value,'suit':'N/A'}
# elif (card1['suit']==card2['suit']):
## print("Flush draw")
# players_initial['dealer_hand']={'hand':'outside flush','value':max_value,'suit':card1['suit']}
else:
# print (max(card1['value'],card2['value']))
players_initial['dealer_hand']={'hand':'high card','value':max_value,'suit':'N/A'}
return(players_initial)
|
7be426a09350d91b77e47914b7ee956edb5e4bab | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 1/Exercise 009 - Compound Interest.py | 1,458 | 3.609375 | 4 | # Fate finta di aver appena aperto un nuovo conto di risparmio che guadagna il 4% di interessi all'anno.
# L'interesse che si guadagna viene pagato alla fine dell'anno e viene aggiunto al saldo del conto di risparmio.
# Scrivete un programma che inizi leggendo l'importo del denaro depositato sul conto dall'utente. Poi il programma
# dovrebbe calcolare e visualizzare l'importo nel conto di risparmio dopo 1, 2 e 3 anni. Visualizzate ogni importo
# in modo che sia arrotondato a 2 cifre decimali.
# interesse per ogni fine anno
int_annuo=4/100 #4%
deposito=float(input("Inserire l'importo da depositare: "))
print("\nIl tuo deposito attuale è di: $",deposito)
deposito2=(deposito*int_annuo) # interesse 4% del primo anno
importo1=deposito+deposito2 # importo del primo anno + l'interesse
print("\nIl primo anno ha generato un'interesse di $%.2f" % deposito2,
"\nil totale nel tuo conto è di $:%.2f" % importo1)
interesse2=importo1*int_annuo # interesse 4% del secondo anno
importo2=importo1+interesse2 # importo del secondo anno + l'interesse
print("\nIl secondo anno ha generato un'interesse di $%.2f" % interesse2,
"\nil totale nel tuo conto è di $:%.2f" % importo2)
interesse3=importo2*int_annuo # interesse 4% del secondo anno
importo3=importo2+interesse3 # importo del secondo anno + l'interesse
print("\nIl terzo anno ha generato un'interesse di $%.2f" % interesse3,
"\nil totale nel tuo conto è di $:%.2f" % importo3)
|
60637bc6ed6c85ac41487ee21451eeebb26d62e0 | DEEPAKVETTU/deepakvettu | /exhun123.py | 140 | 4.125 | 4 | mainstring=input("Enter string:")
sub_str=input("Enter word:")
if(mainstring.find(sub_str)==-1):
print("NO")
else:
print("YES")
|
c5132487d466b91b2000e33025429375f9722434 | rvaughan74/challenge_answers | /python/anglebracket.py | 1,739 | 3.984375 | 4 | """#hired.com coding assessment challenge.
For a given string of angle brackets ensure all < and > are matched off.
example
solution("><<>") -> "<><<>>"
--------------------------------
Ryan Vaughan - 2021-09-21
Reason for saving to github repository: Problem stuck in my mind after a
strange error, and then timeout prevented me from solving properly on
hired.com. (Be very careful with recursion...)
"""
from random import choice, randint
def solver(to_solve="", check="<", opposite=">"):
"""solver - return an array of opposite to close off each check in to_solve.
Args:
to_solve (str, optional): String to close off each case of check
found in. Defaults to "".
check (str, optional): The opening character. Defaults to "<".
opposite (str, optional): The closing character. Defaults to ">".
Returns:
list[str]: The list of opposites for each check.
"""
result = list()
for letter in to_solve:
if letter in check:
result.append(opposite)
elif letter in opposite:
if len(result) > 0:
result.pop()
return result
def solution(st):
"""solution - provide the solution to the assigned problem
Args:
st (str): String to solve the problem on.
Returns:
str: The solution.
"""
closing_queue = solver(st, "<", ">")
opening_queue = solver(st[::-1], ">", "<")
return "".join(opening_queue) + st + "".join(closing_queue)
if __name__ == "__main__":
selection = "<>"
characters = [choice(selection) for i in range(randint(1, 15))]
test = "".join(characters)
# test = "><<>"
print(test)
print(solution(test))
|
bf18f257e357a52af43a1d4b029afe9d88818292 | rafaelperazzo/programacao-web | /moodledata/vpl_data/380/usersdata/322/77671/submittedfiles/testes.py | 174 | 3.734375 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABA
a= int(input('digitar valor para a: '))
b= int(input('digitar valor para b: '))
if(a=b):
print('sim')
else:
print('nao')
|
1917591bbec5b0ccc6efb12cb80feca06bb18251 | aj-spec/emotion-based-music-recommendation | /server/api/rs/rs.py | 15,033 | 3.53125 | 4 | from endpoints import watson, twitter
import pandas as pd
import math
"""
This file contains the necessary recommendation algorithms which identify and suggest the final songs to be added to new playlists. The following emotional mapping between music features and
emotion are estimated with Thayers 2D Emotional Model.
"""
def playlist_rs(feature_data, tones, per_song, num_songs):
"""This is the main playlist generation function. Feature_data is the list of tracks and their associated music feature data retrieved from spotify.
The algorithm will check the users predicted emotion from per_song and this dictionary tells the algorithm how many of each song's emotion type will be added
to the final playlist based on the music feature data. The mapping between valence and energy is calculated based on Thayers 2-D Emotional Model
http://www.icact.org/upload/2011/0386/20110386_finalpaper.pdf
"""
playlist_tracks = []
# using pandas dataframe to manipulate songs
df = pd.DataFrame.from_dict(feature_data)
# all_tracks
all_tracks = df.copy()
all_tracks = all_tracks.drop(['energy', 'valence'], axis=1)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
# joy_tracks
joy_tracks = df.copy()
joy_tracks = joy_tracks[joy_tracks['energy'] > 0.5]
joy_tracks = joy_tracks[joy_tracks['valence'] > 0.5]
# shuffle joy_tracks
joy_tracks = joy_tracks.sample(frac=1).reset_index(drop=True)
# anger_tracks
anger_tracks = df.copy()
anger_tracks = anger_tracks[anger_tracks['energy'] > 0.5]
anger_tracks = anger_tracks[anger_tracks['valence'] < 0.5]
# shuffle anger_tracks
anger_tracks = anger_tracks.sample(frac=1).reset_index(drop=True)
# sad_tracks
sad_tracks = df.copy()
sad_tracks = sad_tracks[sad_tracks['energy'] < 0.5]
sad_tracks = sad_tracks[sad_tracks['valence'] < 0.5]
# shuffle sad_tracks
sad_tracks = sad_tracks.sample(frac=1).reset_index(drop=True)
# calm_tracks
calm_tracks = df.copy()
calm_tracks = calm_tracks[calm_tracks['energy'] < 0.5]
calm_tracks = calm_tracks[calm_tracks['valence'] > 0.5]
# shuffle calm_tracks
calm_tracks = calm_tracks.sample(frac=1).reset_index(drop=True)
# check what tones have been calculated
tone_scores = [0, 0, 0, 0]
songs_per_tone = [0, 0, 0, 0]
# joy[0],anger[1],sadness[2],calm[3]
# fill tone_scores
if 'joy' in tones.keys():
tone_scores[0] = tones['joy']
if 'anger' in tones.keys():
tone_scores[1] = tones['anger']
if 'sadness' in tones.keys():
tone_scores[2] = tones['sadness']
if 'calm' in tones.keys():
tone_scores[3] = tones['calm']
# fill tone_songs
if 'joy' in per_song.keys():
songs_per_tone[0] = per_song['joy']
if 'anger' in per_song.keys():
songs_per_tone[1] = per_song['anger']
if 'sadness' in per_song.keys():
songs_per_tone[2] = per_song['sadness']
if 'calm' in per_song.keys():
songs_per_tone[3] = per_song['calm']
# loop, only decrementing the counter when a song is added to playlist__tracks list of ids
count1 = 0
while(count1 < num_songs):
for i in range(len(tone_scores)): # repeatedly loop through each song type
if songs_per_tone[i] == 0: # no songs to add of this emotion
i += 1 # skip to next song type in list
# Joy
elif songs_per_tone[i] > 0 and i == 0: # songs_per_tone[0] = 25 aka: there are 25 joy songs left to be added to the final playlist
temp_song = joy_tracks.at[0, 'id'] # joy song to be added to playlist
if temp_song not in playlist_tracks: # Prevent duplicate tracks
playlist_tracks.append(temp_song)
songs_per_tone[i] -= 1 # Decrement the song_per_tone value since we added a song to the playlist
joy_tracks.drop(0) # Remove this track from the dataframe since we have added it
joy_tracks = joy_tracks.sample(frac=1).reset_index(drop=True) # Shuffle the dataframe
count1 += 1
else:
joy_tracks = joy_tracks.sample(frac=1).reset_index(drop=True) # Well the track was already in the playlist, so lets shuffle the joy_track list
# Anger
elif songs_per_tone[i] > 0 and i == 1:
temp_song = anger_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
songs_per_tone[i] -= 1
anger_tracks.drop(0)
anger_tracks = anger_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
anger_tracks = anger_tracks.sample(frac=1).reset_index(drop=True)
# Sad
elif songs_per_tone[i] > 0 and i == 2:
temp_song = sad_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
songs_per_tone[i] -= 1
sad_tracks.drop(0)
sad_tracks = sad_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
sad_tracks = sad_tracks.sample(frac=1).reset_index(drop=True)
# Calm
elif songs_per_tone[i] > 0 and i == 3:
temp_song = calm_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
songs_per_tone[i] -= 1
calm_tracks.drop(0)
calm_tracks = calm_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
calm_tracks = calm_tracks.sample(frac=1).reset_index(drop=True)
# Empty List
elif (songs_per_tone[0] == 0) and (songs_per_tone[1] == 0) and (songs_per_tone[2] == 0) and (songs_per_tone[3] == 0):
temp_song = all_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
# songs_per_tone[i] -= 1
all_tracks.drop(0)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
return playlist_tracks
def random_rs(feature_data, num_songs):
"""Given music feature data, it ditches the columns of music feature data and instead generates a random playlist using a list of track ids.
This is an alternative playlist generation method, and it is currently not in use. """
playlist_tracks = []
# using pandas dataframe to manipulate songs
df = pd.DataFrame.from_dict(feature_data)
# all_tracks
all_tracks = df.copy()
all_tracks = all_tracks.drop(['energy', 'valence'], axis=1)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
count1 = 0
while count1 < num_songs:
temp_song = all_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
all_tracks.drop(0)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
return playlist_tracks
def joy_rs(feature_data, num_songs):
"""This is alternate playlist generation function, it creates a playlist of songs which are measured to have certain valence and energy statistics which represent
joyful songs. """
playlist_tracks = []
# Lets keep the playlist size range between 25-50
tot_songs = num_songs
if tot_songs > 50:
tot_songs = 50
# using pandas dataframe to manipulate songs
df = pd.DataFrame.from_dict(feature_data)
# all_tracks
all_tracks = df.copy()
all_tracks = all_tracks.drop(['energy', 'valence'], axis=1)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
# joy_tracks
joy_tracks = df.copy()
joy_tracks = joy_tracks[joy_tracks['energy'] > 0.5]
joy_tracks = joy_tracks[joy_tracks['valence'] > 0.5]
joy_tracks = joy_tracks.sample(frac=1).reset_index(drop=True)
count1 = 0
while count1 < tot_songs:
if joy_tracks.size > 0:
temp_song = joy_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
joy_tracks.drop(0)
joy_tracks = joy_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
joy_tracks = joy_tracks.sample(frac=1).reset_index(drop=True)
else:
# Pull random tracks from all_tracks
temp_song = all_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
all_tracks.drop(0)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
return playlist_tracks
def anger_rs(feature_data, num_songs):
"""This is alternate playlist generation function, it creates a playlist of songs which are measured to have certain valence and energy statistics which represent
angry songs. """
playlist_tracks = []
# Lets keep the playlist size range between 25-50
tot_songs = num_songs
if tot_songs > 50:
tot_songs = 50
# using pandas dataframe to manipulate songs
df = pd.DataFrame.from_dict(feature_data)
# all_tracks
all_tracks = df.copy()
all_tracks = all_tracks.drop(['energy', 'valence'], axis=1)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
# ang_tracks
ang_tracks = df.copy()
ang_tracks = ang_tracks[ang_tracks['energy'] > 0.5]
ang_tracks = ang_tracks[ang_tracks['valence'] < 0.5]
ang_tracks = ang_tracks.sample(frac=1).reset_index(drop=True)
count1 = 0
while count1 < tot_songs:
if ang_tracks.size > 0:
temp_song = ang_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
ang_tracks.drop(0)
ang_tracks = ang_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
ang_tracks = ang_tracks.sample(frac=1).reset_index(drop=True)
else:
# Pull random tracks from all_tracks
temp_song = all_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
all_tracks.drop(0)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
return playlist_tracks
def sad_rs(feature_data, num_songs):
"""This is alternate playlist generation function, it creates a playlist of songs which are measured to have certain valence and energy statistics which represent
sad songs. """
playlist_tracks = []
# Lets keep the playlist size range between 25-50
tot_songs = num_songs
if tot_songs > 50:
tot_songs = 50
# using pandas dataframe to manipulate songs
df = pd.DataFrame.from_dict(feature_data)
# all_tracks
all_tracks = df.copy()
all_tracks = all_tracks.drop(['energy', 'valence'], axis=1)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
# sad_tracks
sad_tracks = df.copy()
sad_tracks = sad_tracks[sad_tracks['energy'] < 0.5]
sad_tracks = sad_tracks[sad_tracks['valence'] < 0.5]
sad_tracks = sad_tracks.sample(frac=1).reset_index(drop=True)
count1 = 0
while count1 < tot_songs:
if sad_tracks.size > 0:
temp_song = sad_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
sad_tracks.drop(0)
sad_tracks = sad_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
sad_tracks = sad_tracks.sample(frac=1).reset_index(drop=True)
else:
# Pull random tracks from all_tracks
temp_song = all_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
all_tracks.drop(0)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
return playlist_tracks
def calm_rs(feature_data, num_songs):
"""This is alternate playlist generation function, it creates a playlist of songs which are measured to have certain valence and energy statistics which represent
calm songs. """
playlist_tracks = []
# Lets keep the playlist size range between 25-50
tot_songs = num_songs
if tot_songs > 50:
tot_songs = 50
# using pandas dataframe to manipulate songs
df = pd.DataFrame.from_dict(feature_data)
# all_tracks
all_tracks = df.copy()
all_tracks = all_tracks.drop(['energy', 'valence'], axis=1)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
# calm_tracks
calm_tracks = df.copy()
calm_tracks = calm_tracks[calm_tracks['energy'] < 0.5]
calm_tracks = calm_tracks[calm_tracks['valence'] > 0.5]
calm_tracks = calm_tracks.sample(frac=1).reset_index(drop=True)
count1 = 0
while count1 < tot_songs:
if calm_tracks.size > 0:
temp_song = calm_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
calm_tracks.drop(0)
calm_tracks = calm_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
calm_tracks = calm_tracks.sample(frac=1).reset_index(drop=True)
else:
# Pull random tracks from all_tracks
temp_song = all_tracks.at[0, 'id']
if temp_song not in playlist_tracks:
playlist_tracks.append(temp_song)
all_tracks.drop(0)
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
count1 += 1
else:
all_tracks = all_tracks.sample(frac=1).reset_index(drop=True)
return playlist_tracks
|
312cf0b7383819a7bdc2e5c0b0dc3e2754d78a22 | daniel-petrov/blackjack | /deck.py | 799 | 3.828125 | 4 | from card import Card
from random import shuffle
class Deck:
def __init__(self):
self.ranks = ['Ace', 'King', 'Queen', 'Jack', '10', '9', '8', '7', '6', '5', '4', '3', '2']
self.suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
# self.deck = []
# for suit in self.suits:
# for rank in self.ranks:
# card = Card(suit, rank)
# self.deck.append(card)
# do the same what's above using list comprehension
self.deck = [Card(suit=i, rank=j) for i in self.suits for j in self.ranks]
# print([i.display() for i in self.deck])
def shuffle(self):
shuffle(self.deck)
def next_card(self):
return self.deck.pop()
def cards_left(self):
return len(self.deck)
|
4e0e7a4a67fc7c2d4d0d84175ce60c26fa51cccf | luis2535/Python | /bhaskaraatualizado.py | 484 | 3.6875 | 4 | import math
def delta(x,y,z):
return y**2-4*x*z
def imprime_raiz(x,y,z):
if delta(x,y,z)==0:
x=(-y)/(2*x)
print("a raiz desta equação é", x)
elif delta>0:
x1=(-y - math.sqrt(delta(x,y,z)))/(2*x)
x2=(-y + math.sqrt(delta(x,y,z)))/(2*x)
print("as raízes da equação são", x1, "e", x2)
else:
print("esta equação não possui raízes reais")
a=float(input())
b=float(input())
c=float(input())
imprime_raiz(a,b,c)
|
15e1283a5de5d9a3da02a6df9f654aaecf56245e | AntonyXXu/Learning | /Python practice/LeetCode/balanceBST.py | 941 | 3.859375 | 4 | class Node:
def __init__(self, val, left = None, right = None):
self.val = val
self.left = left
self.right = right
r = Node(5)
r.left = Node(4)
r.left.left = Node(3)
r.left.left.left = Node(2)
r.left.left.left.left = Node(1)
r.right = Node(6)
def traverse(node, arr):
if not node:
return
traverse(node.left, arr)
arr.append(node.val)
traverse(node.right, arr)
def build(arr, low, high):
if low > high:
return None
mid = (low + high) // 2
node = Node(arr[mid])
node.left = build(arr, low, mid - 1)
node.right = build(arr, mid + 1, high)
return node
def bal(root):
arr = []
curr = root
traverse(curr, arr)
r = build(arr, 0, len(arr)-1)
return r
def show(node):
if not node:
return
show(node.left)
print(node.val)
show(node.right)
show(bal(r))
print(bal(r).val)
print(bal(r).left.val)
print(bal(r).right.val) |
4239f2ebedb0b74d534ecbf95d849762a95a0a16 | aswanthkoleri/Competitive-codes | /Top 20 Dyanammic programs(GFG)/5_rec.py | 191 | 3.71875 | 4 | def count(n):
if n==0:
return 1
elif n<0:
return 0
else:
return count(n-1)+count(n-2)+count(n-3)
def main():
n=int(input())
print(count(n))
main() |
4ce4fb2dc8c4c87cbdb19077a9995216557094e7 | wangdejun/PythonNotes | /basic_practice/reverse_string.py | 112 | 3.71875 | 4 | def reverse(text):
li = ""
for c in text:
li = c + li
return li
print reverse("wangdejun") |
05a818058a8317d73bb14fde74c0b89f80616968 | dervlascully/GirlScriptPython | /Week2/Exercise3.py | 285 | 4 | 4 | # Given a list iterate it and display numbers which are
# divisible by 5 and if you find number greater than 150
# stop the loop iteration
list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
for x in list1:
if x > 150:
break
elif x % 5 == 0:
print(x)
|
f33a20e5b535e2c2e3c9621d8c9352121e222f80 | aa-fahim/practice-python | /ListComprehensions.py | 179 | 3.71875 | 4 | ## Takes array a and places elements which are even in new array then prints it
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
new_a = [i for i in a if i % 2 == 0]
print(new_a) |
3189425ca0e467691aa57adab134815ffef2cbcc | Jwilson1172/Computer-Architecture | /ls8/cpu.py | 24,384 | 3.5625 | 4 | """CPU functionality."""
from sys import argv
import time
from time import time
import numpy as np
from sklearn.linear_model import LinearRegression
# for keyboard int
# and timer int
import sys
import threading
from util import Queue
def add_input(input_queue):
while True:
input_queue.enqueue(sys.stdin.read(1))
return
class CPU:
"""Main CPU class."""
# by default I want to make RAM 256 bytes this is the default for the ls-8
# I also wanted to leave the option open for increasing the ram_size to
# something larger to hold larger programs/stacks
def __init__(self, DBG=False, ram_size=256):
"""Construct a new CPU."""
self.input_queue = Queue()
self.input_thread = threading.Thread(target=add_input,
args=(self.input_queue, ))
self.input_thread.daemon = True
if ram_size >= 4096:
self.signed = True
# set to NOP by default
self.pc = 0
# global toggle settings
self.running = False
# the IR register is just going to hold a copy of the PC reg
self.ir = 0
# init the interuption
self.interruption_signal = 0b00000000
self.interruption_mask = 0b00000000
# stack pointer set to the 7th registry
self.sp = 7
# set the interuption mask pointer to the 5th registry
self.im = 5
# set the interruption status/signal as registry 6
self.IS = 6
# general pourpose registry for holding the arguments for the operations
self.reg = [0] * 8
# setting the stack pointer to the defualt location
# made it scale off of ram size
self.reg[self.sp] = ram_size - (256 - 0xF3)
# set the interruption mask and signal as cleared
self.reg[self.IS] = 0b00000000
self.reg[self.im] = 0b00000000
# from my understanding this part of the ram stores the address to
# the interuption handler
self.I_vectors = [0] * 8
# int toggle
self._w = False
# flag register
self.fl = 0
# initalize the hash table that will be acting as ram
self.RAM = {k: None for k in range(ram_size)}
# global debugging toggle
self.DBG = DBG
self.clock = 0
def ram_read(self, address):
return self.RAM[address]
def ram_write(self, address, value):
self.RAM[address] = value
return
###########################################################################
# Instructions #
###########################################################################
JMP = 0b01010100
LDI = 0b10000010
NOP = 0b00000000
HLT = 0b00000001
INT = 0b01010010
# printing instructions
PRN = 0b01000111
PRA = 0b01001000
# supported cmp jumps
JEQ = 0b01010101
JNE = 0b01010110
# other cmp jumps
JGT = 0b01010111
JGE = 0b01011010
JLE = 0b01011001
JLT = 0b01011000
# counter
DEC = 0b01100110
INC = 0b01100101
# compare
CMP = 0b10100111
# shifting
SHL = 0b10101100
SHR = 0b10101101
# arithmetic
MUL = 0b10100010
MOD = 0b10100100
DIV = 0b10100011
SUB = 0b10100001
ADD = 0b10100000
MLP = 0b10100010
# logic
OR = 0b10101010
NOT = 0b01101001
XOR = 0b10101011
AND = 0b10101000
# ram
LD = 0b10000011
ST = 0b10000100
# stack
PUSH = 0b01000101
POP = 0b01000110
# coroutines
RET = 0b00010001
CALL = 0b01010000
# 16bit instructions
# 0b000000000 0 0 0 0 0 0 0
# 0b123456789 10 11 12 13 14 15 16
# for functions use 0b01
# 0b0100000000000000
# for markers or flags use 0b10
# 0b1000000000000000
ARRAY_START = 0b1000000000000000
ARRAY_STOP = 0b1000000000000001
LOAD_A = 0b0100000000000000
MEAN = 0b0100000000000010
JOIN = 0b0100000000000100
INPUT = 0b0010000000000000
# ML OPS (no not the cool kind)
FIT = 0b0100000000000111
PRED = 0b0100000000000101
# lazy conv
lazy_table = {
0: 1,
1: 2,
2: 4,
3: 8,
4: 16,
5: 32,
6: 64,
7: 128,
}
###########################################################################
# Instruction Functions #
###########################################################################
# Logic
def instr_or(self):
"""Perform a bitwise-OR between the values in registerA and registerB,
storing the result in registerA"""
self.reg[self.ram_read(self.pc +
1)] |= self.reg[self.ram_read(self.pc + 2)]
return
def instr_and(self):
"""REG[A] = AND(REG[A],REG[B])"""
self.reg[self.ram_read(self.pc +
1)] &= self.reg[self.ram_read(self.pc + 2)]
return
def instr_xor(self):
"""REG[A] = XOR(REG[A],REG[B])"""
self.reg[self.ram_read(self.pc +
1)] ^= self.reg[self.ram_read(self.pc + 2)]
return
def instr_not(self):
"""REG[A] = ~REG[A]"""
self.reg[self.ram_read(self.pc +
1)] = ~self.reg[self.ram_read(self.pc + 1)]
return
# stacks
def pop(self):
"""take the value from the top of the stack and load it into the
register that is specified byself.pc+ 1
"""
# not quite sure how to handle the underflow
# of the stack but for now we can hlt
# @TODO
if self.reg[self.sp] >= 0xF3:
print("STACK UNDERFLOW DETECTED")
self.hlt()
return
# get the value from the stack
stack_value = self.ram_read(self.reg[self.sp])
# get the target register from ram
register_number = self.ram_read(self.pc + 1)
# set the value of the register = to the value pulled off the stack
self.reg[register_number] = stack_value
# increment the stack pointer
self.reg[self.sp] += 1
# increment the program counter
self.pc += 2
return
def push(self):
"""loads the args from the ram usingself.pc+ 1,2 respectively
then write the value from the register to the top of the stack then
decrement the stack and advance the pc"""
# @TODO
if self.reg[self.sp] <= self.pc:
print("OverFlow Detected: HALTING")
self.hlt()
return
# decrement the stack pointer
self.reg[self.sp] -= 1
# get the current stack pointer
stack_address = self.reg[self.sp]
# get the register number from ram
register_number = self.ram_read(self.pc + 1)
# pull the data value from the register
value = self.reg[register_number]
# write value to the stack address
self.ram_write(stack_address, value)
# inc. program counter
self.pc += 2
return
# subroutines
def call(self):
# decrement the stack pointer
self.reg[self.sp] -= 1
# get the current stack pointer value
stack_address = self.reg[self.sp]
# address of the next instr to return to
returned_address = self.pc + 2
# write to the stack address with the value of return address
self.ram_write(stack_address, returned_address)
# get the register number from ram
register_number = self.ram_read(self.pc + 1)
# set the current program counter to the value stored in the register
self.pc = self.reg[register_number]
return
def ret(self):
# pull the return address from the stack and set the current program
# counter to that address
self.pc = self.ram_read(self.reg[self.sp])
# increment the stack pointer
self.reg[self.sp] += 1
return
# other operators
def prn(self):
"""prints value in register PC + 1,
then increments the program counter."""
print(self.reg[self.ram_read(self.pc + 1)])
self.pc += 2
return
def pra(self):
print(chr(self.reg[self.ram_read(self.pc + 1)]))
self.pc += 2
def nop(self):
"""Does nothing, advances the PC"""
self.pc += 1
return
def hlt(self):
"""Signals the run while loop to stop"""
self.running = False
self.pc += 1
return
def jmp(self) -> None:
"""Jump to location provided in register"""
self.pc = self.reg[self.ram_read(self.pc + 1)]
return
def ldi(self):
"""f(A,B) | REG[A] = B, PC +3"""
self.reg[self.ram_read(self.pc + 1)] = self.ram_read(self.pc + 2)
self.pc += 3
return
def st(self):
"""f(A,B) | RAM[REG[B]] = REG[A]"""
reg_a, reg_b = self.ram_read(self.pc + 1), self.ram_read(self.pc + 2)
self.ram_write(self.reg[reg_b], self.reg[reg_a])
self.pc += 3
return
# alu instructions
def alu(self, operation, reg_a, reg_b):
"""ALU operations."""
if operation == self.ADD:
self.reg[reg_a] += self.reg[reg_b]
elif operation == self.SUB:
self.reg[reg_a] -= self.reg[reg_b]
elif operation == self.MUL:
self.reg[reg_a] *= self.reg[reg_b]
elif operation == self.DIV:
self.reg[reg_a] /= self.reg[reg_b]
else:
raise Exception("ALU operation not supported")
def add(self):
reg_a = self.ram_read(self.pc + 1)
reg_b = self.ram_read(self.pc + 2)
self.alu(self.ir, reg_a, reg_b)
self.pc += 3
return
def sub(self):
reg_a = self.ram_read(self.pc + 1)
reg_b = self.ram_read(self.pc + 2)
self.alu(self.ir, reg_a, reg_b)
self.pc += 3
return
def mul(self):
reg_a = self.ram_read(self.pc + 1)
reg_b = self.ram_read(self.pc + 2)
self.alu(self.ir, reg_a, reg_b)
self.pc += 3
return
def div(self):
reg_a = self.ram_read(self.pc + 1)
reg_b = self.ram_read(self.pc + 2)
self.alu(self.ir, reg_a, reg_b)
self.pc += 3
return
def mod(self):
reg_a = self.ram_read(self.pc + 1)
reg_b = self.ram_read(self.pc + 2)
self.reg[reg_a] %= self.reg[reg_b]
self.pc += 3
return
def jeq(self):
"""Jump to address stored in REG[PC +1] if the equals flag (self.fl) is set"""
if not self.fl & 0b1:
self.pc += 2
elif self.fl & 0b1:
reg_a = self.ram_read(self.pc + 1)
self.pc = self.reg[reg_a]
return
def jne(self):
"""same as jeq but jumps on not equal"""
if self.fl & 0b1:
self.pc += 2
elif not self.fl & 0b0:
reg_a = self.ram_read(self.pc + 1)
self.pc = self.reg[reg_a]
return
def shl(self):
# get both of the registers
reg_a = self.ram_read(self.pc + 1)
reg_b = self.ram_read(self.pc + 2)
# shift the reg_a by the amount stored in reg_b
self.reg[reg_a] <<= self.reg[reg_b]
# advance pc
self.pc += 3
return
def shr(self):
# get both of the registers
reg_a = self.ram_read(self.pc + 1)
reg_b = self.read_ram(self.pc + 2)
# shift the value in the first registry by the value in the second
# registry and store the result in the reg_a
self.reg[reg_a] >>= self.reg[reg_b]
# advance pc
self.pc += 3
return
def inc(self):
# increment the register that is passed in ram
self.reg[self.ram_read(self.pc + 1)] += 1
# increment the pc
self.pc += 2
return
def dec(self):
# decrement the register that is passed in ram
self.reg[self.ram_read(self.pc + 1)] -= 1
self.pc += 2
return
def cmp(self) -> None:
"""This Function takes the regerister arguments and sets the flag register
accordingly see the spec for a breakdown on the flags
"""
reg_a = self.ram_read(self.pc + 1)
reg_b = self.ram_read(self.pc + 2)
value_a = self.reg[reg_a]
value_b = self.reg[reg_b]
if value_a == value_b:
self.fl = 0b1
elif value_a > value_b:
self.fl = 0b10
elif value_b > value_a:
self.fl = 0b100
self.pc += 3
return
def ld(self):
# Loads registerA with the value at the memory address
# stored in registerB.
self.reg[self.ram_read(self.pc + 1)] = self.ram_read(
self.reg[self.ram_read(self.pc + 2)])
self.pc += 3
return
def inter(self):
# this will set the Nth bit of the IS register where N is Stored in PC + 1
b = self.reg[self.pc + 1]
# some fancy list comp to deal with the 'nth bit' thing
self.IS += int(''.join(['0' if x != b else '1' for x in range(8)]), 2)
pass
def read_array(self):
# reads an array from memory and stores the resulting list object in register specified
# read_array R#, ARRAY_START (flag)
register = self.ram_read(self.pc + 1)
i = 2
a = []
# starting with the ARRAY_START flag and ending with the STOP flag load
while True:
next_instr = self.ram_read(self.pc + i)
a.append(next_instr)
if next_instr == self.ARRAY_STOP:
break
i += 1
# store the resulting array in the register specified by arg
self.reg[register] = a[1:-1] # clean flags before storing
# since we just went n number of spots collecting memebers of the array
# we need to skip to the next instruction
self.pc = i + 1
def mean(self):
"""takes the mean of the array in REG[A] and stores the value at REG[B]"""
# use numpy to take the mean of the array
a = self.reg[self.ram_read(self.pc + 1)]
b = np.mean(a) # take mean
# get the register number to store the value
reg = self.ram_read(self.pc + 2)
# set that register equal to the value
self.reg[reg] = b
# increment the pc
self.pc += 3
return
def join(self):
"""Take the array passed in the array flags and append it
elementwise to the array in REG[A] in a way that adds the values from
the passed array as an additinal column for the array that is stored
in the register"""
# going to want to take the array in REG[pc + 1] and add a column
# onto it using the array that is read from mem
register_num = self.ram_read(self.pc + 1)
a = self.reg[register_num]
# load the second array into the register specified by op1
# changes the pc to the end of ARRAY
self.read_array()
a2 = self.reg[register_num]
# combine the first array with the second array such that a2 is a
# col added to the matrix then store that matrix in reg{a}
self.reg[register_num] = [[c, c1] for c, c1 in zip(a, a2)]
# shouldn't need to change the pc since read_array already did that
return
def predict(self):
pass
def fit(self):
# get the array from reg[A] and assume that the last column is the label
data = self.reg[self.ram_read(self.pc + 1)]
df = pd.DataFrame(data)
target = df.columns.tolist()[:-1]
y = df[target]
x = df.drop(target, axis=1)
self.model = LinearRegression(n_jobs=-1).fit(x, y, fit_intercept=True)
pass
###########################################################################
# UTIL FUNCTIONS #
###########################################################################
def trace(self):
print(f"""
pc: {self.pc}\
main loop iter: {self.clock}
ir: {self.ir}
self.pc+ 1: {self.RAM[self.pc + 1]}
self.pc+ 2: {self.RAM[self.pc + 2]}
registry values:\n{self.reg}\n
stack(top):\n{self.ram_read(self.reg[self.sp])}
""")
return
def load(self, fn):
"""Loads a .ls8 file from disk and runs it
Args:
fn: the name of the file to load into memory
"""
address = 0
with open(fn, "rt") as f:
for line in f:
try:
line = line.split("#", 1)[0]
line = int(line, base=2)
self.RAM[address] = line
address += 1
except ValueError:
pass
# for reloading
self._file_fn = fn
return
def reset(self, *args, **kwargs):
self.__init__(args, kwargs)
return
def kbi_callback(self, inp):
self.IS += 0b1
return
###########################################################################
# MAIN #
###########################################################################
def run(self):
"""Starts the main execution of the program"""
# start the keyboard interupt deamon
self.input_thread.start()
self.running = True
self.dispatch = {
self.ADD: self.add,
self.SUB: self.sub,
self.MUL: self.mul,
self.DIV: self.div,
self.JEQ: self.jeq,
self.JNE: self.jne,
self.CMP: self.cmp,
self.MOD: self.mod,
self.LDI: self.ldi,
self.PRN: self.prn,
self.PRA: self.pra,
self.HLT: self.hlt,
self.NOP: self.nop,
self.PUSH: self.push,
self.POP: self.pop,
self.CALL: self.call,
self.RET: self.ret,
self.DEC: self.dec,
self.INC: self.inc,
self.JMP: self.jmp,
self.ST: self.st,
self.LD: self.ld,
self.INT: self.inter,
self.OR: self.instr_or,
self.NOT: self.instr_not,
self.AND: self.instr_and,
self.XOR: self.instr_xor,
}
self.secondary_dispatch = {
self.ARRAY_START: self.nop,
self.ARRAY_STOP: self.nop,
self.LOAD_A: self.read_array,
self.MEAN: self.mean,
self.JOIN: self.join,
self.PRED: self.predict,
self.FIT: self.fit,
}
while self.running:
try:
# absolute clock counter
self.clock += 1
# DBG HOOK
if self.DBG:
# so that if i have an infinite loop there is a counter
print("CLK: {}".format(self.clock))
breakpoint()
if self.IS != 0:
# bitwise AND interuption_signal reg and interuption_mask reg
self.maskedint = self.im & self.IS
# read instruction and assign the ir register
self.ir = self.ram_read(self.pc)
# if the instruction is in the 8-bit table execute the command
# from the 8-bit table
if self.ir in self.dispatch:
self.dispatch[self.ir]()
# or if it's in the 16bit then launch it from
# that dispatch table
elif self.ir in self.secondary_dispatch:
# if asking for 16-bit function and running in 8-bit mode
# switch to 16-bit mode by increasing the ram alloted to
# the __init__() then reload the program file that was being
# run and run it again
if self.signed is False:
program = self._file_fn
self.__init__(ram_size=4096)
self.load(program)
self.run()
self.secondary_dispatch[self.ir]()
# if the instr isn't found then raise a targeted exception handler
else:
raise KeyError
# adding unknown instr error hook
except KeyError as ke:
print(f"unknown command: {int(self.ir, base=2)}")
self.running = False
return None
# Prior to instruction fetch, the following steps occur:
# 1. The IM register is bitwise AND-ed with the IS register and the
# results stored as `maskedInterrupts`.
# 2. Each bit of `maskedInterrupts` is checked, starting from 0 and going
# up to the 7th bit, one for each interrupt.
# 3. If a bit is found to be set, follow the next sequence of steps. Stop
# further checking of `maskedInterrupts`.
# If a bit is set:
# 1. Disable further interrupts.
# 2. Clear the bit in the IS register.
# 3. The `PC` register is pushed on the stack.
# 4. The `FL` register is pushed on the stack.
# 5. Registers R0-R6 are pushed on the stack in that order.
# 6. The address (_vector_ in interrupt terminology) of the appropriate
# handler is looked up from the interrupt vector table.
# 7. Set the PC is set to the handler address.
# While an interrupt is being serviced (between the handler being called
# and the `IRET`), further interrupts are disabled.
#
# See `IRET`, below, for returning from an interrupt.
#
#### Interrupt numbers
#
# * 0: Timer interrupt. This interrupt triggers once per second.
# * 1: Keyboard interrupt. This interrupt triggers when a key is pressed.
# The value of the key pressed is stored in address `0xF4`.
#
# ```
# top of RAM
# +-----------------------+
# | FF I7 vector | Interrupt vector table
# | FE I6 vector |
# | FD I5 vector |
# | FC I4 vector |
# | FB I3 vector |
# | FA I2 vector |
# | F9 I1 vector |
# | F8 I0 vector |
# | F7 Reserved |
# | F6 Reserved |
# | F5 Reserved |
# | F4 Key pressed | Holds the most recent key pressed on the keyboard
# | F3 Start of Stack |
# | F2 [more stack] | Stack grows down
# | ... |
# | 01 [more program] |
# | 00 Program entry | Program loaded upward in memory starting at 0
# +-----------------------+
# bottom of RAM
# ```
### INT
#
# `INT register`
#
# Issue the interrupt number stored in the given register.
#
# This will set the _n_th bit in the `IS` register to the value in the given
# register.
#
# Machine code:
# ```
# 01010010 00000rrr
# 52 0r
# ```
#
#### IRET
#
# `IRET`
#
# Return from an interrupt handler.
#
# The following steps are executed:
#
# 1. Registers R6-R0 are popped off the stack in that order.
# 2. The `FL` register is popped off the stack.
# 3. The return address is popped off the stack and stored in `PC`.
# 4. Interrupts are re-enabled
#
# Machine code:
# ```
# 00010011
# 13
# ```
def main():
try:
cpu = CPU(DBG=False, ram_size=4096)
if len(argv) > 1:
print("Launching in multi-test mode:\n")
for test in argv[1:]:
print(test)
now = time()
cpu.reset()
cpu.load(test)
cpu.run()
later = time()
print(f"Exec Time: {later - now}/sec")
print("\n")
else:
now = time()
cpu.load("examples/sctest.ls8")
cpu.run()
later = time()
print("Execution time: {}/sec".format(round(later - now, 4)))
except Exception as e:
print(e)
return
if __name__ == "__main__":
main()
|
0840550920662a3d0c1c26245df4c39781ed5734 | mariano-mora/holistic_simulations | /experiments/naming_game_script.py | 5,185 | 3.515625 | 4 | from game import *
from agent import *
from sequence import Sequence
import numpy as np
import time as tp
import argparse
class NamingGameExperiment:
def __init__(self, n_agents=20, n_sequences=10, seq_length=3, n_interactions=None, stability=15, umpire=None):
self.number_of_agents = n_agents
self.number_of_sequences = n_sequences
self.seq_length = seq_length
self.number_of_interactions = n_interactions
self.stability_check = stability
self.agents = []
self.symbols = ['red','orange','yellow','green','blue','indigo', 'violet','black']
self.outcomes = ['run','hide','ignore']
self.sequences = []
self.umpire = umpire if umpire is not None else GameUmpire()
def setup_game(self):
'''
Sets up a list of sequences. This represents the environment: the representations that will
be learned by the agents.
'''
# the environment
for i in range(self.number_of_sequences):
self.sequences.append(Sequence(symbols=self.get_random_symbols()))
# the players
for i in range(self.number_of_agents):
self.agents.append(Agent())
def play_game(self):
if self.number_of_interactions is None:
self.run_game_until_stable()
else:
self.iterate_game()
def run_game_until_stable(self):
is_stable = False
while not is_stable:
self.play_out_interaction()
if self.test_stability():
is_stable = True
self.umpire.number_of_interactions = self.umpire.number_of_interactions + 1
self.umpire.interaction_index = self.umpire.interaction_index + 1
def test_stability(self):
"""
We check stability by counting the number of times the games has been successful in a row.
If the game has been successful a fixed number of times in a row we can then compare the agents
to check that they all have the same architecture
"""
if not self.umpire.success_counter > self.stability_check:
return False
else:
for i in range(1, self.number_of_agents):
if not self.agents[i].has_same_model(self.agents[0]):
self.umpire.success_counter = 0
return False
return True
def game_is_succesful(self):
self.umpire.on_success()
def game_is_failure(self):
self.umpire.on_failure()
def iterate_game(self):
for iter in xrange(self.number_of_interactions):
self.play_out_interaction()
self.umpire.interaction_index = self.umpire.interaction_index + 1
def play_out_interaction(self):
agent_1, agent_2 = self.choose_players()
#we need to make sure both players are not the same
while agent_1 == agent_2:
agent_1, agent_2 = self.choose_players()
# each player takes either the role of the speaker or of the listener
agent_1.set_role(Role.SPEAKER)
agent_2.set_role(Role.LISTENER)
sequence = self.sequences[np.random.randint(0,high=len(self.sequences), size=1)]
if not agent_1.knows_sequence(sequence):
outcome = self.select_outcome()
agent_1.add(sequence, outcome)
agent_2.add(sequence, outcome)
self.game_is_failure()
else:
if agent_2.knows_sequence(sequence):
if agent_1.get_outcome(sequence) != agent_2.get_outcome(sequence):
agent_2.set_outcome(sequence, agent_1.get_outcome(sequence))
self.game_is_failure()
else:
self.game_is_succesful()
else:
agent_2.add(sequence, agent_1.get_outcome(sequence))
self.game_is_failure()
def choose_players(self):
indices = np.random.randint(0, self.number_of_agents, 2)
agent_1 = self.agents[indices[0]]
agent_2 = self.agents[indices[1]]
return agent_1, agent_2
def setup_random(self):
return np.random.RandomState(np.int(np.floor(tp.time())))
def create_sequences(self):
for i in range(self.number_of_sequences):
random_symbols = self.get_random_symbols()
self.sequences.append(Sequence(symbols=random_symbols))
def get_random_symbols(self):
indices = np.random.randint(0, high=len(self.symbols), size=self.seq_length)
random_symbols = []
for index in indices:
random_symbols.append(self.symbols[index])
return random_symbols
def select_outcome(self):
return self.outcomes[np.random.randint(0,high=len(self.outcomes), size=1)]
def carry_out_experiment(self):
""" Utility method to run experiment from the class """
self.setup_game()
self.play_game()
# return self.umpire
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--agents', help='number of agents')
parser.add_argument('--seqs', help='number of sequences')
parser.add_argument('--seq_length', help='length of sequences')
parser.add_argument('--runs', help='number of iterations')
parser.add_argument('--stable', help='number of straight successes which indicate stability')
args = parser.parse_args()
number_of_agents = 20 if not args.agents else int(args.agents)
number_of_sequences = 10 if not args.seqs else int(args.seqs)
seq_length = 3 if not args.seq_length else int(args.seq_length)
number_of_interactions = None if not args.runs else int(args.runs)
stability_check = 15 if not args.stable else int(args.stable)
experiment = NamingGameExperiment(number_of_agents, number_of_sequences, \
seq_length, number_of_interactions, stability_check)
experiment.setup_game()
experiment.play_game()
|
5be42bdd0b31133670b3ba4909bcd072cb5e7138 | jle33/PythonLearning | /PythonMasterCourse/PythonMasterCourse/OOPBasics.py | 1,348 | 4.1875 | 4 | a = 12 #Each datatype is actually an object in python
b = 4
print(a + b) # + calls the same function
print(a.__add__(b)) # __add__ is a method
class Kettle(object):
powerSource = "Electricity"
def __init__(self, make, price): #Similar to a Constructor, is automatically called when a new object is stance of the class is created
self.make = make #Member Variables - must use self.something
self.price = price
self.on = False
def switch_on(self): #A method - different from a function is the presence of a self when defining a method.
self.on = True #Self is the reference to the instance of the class i.e the "object instance of the class"
kenwood = Kettle("Kenwood", 9.99)
print(kenwood.make)
print(kenwood.price)
kenwood.price = 13.99
print(kenwood.price)
hamilton = Kettle("Hamilton", 12.99)
print(hamilton.make)
print(hamilton.price)
print("Models: {.make} = {.price}, {.make} = {.price}".format(kenwood, kenwood, hamilton, hamilton))
print(hamilton.on)
hamilton.switch_on() #Knows that self is hamilton which is an instance of the Kettle Class
print(hamilton.on)
Kettle.switch_on(kenwood) #Alternate way to call switch_on(self) where self is a Kettle object
print(kenwood.on)
Kettle.powerSource = "None"
print(kenwood.powerSource)
print(hamilton.powerSource)
|
1fcd256ecfc4d2233cb471e3fad91a6c9afac696 | ChristianParraMoreno/RSA | /RSA_1.py | 1,692 | 3.65625 | 4 | AlphabetNumbers = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8,
'i':9, 'j':10, 'k':11,'l':12, 'm':13, 'n':14, 'o':15, 'p':16, 'q':17, 'r':18,
's':19, 't':20, 'u':21, 'v':22, 'w':23, 'x':24, 'y':25, 'z':26, ' ':27}
AlphabetNumbers2 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g', 8:'h',
9:'i', 10:'j', 11:'k', 12:'l', 13:'m', 14:'n', 15:'o', 16:'p', 17:'q', 18:'r',
19:'s', 20:'t', 21:'u', 22:'v', 23:'w', 24:'x', 25:'y', 26:'z', 27:' '}
# import random
def gcd(p,q):
# Create the gcd of two positive integers.
while q != 0:
p, q = q, p % q
return p
def keys(p, q):
d = 1
e = 2
if gcd(p, q) != 1:
return 'error numbers are not prime'
n = p * q
phi = (p - 1) * (q - 1)
while gcd(e, phi) != 1:
e += 1
public = e
public2 = n
while d * e % phi != 1:
d += 1
private = d
private2 = n
return public, public2, private, private2
def encrypt(public, public2, word):
container = []
for char in word:
pointer = AlphabetNumbers[char]
pointer = pointer ** public % public2
container.append(pointer)
return container
def decrypt(private, private2, container):
newContainer = []
for number in container:
pointer = number ** private % private2
pointer = str(AlphabetNumbers2[pointer])
newContainer.append(pointer)
return newContainer
public, public2, private, private2 = keys(23,13)
print(public, public2, private, private2)
print(keys(23,13))
print(encrypt(public, public2, 'hello world'))
print(decrypt(private, private2, encrypt(public, public2, 'hello world')))
|
f88f9feb8c820a9609b92bff6ac8a1a35c9b33b7 | ddsuhaimi/Bootcamp-Arkademy-Batch-13 | /nomor4.py | 947 | 3.546875 | 4 | finalMap = {}
input_list = [
{
"name": "Movies", "info": "category_name",
"data": [
{ "name": "Interstellar", "info": "category_data" },
{ "name": "Dark Knight", "info": "category_data" },
]
},
{
"name": "Music", "info": "category_name",
"data": [
{ "name": "Adams", "info": "category_data" },
{ "name": "Nirvana", "info": "category_data" },
]
}
]
def transform(input_list):
A = []
for item in input_list:
dict_movie = {}
for key in item:
if key != 'data':
dict_movie[key] = item[key]
A.append(dict_movie)
else:
for dict_ in item[key]:
A.append(dict_)
return [dict(t) for t in {tuple(d.items()) for d in A}]
print(transform(input_list)) |
4e546cf80a6eea9891595e3d1dd58f72c044616b | chubby-panda/shecodes-python-work | /lists/lists_q3.py | 112 | 4.03125 | 4 | names = []
while len(names) < 3:
name = input("Please enter a name: ")
names.append(name)
print(names) |
4a840327d3a687e5b3c992508e7cc9d0ad88d821 | Matt-McShruggers/Herramientas-Comp-TallerCV | /Resolucion_4.py | 1,106 | 3.65625 | 4 | def casaCambio():
pregunta = int(input("¿Cuantas veces se va a repetir este codigo? "))
for i in range(pregunta):
pesos_colombianos = eval(input("¿Cuantos Pesos colombianos quieres cambiar? "))
moneda_de_cambio = input("¿Quieres cambiar a Dolares, Euros o Yenes? ")
moneda_de_cambio = moneda_de_cambio.lower()
GANANCIA = 0.02
casa_de_cambio = None
dinero_cambio= None
if moneda_de_cambio == "dolares":
casa_de_cambio = pesos_colombianos/3576
dinero_cambio = casa_de_cambio - (GANANCIA*casa_de_cambio)
elif moneda_de_cambio == "yenes":
casa_de_cambio = pesos_colombianos/32.76
dinero_cambio = casa_de_cambio - (GANANCIA*casa_de_cambio)
elif moneda_de_cambio == "euros":
casa_de_cambio = pesos_colombianos/4273.27
dinero_cambio = casa_de_cambio - (GANANCIA*casa_de_cambio)
else:
dinero_cambio = "Error, Moneda no disponible"
print("El total despues del cambio es de: ", casa_de_cambio, moneda_de_cambio)
|
88042dfe5b04f2cd43786c282b5611afe76811dc | cmmorrow/sci-analysis | /sci_analysis/data/numeric.py | 10,410 | 3.5 | 4 | # Import packages
import pandas as pd
import numpy as np
# Import from local
from .data import Data, is_data
from .data_operations import flatten, is_iterable
class EmptyVectorError(Exception):
"""
Exception raised when the length of a Vector object is 0.
"""
pass
class UnequalVectorLengthError(Exception):
"""
Exception raised when the length of two Vector objects are not equal, i.e., len(Vector1) != len(Vector2)
"""
pass
def is_numeric(obj):
"""
Test if the passed array_like argument is a sci_analysis Numeric object.
Parameters
----------
obj : object
The input object.
Returns
-------
test result : bool
The test result of whether seq is a sci_analysis Numeric object or not.
"""
return isinstance(obj, Numeric)
def is_vector(obj):
"""
Test if the passed array_like argument is a sci_analysis Vector object.
Parameters
----------
obj : object
The input object.
Returns
-------
test result : bool
The test result of whether seq is a sci_analysis Vector object or not.
"""
return isinstance(obj, Vector)
class Numeric(Data):
"""An abstract class that all Data classes that represent numeric data should inherit from."""
_ind = 'ind'
_dep = 'dep'
_grp = 'grp'
_lbl = 'lbl'
_col_names = (_ind, _dep, _grp, _lbl)
def __init__(self, sequence=None, other=None, groups=None, labels=None, name=None):
"""Takes an array-like object and converts it to a pandas Series with any non-numeric values converted to NaN.
Parameters
----------
sequence : int | list | set | tuple | np.array | pd.Series
The input object
other : list | set | tuple | np.array | pd.Series, optional
The secondary input object
groups : list | set | tuple | np.array | pd.Series, optional
The sequence of group names for sub-arrays
labels : list | set | tuple | np.array | pd.Series, optional
The sequence of data point labels
name : str, optional
The name of the Numeric object
"""
self._auto_groups = True if groups is None else False
self._values = pd.DataFrame([], columns=self._col_names)
if sequence is None:
super(Numeric, self).__init__(v=self._values, n=name)
self._type = None
self._values.loc[:, self._grp] = self._values[self._grp].astype('category')
elif is_data(sequence):
super(Numeric, self).__init__(v=sequence.values, n=name)
self._type = sequence.data_type
self._auto_groups = sequence.auto_groups
elif isinstance(sequence, pd.DataFrame):
raise ValueError('sequence cannot be a pandas DataFrame object. Use a Series instead.')
else:
sequence = pd.to_numeric(self.data_prep(sequence), errors='coerce')
other = pd.to_numeric(self.data_prep(other), errors='coerce') if other is not None else np.nan
groups = self.data_prep(groups) if groups is not None else 1
# TODO: This try block needs some work
try:
self._values[self._ind] = sequence
self._values[self._dep] = other
self._values[self._grp] = groups
self._values.loc[:, self._grp] = self._values[self._grp].astype('category')
if labels is not None:
self._values[self._lbl] = labels
except ValueError:
raise UnequalVectorLengthError('length of data does not match length of other.')
if any(self._values[self._dep].notnull()):
self._values = self.drop_nan_intersect()
else:
self._values = self.drop_nan()
self._type = self._values[self._ind].dtype
self._name = name
@staticmethod
def data_prep(seq):
"""
Converts the values of _name to conform to the Data object standards.
Parameters
----------
seq : array-like
The input array to be prepared.
Returns
-------
data : np.array
The enclosed data represented as a numpy array.
"""
if hasattr(seq, 'shape'):
if len(seq.shape) > 1:
return flatten(seq)
else:
return seq
else:
return flatten(seq)
def drop_nan(self):
"""
Removes NaN values from the Numeric object and returns the resulting pandas Series. The length of the returned
object is the original object length minus the number of NaN values removed from the object.
Returns
-------
arr : pandas.Series
A copy of the Numeric object's internal Series with all NaN values removed.
"""
return self._values.dropna(how='any', subset=[self._ind])
def drop_nan_intersect(self):
"""
Removes the value from the internal Vector object and seq at i where i is nan in the internal Vector object or
seq.
Returns
-------
arr : pandas.DataFrame
A copy of the Numeric object's internal DataFrame with all nan values removed.
"""
return self._values.dropna(how='any', subset=[self._ind, self._dep])
def drop_groups(self, grps):
"""Drop the specified group name from the Numeric object.
Parameters
----------
grps : str|int|list[str]|list[int]
The name of the group to remove.
Returns
-------
arr : pandas.DataFrame
A copy of the Numeric object's internal DataFrame with all records belonging to the specified group removed.
"""
if not is_iterable(grps):
grps = [grps]
dropped = self._values.query("{} not in {}".format(self._grp, grps)).copy()
dropped[self._grp] = dropped[self._grp].cat.remove_categories(grps)
self._values = dropped
return dropped
@property
def data_type(self):
return self._type
@property
def data(self):
return self._values[self._ind]
@property
def other(self):
return pd.Series([]) if all(self._values[self._dep].isnull()) else self._values[self._dep]
@property
def groups(self):
groups = self._values.groupby(self._grp)
return {grp: seq[self._ind].rename(grp) for grp, seq in groups if not seq.empty}
@property
def labels(self):
return self._values[self._lbl].fillna('None')
@property
def paired_groups(self):
groups = self._values.groupby(self._grp)
return {grp: (df[self._ind], df[self._dep]) for grp, df in groups if not df.empty}
@property
def group_labels(self):
groups = self._values.groupby(self._grp)
return {grp: df[self._lbl] for grp, df in groups if not df.empty}
@property
def values(self):
return self._values
@property
def auto_groups(self):
return self._auto_groups
@property
def has_labels(self):
return any(pd.notna(self._values[self._lbl]))
class Vector(Numeric):
"""
The sci_analysis representation of continuous, numeric data.
"""
def __init__(self, sequence=None, other=None, groups=None, labels=None, name=None):
"""
Takes an array-like object and converts it to a pandas Series of
dtype float64, with any non-numeric values converted to NaN.
Parameters
----------
sequence : array-like or int or float or None
The input object
other : array-like
The secondary input object
groups : array-like
The sequence of group names for sub-arrays
labels : list | set | tuple | np.array | pd.Series, optional
The sequence of data point labels
name : str, optional
The name of the Vector object
"""
super(Vector, self).__init__(sequence=sequence, other=other, groups=groups, labels=labels, name=name)
if not self._values.empty:
self._values[self._ind] = self._values[self._ind].astype('float')
self._values[self._dep] = self._values[self._dep].astype('float')
def is_empty(self):
"""
Overrides the super class's method to also check for length of zero.
Returns
-------
test_result : bool
The result of whether the length of the Vector object is 0 or not.
Examples
--------
>>> Vector([1, 2, 3, 4, 5]).is_empty()
False
>>> Vector([]).is_empty()
True
"""
return self._values.empty
def append(self, other):
"""
Append the values of another vector to self.
Parameters
----------
other : Vector
The Vector object to be appended to self.
Returns
-------
vector : Vector
The original Vector object with new values.
Examples
--------
>>> Vector([1, 2, 3]).append(Vector([4, 5, 6])).data
pandas.Series([1., 2., 3., 4., 5., 6.])
"""
if not is_vector(other):
raise ValueError("Vector object cannot be added to a non-vector object.")
if other.data.empty:
return self
if self.auto_groups and other.auto_groups and len(self._values) > 0:
new_cat = max(self._values[self._grp].cat.categories) + 1
other.values['grp'] = new_cat
self._values = pd.concat([self._values, other.values], copy=False)
self._values.reset_index(inplace=True, drop=True)
self._values.loc[:, self._grp] = self._values[self._grp].astype('category')
return self
def flatten(self):
"""
Disassociates independent and dependent data into individual groups.
Returns
-------
data : tuple(Series)
A tuple of pandas Series.
"""
if not self.other.empty:
return (tuple(data[self._ind] for grp, data in self.values.groupby(self._grp)) +
tuple(data[self._dep] for grp, data in self.values.groupby(self._grp)))
else:
return tuple(data[self._ind] for grp, data in self.values.groupby(self._grp))
|
fde0e7d37e0d3e935c5e619c79af596e5a7eb6f7 | aaroncymor/coding-bat-python-exercises | /String-1/make_out_word.py | 439 | 3.875 | 4 | """
Given an "out" string length 4, such sa "<<>>", and a word, return a new string where the word is
is the middle of the out string, e.g. "<<word>>"
"""
def make_out_word(out,word):
new_formed_str = ''
if len(out) % 2 == 0:
i = 0
j = len(out) / 2
while i <= 1:
new_formed_str += out[i]
i += 1
new_formed_str += word
while j <= (len(out)/2) + 1:
new_formed_str += out[j]
j += 1
return new_formed_str
|
09b1276802449b5afb9a9a90f5adbc4a480cb4ea | Giordano26/Python-Web | /Ref/especialchar.py | 146 | 3.5 | 4 | import re
x = 'We just received $10.00 for cookies.'
y = re.findall('\$[0-9.]+',x) #use \ for special char to turn them into normal char
print(y)
|
891b66011167389a99b618126e311d7b0e45fab7 | ThreeFDDI/ATBS | /ATBS-15_stopwatch.py | 657 | 3.84375 | 4 | #!/usr/local/bin/python3
# Chapter 15 – Super Stopwatch
# ATBS-15_stopwatch.py
import time
# display the program's instructions
print("Press ENTER to begin. Afterwards, press ENTER to 'click' the stopwatch. \
Press Ctrl-C to quit")
# press ENTER to begin
input()
print("Started")
startTime = time.time()
lastTime = startTime
lapNum = 1
try:
while True:
input()
lapTime = round(time.time() - lastTime, 2)
totalTime = round(time.time() - startTime, 2)
print(f"Lap {lapNum}: {totalTime} {lapTime}")
lapNum += 1
lastTime = time.time()
except KeyboardInterrupt:
print("\nDone.")
pass |
ec9ff510c0d6d5351c00d6b9b4a9b8d4a3e7c323 | daniel-scholz/setlpy | /setlx/utils.py | 795 | 3.734375 | 4 | from itertools import product
from numbers import Number
from copy import deepcopy
def cartesian(v1, v2):
type_v1 = type(v1)
type_v2 = type(v2)
if type_v1 != type_v2:
raise f"cannot compute cartesian product for {type_v1} and {type_v2}"
if type_v1 is list:
if len(v1) != len(v2):
raise "both lists must have same size"
return [[x, v2[i]] for i, x in enumerate(v1)]
# TODO for sets
raise f"cannot compute cartesian product for type {type_v1}"
def iterate(**iterables):
return product(iterables)
def is_number(n):
# bool is int in python (True=0, False=1)
return isinstance(n, Number) and not isinstance(n, bool)
def is_integer(value):
return isinstance(value, int)
def copy(value):
return deepcopy(value) |
8fb571c80096fcedafb0579cea0da29bce032a5c | jalencato/Leetcode | /Leetcode/Problem 688/Problem 688.py | 837 | 3.875 | 4 | # possibility of still remaining on the board
# N: size of the board
# K: the possible moving steps
# r: the initial row
# c: the initial col
import functools
class Solution:
movement = [(2, 1), (2, -1), (1, 2), (1, -2), (-2, -1), (-2, 1), (-1, 2), (-1, -2)]
def knightProbability(self, N: int, K: int, r: int, c: int) -> float:
@functools.lru_cache(None)
def dp(row, col, step):
if row < 0 or row >= N or col < 0 or col >= N:
return 0
elif step == 0:
return 1
else:
res = sum([dp(row + r, col + c, step - 1) for r, c in self.movement]) / 8.0
return res
return dp(r, c, K)
if __name__ == '__main__':
s = Solution()
N = 3
k = 2
r = 0
c = 0
print(s.knightProbability(N, k, r, c))
|
48bdc3baa00fdfbde1444651b642096e841f752c | timcurrell/dev | /python/IdeaProjects/MyWork/StringFormatting1.py | 880 | 4.25 | 4 | # String Formatting %
# Python provides string functionality similar to the java
# printf() function. This is where a string is generated
# which includes placeholders which are later filled with
# either string literals or variable values.
#
# The placeholders are specific to the type of value:
#
# %c single character %s string
# %i signed integer %d signed integer
# %u unsigned integer %f floating point number
#
# The '%' is also used to separate the string from the tuple
# that provides the values to be inserted.
print("St. Louis penalty to number %d, %s, two minutes for %s." % (35, 'Steve Ott', 'slashing'))
ex_form1 = "Lions"
ex_form2 = "Tigers"
ex_form3 = "Bears"
print("%s and %s and %s, oh my!" % (ex_form1, ex_form2, ex_form3))
ex_form1 = "Patriots"
ex_form2 = "Packers"
ex_form3 = "Rams"
print("%s and %s and %s, oh my!" % (ex_form1, ex_form2, ex_form3))
|
d593cddc6f11cad9ef4168959891b4a70b12513c | scarlett-ohara91/Nguyen-Thuy-Duong | /session 3 - bai lam/Serious exercise 1.py | 701 | 3.578125 | 4 | items = ['T-Shirt', 'Sweater']
times = 0
while True:
ans = input('Welcome to our shop, what do you want (C, R, U, D)? ').upper()
times = times + 1
if ans == 'R':
print('Our items: ', ','.join(items))
elif ans == 'C':
new = input('Enter new item: ')
items.append(new)
print('Our items: ', ','.join(items))
elif ans == 'U':
upd = int(input('Update position? '))-1
new = input('New item: ')
items[upd] = new
print('Our items: ', ','.join(items))
elif ans == 'D':
dele = int(input('Delete position? '))-1
del items[dele]
print('Our items: ', ','.join(items))
if times > 4:
break
|
e79cb2d597ddec25d3963e4e27c5c91ee721e0de | Williamj6710/CTI110 | /P3HW1_MonthNum_JacobWilliams.py | 1,187 | 4.65625 | 5 | #CTI-110
#P3HW1 - Month Number
#Jacob Williams
#10-04-19
#
#Convert user inputed number to month of the year
#PsuedoCode
#Ask user to input number of desired month
#Assign user input to User_Input variable
#Use user input to print name of month input
#Create error message if input is not between 1-12
#Get input from user
User_Input =input("Enter number of desired month:")
#Use user input to print correlating month name
if User_Input =='1':
print("January")
elif User_Input =='2':
print('February')
elif User_Input =='3':
print('March')
elif User_Input =='4':
print('April')
elif User_Input =='5':
print('May')
elif User_Input =='6':
print('June')
elif User_Input =='7':
print('July')
elif User_Input =='8':
print('August')
elif User_Input =='9':
print('September')
elif User_Input =='10':
print('October')
elif User_Input =='11':
print('November')
elif User_Input =='12':
print('December')
#Print error message if User_Input is outside of the 1-12 range
if User_Input >'12':
print('Please enter a number between 1-12')
if User_Input < '1':
print('Please enter a number between 1-12')
|
4f7aa162d0ffb55b1b8303815a6c95e3cce605c3 | EXALLENGE/Sorokina_task_1_ | /Main.py | 203 | 3.859375 | 4 | def f42(x):
if x == 42:
print("Вы угадали")
str = "Win"
else:
print("Попробуйте еще")
str = "Lose"
return str
x = float(input())
f42(x)
|
66771b5c77aa1f27f79866e2aa32135160fd48f7 | sohaibsohail98/OOP_Exercises | /Exercise 1/Python_calculator.py | 1,751 | 4.5 | 4 | import python_operators
class Calculator:
def calculate(self):
#This is to provide options for the user to perform calculator functions
print("Select which operation would you like to proceed with.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Working out the remainder")
print("6.Working out the area of a triangle")
choiceof_operation = int(input("Please choose which of the operations you would like to proceed with "))
#This is allowing the user to enter one of the options
# This is gather the input of the user to complete the calculator function
num1 = int(input("Enter a number: "))
num2 = int(input("Enter the second number: "))
# These are if and else statements, finding the user's choice of calculation and completing it using the python
# operators file.
if choiceof_operation == 1:
print(python_operators.adding_values(num1, num2))
elif choiceof_operation == 2:
print(python_operators.subtracting_values(num1,num2))
elif choiceof_operation == 3:
print(python_operators.multiplying_values(num1, num2))
elif choiceof_operation == 4:
print(python_operators.dividing_values(num1, num2))
elif choiceof_operation == 5:
print(python_operators.modulous_values(num1, num2))
elif choiceof_operation == 6:
print("The area of the triangle is")
print(python_operators.area_of_triangle(num1, num2))
else:
print("An error has occurred, please try again.")
ultimatecalculator = Calculator()
ultimatecalculator.calculate()
|
20c17bd1c4e5e45cd272e0e4612206056ddd97fd | shrinaparikh/nyu | /Past Classes/AI/ShrinaParikh_asg2/frontend.py | 6,849 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 21:11:01 2020
@author: shrinaparikh
"""
import re
f = open("frontend_input.txt", "r")
dp_input = f.read()
dp_input = dp_input.split('\n')
line1 = dp_input[0].split()
holes = int(line1[0])
empty_hole = int(line1[1])
potential_jumps = []
for line in dp_input:
line = line.split()
if(len(line) == 2):
continue
potential_jumps.append([line[0], line[1], line[2]])
###file to write to
f = open("frontend_output.txt", "w")
max_time = holes - 1
axioms = []
jumps = []
pegs = []
axiom_counter = 0
#turning input into sentences - jumps, appending to axioms as well
for jump in potential_jumps:
for time in range(1, max_time):
j = "Jump(" + jump[0] + "," + jump[1] + "," + jump[2] + "," + str(time) + ")"
axioms.append(j)
jumps.append(j)
for time in range(1, max_time):
j2 = "Jump(" + jump[2] + "," + jump[1] + "," + jump[0] + "," + str(time) + ")"
axioms.append(j2)
jumps.append(j2)
#now append pegs to axioms
for i in range(1,holes+1):
for j in range(1, max_time+1):
peg = "Peg(" + str(i) + "," + str(j) + ")"
axioms.append(peg)
#create starting state, as an array
def create_starting():
pegs = []
for h in range(1,holes+1):
if (h == empty_hole):
pegs.append("-Peg(" + str(h) + ",1)")
else:
pegs.append("Peg(" + str(h) + ",1)")
return pegs
create_starting()
#for h in range(1,holes+1):
# if (h == empty_hole):
# pegs.append("-Peg(" + str(h) + ",1)")
# for t in range(2,max_time+1):
# pegs.append("Peg(" + str(h) + "," + str(t) + ")")
# continue
# for t in range(1,max_time+1):
# pegs.append("Peg(" + str(h) + "," + str(t) + ")")
#create starting state sentence, now as a string
#start = ''
#for peg in pegs:
# if(peg == pegs[0]):
# start = peg
# continue
# start = start + " ^ " + peg
#print("\n Starting State: ", start)
def get_nums(jump):
nums = []
jump_arr = re.split('\(|\)|,',jump)
nums.append(jump_arr[1]) #peg1
nums.append(jump_arr[2]) #peg2
nums.append(jump_arr[3]) #peg3
nums.append(jump_arr[4]) #time
return nums
####GETTING ALL AXIOMS AS STRINGS
precondition_axioms = []
def get_precondition_axioms(jumps):
for jump in jumps:
nums = get_nums(jump)
peg1 = nums[0]
peg2 = nums[1]
peg3 = nums[2]
time = nums[3]
axiom = jump + " => " + "Peg(" + peg1 + "," + time + ")"
axiom = axiom + " ^ " + "Peg(" + peg2 + "," + time + ")" + " ^ " + "-Peg(" + peg3 + "," + time + ")"
precondition_axioms.append(axiom)
get_precondition_axioms(jumps)
casual_axioms = []
def get_casual_axioms(jumps):
for jump in jumps:
nums = get_nums(jump)
peg1 = nums[0]
peg2 = nums[1]
peg3 = nums[2]
time = str(int(nums[3]) + 1)
axiom = jump + " => " + "-Peg(" + peg1 + "," + time + ")" + " ^ "
axiom = axiom + "-Peg(" + peg2 + "," + time + ")" + " ^ " + "Peg(" + peg3 + "," + time + ")"
casual_axioms.append(axiom)
get_casual_axioms(jumps)
##frame axioms now
frame_axioms = []
def get_frame_axioms():
for i in range(1,holes+1):
for j in range(1, max_time):
options = ''
peg1 = "Peg(" + str(i) + "," + str(j) + ")"
peg2 = "-Peg(" + str(i) + "," + str(j+1) + ")"
for jump in jumps:
nums = get_nums(jump)
peg1_num = nums[0]
peg2_num = nums[1]
time = nums[3]
if((peg1_num == str(i) or peg2_num == str(i)) and (peg1[-2] == time)):
if(options == ''):
options = jump
else:
options = options + " V " + jump
axiom = peg1 + " ^ " + peg2 + " => " + options
frame_axioms.append(axiom)
get_frame_axioms()
#No two axioms can be executed at the same time
one_at_a_time = []
def check():
for i in range(0,len(jumps)):
one = jumps[i]
for j in range(i+(max_time-1), len(jumps), max_time-1):
two = jumps[j]
axiom = "-(" + one + " ^ "
axiom = axiom + two + ")"
one_at_a_time.append(axiom)
check()
ending = []
def check_ending():
for i in range(1, holes):
peg1 = "Peg(" + str(i) + "," + str(max_time) + ")"
for j in range(i+1, holes+1):
peg2 = "Peg(" + str(j) + "," + str(max_time) + ")"
ending.append("-(" + peg1 + " ^ " + peg2 + ")")
check_ending()
def encoding():
for jump in axioms:
if (jump[0] != 'J'):
break
else:
for ele in precondition_axioms:
if jump in ele:
ele = ele.split()
f.write("-" + str(axioms.index(jump) + 1) + " " + str(axioms.index(ele[2]) + 1) + "\n")
f.write("-" + str(axioms.index(jump) + 1) + " " + str(axioms.index(ele[4]) + 1) + "\n")
f.write("-" + str(axioms.index(jump) + 1) + " -" + str(axioms.index(ele[6][1:]) + 1) + "\n")
for jump in axioms:
if(jump[0] != 'J'):
break;
else:
for ele in casual_axioms:
if jump in ele:
ele = ele.split()
f.write("-" + str(axioms.index(jump) + 1) + " -" + str(axioms.index(ele[2][1:]) + 1) + "\n")
f.write("-" + str(axioms.index(jump) + 1) + " -" + str(axioms.index(ele[4][1:]) + 1) + "\n")
f.write("-" + str(axioms.index(jump) + 1) + " " + str(axioms.index(ele[6]) + 1) + "\n")
for ele in frame_axioms:
ele = ele.split()
out = "-" + str(axioms.index(ele[0]) + 1) + " " + str(axioms.index(ele[2][1:]) + 1) + " "
for i in range(4, len(ele), 2):
out = out + str(axioms.index(ele[i]) + 1) + " "
out = out + "\n"
f.write(out)
for ele in one_at_a_time:
ele = ele.split()
f.write("-" + str(axioms.index(ele[0][2:])+1) + " -" + str(axioms.index(ele[2][:-1])+1) + "\n")
start = create_starting()
for ele in start:
if(ele[0] == '-'):
f.write("-" + str(axioms.index(ele[1:]) + 1) + '\n')
else:
f.write(str(axioms.index(ele) + 1) + '\n')
for ele in ending:
ele = ele.split()
f.write("-" + str(axioms.index(ele[0][2:])+1) + " -" + str(axioms.index(ele[2][:-1])+1) + "\n")
f.write("0\n")
for item in axioms:
f.write(str(axioms.index(item) + 1) + " " + item + "\n")
encoding()
f.close() |
9ea8bc280c762b7d90297b6249f561bb46cef6d9 | Shaggy-Rogers/ProjectEuler | /check.py | 499 | 3.625 | 4 | def palendrome(input):
sinput = "junk"
sinput = str(input)
if sinput == sinput[::-1]:
return(True)
return(False)
def prime(input):
if input % 2 != 0 and input % 3 != 0 and input % 5 != 0:
if input % 7 != 0:
return(True)
if input == 2 or input == 3 or input == 5 or input == 7:
return(True)
if input == 0:
return(False)
return(False)
def whole(input):
if input % 1 != 0:
return(False)
return(True) |
f9254f549cb122ae8e8dc6f14da93e6427d5ef24 | adambatchelor2/python | /Edabit_Count vowels.py | 275 | 3.84375 | 4 | #Count vowels
# count_vowels("Celebration") ➞ 5
# count_vowels("Palm") ➞ 1
# count_vowels("Prediction") ➞ 4
str_vowel = "ADA"
count = 0
vowels = ["a","e","i","o","u"]
for x in range(0,len(str_vowel)):
if str_vowel[x].lower() in vowels:
count += 1
print (count) |
3aa1e6254d5c096bfc433246a0a5eb1626cc07f7 | nwinans/cs-4102 | /dynamic_programming/drainage.py | 4,118 | 4.375 | 4 | elevation_map = [] # Input grid
drain_map = [] # grid to keep track of subproblems' solutions
def backtrack(start_x, start_y):
"""
After running longest_drain, Backtracking can be used to reconstruct
the longest path found using the DP memory (drain_map in this case).
Backtracking will begin from a given location (start_x, start_y).
We know that drain_map[start_x][start_y] contains the length of
the longest river that ends at location (start_x, start_y), call this
value "length". To reconstruct that longest river, we know that the
second-from-last location must be adjacent to (start_x, start_y) and
contain value "length - 1". The third-from-last location must be
adjacent to the second-from-last location and contain the value
"length - 2", etc.
"""
if drain_map[start_x][start_y] == 1:
return [elevation_map[start_x][start_y]]
length = len(drain_map)
directions = [[0,1],[0,-1],[1,0],[-1,0]]
for a, b in directions:
# check if the direction even exists
if start_x+a >= length or start_y+b >= length or start_x+a < 0 or start_y+b < 0:
continue
if not drain_map[start_x+a][start_y+b]:
continue
if drain_map[start_x+a][start_y+b] == drain_map[start_x][start_y] - 1:
previous = backtrack(start_x+a, start_y+b)
previous.append(elevation_map[start_x][start_y])
return previous
return []
def find_drain(x, y):
"""
This function will be used to find the longest river that ends at
location (x,y). This function is where we will be making use of
the dynamic programming paradigm. Think about how to the value of
drain_map[x][y] relates to the drain_map values of its neighbors.
In the opinion of the course staff, this particular function is
much easier to implement as "top-down".
"""
length = len(elevation_map)
# check if we have solved the current problem already, dynamic programming!
if drain_map[x][y] != -1:
return drain_map[x][y]
# only care about heights directly adjacent to current cell N,S,E,W
directions = [[0,1],[0,-1],[1,0],[-1,0]]
optimal = -1
for a, b in directions:
# check if the direction even exists
if x+a >= length or y+b >= length or x+a < 0 or y+b < 0:
continue
if not elevation_map[x+a][y+b]:
continue
if elevation_map[x+a][y+b] > elevation_map[x][y]:
optimal = max(optimal, find_drain(x+a,y+b))
if optimal == -1: # this is a (local) max
drain_map[x][y] = 1
return 1
drain_map[x][y] = 1 + optimal
return drain_map[x][y]
def longest_drain(grid, backtracking=False):
"""
Invoke this function to find the longest path. The way this works
is that it will invoke find_drain on every location in the
elevation_map to find the longest drain ending there, saving the
longest seen.
If backtracking is enabled (i.e. the function is invoked with the
optional parameter "backtracking" assigned the value True), then
this function will reconstruct and print the path of the flow as a
sequence of elevations.
There is nothing for you to implement here.
"""
global elevation_map, drain_map
elevation_map = grid
size = len(elevation_map)
drain_map = [[-1 for i in range(size)] for j in range(size)] # initialize drain_map
longest = -1
for x in range(size):
for y in range(size):
longest = max(longest, find_drain(x, y)) # find longest drain ending at each location, keep the max
if backtracking:
for x in range(size):
for y in range(size):
if drain_map[x][y] == longest:
path = backtrack(x, y) # if backtracking is enabled, print the sequence of elevations
print("Path:", end=" ")
for elevation in path:
print(elevation, end=" ")
print()
return longest
return longest
|
697daf558d6a5487ee10643d301bdc089fd8b8bd | ydong08/PythonCode | /sourcecode/07/7.1.7/find_file.py | 455 | 3.640625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
# ļIJ
f1 = file("hello.txt", "r")
count = 0
for s in f1.readlines():
li = re.findall("hello", s)
if len(li) > 0:
count = count + li.count("hello")
print "ҵ" + str(count) + "hello"
f1.close()
# ļ滻
f1 = file("hello.txt", "r")
f2 = file("hello3.txt", "w")
for s in f1.readlines():
f2.write(s.replace("hello", "hi"))
f1.close()
f2.close()
|
b9d8874fb0e0f63bf98db9868205b073940de3c8 | DongmeeKim/Python-Study | /fucntion/function.py | 1,656 | 3.96875 | 4 | #함수 (fucntion)
#문자열 포맷팅 함수 format()
print("You've {0} a friend".format("got"))
str = "{2} {0} {1}".format("a",100,200)
print(str)
number = 100
day = "sunday"
print("오늘은 우리가 사귄지 {0}일째 되는 날이야. {1}이야.".format(number,day))
#인덱스와 이름을 혼용해서 사용하기
print("오늘은 우리가 사귄지 {0}일째 되는 날이다. {day}이야".format(100,day = "sunday"))
#좌측정렬
name = "다니엘라"
print("{0:<10}".format(name))
#우측정렬
print("{0:>10}".format(name))
#가운데정렬
#예시 1
print("{0:^10}".format(name))
#예시 2
print("{0:-^20}".format(name))
#소문자를 대문자로 바꾸는 함수
aa = "hello"
aa1 = aa.upper()
print(aa1)
#대문자를 소문자로 바꾸는 함수 : lower()
#문자의 갯수를 리턴하는 함수
aa = "abcde"
cnt = aa.count('d')
print(cnt)
#문자의 길이를 구하는 함수
cnt = len(aa)
print(cnt)
#문자의 위치 찾기 함수 : 문자열에서 찾고자하는 문자의 첫번째 위치 리턴
bb = "cafrdifff"
loc = bb.find("f")
print(loc) # 찾고자하는 함수가 없는 경우에는 -1 값을 반환한다
#공백지우기 함수 (strip/lstrip/rstrip)
aa = " good "
print(aa.lstrip()+"morning")
print(aa.rstrip()+"morning")
print(aa.strip()+"morning")
#문자열 대체함수(replace) : 문자열 내의 특정 값을 다른 값으로 교체
aa = "good morning Daniela"
print(aa.replace("morning","night")) #(바뀔 대상, 바뀐 결과값)
#문자열 나누기(split)
str = "good morning Daniela"
str_split = str.split()
print(str_split)
str = "홍길동/28/서울시 강남구/010-1234-5667"
print(str.split('/')) |
eb08fddb9159ddc5f6ecb72d259169005809a216 | nlbao/competitive-programming | /library/Algorithm/fastcomp.py | 3,242 | 3.671875 | 4 | #!/usr/bin/python
# http://writingarchives.sakura.ne.jp/fastcomp/
# Fast String Comparator is an efficient tool to determine
# whether two strings are within two edit distance or not.
# Given two strings of length m and n (m <= n), the computation requires O(1) space
# and O(n) time, which is much smaller and faster than when
# using well-known algorithm with O(mn) space and time for the same purpose.
# It is mainly targeted at the use in spell checker, where considering words
# within two edit distance suffices.
# Usage:
# The fastcomp.py has a function named compare().
# It takes two strings as arguments and returns an integer, which is...
# + The exact distance between two strings (if they are within two edit distance)
# + -1 (if they are over two edit distance away)
# Therefore, the return value should be any one of 0, 1, 2 or -1.
def compare(str1, str2):
replace, insert, delete = "r", "i", "d"
L1, L2 = len(str1), len(str2)
if L1 < L2:
L1, L2 = L2, L1
str1, str2 = str2, str1
if L1 - L2 == 0:
models = (insert+delete, delete+insert, replace+replace)
elif L1 - L2 == 1:
models = (delete+replace, replace+delete)
elif L1 - L2 == 2:
models = (delete+delete,)
else:
return -1
res = 3
for model in models:
i, j, c = 0, 0, 0
while (i < L1) and (j < L2):
if str1[i] != str2[j]:
c = c+1
if 2 < c:
break
cmd = model[c-1]
if cmd == delete:
i = i+1
elif cmd == insert:
j = j+1
else:
assert cmd == replace
i,j = i+1, j+1
else:
i,j = i+1, j+1
if 2 < c:
continue
elif i < L1:
if L1-i <= model[c:].count(delete):
c = c + (L1-i)
else:
continue
elif j < L2:
if L2-j <= model[c:].count(insert):
c = c + (L2-j)
else:
continue
if c < res:
res = c
if res == 3:
res = -1
return res
def test():
assert compare("abc", "abc") == 0 # Same
assert compare("abc", "abcd") == 1 # Insertion
assert compare("abc", "abd") == 1 # Substitute
assert compare("abc", "bc") == 1 # Delete
assert compare("abcde", "acdfe") == 2 # Distance 2 and L1-L2 = 0
assert compare("acdfe", "abcde") == 2
assert compare("abc", "bcd") == 2
assert compare("bcd", "abc") == 2
assert compare("abc", "ade") == 2
assert compare("abc", "eabf") == 2 # Distance 2 and L1-L2 = 1
assert compare("abc", "ebfc") == 2
assert compare("abc", "a") == 2 # Distance 2 and L1-L2 = 2
assert compare("c", "abc") == 2
assert compare("abcde", "bcdgf") == -1 # Distance 3
assert compare("abc", "efg") == -1
assert compare("abc", "") == -1 # Comparing with Null string
assert compare("", "abc") == -1
assert compare("", "ab") == 2
assert compare("", "a") == 1
assert compare("", "") == 0
return
if __name__ == "__main__":
test()
|
8183c2fe9bc292355ef0d61eddc2246585680c8b | ashok90/AppliedAlgorithm | /Programming Assignment 2/mergeSort.py | 856 | 3.828125 | 4 | import time as t
def main():
a = [14, 4, 6, 3, 0, 84,7,8]
print a
def merge(a,s,l,e):
left=a[s:l+1]
right=a[l+1:e+1]
i=0
j=0
print a
for k in xrange(s,e):
if left[i]<=right[j]:
a[k]=left[i]
a[k+1]=right[j]
i=i+1
else:
a[k]=right[j]
a[k+1]=left[i]
j=j+1
#print a
def mergeSort(a, s, e):
if s < e:
length = (e+s) / 2
mergeSort(a, s, length)
mergeSort(a, length+1, e)
merge(a,s,length,e)
mergeSort(a, 0, len(a)-1)
if __name__ == "__main__":
main()
"""
Reference :
Introduction to Algorithms - 3RD edition
http://www.python-course.eu/passing_arguments.php
"""
|
09f1ecc3f49a6b6883c1b30e898cf9cd0e4069e2 | vinceajcs/all-things-python | /algorithms/tree/binary_tree/bst/kth_smallest_element.py | 410 | 3.796875 | 4 | """Find the kth smallest element in a given BST.
We can use an inorder traversal to solve this.
Time: O(max(n, k))
Space: O(n)
"""
def kth_smallest(root, k):
stack = []
while root:
while root or stack:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if k == 0:
break
root = root.right
return root.val
|
8ad21db64bbccdfad4f807d89c379ebe817dbe44 | ljrdemail/AID1810 | /PythonBasic/Day02/if3.py | 273 | 3.859375 | 4 | # 输入并判断基数还是偶数
x = input("请输入需要判断的数:")
xnum = int(x)
if (xnum % 2): #(xnum % 2 ==1 走这一句
print("是奇数")
else :
#else: #else 子句当上述所有所有的条件都不符合的时候走else
print("是偶数")
|
345d4da252d3cdff6df2d8a3177bad34a9f63f9a | ronitpatt/YOLOnn | /tsting.py | 1,338 | 3.53125 | 4 |
import pandas as pd
def remove_s(temp):
idx_a = temp.find(',')
temp = temp[0:idx_a - 1] + temp[idx_a:]
return temp
if __name__ == '__main__':
dict_t = {}
dict_t[2] = ['label']
dict_t[2].append('dog')
cl = []
cl.append(dict_t)
print(cl)
def func(yolo):
for z in yolo['label']:
# Find number
ctr = ctr + 1
nums = [int(i) for i in z.split() if i.isdigit()]
if z.count(',') >= 2:
idx_a = z.find(',') - 1
if nums[0] > 2: # Removes 's' from back of label due to plurality. Ex: persons -> person
z = z[:idx_a] + z[idx_a + 1:]
if nums[1] > 2:
start_idx = idx_a + 2
idx_c = z.find(',', start_idx)
z = z[:idx_c] + z[idx_c + 1:]
while nums[0] > 0:
# remove string from back
yolo.loc[ctr, 'label'] = z[0:z.find(',') + 1]
nums[0] = nums[0] - 1
while nums[1] > 0:
# remove beginning string
yolo.loc[ctr, 'label'] = z[z.find(',') + 1:]
nums[1] = nums[1] - 1
z = ''.join([i for i in z if not i.isdigit()])
z = z.strip()
# and (z.count(',') >= 2)
z = str(z)
if z in set_dlt:
idx_drop.append(ctr)
|
bbaf317564a14b6c337768b6ef169937430416b6 | jmcharter/projecteuler_python | /problem07.py | 506 | 3.921875 | 4 | '''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
import time
start = time.time()
def isItPrime(x):
for i in range(2, x):
if x%i == 0:
return False
return True
def primeN(n):
prime = 2
count = 1
step = 3
while count < n:
if isItPrime(step):
prime = step
count += 1
step += 2
return prime
print (primeN(10001))
elapsed = time.time() - start
print ("This took %s seconds" % elapsed) |
788f839f4d47211edec194738dbba00986b053fd | wjakew/pdfmaker | /gui_selectionwindow.py | 1,579 | 3.9375 | 4 | import tkinter as tk
from tkinter import messagebox
# class creating object for naming
class Gui_selectionwindow:
# function for getting data from entry
def get_data(self):
if self.entry.get() != "":
print("Selected name: " + self.entry.get())
self.return_data = self.entry.get()
self.root.dispose()
else:
messagebox.showerror("Input error","Your input is blank!")
pass
# constructor
def __init__(self,string_prompt,string_title,string_button,width_px,height_px):
# field for user input
self.return_data = ""
self.window_message = string_prompt
self.window_title = string_title
self.button_title = string_button
self.width_px_entry = width_px/2
self.height_px_entry = height_px/2
# setting root window
self.root = tk.Tk()
# getting canvas on the root window
self.main_canvas = tk.Canvas(self.root,width = width_px,height = height_px)
self.main_canvas.pack()
# setting input box
self.entry = tk.Entry(self.root)
# creating window
self.main_canvas.create_window(self.width_px_entry,self.height_px_entry,window=self.entry)
self.button1 = tk.Button(self.root,text=self.button_title,command = self.get_data,
bg = "black",fg = "white", font = ("helvetica",9,"bold"))
self.main_canvas.create_window(self.width_px_entry,self.height_px_entry+50,window = self.button1)
self.root.mainloop()
|
1e1a2c87531c8f3d4ec6c566f68f569862bb5336 | jangjichang/Today-I-Learn | /Algorithm/Programmers/numbergame/test_numbergame.py | 1,893 | 3.5625 | 4 | import pytest
"""
대진표가 노출된 A를 보면서 B에서 출전할 사람을 구한다.
A, B를 정렬한다.
A의 요소들에 대해 다음을 확인한다.
B의 요소 중 그 요소보다 큰 수 중 A에서 가장 작은 수를 찾고 삭제한다. answer += 1
만약 그런 수가 없다면, 가장 작은 수를 찾고 삭제한다. answer += 0
A, B를 내림차순 정렬한다.
A와 B를 비교한다.
B가 A보다 작을 경우
"""
def test_simple():
assert 3 == solution([5, 1, 3, 7], [2, 2, 6, 8])
assert 3 == solution([5, 4, 3, 2, 1], [4, 3, 2, 1, 1])
assert 2 == solution([5, 4, 3, 3, 1], [1, 1, 4, 2, 3])
assert 0 == solution([2, 2, 2, 2], [1, 1, 1, 1])
def solution(A, B):
"""
answer = 0
A.sort()
A.reverse()
B.sort()
B.reverse()
loop_number = len(A)
for i in range(0, loop_number):
if A[0] < B[0]:
index = 0
while True:
if index >= len(B):
B.pop()
answer += 1
break
elif A[0] < B[index]:
index += 1
elif A[0] >= B[index]:
B.pop(index-1)
answer += 1
break
A.pop(0)
else:
B.pop()
A.pop(0)
return answer
"""
"""
1 2 3 5 7
2 2 6 8 9
if a < b:
remove a
remove b
else:
3 5 7
2 6 8
3 5 7
6 8
2 2 2 2
1 1 1 1
"""
answer = 0
A.sort()
A.reverse()
B.sort()
B.reverse()
while A:
if A[0] >= B[0]:
del A[0]
else:
answer += 1
del A[0]
del B[0]
return answer
if __name__ == '__main__':
solution([5, 1, 3, 7], [2, 2, 6, 8])
# solution([2, 2, 2, 2], [1, 1, 1, 1])
|
a057a3e4d9eec545840fa0cfa22dd871ab5f910a | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/sum-of-multiples/5c1375fc205244a29b775c99a780f24a.py | 789 | 3.953125 | 4 | def find_multiples(mults, limit):
"""Returns multiples of each mults up to to"""
multiples = []
for i in range(3, limit):
for mult in mults:
if i % mult == 0:
# print ('Found multiple', i)
multiples += [i]
return set(multiples)
class SumOfMultiples:
"""Returns the sum of all multiples of inputs up to a limit, excluding itself"""
def __init__(self, *mults):
"""Creates a SumOfMults object"""
if not mults:
mults = [3,5]
self._mults = mults
def to(self, limit=10):
"""Returns the sum of the multiples of mults up to a given limit"""
return sum(find_multiples(self._mults, limit))
if __name__ == "__main__":
a = SumOfMultiples().to(10)
|
925246e1fc3679d838a6f1c8ccc960990d62ab37 | akhi1212/pythonpracticse | /SwapListFirstLastValue.py | 276 | 4.15625 | 4 | """
Frequently Asked Python Program 8: How To Swap First & Last Elements of a List
"""
mylist = [204,4224,"This is Akhilesh",29,00,90]
print("This is original list:", mylist)
mylist[0],mylist[-1] = mylist[-1],mylist[0]
print("Replacing list is not displaying like:", mylist) |
f59f74d1573e1f6bdac20b0167b7fec555bf7567 | arpancodes/100DaysOfCode__Python | /day-14/higherlower.py | 1,044 | 3.953125 | 4 | from game_data import data
from art import logo, vs
import random
print(logo)
score = 0
while True:
x = random.randint(0, len(data) - 1)
first = data[x]
second = data[x+1]
print(first["name"])
print(f"A. {first['name']}, {first['description']}, {first['country']}")
print(vs)
print(f"B. {second['name']}, {second['description']}, {second['country']}")
choice = input("Who do you think has the higher followers? A or B: ").lower()
if choice == "a":
if first["follower_count"] > second["follower_count"]:
score += 1
print("====================================================")
print("Correct!")
print("====================================================")
else:
print("Wrong Answer!")
break
else:
if first["follower_count"] < second["follower_count"]:
score += 1
print("====================================================")
print("Correct!")
print("====================================================")
else:
print("Wrong Answer!")
break
print(f"Game over! your score was: {score}")
|
dc30abf20ed9738b55939e478575a3700606f8a4 | devopsvj/PythonAndMe | /strings/space_count.py | 268 | 4.25 | 4 | print "Counting the number of spaces in the string"
print "--------------------------------------------"
str1=raw_input("Enter the String :")
count=0
for ch in str1:
if ch.isspace():
count=count+1
print "Number of spaces in the given string is : ",count
|
ee7a43b628a22b92ab5541aa1290dcbe3780efe4 | erjan/coding_exercises | /shortest_path_in_binary_matrix.py | 2,258 | 4.03125 | 4 | '''
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:
All the visited cells of the path are 0.
All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).
The length of a clear path is the number of visited cells of this path.
'''
import collections
class Solution(object):
def shortestPathBinaryMatrix(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0] or grid[0][0] == 1 or grid[-1][-1] == 1: return -1
visited = set((0, 0))
queue = collections.deque([(0, 0, 1)])
while queue:
x, y, level = queue.popleft()
if (x, y) == (len(grid) - 1, len(grid[0]) - 1): return level
for dx, dy in [(0, 1), (1, 0), (-1, 0), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]:
if 0 <= x + dx < len(grid) and 0 <= y + dy < len(grid[0]) and grid[x + dx][y + dy] == 0 and (x + dx, y + dy) not in visited:
visited.add((x + dx, y + dy))
queue.append((x + dx, y + dy, level + 1))
return -1
-------------------------------------------------------------------------------------------------------------------------------------------------------
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] == 1:
return -1
q = [(0,0,1)]#min length is 1
while len(q) > 0:
x,y,d = q.pop(0)
if x== n-1 and y == n-1:
return d
directions = [(x-1,y-1), (x+1,y+1),(x-1,y), (x+1,y), (x,y+1), (x,y-1),(x-1,y+1), (x+1,y-1)]
for a,b in directions:
if 0<=a<n and 0<=b<n and grid[a][b] == 0:
grid[a][b] = 1
q.append((a,b,d+1))
return -1
|
e3cb393de32f6c2a268e4b8ec26f5cab422961b2 | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/mbnbon015/question1.py | 240 | 4.15625 | 4 | #program to to point out wheather a year is a leap year or not
year=eval(input("Enter a year:\n"))
if((year%400)==0 and (year%4)==0 and (year%100)!=0):
print(year,"is a leap year.")
else:
print(year,"is not a leap year.")
|
9ba2aa145d827e2b12436cdb9e8bb1c5adcc23eb | amitupadhyay6/My-Python-Program | /My Codes/16.Constructor.py | 388 | 4.125 | 4 |
# Constructors is called at the time of creating object.
class point:
def __init__(self, x, y): # we need add special method or function called constructor
self.x=x
self.y=y
def move(self):
print("Move")
print(self.x)
def draw(self):
print("draw")
point=point(10, 20)
point.draw()
point.move()
print(point.x, point.y)
|
d45c39f9f684864ed810e78cd0e4dc568d16766d | CateGitau/Python_programming | /Packt_Python_programming/Chapter_3/exercise57.py | 435 | 4.25 | 4 | # Filtering with Lambda Functions
#The filter is another special function that, like map,
#takes a function and iterables (for example, a list) as inputs. It returns the elements
# for which the function returns True.
#In this exercise, we will be calculating the sum of all the multiples of 3 or 7 below 1,000
nums = list(range(1000))
filtered = filter(lambda nums: nums % 3 == 0 or nums % 7 == 0, nums)
print(sum(filtered))
|
4b37de08516678027831499ea05744072407ada4 | quantshah/qml | /demonstrations/tutorial_qft_arithmetics.py | 18,973 | 3.875 | 4 | r""".. _qft_arithmetics:
Basic arithmetic with the quantum Fourier transform (QFT)
=======================================
.. meta::
:property="og:description": Learn how to use the quantum Fourier transform (QFT) to do basic arithmetic
:property="og:image": https://pennylane.ai/qml/_images/qft_arithmetics_thumbnail.png
.. related::
tutorial_qubit_rotation Basis tutorial: qubit rotation
*Author: Guillermo Alonso-Linaje — Posted: 07 November 2022.*
Arithmetic is a fundamental branch of mathematics that consists of the study of the main operations with numbers such as
addition, multiplication, subtraction and division. Using arithmetic operations we can understand the world around us
and solve many of our daily tasks.
Arithmetic is crucial for the implementation of any kind of algorithm in classical computer science, but also in quantum computing. For this reason, in this demo we are going to show
an approach to defining arithmetic operations on quantum computers. The simplest and most direct way to achieve this goal is to use the
quantum Fourier transform (QFT), which we will demonstrate on a basic level.
In this demo we will not focus on understanding how the QFT is built,
as we can find a great explanation in the
`Xanadu Quantum Codebook <https://codebook.xanadu.ai/F.1>`__. Instead, we will develop the
intuition for how it works and how we can best take advantage of it.
Motivation
----------
The first question we have to ask ourselves is whether it makes sense to perform these basic operations on a quantum computer. Is the
goal purely academic or is it really something that is needed in certain algorithms? Why implement in a quantum computer
something that we can do with a calculator?
When it comes to basic quantum computing algorithms like the Deustch–Jozsa or
Grover's algorithm, we might think that we have never needed to apply any arithmetic operations such as addition or multiplication.
However, the reality is different. When we learn about these algorithms from an academic point of view,
we work with a ready-made operator that we never have to worry about, the *oracle*.
Unfortunately, in real-world situations, we will have to build this seemingly magical operator by hand.
As an example, let's imagine that we want to use Grover's algorithm to search for `magic squares <https://en.wikipedia.org/wiki/Magic_square>`__.
To define the oracle, which determines whether a solution is valid or not, we must perform sums over the rows and
columns to check that they all have the same value. Therefore, to create this oracle,
we will need to define a sum operator within the quantum computer.
The second question we face is why we should work with the QFT at all. There are other procedures that could be used to perform these basic operations; for example, by
imitating the classical algorithm. But, as we can see in [#Draper2000]_, it has already been proven that the QFT needs fewer qubits to perform these operations, which is
nowadays of vital importance.
We will organize the demo as follows. Initially, we will talk about the Fourier basis to give an intuitive idea of how
it works, after which we will address different basic arithmetic operations. Finally, we will move on to a practical example
in which we will factor numbers using Grover's algorithm.
QFT representation
-----------------
To apply the QFT to basic arithmetic operations, our objective now is to learn how to add,
subtract and multiply numbers using quantum devices. As we are working with qubits,
—which, like bits, can take the
values :math:`0` or :math:`1`—we will represent the numbers in binary. For the
purposes of this tutorial, we will assume that we are working only with
integers. Therefore, if we have :math:`n` qubits, we will be able to
represent the numbers from :math:`0` to :math:`2^n-1`.
The first thing we need to know is PennyLane's
standard for encoding numbers in a binary format. A binary number can be
represented as a string of 1s and 0s, which we can represent as the multi-qubit state
.. math:: \vert m \rangle = \vert \overline{q_0q_1...q_{n-1}}\rangle,
where the formula to obtain the equivalent decimal number :math:`m` will be:
.. math:: m= \sum_{i = 0}^{n-1}2^{n-1-i}q_i.
Note that :math:`\vert m \rangle` refers to the basic state
generated by the binary encoding of the number :math:`m`.
For instance, the natural number :math:`6`
is represented by the quantum state :math:`\vert 110\rangle,` since :math:`\vert 110 \rangle = 1 \cdot 2^2 + 1\cdot 2^1+0\cdot 2^0 = 6`.
Let’s see how we would represent all the integers from :math:`0` to :math:`7` using the product state of three qubits, visualized by separate Bloch spheres for each qubit.
.. figure:: /demonstrations/qft_arithmetics/3_qubits_computational_basis.gif
:width: 90%
:align: center
Representation of integers using a computational basis of three qubits.
.. note::
The `Bloch sphere <https://en.wikipedia.org/wiki/Bloch_sphere>`_
is a way of graphically representing the state of a qubit.
At the top of the sphere we place the state :math:`\vert 0 \rangle,` at the bottom
:math:`\vert 1 \rangle`, and in the rest of the
sphere we will place the possible states in superposition. It is a very useful
representation that helps better visualize and interpret quantum gates such as rotations.
We can use
the :class:`qml.BasisEmbedding <pennylane.BasisEmbedding>`
template to obtain the binary representation in a simple way.
Let's see how we would code the number :math:`6`.
"""
import pennylane as qml
import matplotlib.pyplot as plt
dev = qml.device("default.qubit", wires=3)
@qml.qnode(dev)
@qml.compile()
def basis_embedding_circuit(m):
qml.BasisEmbedding(m, wires=range(3))
return qml.state()
m = 6 # number to be encoded
qml.draw_mpl(basis_embedding_circuit, show_all_wires=True)(m)
plt.show()
######################################################################
#
# As we can see, the first qubit—the :math:`0`-th wire—is placed on top and the rest of the qubits are
# below it. However, this is not the only way we could represent numbers.
# We can also represent them in different bases, such as the so-called *Fourier base*.
#
# In this case, all the states of the basis will be represented via qubits in
# the XY-plane of the Bloch sphere, each rotated by a certain
# amount.
#
#
# How do we know how much we must rotate each qubit to represent a certain number?
# It is actually very easy! Suppose we are working with
# :math:`n` qubits and we want to represent the number :math:`m` in the
# Fourier basis. Then the :math:`j`-th qubit will have the phase:
#
# .. math:: \alpha_j = \frac{2m\pi}{2^{j}}.
#
# Now we can represent numbers in the Fourier basis using three qubits:
#
# .. figure:: /demonstrations/qft_arithmetics/3_qubits_fourier_basis.gif
# :width: 90%
# :align: center
#
# Representation of integers using the Fourier basis with three qubits
#
# As we can see, the third qubit will rotate
# :math:`\frac{1}{8}` of a turn counterclockwise with each number. The next qubit
# rotates :math:`\frac{1}{4}` of a full turn and, finally, the first qubit rotates
# half a turn for each increase in number.
#
# Adding a number to a register
# ------------------------------
#
# The fact that the states encoding the numbers are now in phase gives us great
# flexibility in carrying out our arithmetic operations. To see this in practice,
# let’s look at the situation in which want to create an operator Sum
# such that:
#
# .. math:: \text{Sum(k)}\vert m \rangle = \vert m + k \rangle.
#
# The procedure to implement this unitary operation is the following:
#
# #. We convert the state from the computational basis into the Fourier basis by applying the QFT to the :math:`\vert m \rangle` state via the :class:`~pennylane.QFT` operator.
#
# #. We rotate the :math:`j`-th qubit by the angle :math:`\frac{2k\pi}{2^{j}}` using the :math:`R_Z` gate, which leads to the new phases, :math:`\frac{2(m + k)\pi}{2^{j}}`.
#
# #. We apply the QFT inverse to return to the computational basis and obtain :math:`m+k`.
#
#
# Let's see how this process would look in PennyLane.
#
import pennylane as qml
from pennylane import numpy as np
n_wires = 4
dev = qml.device("default.qubit", wires=n_wires, shots=1)
def add_k_fourier(k, wires):
for j in range(len(wires)):
qml.RZ(k * np.pi / (2**j), wires=wires[j])
@qml.qnode(dev)
def sum(m, k):
qml.BasisEmbedding(m, wires=range(n_wires)) # m encoding
qml.QFT(wires=range(n_wires)) # step 1
add_k_fourier(k, range(n_wires)) # step 2
qml.adjoint(qml.QFT)(wires=range(n_wires)) # step 3
return qml.sample()
print(f"The ket representation of the sum of 3 and 4 is {sum(3,4)}")
######################################################################
# Perfect, we have obtained :math:`\vert 0111 \rangle`, which is equivalent to the number :math:`7` in binary!
#
# Note that this is a deterministic algorithm, which means that we have obtained the desired solution by executing a single shot.
# On the other hand, if the result of an operation is greater than the maximum
# value :math:`2^n-1`, we will start again from zero, that is to say, we
# will calculate the sum modulo :math:`2^n-1.` For instance, in our three-qubit example, suppose that
# we want to calculate :math:`6+3.` We see that we do not have
# enough memory space, as :math:`6+3 = 9 > 2^3-1`. The result we will get will
# be :math:`9 \pmod 8 = 1`, or :math:`\vert 001 \rangle` in binary. Make sure to use
# enough qubits to represent your solutions!
# Finally, it is important to point out that it is not necessary to know how the
# QFT is constructed in order to use it. By knowing the properties of the
# new basis, we can use it in a simple way.
#
# Adding two different registers
# ------------------------------
#
# In this previous algorithm, we had to pass to the operator the value of :math:`k` that we wanted to add to the starting state.
# But at other times, instead of passing that value to the operator, we would like it to pull the information from another register.
# That is, we are looking for a new operator :math:`\text{Sum}_2` such that
#
# .. math:: \text{Sum}_2\vert m \rangle \vert k \rangle \vert 0 \rangle = \vert m \rangle \vert k \rangle \vert m+k \rangle.
#
# In this case, we can understand the third register (which is initially
# at :math:`0`) as a counter that will tally as many units as :math:`m` and
# :math:`k` combined. The binary decomposition will
# make this simple. If we have :math:`\vert m \rangle = \vert \overline{q_0q_1q_2} \rangle`, we will
# have to add :math:`1` to the counter if :math:`q_2 = 1` and nothing
# otherwise. In general, we should add :math:`2^{n-i-1}` units if the :math:`i`-th
# qubit is in state :math:`\vert 1 \rangle` and 0 otherwise. As we can see, this is the same idea that is also
# behind the concept of a controlled gate. Indeed, observe that we will, indeed, apply a corresponding
# phase if indeed the control qubit is in the state :math:`\vert 1\rangle`.
# Let us now code the :math:`\text{Sum}_2` operator.
wires_m = [0, 1, 2] # qubits needed to encode m
wires_k = [3, 4, 5] # qubits needed to encode k
wires_solution = [6, 7, 8, 9] # qubits needed to encode the solution
dev = qml.device("default.qubit", wires=wires_m + wires_k + wires_solution, shots=1)
n_wires = len(dev.wires) # total number of qubits used
def addition(wires_m, wires_k, wires_sol):
# prepare solution qubits to counting
qml.QFT(wires=wires_solution)
# add m to the counter
for i in range(len(wires_m)):
qml.ctrl(add_k_fourier, control=wires_m[i])(2 **(len(wires_m) - i - 1), wires_solution)
# add k to the counter
for i in range(len(wires_k)):
qml.ctrl(add_k_fourier, control=wires_k[i])(2 **(len(wires_k) - i - 1), wires_solution)
# return to computational basis
qml.adjoint(qml.QFT)(wires=wires_solution)
@qml.qnode(dev)
def sum2(m, k, wires_m, wires_k, wires_solution):
# m and k codification
qml.BasisEmbedding(m, wires=wires_m)
qml.BasisEmbedding(k, wires=wires_k)
# apply the addition circuit
addition(wires_m, wires_k, wires_solution)
return qml.sample(wires=wires_solution)
print(f"The ket representation of the sum of 7 and 3 is "
f"{sum2(7, 3, wires_m, wires_k, wires_solution)}")
qml.draw_mpl(sum2, show_all_wires=True)(7, 3, wires_m, wires_k, wires_solution)
plt.show()
######################################################################
# Great! We have just seen how to add a number to a counter. In the example above,
# we added :math:`3 + 7` to get :math:`10`, which in binary
# is :math:`\vert 1010 \rangle`.
#
# Multiplying qubits
# -------------------
#
# Following the same idea, we will see how easily we can
# implement multiplication. For this purpose we'll take two arbitrary numbers :math:`m` and :math:`k`
# to carry out the operation. This time, we look for an operator Mul such that
#
# .. math:: \text{Mul}\vert m \rangle \vert k \rangle \vert 0 \rangle = \vert m \rangle \vert k \rangle \vert m\cdot k \rangle.
#
# To understand the multiplication process, let's work with the binary decomposition of
# :math:`k:=\sum_{i=0}^{n-1}2^{n-i-1}k_i` and
# :math:`m:=\sum_{j=0}^{l-1}2^{l-j-1}m_i`. In this case, the product would
# be:
#
# .. math:: k \cdot m = \sum_{i=0}^{n-1}\sum_{j = 0}^{l-1}m_ik_i (2^{n-i-1} \cdot 2^{l-j-1}).
#
# In other words, if :math:`k_i = 1` and :math:`m_i = 1`, we would add
# :math:`2^{n-i-1} \cdot 2^{l-j-1}` units to the counter, where :math:`n` and :math:`l`
# are the number of qubits with which we encode :math:`m` and :math:`k` respectively.
# Let's code to see how it works!
wires_m = [0, 1, 2] # qubits needed to encode m
wires_k = [3, 4, 5] # qubits needed to encode k
wires_solution = [6, 7, 8, 9, 10] # qubits needed to encode the solution
dev = qml.device("default.qubit", wires=wires_m + wires_k + wires_solution, shots=1)
n_wires = len(dev.wires)
def multiplication(wires_m, wires_k, wires_solution):
# prepare sol-qubits to counting
qml.QFT(wires=wires_solution)
# add m to the counter
for i in range(len(wires_k)):
for j in range(len(wires_m)):
coeff = 2 ** (len(wires_m) + len(wires_k) - i - j - 2)
qml.ctrl(add_k_fourier, control=[wires_k[i], wires_m[j]])(coeff, wires_solution)
# return to computational basis
qml.adjoint(qml.QFT)(wires=wires_solution)
@qml.qnode(dev)
def mul(m, k):
# m and k codification
qml.BasisEmbedding(m, wires=wires_m)
qml.BasisEmbedding(k, wires=wires_k)
# Apply multiplication
multiplication(wires_m, wires_k, wires_solution)
return qml.sample(wires=wires_solution)
print(f"The ket representation of the multiplication of 3 and 7 is {mul(3,7)}")
qml.draw_mpl(mul, show_all_wires=True)(3, 7)
plt.show()
######################################################################
# Awesome! We have multiplied :math:`7 \cdot 3` and, as a result, we have
# :math:`\vert 10101 \rangle`, which is :math:`21` in binary.
#
#
# Factorization with Grover
# -------------------------
#
# With this, we have already gained a large repertoire of interesting
# operations that we can do, but we can give the idea one more twist and
# apply what we have learned in an example.
#
# Let’s imagine now that we want just the opposite: to factor the
# number :math:`21` as a product of two terms. Is this something we could do
# using our previous reasoning? The answer is yes! We can make use of
# `Grover's algorithm <https://en.wikipedia.org/wiki/Grover%27s_algorithm>`_ to
# amplify the states whose product is the number we
# are looking for. All we would need is to construct the oracle :math:`U`, i.e., an
# operator such that
#
# .. math:: U\vert m \rangle \vert k \rangle = \vert m \rangle \vert k \rangle \text{ if }m\cdot k \not = 21,
#
# .. math:: U\vert m \rangle \vert k \rangle = -\vert m \rangle \vert k \rangle \text{ if }m\cdot k = 21
#
# The idea of the oracle is as simple as this:
#
# #. use auxiliary registers to store the product,
# #. check if the product state is :math:`\vert 10101 \rangle` and, in that case, change the sign,
# #. execute the inverse of the circuit to clear the auxiliary qubits.
# #. calculate the probabilities and see which states have been amplified.
#
# Let's go back to PennyLane to implement this idea.
n = 21 # number we want to factor
wires_m = [0, 1, 2] # qubits needed to encode m
wires_k = [3, 4, 5] # qubits needed to encode k
wires_solution = [6, 7, 8, 9, 10] # qubits needed to encode the solution
dev = qml.device("default.qubit", wires=wires_m + wires_k + wires_solution)
n_wires = len(dev.wires)
@qml.qnode(dev)
def factorization(n, wires_m, wires_k, wires_solution):
# Superposition of the input
for wire in wires_m:
qml.Hadamard(wires=wire)
for wire in wires_k:
qml.Hadamard(wires=wire)
# Apply the multiplication
multiplication(wires_m, wires_k, wires_solution)
# Change sign of n
qml.FlipSign(n, wires=wires_solution)
# Uncompute multiplication
qml.adjoint(multiplication)(wires_m, wires_k, wires_solution)
# Apply Grover operator
qml.GroverOperator(wires=wires_m + wires_k)
return qml.probs(wires=wires_m)
plt.bar(range(2 ** len(wires_m)), factorization(n, wires_m, wires_k, wires_solution))
plt.xlabel("Basic states")
plt.ylabel("Probability")
plt.show()
######################################################################
# By plotting the probabilities of obtaining each basic state we see that
# prime factors have been amplified! Factorization via Grover’s algorithm
# does not achieve exponential improvement that
# `Shor's algorithm <https://en.wikipedia.org/wiki/Shor%27s_algorithm>`_ does, but we
# can see that this construction is simple and a great example to
# illustrate basic arithmetic!
#
# I hope we can now all see that oracles are not something magical and that there
# is a lot of work behind their construction! This will help us in the future to build
# more complicated operators, but until then, let’s keep on learning. 🚀
#
# References
# ----------
#
# .. [#Draper2000]
#
# Thomas G. Draper, "Addition on a Quantum Computer". `arXiv:quant-ph/0008033 <https://arxiv.org/abs/quant-ph/0008033>`__.
#
#
# About the author
# ----------------
#
# .. include:: ../_static/authors/guillermo_alonso.txt
#
|
e7542fb5475e6ab8d42433942a5f16a65810aca1 | erikagreen7777/php_piscine | /d01/ex03/main.py | 289 | 3.53125 | 4 | #!/usr/bin/python
from ft_split import ft_split
def main():
array = ft_split(("Hello World AAA"))
i = 0
print("Array\n(")
while i < len(array):
print("\t[%d] => %s" % (i, array[i]))
i += 1
print(")")
if __name__ == "__main__":
main() |
6715ee34eed36eb9bf6570a660f920ba0c0ba8f8 | souza-joao/cursoemvideo-python3 | /087.py | 755 | 3.640625 | 4 | mat = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
par = []
col3 = []
maior = 0
for l in range(0, 3):
for c in range(0, 3):
mat[l][c] = int(input(f'Digite um número para [{l}, {c}]: '))
if mat[l][c] % 2 == 0:
par.append(mat[l][c])
if c == 2:
col3.append(mat[l][c])
if l == 1:
if c == 0:
maior = mat[l][c]
else:
if mat[l][c] > maior:
maior = mat[l][c]
for l in range(0, 3):
for c in range(0, 3):
print(f'[{mat[l][c]:^5}]', end=' ')
print()
print(f'A soma de todos os valores pares é {sum(par)}.')
print(f'A soma de todos os valores da 3ª coluna é {sum(col3)}.')
print(f'O maior valor da 2ª linha é {maior}.')
|
3625808539ae796679a8635bc00f96f8fe393ed4 | april-april/Leetcode | /loleetcode/same_tree.py | 1,479 | 3.921875 | 4 | class Node:
# A utility function to create a new node
def __init__(self ,key):
self.data = key
self.left = None
self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if not p and not q:
return True
elif not p or not q:
return False
elif p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
def isSameTree2(self, p, q):
if p and q:
return p.val == q.val and self.isSameTree2(p.left, q.left) and self.isSameTree2(p.right, q.right)
return p is q
def isSameTree3(self, p, q):
stack = [(p, q)]
while stack:
n1, n2 = stack.pop()
if n1 and n2 and n1.val == n2.val:
stack.append((n1.right, n2.right))
stack.append((n1.left, n2.left))
elif not n1 and not n2:
continue
else:
return False
return True
def main():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root2 = Node(1)
root2.left = Node(2)
root2.right = Node(3)
root2.left.left = Node(5)
solution = Solution()
print(solution.isSameTree2(root, root2))
if __name__ == "__main__":
main() |
f4664fd8534777775b4227dc78cb5eefde90a9b9 | EricRovell/project-euler | /deprecated/039/python/039.py | 2,027 | 3.796875 | 4 | # returns all primitive (as tuples) or non-primitive too (as lists)
# pythagorean triplets for a given limit
def pythagorian_triplets(limit, primitive = False):
def children(parent):
a, b, c = parent[0], parent[1], parent[2]
children = []
children.append((a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c))
children.append((a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c))
children.append((-a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c))
return children
primitives = [(3, 4, 5)]
seed = primitives[0]
genetation = children(seed)
while len(genetation) != 0:
genetation = [triplet for triplet in genetation if all(side < limit for side in triplet)]
primitives.extend(genetation)
new_generation = []
for triplet in genetation:
new_generation.extend(children(triplet))
genetation = new_generation
if primitive == True:
return primitives
else:
for triplet in primitives:
k = 2
while True:
non_primitive = [k * side for side in triplet]
if all(side < limit for side in non_primitive):
if non_primitive not in primitives:
primitives.append(non_primitive)
else:
break
k += 1
return primitives
# returns the perimeter with the greatest number of triplets associated with it
def triplet_perimeter_dict(perimeter):
# usually the hypotenuse is a bit less than half of perimeter
# generating triplets up to perimeter / 2 as side length limit
triplets = pythagorian_triplets(perimeter/2)
perimeter_dict = {}
for triplet in triplets:
P = sum(triplet)
if P <= perimeter:
if P not in perimeter_dict:
perimeter_dict[P] = 1
else:
perimeter_dict[P] += 1
greatest_P = max(perimeter_dict, key = perimeter_dict.get)
triplets_P = perimeter_dict[greatest_P]
return f'Perimeter with value of {greatest_P} has the greatest number of triplets: {triplets_P}.'
# tests
print(triplet_perimeter_dict(1000)) |
18e0418403d60001fb81782a91ccc338518e89ac | civrev/PythonTutorials | /Packages/reader/compressed/gzipped.py | 960 | 3.5625 | 4 | #a file reader for opening compressed files
#based on a course I got from PluralSight.com 'Python Beyond Basics'
import gzip
import sys
#create an instance of the gzip.open function
opener = gzip.open
if __name__ == '__main__':
#argv are argument values that you put in at command line
#w is 'write' access, and also allows you to create files that aren't currently there
f = gzip.open(sys.argv[1], mode='wt')
f.write(' '.join(sys.argv[2:]))
f.close()
#now let's try it out!
'''
>>> import reader.compressed
>>> import reader.compressed.gzipped
>>> import reader.compressed.bzipped
'''
#no errors so it works great!
#now let's make a file with this
#note how argv plays into this
'''
christian@christian-900X3L:~/PythonTutorials/Packages$ python3 -m reader.compressed.gzipped test.gz data compressed with gz
'''
#take a look at what we have now
'''
christian@christian-900X3L:~/PythonTutorials/Packages$ ls
not_searched reader test.bz2 test.gz
'''
|
899a692d38bd3e70215853f86aca4d503c1f2c55 | qhuydtvt/C4E3 | /Assignment_Submission/phucnh/Session 5 - Assignment 1/5.2.py | 1,445 | 4.03125 | 4 |
#1
flock=[5,7,300,90,24,50,75]
print ("Hello, my name is Hiep and these are my ship sizes \n",flock)
#2
flock_max=max(flock)
print ("Hello, my biggest sheep has size",flock_max,"let's shear it")
#3
max_index=flock.index(flock_max)
flock[max_index]=8
print ("After shearing, here is my flock \n", flock)
#4
i=0
for sheep in flock:
flock[i]=flock[i]+50
i=i+1
print("One month has passed, now here is my flock \n",flock)
flock_max=max(flock)
#5
print("\n\n#5")
def tang_50():
i=0
for sheep in flock:
flock[i]=flock[i]+50
i=i+1
print("One month has passed, now here is my flock \n",flock)
def xen_max():
flock_max=max(flock)
print ("Now my biggest sheep has size",flock_max,"let's shear it")
max_index=flock.index(flock_max)
flock[max_index]=8
print ("After shearing, here is my flock \n", flock)
def one_month(month):
x=1
while x<=month:
print("\nMONTH",x)
tang_50()
xen_max()
x=x+1
flock=[5,7,300,90,24,50,75]
print ("Hello, my name is Hiep and these are my ship sizes \n",flock)
one_month(3)
#6
print("\n\n#6")
flock=[5,7,300,90,24,50,75]
print ("Hello, my name is Hiep and these are my ship sizes \n",flock)
xen_max()
one_month(2)
print("MONTH",3)
tang_50()
total=0
for sheep in flock:
total=total+sheep
print("My flock has size in total:",total)
print(str.format("I would get {0} * 2$ = {1}$",total, total*2))
|
3a99dcd363e536c1302e50929f63d1e3349f6853 | DadongZ/python_dev | /sec6_OOP/oop_template.py | 892 | 3.609375 | 4 | # four pillars of oop
#1 encapsulation: binding data type and functions
#2 abstraction: giving access to only what's necessary
### private vs public variable: use underscore for private such as self._name (but no guarantee)
#3 inheritance: allows new objects to take on the properties of existing objects.
#4 polymorphism: the way in which object classes can share the same method name but these names can act differently based on what obect calls now.
class NameOfClass():
class_attribute = 'value' #global attributes
def __init__(self, param1, param2):
self.param1 = param1 #object attributes
self.param2 = param2
def method(self):
pass
@classmethod
def cls_method(cls, parameter_list):
pass
@staticmethod
def stc_method(parameter_list):
pass
#introspection: the ability to determine the type of an object at runtime |
76a1f258e857f8fd958aaf4cdc5b794469ffe8d3 | LKunz/ProjectProg | /RSA.py | 7,261 | 4 | 4 | # This file contains functions that implement the RSA algortihm
# Inspiration: https://gist.github.com/JonCooperWorks/5314103
# Import packages
import random
# Function to compute the gcd (greatest common divisor)
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# Function that implements the Extended Euclidean algorithm
# (see : https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm)
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
# Function to compute multiplicative inverse
def multiplicative_inverse(e, phi):
g, x, y = egcd(e, phi)
if g != 1:
raise Exception('Error: modular inverse does not exist')
else:
return x % phi
# Function to test if a number is prime
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True
def generate_keypair(p, q):
""" Generate private and public keys from p and q
Parameters:
p (int): 1st prime number
q (int): 2nd prime number
Algorithm:
Compute n
Compute e and d using previously defined functions
Return:
public_key, private_key : both keys (tuples)
Example:
p = 17
q = 19
public_key, private_key = generate_keypair(p, q)
print(public_key, private_key)
>>> (209, 323) (113, 323)
Remarks:
The keys can change since e is genareted randomly
"""
# Test if p and q are prime numbers
if not (is_prime(p) and is_prime(q)):
raise ValueError('Both p and q must be prime')
elif p == q:
raise ValueError('p and q cannot be equal')
# Compute n
n = p * q
# Compute phi
phi = (p-1) * (q-1)
# Compute e using Euclid's Algorithm
min_bound = max(p,q)
e = random.randrange(min_bound, phi)
g = gcd(e, phi)
while g != 1:
e = random.randrange(min_bound, phi)
g = gcd(e, phi)
# Compute d using Extended Euclid's Algorithm
d = multiplicative_inverse(e, phi)
# Return public and private keys
# Public key is (e, n) and private key is (d, n)
return ((e, n), (d, n))
def make_blocks(text, n, size=3):
"""
Make blocks from text
Parameters:
text (str): text from which to make blocks
n (int): n from RSA algortihm - we pass it as argument to avoid error
in encoding blocks
size (int): size of each block we want to create
Algorithm:
Use (shifted) ASCII to match all characters in
text to a number in [00,99]
Divide number into blocks of same length (size)
Return:
Blocks version of text (list)
Example:
message = "I love programming"
blocks = make_blocks(message,'1000')
print(blocks)
>>> [410, 76, 798, 669, 8, 82, 797, 182, 657, 777, 737, 871]
"""
# Define output
blocks = ""
# Check parameters (for encryption to work)
if size <= 1:
raise Exception('p and q are too small')
elif size >= len(str(n)):
raise Exception('p and q are too small')
# Encode characters into blocks
else:
for i in text:
tmp = str(ord(i) - 32) # To be in good range (< 3 numbers)
if (len(tmp) == 1): # Add zero at the start
tmp = '0' + tmp
blocks += tmp
# Make blocks
blocks = [int(blocks[i * (size):(i + 1) * (size)]) \
for i in range((len(blocks) + size - 1) // (size) )]
return blocks
def make_text(blocks, size=3):
"""
Recover text from block of defined size
Parameters:
blocks (list): list of integers to convert into text
size (int): size of each block we want to convert
Algorithm:
Merge blocks
Use (shifted) ASCII to match all resulting integers to characters
Return:
text version of blocks (str)
Example:
blocks = [410, 76, 798, 669, 8, 82, 797, 182, 657, 777, 737, 871]
text = make_text(blocks, size=3)
print(text)
>>> I love programming
Remarks:
The size must be the same as in function make_blocks for the
algorithm to work properly
"""
# Define outputs
text = ""
text_tmp = ""
# Conversion
for i in range(len(blocks)):
tmp = str(blocks[i])
if i < (len(blocks)-1): # Avoid error at the end
while (len(tmp) < size):
tmp = '0' + tmp
text_tmp += tmp
text_tmp = [int(text_tmp[i * (2):(i + 1) * (2)]) \
for i in range((len(text_tmp) + 2 - 1) // (2) )]
for i in text_tmp:
text += chr(i+32) # Shifted match
return text
def EncryptRSA(plaintext, pub_key):
""" Implement RSA encryption
Parameters:
plaintext (str): text to be encrypted
pub_key (tuple): the public key (e, n)
Algorithm:
Implement RSA agorithm
See: https://people.csail.mit.edu/rivest/Rsapaper.pdf for more info
Return:
Encrypted version of plaintext (list of blocks)
Example:
public_key = (3917, 5917) # Created with generate_keypair(p, q)
plain = "I love programming!"
cipher = EncryptRSA(plain, public_key)
print(cipher)
>>> [2447, 286, 5648, 2579, 2346, 1127, 3400, 609, 2209,
4075, 1805, 420, 1]
Remarks:
All characters are encrypted (including spaces, ponctuation, etc.)
"""
# Get e and n from public key
e, n = pub_key
# Convert plaintext into blocks
blocks = make_blocks(plaintext, n)
# Encrypt blocks using formula (C = M^e mod n)
cipher = [(block ** e) % n for block in blocks]
# Return list of encrypted blocks
return cipher
def DecryptRSA(cipher, priv_key):
""" Implement RSA decryption
Parameters:
cipher (list): cipher to be decrypted
priv_key (tuple): the private key (d, n)
Algorithm:
Implement RSA agorithm
See: https://people.csail.mit.edu/rivest/Rsapaper.pdf for more info
Returns:
Decrypted version of chiphertext (str)
Example:
private_key = (4613, 5917) # Created with generate_keypair(p, q)
cipher = [2447, 286, 5648, 2579, 2346, 1127, 3400, 609, 2209, 4075,
1805, 420, 1]
plain = DecryptRSA(cipher, private_key)
print(plain)
>>> I love programming!
"""
# Get d and n from private key
d, n = priv_key
# Apply decryption formula (M = C^d mod n)
plain_blocks = [(block ** d) % n \
for block in cipher]
# Convert into text
plaintext = make_text(plain_blocks)
# Return plaintext (string)
return plaintext
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.