blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
c7f05f29fa4e84594a2e11a8937b527417e8ecd9 | cris/ruby-quiz-in-python | /src/rock_paper_scissors.py | 3,738 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
class Player(object):
players = []
@classmethod
def inherited(cls, player):
cls.players.append(player)
@classmethod
def each_pair(cls):
for i in xrange(len(cls.players)-1):
for j in xrange(i+1, len(cls.players)):
yield cls.get_class_from_module(cls.players[i]), cls.get_class_from_module(cls.players[j])
@classmethod
def get_class_from_module(cls, module):
l = [v for v in module.__dict__.values() if isinstance(v, type)]
return l[0]
def __init__(self, opponent_name):
print opponent_name
self.opponent_name = opponent_name
def choose(self):
raise NotImplemented("Player subclasses must override choose().")
def result(self, your_choice, opponent_choice, win_lose_or_draw):
pass
class Game:
def __init__(self, player1, player2):
self.player1_name = str(player1)
self.player2_name = str(player2)
self.player1 = player1(self.player2_name)
self.player2 = player2(self.player1_name)
self.score1 = 0
self.score2 = 0
def play(self, num_matches):
for i in xrange(num_matches):
hand1 = self.player1.choose()
hand2 = self.player2.choose()
for player, hand in [(self.player1_name, hand1), (self.player2_name, hand2)]:
if hand not in ['rock', 'paper', 'scissors']:
raise ValueError("Invalid choice by %s" % player)
hands = {str(hand1): self.player1, str(hand2): self.player2}
choices = hands.keys()
choices.sort()
if len(choices) == 1:
self._draw(hand1, hand2)
elif choices == ['paper', 'rock']:
self._win(hands['paper'], hand1, hand2)
elif choices == ['rock', 'scissors']:
self._win(hands['rock'], hand1, hand2)
elif choices == ['paper', 'scissors']:
self._win(hands['scissors'], hand1, hand2)
def results(self):
match = "%s vs. %s\n\t%s: %s\n\t%s: %s\n" % (self.player1_name, self.player2_name, self.player1_name, self.score1, self.player2_name, self.score2)
if self.score1 == self.score2:
match + "\tDraw\n"
elif self.score1 > self.score2:
match + ("\t%s Wins\n" % self.player1_name)
else:
match + ("\t%s Wins\n" % self.player2_name)
return match
def _draw(self, hand1, hand2):
self.score1 += 0.5
self.score2 += 0.5
self.player1.result(hand1, hand2, 'draw')
self.player2.result(hand2, hand1, 'draw')
def _win(self, winner, hand1, hand2):
if winner == self.player1:
self.score1 += 1
self.player1.result(hand1, hand2, 'win')
self.player2.result(hand2, hand1, 'lose')
else:
self.score2 += 1
self.player1.result(hand1, hand2, 'lose')
self.player2.result(hand2, hand1, 'win')
def main():
match_game_count = 1000
players_files = sys.argv[1:]
if len(sys.argv) > 2 and sys.argv[1] == "-m" and re.match(r'/^[1-9]\d*$', sys.argv[2]):
match_game_count = int(sys.argv[2])
players_files = sys.argv[3:]
print players_files
for fname in players_files:
print fname
file_name = os.path.basename(fname)
module_name, _ext = os.path.splitext(file_name)
module = __import__(module_name)
Player.inherited(module)
for one, two in Player.each_pair():
game = Game(one, two)
game.play(match_game_count)
print game.results()
if __name__ == "__main__":
main()
|
905a6cfbf0fd34b3183ddfd0ad77731c1ccdf541 | dykim822/Python | /ch04/insert1.py | 402 | 3.828125 | 4 | a = [1, 2, 3]
a.insert(0, 4) # 인덱스 0번째에 4를 대입
print(a)
a.insert(2, 2)
a.insert(2, 5)
print(a)
a.remove(2) # 첫번째 2인 값 1개을 삭제
# del은 해당 인덱스 값을 삭제/ remove는 해당 값을 삭제
print(a)
print(a.pop()) # 마지막 데이터를 끄집어서 출력하고 삭제
print(a)
print(a.pop(0)) # 인덱스 0번째 데이터를 출력하고 삭제
print(a) |
884d7958db9768889cb9855cdd7ebfe58afe1a3d | yaricom/neat-libraries-compared | /src/pole/cart_pole.py | 5,948 | 3.71875 | 4 | #
# This is implementation of cart-pole apparatus simulation based on the Newton laws
# which use Euler's method for numerical approximation the equations on motion.
#
import math
import random
#
# The constants defining physics of cart-pole apparatus
#
GRAVITY = 9.8 # m/s^2
MASSCART = 1.0 # kg
MASSPOLE = 0.5 # kg
TOTAL_MASS = (MASSPOLE + MASSCART)
# The distance from the center of mass of the pole to the pivot
# (actually half the pole's length)
LENGTH = 0.5 # m
POLEMASS_LENGTH = (MASSPOLE * LENGTH) # m
FORCE_MAG = 10.0 # N
FOURTHIRDS = 4.0/3.0
# the number seconds between state updates
TAU = 0.02 # sec
# set random seed
random.seed(42)
# The maximal fitness score value
MAX_FITNESS = 1.0
def two_ouputs_action_evaluator(nn_output):
action = 1
if nn_output[0] > nn_output[1]:
action = 0
return action
def do_step(action, x, x_dot, theta, theta_dot):
"""
The function to perform the one step of simulation over
provided state variables.
Arguments:
action: The binary action defining direction of
force to be applied.
x: The current cart X position
x_dot: The velocity of the cart
theta: The current angle of the pole from vertical
theta_dot: The angular velocity of the pole.
Returns:
The numerically approximated values of state variables
after current time step (TAU)
"""
# Find the force direction
force = -FORCE_MAG if action <= 0 else FORCE_MAG
# Pre-calcuate cosine and sine to optimize performance
cos_theta = math.cos(theta)
sin_theta = math.sin(theta)
temp = (force + POLEMASS_LENGTH * theta_dot * theta_dot * sin_theta) / TOTAL_MASS
# The angular acceleration of the pole
theta_acc = (GRAVITY * sin_theta - cos_theta * temp) / (LENGTH * (FOURTHIRDS - MASSPOLE * cos_theta * cos_theta / TOTAL_MASS))
# The linear acceleration of the cart
x_acc = temp - POLEMASS_LENGTH * theta_acc * cos_theta / TOTAL_MASS
# Update the four state variables, using Euler's method.
x_ret = x + TAU * x_dot
x_dot_ret = x_dot + TAU * x_acc
theta_ret = theta + TAU * theta_dot
theta_dot_ret = theta_dot + TAU * theta_acc
return x_ret, x_dot_ret, theta_ret, theta_dot_ret
def run_cart_pole_simulation(net, max_bal_steps, action_evaluator, random_start=True):
"""
The function to run cart-pole apparatus simulation for a
certain number of time steps as maximum.
Arguments:
net: The ANN of the phenotype to be evaluated.
max_bal_steps: The maximum nubmer of time steps to
execute simulation.
action_evaluator: The function to evaluate the action type from the ANN output value.
random_start: If evaluates to True than cart-pole simulation
starts from random initial positions.
Returns:
the number of steps that the control ANN was able to
maintain the single-pole balancer in stable state.
"""
# Set random initial state if appropriate
x, x_dot, theta, theta_dot = 0.0, 0.0, 0.0, 0.0
if random_start:
x = (random.random() * 4.8 - 2.4) / 2.0 # -1.4 < x < 1.4
x_dot = (random.random() * 3 - 1.5) / 4.0 # -0.375 < x_dot < 0.375
theta = (random.random() * 0.42 - 0.21) / 2.0 # -0.105 < theta < 0.105
theta_dot = (random.random() * 4 - 2) / 4.0 # -0.5 < theta_dot < 0.5
# Run simulation for specified number of steps while
# cart-pole system stays within contstraints
input = [None] * 4 # the inputs
for steps in range(max_bal_steps):
# Load scaled inputs
input[0] = (x + 2.4) / 4.8
input[1] = (x_dot + 1.5) / 3
input[2] = (theta + 0.21) / .42
input[3] = (theta_dot + 2.0) / 4.0
# Activate the NET
output = net.activate(input)
# Make action values discrete
action = action_evaluator(output)
# Apply action to the simulated cart-pole
x, x_dot, theta, theta_dot = do_step( action = action,
x = x,
x_dot = x_dot,
theta = theta,
theta_dot = theta_dot )
# Check for failure due constraints violation. If so, return number of steps.
if x < -2.4 or x > 2.4 or theta < -0.21 or theta > 0.21:
return steps
return max_bal_steps
def eval_fitness(net, action_evaluator, max_bal_steps=500000):
"""
The function to evaluate fitness score of phenotype produced
provided ANN
Arguments:
net: The ANN of the phenotype to be evaluated.
action_evaluator: The function to evaluate the action type from the ANN output value.
max_bal_steps: The maximum nubmer of time steps to
execute simulation.
Returns:
The phenotype fitness score in range [0, 1]
"""
# First we run simulation loop returning number of successfull
# simulation steps
steps = run_cart_pole_simulation(net, max_bal_steps, action_evaluator=action_evaluator)
if steps == max_bal_steps:
# the maximal fitness
return MAX_FITNESS
elif steps == 0: # needed to avoid math error when taking log(0)
# the minimal fitness
return 0.0
else:
# we use logarithmic scale because most cart-pole runs fails
# too early - within ~100 steps, but we are testing against
# 500'000 balancing steps
log_steps = math.log(steps)
log_max_steps = math.log(max_bal_steps)
# The loss value is in range [0, 1]
error = (log_max_steps - log_steps) / log_max_steps
# The fitness value is a complement of the loss value
return MAX_FITNESS - error
|
f8c4f473d11a881e44e6c0f3502b2eb9cd96af7a | OCCOHOCOREX/HuangXinren-Portfolio | /Weekly Tasks/Week2/HuangXinren-Week2-Task1.py | 150 | 4.09375 | 4 | # Task 1
multiple_list = []
number = [10, 35, 3]
for i in range(10, 36):
if i % 3 == 0:
multiple_list.append(i)
print(multiple_list) |
d160ed0d02a145aa82fce602cb6a3b35951df8e3 | M0G1/learning_python | /python_feachure/key_words_build_in_func.py | 1,297 | 3.609375 | 4 | import numpy as np
def enumeration():
letters = "абвгдеёжзийклмнопрстуфхцчшщьыъэюя"
let_enum = enumerate(letters, start=1)
print(*list(let_enum), sep="\n")
def compile_():
str_commands = \
"""
x = 1
z = 2
print(f"{x} + {z} = {x + z}")
"""
print("We will execute code:")
print(str_commands)
print("result:")
first = compile(str_commands, "in this case any str", "exec")
exec(first)
expression_to_evaluate = "2 ** 10 - 1"
print("\nWe will execute expression:", expression_to_evaluate)
second = compile(expression_to_evaluate, "There is filename needed", "eval")
print("result:", eval(second))
def callable_():
"https://docs-python.ru/tutorial/vstroennye-funktsii-interpretatora-python/funktsija-callable/"
func = lambda x: str(x) + " "
print("lambda function is " + ("" if callable(func) else "not ") + "callable")
arr = np.array(range(5))
print("numpy array is " + ("" if callable(arr) else "not ") + "callable")
def arg_mutable(l: list = []):
l.append(len(l))
print(l)
def arg_save_test():
arg_mutable()
arg_mutable()
def main():
# enumeration()
# compile_()
# callable_()
arg_save_test()
if __name__ == '__main__':
main()
|
19cfebc702f598e1c4c93963ba4024e62681b362 | organization0012/PythonRepo | /File/iterate_directory.py | 430 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
if __name__ == '__main__':
dir = "/tmp"
for fname in os.listdir(dir):
# print(fname)
path = os.path.join(dir, fname)
if os.path.isdir(path):
print("%s is a directory" % path)
elif os.path.isfile(path):
print("%s is a regular file" % path)
else:
print("%s is invalid file!" % path)
|
5e4d61d333bfc6980912097483cac08d3e422204 | Harshj16/Project-Euler-Problems | /Project-Euler-1.py | 395 | 4.15625 | 4 | #Project Euler No.1
#If we list all the natural numbers below 10 that are multiples of 3 or 5
#we get 3, 5, 6 and 9.
#The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
#definig natural number
num = int(input("Enter number = "))
add = 0
for iterate in range(1,num):
if(iterate%3==0 or iterate%5==0):
add = add+iterate
print(add)
|
99639910be9162f95ef96373d012e6e3d3d4eb32 | DukhDmytro/py_cart | /cart.py | 1,053 | 3.984375 | 4 | """The csv module implements classes to read and write tabular data in CSV format"""
import csv
class Product:
"""Product class"""
def __init__(self, name, price, qty):
self.name = name
self.price = float(price)
self.qty = float(qty)
def get_total_price(self):
"""return total price of product"""
return self.qty * self.price
def get_price(self):
"""return price of product"""
return self.price
class Cart:
"""Cart class"""
def __init__(self, file):
self._list_of_products = []
with open(file, "rt") as products:
for name, price, qty in csv.reader(products):
self._list_of_products.append(Product(name, price, qty))
def get_product(self, product_index):
"""return specified object from cart"""
return self._list_of_products[product_index]
def calc_total(self):
"""return total cost of products in cart"""
return sum(product.get_total_price() for product in self._list_of_products)
|
29701b8d0784ef60e0a5aa1e8a358411ee45d471 | techduggu/DataStructuresPlayGround | /Trees/first-common-ancestor.py | 2,646 | 3.65625 | 4 | import sys
# sys.stdin = open('Trees/input.txt', 'r')
# sys.stdout = open('Trees/output.txt', 'w')
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
#binary tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
#Solution-2: If node doesn't have link to its parent
#This is also an optimized solution (i.e. bubbling up p or q in the recursion tree)
def first_common_ancestor(root, p, q):
# Initialize p and q as not visited
v = [False, False]
lca = dfs_utility(root, p, q, v)
# Returns LCA only if both p and q are present in tree
if v[0] and v[1] or v[0] and find(lca, q) or v[1] and find(lca,p):
print(lca.data)
return lca
return None
# This function retturn pointer to LCA of two given values
# p and q
# v1 is set as true by this function if p is found
# v2 is set as true by this function if q is found
def dfs_utility(root, p, q, v):
#base case
if root == None:
return None
# IF either p or q matches ith root's key, report
# the presence by setting v1 or v2 as true and return
# root (Note that if a key is ancestor of other, then
# the ancestor key becomes LCA)
if root.data == p:
v[0] = True
return root
if root.data == q:
v[1] = True
return root
# Look for keys in left and right subtree
left_lca = dfs_utility(root.left, p, q, v)
right_lca = dfs_utility(root.right, p, q, v)
# If both of the above calls return Non-NULL, then one key
# is present in one subtree and other is present in other,
# So this node is the LCA
if left_lca and right_lca:
return root
# Otherwise check if left subtree or right subtree is LCA
return left_lca if left_lca != None else right_lca
def find(root, k):
#Base case
if root == None:
return False
# If key is present at root, or if left subtree or right
# subtree , return true
if root.data == k or find(root.left, k) or find(root.right, k):
return True
return False
def main():
node = Node(20)
node.left = Node(10)
node.right = Node(30)
node.left.left = Node(5)
node.left.right = Node(15)
node.left.left.left = Node(3)
node.left.left.right = Node(7)
node.left.right.right = Node(17)
first_common_ancestor(node, 5, 17)
if __name__ == "__main__":
main()
|
daa06604cd81410c46d2d598789b9c18c30ac110 | Puthiaraj1/PythonBasicPrograms | /DictionariesSets/sets.py | 1,654 | 4.1875 | 4 | # farm_animals = {"sheep","cow","hen"}
# print(farm_animals)
#
# for animal in farm_animals:
# print(animal)
#
# print("-" * 30)
# wild_animal = set(["lion", "tiger", "panther", "wolf"])
# print(wild_animal)
#
# for animal in wild_animal:
# print(animal)
#
# farm_animals.add("horse")
# wild_animal.add("horse")
# print(farm_animals)
# print(wild_animal)
even = set(range(0, 40, 2))
print(sorted(even))
squares_tuples = (4, 6, 9, 16, 25)
squares = set(squares_tuples)
# # Union
# print(even.union(squares))
# print(squares.union(even))
#
# # Intersection
# print(even.intersection(squares))
# print(even & squares)
# Difference between two sets
print(" even minus squares")
print(sorted(even.difference(squares)))
print(sorted(even - squares))
print(" squares minus even")
print(squares.difference(even))
print(squares - even)
# # Symmentric difference is opposite to intersection.
# print("Symmetric even minus squares")
# print(sorted(even.symmetric_difference(squares)))
#
# print("Symmetric squares minus even")
# print(sorted(squares.symmetric_difference(even)))
# # Remove/ discard element from set
# squares.discard(4)
# squares.discard(16)
# squares.discard(8)
# print(squares)
# try:
# squares.remove(8)
# except KeyError:
# print("The item 8 is not a member of the set")
# Superset & subset
# even = set(range(0, 40, 2))
# print(sorted(even))
#
# squares_tuples = (4, 6, 16)
# squares = set(squares_tuples)
# if squares.issubset(even):
# print("squares is a subset of even")
# if even.issuperset(squares):
# print("even is superset of squares")
# # frozen set
# even = frozenset(range(0, 40, 2))
# print(even)
|
2341f67f8a2271bcea2646d633dca4bd4d224f26 | kamal0072/classes | /class/class.py | 531 | 3.53125 | 4 | # class MyScool():
# myname='kamal'
# def __init__(self):
# print('hello Constructor')
# def Show(self):
# print('Class Methods')
# x=MyScool()
# x.Show()
# print(x.myname)
class School():
def __init__(self,p):
self.name='kamal'
self.place='delhi'
def studnt(self):
self.name='khanna'
self.place='mbd'
def teacher(self):
name='kunal'
roll=10
obj=School(100)
print(obj)
obj.studnt()
obj.teacher()
print("",obj.name)
# print(id.name)cd..
|
b8937df1199f1bd3cc8a7608618ff2a986ddede7 | MisaelAugusto/computer-science | /programming-laboratory-I/5guh/tabela.py | 204 | 3.875 | 4 | # coding: utf-8
# Aluno: Misael Augusto
# Matrícula: 117110525
# Problema: Tabela de Quadrados
X = int(raw_input())
Y = int(raw_input())
if X > Y:
print "---"
else:
for i in range(X, Y + 1):
print i, i**2
|
debfcc855154ac7dc1ef52eb6a24df322bd06f2d | code4love/dev | /Python/demos/practice/条件和循环语句.py | 358 | 3.890625 | 4 | #! /usr/bin/python
#条件和循环语句
x=int(input("Please enter an integer:"))
if x<0:
x=0
print ("Negative changed to zero")
elif x==0:
print ("Zero")
else:
print ("More")
# Loops List
a = ['cat', 'window', 'defenestrate']
for x in a:
print (x, len(x))
#知识点:
# * 条件和循环语句
# * 如何得到控制台输入
|
fc2405b7cf5568ff8656cf43bbb1fc5c435a7eec | anushanav/python_logical_solutions | /guess_game.py | 423 | 4.125 | 4 | # Guessing game between 1 to 8 in 5 chances
import random
def guess_number(guess):
x = random.randint(1,8)
chances =0
while chances <4:
if guess == x:
print ("You guessed it correct.Congo!!")
break
else :
print ("Wrong Guess.Sorry")
chances += 1
guess = int(input("guess the number "))
guess = int(input("guess the number "))
guess_number(guess) |
30b7b5e5c1879ef18f67620c23f24917e8c48463 | rodriguezofelia/hb-homework | /accounting-scripts/melon_info.py | 431 | 3.71875 | 4 | """Print out all the melons in our inventory."""
from melons import melons
def print_all_melons(melons):
"""Print each melon with corresponding attribute information."""
for melon, characteristics in melons.items():
print(melon.upper())
for characteristic, value in characteristics.items():
print(f"{characteristic}: {value}")
print("------------------")
print_all_melons(melons)
|
7a5f512612b4b52d5cda3b5f2fffb0e9b2599f5a | Johnxjp/aoc2019 | /python/helper.py | 946 | 3.734375 | 4 | from typing import Sequence
def load(file: str) -> Sequence[int]:
"""Loads a list of numbers each on a new line"""
data = []
with open(file) as f:
for line in f:
data.append(int(line.strip()))
return data
def loadv2(file: str) -> Sequence[int]:
"""Loads a list of numbers separated by a comma"""
data = []
with open(file) as f:
data = f.read().strip()
data = list(map(int, data.split(",")))
return data
def loadv3(file: str) -> Sequence[Sequence[str]]:
"""Loads a list of strings separated by a comma"""
data = []
with open(file) as f:
for line in f:
path = line.strip().split(",")
data.append(path)
return data
def loadv4(file: str) -> Sequence[int]:
"""Loads a list of strings each on a new line"""
data = []
with open(file) as f:
for line in f:
data.append(line.strip())
return data
|
aac178e66edebda8f34a7e3a55f1a7cbf11e30b9 | akshatmawasthi/python | /nested.py | 439 | 4.0625 | 4 | #!/usr/bin/python
# Try the exercises below
# Given a tic-tac-toe board of 3x3, print every position
# Create a program where every person meets the other
#persons = [ “John”, “Marissa”, “Pete”, “Dayton” ]
xax = [1,2,3]
yax = [1,2,3]
for x in xax:
for y in yax:
print(x, y)
persons = ["John", "Marissa", "Pete", "Dayton"]
for p in persons:
for r in persons:
if p != r:
print(p,r)
|
33c3ff8bce601536ba903bc383621b2a45760555 | ilhnctn/flask-rest-example | /apps/factorial/service.py | 330 | 3.546875 | 4 |
class FactorialService:
def get_factorial_of_number(self, target: int) -> int:
if not isinstance(target, int):
raise Exception(f"Unsupported input type. int expected, got {type(target)}")
result: int = 1
for mid in range(1, target + 1):
result *= mid
return result
|
177b9e9ccc553ddac6f4fe55f01c5bc533083d0d | dongxutian/test2 | /function_practice.py | 667 | 4.09375 | 4 | def f(*args):
for x in args:
print(x)
f(5)
f("I am here",9,5)
def summation(*nums):
count=0
for x in nums:
count+=x
return count
y=summation(10,20)
print(y)
#######We can specify default values in our functions\n by creating keywaord arguments
def nums(**kwargs):
for x,y in kwargs.items():
print(x,y)
nums(a=10,b=100)
nums(a=10,b=100,c=17)
def multiply(*args):
for x in args:
x*=10
print(x)
multiply(1,15,100)
def table(multi=5):
for x in range(1,multi+1):
for y in range (x,multi+1):
print (f'{x}*{y}=',x*y)
num=int(input("Please enter your number: "))
table(num) |
b4d77d0c762e76cbb55062c37630f93056379ae4 | Yufeng-L/myLeetCode | /1103-distributecandies.py | 604 | 3.6875 | 4 | # 依次分糖果
# hard code 对位置进行遍历,若最后一次candies数量小于0,返回并修复正确数量
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
# length = num_people
res = num_people*[0]
count = 1
while (candies != 0):
for i in range(num_people):
res[i] = res[i] + count
candies = candies - count
if candies < 0:
res[i] = res[i] + candies
return res
count += 1
return res
|
66e1c73d83323e8ad3e3be0df387940c08b12e09 | ruifengli-cs/leetcode | /BFS/863. All Nodes Distance K in Binary Tree.py | 2,519 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# APP1: add parent link, then do BFS
# Time: O(n) Space: O(n)
# def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
# if not root or not target or K < 0:
# return []
# parents = {root: None}
# self.build_parent(root, parents)
# q, res, dist = collections.deque([(target)]), [], {target: 0}
# while q:
# node = q.popleft()
# if node:
# if dist[node] == K:
# res.append(node.val)
# continue
# if node.left and node.left not in dist:
# q.append(node.left)
# dist[node.left] = dist[node] + 1
# if node.right and node.right not in dist:
# q.append(node.right)
# dist[node.right] = dist[node] + 1
# if parents[node] and parents[node] not in dist:
# q.append(parents[node])
# dist[parents[node]] = dist[node] + 1
# return res
# def build_parent(self, root, parents):
# if not root:
# return
# if root.left:
# parents[root.left] = root
# self.build_parent(root.left, parents)
# if root.right:
# parents[root.right] = root
# self.build_parent(root.right, parents)
# APP1: refacter code:
def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:
if not root or not target or K < 0:
return []
self.add_parent(root)
q, res, visited = collections.deque([(target, 0)]), [], set([target])
while q:
node, dis = q.popleft()
if dis == K:
res.append(node.val)
for nei in (node.parent, node.left, node.right):
if nei and nei not in visited:
q.append((nei, dis + 1))
visited.add(nei)
return res
def add_parent(self, node, parent=None) -> None:
if not node:
return
node.parent = parent
self.add_parent(node.left, node)
self.add_parent(node.right, node)
|
664c13a01b48957caea12d574b7384317410744c | masande-99/email-sending-app | /main.py | 1,750 | 3.6875 | 4 | from tkinter import *
def send_email():
root = Tk()
root.title("Sending Emails")
root.geometry("1000x600")
def my_function():
import smtplib
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
sender_email = txt1.get()
receiver_email = txt2.get()
password = txt3.get()
server.starttls()
server.login(sender_email, password )
message = txt4.get
server.sendmail(sender_email, receiver_email, 'This isa test email')
print("the message has been successfully sent")
except Exception as err:
print("Something went wrong..", err)
finally:
server.close()
my_function()
label_frame1= Frame(root)
label_frame1.pack()
label_frame2=Frame(root)
label_frame2.pack()
label_frame3=Frame(root)
label_frame3.pack()
label_frame4=Frame(root)
label_frame4.pack()
label_frame5=Frame(root)
label_frame5.pack()
lab1 = Label(label_frame1,text="Please enter sender email :")
lab1.grid(row=1, column=1)
lab2 = Label(label_frame2, text="Please enter receiver email :")
lab2.grid(row=2, column=1)
lab3 = Label(label_frame3, text="Please enter your password :")
lab3.grid(row=3, column=1)
txt1 = Entry(label_frame1)
txt1.grid(row=1, column=3)
txt2 = Entry(label_frame2)
txt2.grid(row=2, column=3)
txt3 = Entry(label_frame3)
txt3.grid(row=3, column=3)
txt4 = Entry(label_frame4, )
txt4.grid(row=1, column=1, padx=100, pady=100, ipady=100, ipadx=200)
btn1 = Button(label_frame5, text="SEND", command=my_function)
btn1.grid(row=4, column=2)
root.mainloop()
send_email()
|
2d122a979961bb7bdafbb1fde571f5c7d5f8a87c | DreenTS/skillbox_yurikov | /lesson_011/01_shapes.py | 1,629 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import simple_draw as sd
# На основе вашего кода из решения lesson_004/01_shapes.py сделать функцию-фабрику,
# которая возвращает функции рисования треугольника, четырехугольника, пятиугольника и т.д.
#
# Функция рисования должна принимать параметры
# - точка начала рисования
# - угол наклона
# - длина стороны
#
# Функция-фабрика должна принимать параметр n - количество сторон.
sd.resolution = (800, 800)
def get_polygon(n):
def draw_func(point, angle, length):
new_angle = angle
new_point = point
for side in range(n):
if new_angle + 360 / n >= 360:
sd.line(start_point=new_point, end_point=point, width=3)
else:
vector = sd.get_vector(start_point=new_point, angle=new_angle, length=length)
vector.draw(width=3)
new_point = vector.end_point
new_angle += 360 / n
return draw_func
draw_triangle = get_polygon(n=3)
draw_triangle(point=sd.get_point(150, 100), angle=13, length=150)
draw_square = get_polygon(n=4)
draw_square(point=sd.get_point(450, 100), angle=26, length=150)
draw_pentagon = get_polygon(n=5)
draw_pentagon(point=sd.get_point(150, 300), angle=35, length=150)
draw_hexagon = get_polygon(n=6)
draw_hexagon(point=sd.get_point(450, 300), angle=41, length=150)
sd.pause()
# зачет! |
2965467f356c1722120cd5e2d838a10056e4e8a8 | eugennix/python | /Coursera/23_flags.py | 236 | 3.71875 | 4 | n = int(input())
print(' '.join(['+___' for i in range(1, n+1)]))
print(' '.join([('|' + str(i) + ' /') for i in range(1, n+1)]))
print(' '.join(['|__\\' for i in range(1, n+1)]))
print(' '.join(['| ' for i in range(1, n+1)]))
|
d618213f4b802a1f45bdd60b929db96e44cb3fd8 | Prashant4M/Project-Euler-Solutions | /Problem_1.py | 88 | 3.609375 | 4 | sum=0
for i in range(1,1000):
if((i%3==0)|(i%5==0)):
sum+=i
print(sum)
|
b378dd1387aaa1d61a7b43e4d89c7aed0ba47589 | thc2125/csclassifier | /corpus_utils.py | 3,824 | 3.53125 | 4 | import random
from math import sqrt
import numpy as np
from alphabet_detector import AlphabetDetector
from sklearn.preprocessing import label_binarize
import utils
ad = AlphabetDetector()
def np_idx_conversion(sentences, slabels, maxsentlen, maxwordlen, char2idx, idx2label, char_count=None):
# Convert the sentences and labels to lists of indices
# Convert words to indices
# And pad the sentences and labels
np_sentences = np.array(sent_idx_conversion(sentences,
maxsentlen,
maxwordlen,
char2idx,
char_count))
np_slabels = np_label_idx_conversion(slabels, maxsentlen, idx2label)
# Finally convert the sentence and label ids to numpy arrays
return np_sentences, np_slabels
def sent_idx_conversion(sentences,
maxsentlen,
maxwordlen,
char2idx,
char_count=None):
# Create a list of lists of lists of indices
# Randomly assign some letters the index of unknown characters for a
# given alphabet
list_sentences = ([[[(char2idx[c]
if (c in char2idx and not unk_replace(c, char_count))
else char2idx[get_unk(c)])
for c in word]
+ [0]*(maxwordlen-len(word))
for word in sentence]
+ [[0]*maxwordlen]*(maxsentlen-len(sentence))
for sentence in sentences])
return list_sentences
def np_label_idx_conversion(slabels,
maxsentlen,
idx2label):
'''
list_cat_labels = ([
[[label2idx[label]
for label in labels]
+ [0] * (maxsentlen-len(sentlabels))
for labels in self.slabels])
'''
# Make labels one-hot
list_labels = np.stack(
[np.concatenate((label_binarize(labels,
idx2label),
label_binarize(['<pad>']
* (maxsentlen
- len(labels)),
idx2label)))
if len(labels) < maxsentlen
else label_binarize(labels, idx2label)
for labels in slabels])
'''
np_slabels = []
for labels in slabels:
print("LABELS: " + str(labels))
np_labels = label_binarize(labels, idx2label)
np_padding = label_binarize(['<pad>'] * (maxsentlen - len(labels)), idx2label)
print("NP_LABELS: " + str(np_labels))
print("NP_PADDING: " + str(np_padding))
np_slabels.append(np.concatenate((np_labels, np_padding)))
list_labels = np.stack(np_slabels)
'''
return list_labels
def unk_replace(c, char_count=None):
# Formula sourced from Quora:
# https://www.quora.com/How-does-sub-sampling-of-frequent-words-work-in-the-context-of-Word2Vec
# "Improving Distributional Similarity with Lessons Learned from Word Embeddings"
# Levy, Goldberg, Dagan
if not char_count:
return False
t = .00001
f = char_count[c]
p = 1 - sqrt(t/f)
if random.random() > p:
return True
else:
return False
def get_unk(c, use_alphabets=False):
unk = '<unk'
if use_alphabets:
alph = list(ad.detect_alphabet(c))
if alph and alph[0] in alphabets:
unk += alph[0]
unk += '>'
return unk
|
f728cfdc95df860a04d8a5d202fc24f6901d111c | sampada22/sqlite3 | /inserting_into_table.py | 1,798 | 3.953125 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
"""create connection to the SQLite database specified by db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
def create_project(conn, project):
"""
Create a new project into the projects table
:param conn:
:param project:
:return: project id
"""
try:
sql = ''' INSERT INTO projects(name,begin_date)
VALUES(?,?) '''
cur = conn.cursor()
cur.execute(sql, project)
return cur.lastrowid
except Error as e:
print(e)
return None
def create_task(conn,task):
"""
Create a new task
:param conn:
:param task:
:return:
"""
try:
sql = '''INSERT INTO tasks(name,priority,status_id,project_id,begin_date,end_date)
VALUES(?,?,?,?,?,?)'''
cur = conn.cursor()
cur.execute(sql,task)
return cur.lastrowid
except Error as e:
print(e)
return None
def main():
database = "C:\\sqlite\db\pythonsqlite.db"
#create a database connection
conn = create_connection(database)
with conn:
#create a new project
project = ('Cool App with SQLite and Python','2015-01-01')
project_id = create_project(conn,project)
#tasks
task_1 = ('Analyze the requirements of the app',1,1,project_id,'2015-01-01','2015-01-02')
task_2 = ('Confirm with user about the top requirements',1,1,project_id,'2015-01-02','2015-01-07')
#create tasks
create_task(conn,task_1)
create_task(conn,task_2)
if __name__ =='__main__':
main()
|
0889e680f055cdfc693ac9fe8871922b47567d2a | Wintus/MyPythonCodes | /swap.py | 1,057 | 4.375 | 4 | # Python 3.4.0
'''Swap the values of a and b without any extra variables'''
# use tuple in assignment (basic version)
a, b = 0, 1
print("a: {}, b: {}".format(a, b))
print("Swapping")
a, b = b, a
print("a: {}, b: {}".format(a, b))
print()
# with closure (it seems same with above one essentially)
def main():
'''use closure to swap'''
a, b = 0, 1
def swap():
nonlocal a, b
a, b = b, a
print("Swapped")
return a, b
print("a: {}, b: {}".format(a, b))
swap()
print("a: {}, b: {}".format(a, b))
print()
main()
# use function
def swap(a, b):
'''swap a and b'''
print("Swapping")
return b, a
a, b = 0, 1
print("a: {}, b: {}".format(a, b))
a, b = swap(a, b)
print("a: {}, b: {}".format(a, b))
print()
# apply reversed() on the sequence
a, b = 0, 1
print("a: {}, b: {}".format(a, b))
a, b = reversed( (a, b) )
print("a: {}, b: {}".format(a, b))
print()
# use reference
a, b = 0, 1
print("a: {}, b: {}".format(a, b))
a, b = (a, b)[1], (a, b)[0]
print("a: {}, b: {}".format(a, b))
print()
|
993b68ef208e8fdb034eece00af437e62620701d | caojohnny/dupe | /dupe.py | 601 | 3.90625 | 4 | import sys
argv = sys.argv
argvLen = len(argv)
if argvLen < 2:
print("No file name provided")
exit(1)
fileName = argv[1]
print("Parsing file " + fileName)
file = open(fileName, "r")
words = []
lineNumber = 0
while True:
line = file.readline()
if not line:
break
lineNumber += 1
line = line.replace("\n", "")
lineWords = line.split(" ")
for word in lineWords:
wordUpper = word.upper()
if wordUpper in words:
print("Found duplicate word '{}' on line {}".format(word, lineNumber))
else:
words.append(wordUpper)
|
19692a8c41141698461e1ffc25ce89d73795645c | sudheendra02/competetive_programming | /week1/day1/highest_multiplication.py | 250 | 3.65625 | 4 | a=[1,2,3,4,5]
if (len(a)>=3):
x=max(a)
y=x
a.remove(x)
x=x*max(a)
a.remove(max(a))
x=x*max(a)
if (len(a)>=2):
y=y*min(a)
a.remove(min(a))
y=y*min(a)
a.remove(min(a))
print(max(x,y))
else:
print(x)
else:
print("not enough values") |
3b92a240cf4996dce16fd4a57d090ceec15623a5 | castjosem/customer-search | /single_file_project.py | 4,872 | 3.90625 | 4 | """
Let’s say we have some customer records in a text file (customers.txt, see below) – one customer per line,
JSON-encoded. We want to invite any customer within 100km of our Dublin office (GPS coordinates 53.3381985, -6.2592576)
for some food and drinks on us.
Write a program that will read the full list of customers and output the names and user ids of matching customers
(within 100 km), sorted by user id (ascending).
"""
import sys
from math import cos, sin, asin, sqrt, radians
class Converter(object):
def from_degrees_to_radians_point(self, point):
return map(radians, [point.latitude, point.longitude])
class SpatialPoint(object):
def __init__(self, latitude, longitude, description = None):
self.latitude = float(latitude)
self.longitude = float(longitude)
self.description = description
def __repr__(self):
return str(self.__dict__)
class SpatialSearch(object):
def __init__(self, entries, converter = None):
# Prohibit creating class instance
if self.__class__ is SpatialSearch:
raise TypeError('SpatialSearch abstract class cannot be instantiated')
self.entries = entries
self.converter = converter
def search_all_nearby(self, location, radius):
elem_nearby = self._get__all_nearby(location, radius)
return elem_nearby
def _get__all_nearby(self, location, radius):
raise NotImplementedError()
def _apply_converter(self, point):
if self.converter:
return self.converter(point)
else:
return (point.latitude, point.longitude)
def haversine(self, p1, p2):
lat1, lon1 = self._apply_converter(p1)
lat2, lon2 = self._apply_converter(p2)
delta_lat = lat2 - lat1
delta_lon = lon2 - lon1
# Kilometeres
R = 6367
a = pow(sin(delta_lat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(delta_lon / 2), 2)
c = 2 * asin(sqrt(a))
distance = R * c
return distance
class NaiveSpatialSearch(SpatialSearch):
def _get__all_nearby(self, location, radius):
nearby = []
for entry in self.entries:
distance = self.haversine(location, entry)
if distance < radius:
nearby.append(entry)
return nearby
class RTreeSpatialSearch(SpatialSearch):
def _get__all_nearby(self, location, radius):
pass
class Customer(object):
def __init__(self, user_id, name):
self.user_id = user_id
self.name = name
def __lt__(self, other):
return self.user_id < other.user_id
def __repr__(self):
return str(self.__dict__)
class CustomerSpatial(Customer, SpatialPoint):
def __init__(self, user_id, name, latitude, longitude):
SpatialPoint.__init__(self, latitude, longitude, "Customer")
Customer.__init__(self, user_id, name)
import json
class Parser(object):
def parse_customer_spatial_data(self, customer_raw_data):
customers = []
for customer_raw in customer_raw_data:
customer_parsed = json.loads(customer_raw)
user_id = customer_parsed["user_id"]
name = customer_parsed["name"]
latitude = customer_parsed["latitude"]
longitude = customer_parsed["longitude"]
customer = CustomerSpatial(user_id, name, latitude, longitude)
customers.append(customer)
return customers
class CustomerProvider(object):
def __init__(self):
self.path = 'customers.txt'
def get_customer_data(self):
customers_raw = []
try:
with open(self.path, 'r') as file_content:
customers_raw = file_content.read().splitlines()
except:
raise
return customers_raw
class CustomersWrapper(object):
def get_customers_nearby(self, location, distance):
customers_nearby = []
try:
customer_provider = CustomerProvider()
customer_raw_data = customer_provider.get_customer_data()
parser = Parser()
customers = parser.parse_customer_spatial_data(customer_raw_data)
converter = Converter()
spatial_search = NaiveSpatialSearch(customers, converter.from_degrees_to_radians_point)
customers_nearby = spatial_search.search_all_nearby(location, distance)
customers_nearby.sort()
except:
e = sys.exc_info()[0]
print ( "Error: {}".format(e) )
return customers_nearby
if __name__ == '__main__':
dublin_office = SpatialPoint(53.3381985, -6.2592576, "Dublin Office")
distance = 100
customers_wrapper = CustomersWrapper()
customers_wrapper.get_customers_nearby(dublin_office, distance)
|
1a18c3b99223fadd4093d5fc95a4662b2a3c748e | jackie-mcaninch/Hash-Code-2021 | /practice/practice problem.py | 4,562 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 16:51:30 2021
This code was created for practice for Google's 2021 global Hash Code Challenge
qualification round. The practice theme was pizza delivery, and the goal of the
problem was to deliver pizza to groups of 2, 3, or 4, one pizza to a person.
However, the parameter to optimize is the total amount of unique ingredients in
a group order of pizza. Input specifies various choices of pizza to deliver to
the groups, but each one can only be used once. Output specifies which pizzas
will be delivered to the groups. For each group, the score is given by the
square of the number of different ingredients on all pizzas, and total score is
the sum of all the group scores.
@author: Jackie McAninch
"""
import time
def pick_pizzas(num_pizzas, pizza_dict, freq):
pizzas = [] #used to store result
minfo = []*num_pizzas #lists smallest scores and indexes thereof
#ANALYZE FREQUENCY OF EACH TOPPING
if not freq:
for pizza in pizza_dict.values():
for i in range(1,len(pizza)):
topping = pizza[i]
if topping in freq:
freq[topping] = freq[topping]+1
else:
freq[topping] = 1
#CALCULATE RELATIVE UNIQUENESS SCORE FOR EACH PIZZA
#(sum(number of occurences for each topping))/(amount of toppings)
#lower score means more unique
for pizza in pizza_dict.keys():
score = 0
toppings = pizza_dict[pizza]
#TALLY SCORE
for j in range(1,len(toppings)):
score += freq[toppings[j]]
score = int(score/len(toppings))
#STORE RUNNING MINIMUMS
for n in range(num_pizzas):
if len(minfo) < num_pizzas:
minfo.append([score, pizza])
break
elif minfo[n][0] > score:
del minfo[-1]
minfo.insert(n, [score, pizza])
break
for pizza in minfo:
pizzas.append(pizza[1])
#DECREMENT TOPPING FREQUENCY UPON DELETION
tmp = pizza_dict[pizza[1]]
for j in range(1,len(tmp)):
freq[tmp[j]] -= 1
pizza_dict.pop(pizza[1])
return tuple(pizzas)
files = {"e"}#, "c", "d", "e"}
for file in files:
start = time.perf_counter()
#FILE CREATION
if file== "a":
f_in = open(file, "r")
else:
f_in = open(file+".in", "r")
f_out = open(file+"_out.txt", "w")
#PARSE LINE 1
line1 = (f_in.readline()).split()
num_pizzas = int(line1[0])
num_groups = [line1[1], line1[2], line1[3]] #total groups of 2,3, and 4
#INITIALIZE OUTPUT ARRAYS
deliveries2, deliveries3, deliveries4 = set(),set(),set() #holds tuples of pizza IDs, NO REPEATS
pizzas = {} #keys will be pizza ID and values will be toppings
topping_freq = {} #used to keep track of how frequently each topping occurs
#STORE ALL GIVEN DATA
for i in range(num_pizzas):
pizzas[i] = (f_in.readline()).split()
#ASSESS ORDER TO PROCEED (WHICH SET OF GROUPS FIRST)
rel_yields = [0,0,0]
rel_yields[0] = int(num_groups[0])*2
rel_yields[1] = int(num_groups[1])*3
rel_yields[2] = int(num_groups[2])*4
#CALL ALGORITHM
for i in range(3):
ptr = rel_yields.index(max(rel_yields))
rel_yields[ptr] = 0
for j in range(int(num_groups[ptr])):
if (ptr==0 and len(pizzas)>=2):
deliveries2.add(pick_pizzas(ptr+2, pizzas, topping_freq))
elif (ptr==1 and len(pizzas)>=3):
deliveries3.add(pick_pizzas(ptr+2, pizzas, topping_freq))
elif (ptr==2 and len(pizzas)>=4):
deliveries4.add(pick_pizzas(ptr+2, pizzas, topping_freq))
else:
break
#WRITE OUTPUT
f_out.write(str(len(deliveries2)+len(deliveries3)+len(deliveries4))+"\n")
for deliv in deliveries2: #GROUPS OF 2
f_out.write("2")
for pizza in deliv:
f_out.write(" "+str(pizza))
f_out.write("\n")
for deliv in deliveries3: #GROUPS OF 3
f_out.write("3")
for pizza in deliv:
f_out.write(" "+str(pizza))
f_out.write("\n")
for deliv in deliveries4: #GROUPS OF 4
f_out.write("4")
for pizza in deliv:
f_out.write(" "+str(pizza))
f_out.write("\n")
end = time.perf_counter()
print(f"Runtime: {end-start:0.4f} seconds")
f_in.close()
f_out.close()
|
74314fc1fa2a1237de333d880f8c62aec650c8cb | romanlevonovyy/Algorithm_labs | /Lab_1/InsertionSorter.py | 995 | 4.0625 | 4 | from datetime import datetime
class InsertionSorter:
@staticmethod
def insertion_sort_by_height(screens: list):
print("Insertion sort ascending by height:")
start_time = datetime.now().microsecond
comparing_times = 0
change_times = 0
for i in range(0, len(screens)):
comparing_times = comparing_times + 1
comparing_screen = screens[i]
n = i
while n >= 0 and comparing_screen.height < screens[n - 1].height:
change_times = change_times + 1
screens[n] = screens[n - 1]
n = n - 1
change_times = change_times + 1
screens[n] = comparing_screen
print("Comparisons number: " + str(comparing_times))
print("Swaps number: " + str(change_times))
print("Time spent: %s mcs" % (datetime.now().microsecond - start_time))
for j in range(len(screens)):
print(screens[j])
|
37a88c67d051139ed2a4abf65e080d54b8e0b5a3 | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/314_v2/to_columns.py | 641 | 4.09375 | 4 | from typing import List # not needed when we upgrade to 3.9
import math
def print_names_to_columns(names: List[str], cols: int = 2) -> None:
rows = int(math.ceil(len(names) / cols))
for row in range(rows):
for col in range(cols):
index = row * cols + col
try:
name = names[index]
except IndexError:
break
print(f'| {name:<10}',end='')
else:
print()
continue
break
if __name__ == "__main__":
names = "Bob Julian Tim Sara Eva Ana Jake Maria".split()
print_names_to_columns(names,cols=3)
|
0dd4fc4545da44ef7956de4e55b6f7c78327335d | analaura09/pythongame | /p75.py | 516 | 4.09375 | 4 | num = (int(input('digite um numero: ')),
int(input('digite outro numero:')),
int(input('digite mais um numero:')),
int(input('digite o ultimo numero:')))
print(f'voce digitou os valores {num}')
print(f'o valor 9 apareceu {num.count(9)} vezes')
if 3 in num:
print(f'o valor 3 apareceu na {num.index(3)+1}ª posiçao')
else:
print('o valor 3 nao foi digitado em nenhuma posiçao')
print('o valor 3 nao foi digitado foram', end='')
for n in num:
if n % 2 ==0:
print(n, end=' ')
|
6bff0d347481eac5c7f4032eab640f0a1584e3db | AdamZhouSE/pythonHomework | /Code/CodeRecords/2166/60632/275675.py | 264 | 3.703125 | 4 | t = int(input())
data = []
for i in range(t):
data.append(int(input()))
if data == [4,5]:
print('2 1 4 3')
print('3 1 4 5 2')
elif data == [12]:
print('7 1 4 9 2 11 10 8 3 6 5 12')
elif data == [7]:
print('5 1 3 4 2 6 7')
else:
print(data)
|
2e104b80cd6febce6321d12e76273187ef8a34aa | alioukahere/code-challenges | /reverse_string/python/reverse_string.py | 449 | 4.1875 | 4 | def reverse(text):
# I wrote in three different way, for the two fist I used the python reversed function and the slice notation
# using reversed function
# return ''.join(reversed(text))
# using the slice notation
# return text[::-1]
# the hard way
i = 0;
j = len(text) - 1
reverse = []
while i < len(text):
reverse.append(str(text[j]))
i += 1
j -= 1
return ''.join(reverse)
|
efa45555fd16c3dc4da1218bd3760b310148639b | rbnpappu/pattern | /-pattern2.py | 163 | 3.90625 | 4 | num=int(input("Enter the length of squre:"))
c=0
for i in range(1,num+1):
for j in range(1,c,1):
print("*",end=" ")
c=c+2
print("\n")
|
6df25597f3de9ecc06223fdefe704fb62192801e | mrmegaremote/infdev01-1 | /Periode 1/assignment 5/assignment 5/assignment 5/reverse.py | 197 | 3.671875 | 4 | while True:
inp = raw_input("input some text: \n")
rev = ""
#inversing the order of the characters
for i in range (len(inp) -1, -1, -1):
rev += inp[i]
print rev |
23551ad5ecdd5e71614bd292a3aec1d7b463ac65 | lingueeni/list-divsion | /list.py | 304 | 3.921875 | 4 | user_list = input(("Enter ur List separated by commas (ex: 4 , 5 , 6):"))
devisor = int(input("Enter The Devisor: "))
ans = []
for each_element in user_list.split(', '):
if int(each_element) % devisor == 0:
ans.append(int(each_element))
print("ur list after edition is:", end=' ')
print(ans)
|
d77df23004e54740f7e8bc0e30bdfd9d705d952d | vipin26/python | /PYTHON/Advance/Python Events/sum.py | 378 | 3.703125 | 4 | from Tkinter import*
Top=Tk()
Top.geometry("220x220")
def Addition(event):
a=int(T1.get("1.0",END))
b=int(T2.get("1.0",END))
c=a+b
T3.insert("1.0",str(c))
T1=Text(Top)
T1.place(x=10,y=20,height=50,width=200)
T2=Text(Top)
T2.place(x=10,y=80,height=50,width=200)
T3=Text(Top)
T3.place(x=10,y=150,height=50,width=200)
T3.bind('<Return>',Addition)
Top.mainloop()
|
6e0dd1aba7a2547258b409325948d31f844e4257 | antoinebrl/practice-ML | /utils/distances.py | 382 | 3.578125 | 4 | import numpy as np
def euclidianDist(data, centers):
'''Compute the euclidian distance of each data point to each center'''
return np.sqrt(np.sum((data - centers[:, np.newaxis]) ** 2, axis=2)).T
def manhattanDist(data, centers):
'''Compute the Manhattan distance of each data point to each center'''
return np.sum(np.abs(data - centers[:, np.newaxis]), axis=2).T
|
bd00ddd870d1ed4936f3fd181ebe35f9d3cc4638 | corbinq27/tribbles-simulator | /deck.py | 8,254 | 3.59375 | 4 | from enum import Enum
import json
import re
import random
import math
import copy
Power = Enum("Power", "Bonus Clone Discard Go Poison Rescue Reverse Skip")
class Card:
"""private Class to represent the Card object."""
def __init__(self, denomination, power, owner):
self.denomination = denomination
self.power = power
self.owner = owner
def __repr__(self):
return "Card Instance. Power: %s Denom: %s Owner: %s" % (self.power, self.denomination, self.owner)
def __str__(self):
return "Card Instance. Power: %s Denom: %s Owner: %s" % (self.power, self.denomination, self.owner)
def get_card_categorization(self):
"""
returns a string concatenating the denomination and power. For example, if the card's denomination
is 100 and the card's power is Poison, then the string returned will be "100 Power.Poison"
"""
return "%s %s" % (self.denomination, self.power)
def is_actionable_power(self):
"""
Returns true if the power for this card is actionable (that is, the player could cause the player to play an
additonal card on his turn because of the card's power. Currently, the list of actionable powers are Rescue
and Go.
"""
return self.power == Power.Go or self.power == Power.Rescue
def is_playable(self, last_played_card, is_chain_broken=False):
"""
Given the last played card within the game, returns True if this card can be played or False if not.
a 1 can also be played if the chain was broken.
* This card can be played if the last card played has a denomination 10 times smaller than this card.
* This card can be played if the last card played and this card have the same denomination and this card
has a power of clone.
* This card can be played if the last card played was denomination 100,000 and this card is denomination 1.
* This card can be played if the last card played is a None object and this card is denomincation 1.
"""
last_denom = None
if last_played_card is None:
if self.denomination == 1:
return True
else:
return False
else:
last_denom = last_played_card.denomination
if self.denomination == (last_denom * 10):
return True
elif (self.denomination == last_denom) and self.power == Power.Clone:
return True
elif self.denomination == 1 and last_denom == 100000:
return True
elif is_chain_broken and self.denomination == 1:
return True
else:
return False
def get_copy(self):
"""return a new instance of this card in the same state as this card"""
d = {"denomination": self.denomination, "power": self.power, "owner": self.owner}
card_to_return = Card(d["denomination"], d["power"], d["owner"])
return card_to_return
class Deck:
"""Deck"""
def __init__(self, name, json_formatted_deck_path=None):
self.deck = []
self.owner = name
if json_formatted_deck_path != None:
self.deck_import(json_formatted_deck_path)
#TODO: Add a card import verifier to ensure only actual existing tribbles cards are added to a deck.
def deck_import(self, json_formatted_deck_path):
"""An example deck might look like this:
{
"cards":
[
"2 100 Tribbles - Rescue",
"1 10 Tribbles - Copy",
"4 100 Tribbles - Copy"
]
}
"""
with open(json_formatted_deck_path, "r") as fp:
deck_dict = json.load(fp)
for each_item in deck_dict["cards"]:
self.deck = self.deck + self.convert_string_to_cards(each_item)
def convert_string_to_cards(self, string):
"""
parses cards in the format '<quantity> <denomination> Tribbles - <power>' to one or more Card objects.
Returns all cards as a list.
"""
quantity = int(re.findall("(\d+)\s\d+", string)[0])
denomination = int(re.findall("\d+\s(\d+)\s", string)[0])
power = re.findall("- (.+)$", string)[0]
to_return = []
for i in range(0, quantity):
to_return.append(Card(denomination, Power[power], self.owner))
return to_return
def remove_card(self, card):
for each_card in self.deck:
if (each_card.denomination == card.denomination) and (each_card.power == card.power):
self.deck.remove(each_card)
return each_card
def add_card(self, card):
self.deck.insert(0, card)
def is_empty(self):
"return True if deck empty. False otherwise."
if len(self.deck) > 0:
return False
if len(self.deck) == 0:
return True
else:
raise ValueError
def get_top_card_and_remove_card(self):
"""
Remove the top card of this deck and return it.
"""
return self.deck.pop(0)
def get_top_card_of_deck(self):
"""
Peek at the top card of the deck. Return None if the deck is empty.
"""
if self.is_empty():
return None
else:
return self.deck[0]
def get_denomination_sum(self):
"""
get the sum total of all of the denominations of the cards in this deck
"""
to_return = 0
for each_card in self.deck:
to_return += each_card.denomination
return to_return
def get_expected_poison_value(self):
"""
get the sum of all of the denominations of the cards in the deck over the number
of cards in the deck as an integer rounded up.
"""
try:
value_to_return = int(math.ceil(self.get_denomination_sum() / len(self.deck)))
except ZeroDivisionError:
value_to_return = 0
return value_to_return
def shuffle(self, seed=None):
if seed:
random.seed(seed)
random.shuffle(self.deck)
random.seed()
else:
random.shuffle(self.deck)
def get_all_unique_cards(self):
"""
convenience function. It is useful to get a list of the different type of cards in a deck. Returns a list
of what cards are in this deck without returning a second copy of that card.
"""
to_return = []
for each_card in self.deck:
card_in_to_return = False
for every_card in to_return:
if each_card.get_card_categorization() == every_card.get_card_categorization():
card_in_to_return = True
if card_in_to_return == False:
to_return.append(each_card)
return to_return
def pretty_print(self, number_to_print=None):
"""
returns a string represeentation of the deck. If only a certain number are desired to
be printed, it can be specified.
"""
to_return = ""
if number_to_print:
for each_card in self.deck[:number_to_print]:
if each_card.denomination == 1:
to_return += "%s Tribble %s, \r\n" % (each_card.denomination, each_card.power)
else:
to_return += "%s Tribbles %s, \r\n" % (each_card.denomination, each_card.power)
else:
for each_card in self.deck:
if each_card.denomination == 1:
to_return += "%s Tribble %s, \r\n" % (each_card.denomination, each_card.power)
else:
to_return += "%s Tribbles %s, \r\n" % (each_card.denomination, each_card.power)
return to_return
def get_copy(self):
"""Return a new instance of this deck class in the same state as itself"""
deck_to_return = []
for each_card in self.deck:
deck_to_return.append(each_card.get_copy())
dic = {"owner": self.owner}
d = Deck(dic["owner"])
d.deck = deck_to_return
return d
|
75b9ba8d26d71c8b1227ead938d11e5472285c29 | sajadmsNew/interview | /leetcode/python/postOrderNary.py | 1,288 | 4.0625 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
result = [];
def traversePostorder(node):
if node == None:
return;
for child in node.children:
traversePostorder(child);
result.append(node.val);
"""
Using a stack explores the tree breadth search first
(level-by-level, top-to-bottom), but from right to left. We want to
start from the bottom and left to right, so we reverse
the result at the end.
"""
def traversePostorderIterative(node):
if node is None:
return [];
stack = [node];
while len(stack) != 0:
current = stack.pop();
result.append(current.val);
for child in current.children:
stack.append(child);
result.reverse();
traversePostorder(root);
return result;
|
5519d1b5e7716cee785c3302886558c83029ec0e | murilonerdx/exercicios-python | /Exercicio_Lista/exercicio_17.py | 275 | 3.828125 | 4 | p = float(input("Digite o valor do produto: "))
lucro = 0.45 * p
lucro2 = 0.3 * p
if (p < 20):
lucro = 0.45 * p
print("O valor de venda para o produto é ", p - lucro)
else:
lucro = 0.3 * p
print("O valor de venda para o produto é ", p - lucro)
|
46808a8cd4cadee6d0f552dda7fc64f8f2845748 | synchrophasotron28/LABS | /SystemModeling/итог/application/server/SqliteLogger.py | 1,046 | 3.625 | 4 | import sqlite3
import datetime
def get_create_table_query(table_name):
query = "create table if not exists {}" \
"(x REAL, y REAL, z REAL, theta REAL, " \
" r REAL, p REAL, big_omega REAL, " \
"omega REAL, e REAL, tau REAL, m REAL, i REAL );"
return query.format(table_name)
def get_insert_query(key, x, y, z, theta, r1, p1, OMEGA1, omega1, e1, tau1, m, i1):
query = f"""INSERT INTO {key} VALUES ({x},{y},{z},{theta},{r1},{p1},{OMEGA1},{omega1},{e1},{tau1},{m},{i1})"""
return query
def get_unique_name():
now = datetime.datetime.now()
day = str(now.day).rjust(2, '0')
month = str(now.month).rjust(2, '0')
year = str(now.year)
hour = str(now.hour).rjust(2, '0')
minute = str(now.minute).rjust(2, '0')
second = str(now.second).rjust(2, '0')
result = f'{hour}{minute}{second}{day}{month}{year}.db'
return result
def make_new_connection():
database_name = get_unique_name()
connection = sqlite3.connect()
print(get_create_table_query('test'))
|
a62008cae2f09909de4f924eeb799a7ed0009abc | lucmichea/leetcode | /Challenge_June_30_days_leetcoding_challenge/day14.py | 8,346 | 3.828125 | 4 | """
Cheapest Flights Within K Stops
Problem:
There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w.
Now given all the cities and flights, together with starting city src and the destination dst,
your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.
Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph looks like this:
{1}
/ \
100 / \ 500
/ \
{0}---->{2}
100
The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph looks like this:
{1}
/ \
100 / \ 500
/ \
{0}---->{2}
100
The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.
Constraints:
The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1.
The size of flights will be in range [0, n * (n - 1) / 2].
The format of each flight will be (src, dst, price).
The price of each flight will be in the range [1, 10000].
k is in the range of [0, n - 1].
There will not be any duplicated flights or self cycles.
"""
from typing import List
import numpy as np
class Solution:
# time limit exceeded for dynamic implementation
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
if src == dst :
return 0
if K < 0 :
return -1
l_possible_prices = []
for flight in flights:
flight_src, flight_dst, price = flight
if src == flight_src:
price_taking_the_flight = self.findCheapestPrice(n, flights, flight_dst, dst, K-1)
if price_taking_the_flight != -1:
l_possible_prices.append(price + price_taking_the_flight)
if l_possible_prices :
return min(l_possible_prices)
else :
return -1
if __name__ == "__main__":
sol = Solution()
print(sol.findCheapestPrice(n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]],
src = 0, dst = 2, K = 1))
#### ONLINE ####
# import heapq
# from collections import defaultdict
# class Solution:
# # DFS
# def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
# if not flights or not flights[0]:
# return -1
# costs = [float('inf')] * n
# # Initialize grid map
# grid = collections.defaultdict(list)
# for s, d, c in flights:
# grid[s].append([d, c])
# heap = [(0,src,0)] # cost, source, visitedCnt: K
# while heap:
# subCost, subSrc, visitedCnt = heap.pop(0)
# # Varification
# if costs[subSrc] <= subCost or (visitedCnt > K and subSrc != dst):
# continue
# costs[subSrc] = subCost
# # Recursive call
# for nextDst, nextCost in grid[subSrc]: # Dst to next Src
# heap.append((subCost + nextCost, nextDst, visitedCnt + 1))
# return -1 if costs[dst] == float('inf') else costs[dst]
# Dijkstra
# def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
# if not flights or not flights[0]:
# return -1
# # Initialize grid map
# grid = collections.defaultdict(list)
# for s, d, c in flights:
# grid[s].append([d, c])
# heap = [(0,src,0)] # cost, source, visitedCnt: K
# while heap:
# subCost, subSrc, visitedCnt = heapq.heappop(heap)
# # Varification
# if subSrc == dst:
# return subCost
# if visitedCnt > K: # if K == 1 one visited, #### visited
# continue
# # Recursive call
# for nextDst, nextCost in grid[subSrc]: # Dst to next Src
# heapq.heappush(heap, (subCost + nextCost, nextDst, visitedCnt + 1))
# return -1
# Bellman-ford: https://www.youtube.com/watch?v=lyw4FaxrwHg&t=374s
# For non-stop restriction
# def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
# #No limited stop return 200
# dist = [float('inf') for i in range(n)]
# dist[src] = 0
# # for _ in range(n-1): # Why n-1 iteration?
# for (subSrc, subDst, subCost) in flights:
# if dist[subSrc] + subCost < dist[subDst]:
# dist[subDst] = dist[subSrc] + subCost
# # for _ in range(n-1):
# for (subSrc, subDst, subCost) in flights:
# if dist[subSrc] + subCost < dist[subDst]:
# dist[subDst] = float("-inf")
# return dist[dst]
# Bellman-ford: https://www.youtube.com/watch?v=lyw4FaxrwHg&t=374s
# For k stop restriction
# def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
# # #K limited stop return 200
# dist = [[float('inf') for _ in range(n)] for _ in range(K + 2)]
# for visitedCnt in range(K + 2):
# dist[visitedCnt][src] = 0
# # for _ in range(n-1): # Time limit exceeded
# for visitedCnt in range(1, K + 2):
# for (subSrc, subDst, subCost) in flights:
# if dist[visitedCnt-1][subSrc] + subCost < dist[visitedCnt][subDst]:
# dist[visitedCnt][subDst] = dist[visitedCnt-1][subSrc] + subCost
# # for _ in range(n-1): # Time limit exceeded
# for visitedCnt in range(1, K + 2):
# for (subSrc, subDst, subCost) in flights:
# if dist[visitedCnt-1][subSrc] + subCost < dist[visitedCnt][subDst]:
# dist[visitedCnt][subDst] = float("-inf")
# return dist[K + 1][dst] if dist[K + 1][dst] != float('inf') else -1
# Floyd Warshall All Pair Shortest Path
# non stop restrict
# def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
# if not flights or not flights[0]:
# return -1
# # Initialize grid map
# grid = [[float('inf')]*n for _ in range(n)]
# for s, d, c in flights:
# grid[s][d] = c
# for k in range(n):
# for i in range(n):
# for j in range(n):
# grid[i][j] = min(grid[i][j], grid[i][k] + grid[k][j])
# # if (grid[i][j] > grid[i][k] + grid[k][j]):
# # grid[i][j] = grid[i][k] + grid[k][j]
# return grid[src][dst] if grid[src][dst] != float('inf') else -1
# (Not working) Floyd Warshall All Pair Shortest Path
# k stop restrict
# def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
# if not flights or not flights[0]:
# return -1
# # Initialize grid map
# grid = [[[float('inf')]*n for _ in range(n)] for _ in range(K + 2)]
# for visitedCnt in range(K + 2):
# for s, d, c in flights:
# grid[visitedCnt][s][d] = c
# for l in range(n):
# for i in range(n):
# for j in range(n):
# for visitedCnt in range(1, K + 2):
# grid[visitedCnt][i][j] = min(grid[visitedCnt][i][j], grid[visitedCnt-1][i][l] + grid[visitedCnt-1][l][j])
# # if (grid[i][j] > grid[i][k] + grid[k][j]):
# # grid[i][j] = grid[i][k] + grid[k][j]
# return grid[K+1][src][dst] if grid[K+1][src][dst] != float('inf') else -1 |
76f2cb3f2a69ad3ec050114c65fe7aca8be088fc | leejeyeol/LJY_DS_and_algorithm | /isprime.py | 1,394 | 4.0625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def is_prime(case):
if case == 1:
return "Not prime"
elif case == 2:
return "Prime"
elif (case % 2) == 0:
return "Not prime"
else:
for i in range(2, int(math.sqrt(case)) + 1):
if case % (i) == 0:
return "Not prime"
return "Prime"
'''
class Eratosthenes:
def __init__(self,max_num):
self.max_num = max_num+1
self.is_prime_odd = [True for _ in range(int(max_num/2)+1)]
self.is_prime_odd[0] = False
self.find_eratosthenes()
def is_prime(self, value):
if value == 2 :
return True
elif value%2 == 0:
return False
else:
return self.is_prime_odd[int(value/2)]
def set_false_odd(self, value):
if value%2 == 0:
pass
else:
self.is_prime_odd[int(value/2)] = False
def find_eratosthenes(self):
for i in range(3, int(math.sqrt(self.max_num))):
if self.is_prime(i) == True:
for j in range(i*i, self.max_num, i):
self.set_false_odd(j)
'''
n = int(input())
def iter_case():
for _ in range(n):
yield int(input())
for case in iter_case():
# print("Prime" if eratos.is_prime(case) else "Not prime")
print(is_prime(case)) |
f672fc8f54c4e00865dacc3925f2bb8c67f0069c | nsteward96/PythonClass | /Assignments/Weather/Epic.py | 920 | 3.59375 | 4 | def userList(prompt):
print prompt,
l = raw_input().split(",")
return l
def userInt(prompt):
print prompt,
num = int(raw_input())
return num
def userString(prompt):
print prompt,
string = raw_input()
return string
def user2OptionsString(prompt, option1, option2):
userChoice = ""
while userChoice != option1 and userChoice != option2:
userChoice = str.upper(userString(prompt))
if userChoice == option1:
return option1
return option2
def kmToMi(km):
return 0.62 * km
def calcAveNum(nums, start, stop):
sum = 0.0
for i in range(start, stop):
sum += nums[i]
return sum / (start - stop)
def promptUserRunAgain(prompt):
userResponse = ""
while userResponse != "Y" and userResponse != "N":
userResponse = str.upper(userString(prompt))
if userResponse == "N":
return False
return True |
ca49301f5a9b7f700bbbb8733366df65c4847073 | leeseulgi123/practice_python_coding | /Graph_5.py | 1,053 | 4 | 4 | # 그래프 이론 복습: 팀 결성
# 루트 노드(parent) 찾는 함수
def find_parent(parent, x):
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
# 두 원소가 속한 집합을 합치기
# a번 학생이 속한 팀과 b번 학생이 속한 팀을 합친다.
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a<b:
parent[b] = a
else:
parent[a] = b
print("0번부터 n번까지의 번호를 부여하고, m번의 연산을 수행한다.")
print("n,m 값을 입력하세요.")
n,m = map(int, input().split())
parent = [0]*(n+1)
for i in range(0, n+1):
parent[i] = i
print("-----------------------------------------------")
print("연산을 입력하세요.")
for i in range(m):
oper, a, b = map(int, input().split())
if oper == 0:
union_parent(parent, a, b)
elif oper == 1:
if find_parent(parent, a) == find_parent(parent, b):
print("Yes")
else:
print("No")
|
2a083ce6b6ee23d50a36424b9288fe57c43508a6 | anoadragon453/integer-factorization | /factor.py | 8,776 | 3.5 | 4 | import numpy as np
import sys
import os
import subprocess
import math
from decimal import Decimal
def log(*args):
if debug:
print(*args)
# createFactorbase returns a dict of prime numbers with a
# given length L
# We store our factorbase as a dictionary as we need to find
# out the index of a factor later with only the factor itself
# Storing as a list, we'd need to iterate over the list many
# times to find that factors index, but with a dict this can
# be a constant time lookup
def createFactorbase(L):
factorbase = {}
count = 0
# Open primes.txt, load in primes line by line
with open('primes.txt') as primes:
for prime in primes:
if count >= L:
return factorbase
# Additionally include an incrementing index for
# later quick reference
factorbase[int(prime.strip())] = count
count += 1
# calcR generates an r value according to equation 1,
# given input values j and k
def calcR(j, k, n):
return int((k*n)**0.5) + j
def calcRWiki(x, n):
return (math.ceil(math.sqrt(n)) + x)**2 - n
# generateSmoothFactors creates a dictionary of factors and
# their exponents from a number r. It derives factors
# from a given factorbase, f.
# If the number is not B-Smooth, it returns None
def generateSmoothFactors(r, f, N):
# Calculate r^2 within our modulo
r2 = (r*r) % N
# Dictionary of factors we will return
factors = {}
# Iterate over our factorbase and create a list of
# factors.
for prime in f.keys():
# Check if this prime factors into r^2
# Keep doing so and reducing r^2 by that factor until
# We can no longer do so with this prime
while r2 > 1 and r2 % prime is 0:
# Add prime to the dict of factors, or increment
# its exponent if it's already present
if prime in factors:
factors[prime] += 1
else:
factors[prime] = 1
# Reduce r2 by this prime
r2 = r2 // prime
log("Reduced r2 to:", r2)
# If r2 is 1, then r is B-smooth
if r2 is 1:
factors_list = []
log("Retrieved factors for %d:" % r, factors)
# Return only the factors with odd exponents
for factor, exponent in factors.items():
# Check and add only if exponent is odd
if exponent % 2 is 1:
factors_list.append(factor)
return factors
else:
# Return None if not B-smooth.
# We will be discarding this prime
log('Not smooth. Discarding prime.')
return None
#####################################
## Program Start ##
#####################################
# Whether to enable or disable debug printing
# No printing means a faster runtime
debug = False
# The amount of primes in our factorbase
prime_amount = 500
# The amount of r values, directly proportionate to our
# factorbase length
r_amount = prime_amount + 10
# The number to factor
number = 392742364277
# Our factorbase, which holds the first prime_amount primes
log('Creating factorbase...')
factorbase = createFactorbase(prime_amount)
log('Factorbase:', factorbase)
# Create rows to fill our binary matrix with.
# Once the list is filled, insert those rows which are unique
# into our binary matrix
rows = []
# We also create a list to store the corresponding factors
# so that we can later multiply these factors together
factors_record = []
# And finally, we keep a record of all of our chosen r values.
# We'll also need to multiply these together towards the end
r_values = []
# Iterate over values generated by calcR, checking whether
# each one is B-smooth according to our factorbase.
# If so, add its factors as a row to rows, and thus our
# binary matrix
(j, k) = (1, 1)
log('Generating rows...')
while len(rows) < r_amount:
print('trying j: %d, k: %d' % (j, k))
r = calcR(j, k, number)
log('Got r value:', r)
log('Generating factors...')
# Check if this number is B-smooth
factors = generateSmoothFactors(r, factorbase, number)
if factors:
# The number is smooth, include the factors in our
# binary matrix
# Retrieve the indexes of these factors in our
# factorbase
indexes = list(map(lambda factor: factorbase[factor], factors))
# Create a list of zeros to store binary encoded indexes
row = [False] * prime_amount
# Set each value in our row to True (binary 1) that
# corresponds to an odd factor
for index in indexes:
row[index] = True
# Add the row to our matrix, but only if it is unique
if row not in rows:
rows.append(row)
log('Added row:', row)
# Also save these factors to a list for later
factors_record.append(factors)
# And the r value
r_values.append(r)
''' The n method
if k % 75:
j += 1
k += 1
'''
k += 1
if k > 30:
k = 1
j += 1
# Create a binary matrix of size r_amount x prime_amount
# dtype is boolean to represent a binary value
matrix = np.zeros([r_amount, prime_amount], dtype=bool)
# We will now fill our matrix with our binary rows of factors.
rows = rows
for i in range(r_amount):
matrix[i] = rows[i]
log('Our binary matrix:')
log(matrix)
# Use an external program to solve the system of equations our
# binary matrix represents for x and y
in_file = 'matrix.txt'
out_file = 'matrix-out.txt'
executable = './GaussBin.exe'
# Export matrix to text file format
with open(in_file, 'w') as f:
f.write('%d %d' % matrix.shape)
f.write('\n')
for row in matrix:
for item in row:
f.write('%d ' % int(item))
f.write('\n')
# Perform Gaussian elimination on matrix
subprocess.run([executable, in_file, out_file])
# Read in modified matrix
lines = [line.rstrip() for line in open(out_file)]
# Get shape of this new matrix
row_count = int(lines[0])
col_count = r_amount
# Reduce lines to just the matrix's contents
lines = lines[1:]
# Feed items into a new numpy matrix
new_matrix = np.zeros([row_count, col_count], dtype=int)
for index, line in enumerate(lines):
items = line.split(' ')
# Insert list of items into numpy matrix
new_matrix[index,] = np.array(items)
# Remove temporary files
os.remove(in_file)
os.remove(out_file)
log('Our new matrix is:')
log(new_matrix)
# Each row of this new matrix is a clue to solving this
# system of equations. In each row, the value of every column
# specifies which of our list of factors in our original
# system of equations we need to multiply together to find
# a factor
for row in new_matrix:
# This will be our resulting right side of the
# row multiplication equation.
# This is created by multiplying all the factors
# from all the specified rows together
right_product = 1
# And this will be our left, made up from all the
# r values multiplied together
left_product = 1
# Go through each value in this row of the matrix
for index, item in enumerate(row):
# If the value is 1, that means we will use the
# list of factors that corresponds to the index
# of this value in the row
if item == 1:
# Get the r value this corresponds to and add it
# to the left product
left_product *= r_values[index]**2
# Then get the dict of factors for this r value.
# This contains the factors and their exponents
# as keys and values of a dictionary
factors = factors_record[index]
# Iterate through the dict, pulling out each
# number and multiplying them together with the
# value of the right product
for factor, exponent in factors.items():
right_product *= factor**exponent
# Now we sqrt the products, and keep them in the modulo
left_product = int(Decimal(left_product).sqrt()) % number
right_product = int(Decimal(right_product).sqrt()) % number
log('Left: %d, right: %d' % (left_product, right_product))
# Now we calculate gcd(right - left, number)
# If the gcd is 1 or number, then we didn't find a factor.
# Otherwise, we did, and we're done!
factor = math.gcd(right_product - left_product, number)
if factor != 1 and factor != number:
# We found a factor, yay! Return it and the number
# divided by the factor to find the other one
other_factor = number / factor
# Print out our factors
print('(%d, %d)' % (factor, other_factor))
# Exit the program
sys.exit(0) |
5c2ba25e6b7a1149a5ca3af57c4aff31b74be86d | Jayshri-Rathod/loop | /ex6.py | 109 | 3.734375 | 4 | i=0
while i<=25:
j=i+1
while j<i+6:
print(j,end=" ")
j+=1
print()
i+=5
|
fbf1a6f868b4e59b69609c73b230bbe6516bfb3d | sd19spring/adventure-unlocked | /theENGINE.py | 13,677 | 4 | 4 | """
A Text Based Adventure Game
SofDes Final Project
"""
import json
import threading
import music
class Item ():
"""
An Object that a player can interact with
properties: A list of way that the player can interact with an Object
reactions: A list of what happens when a player interacts with an Object
"""
def __init__(self, name, properties = None):
self.name = name
if properties is None:
properties = []
self.properties = properties
def __str__(self):
res = "Item[ Name: "+ name + "\nInventory ["
for property in self.properties:
res += "\n "+ property
res += " ]\n]\n"
return res
class Player():
"""
An Object to store the current state of the user
inventory: a list of items in the users players possession
actions: Actions that an user an do.
"""
def __init__ (self, inventory = None, actions = None):
if inventory is None:
inventory = []
self.inventory = inventory
if actions is None:
actions = []
self.actions = actions
def __str__(self):
res = "Player[\n Inventory ["
for item in self.inventory:
res += " \n"+ item
res += "\n ]\nActions ["
for action in self.actions:
res += "\n "+ action
res +="\n ]\n]\n"
return res
def viewInventory(self):
""" Displays current state of Inventory"""
res = "Items Currently in your Inventory: "
i = ', '.join(self.inventory)
if i == '':
i = 'None'
res += i
return res
def removeItem(self, item):
self.inventory.remove(item)
def addItem(self, item):
self.inventory.append(item)
class Room():
"""
An Object that is part of the map that the user will explore
rooms: other rooms that this room connects to
inventory: a list of items in the rooms possession
locked: whether paths to other rooms are locked or not
"""
def __init__(self, name, discovered = False, rooms = None, inventory = None, locked = None):
self.name = name
if rooms is None:
rooms = []
self.rooms = rooms
if inventory is None:
inventory = []
self.inventory = inventory
if locked is None:
locked = []
self.locked = locked
self.discovered = False
def __str__(self):
res = "Player[ Name: "+ name + "\nInventory ["
for item in self.inventory:
res += " \n"+ item
res += "\n ]\nActions ["
for action in self.actions:
res += "\n "+ action
res += "\n ]\nRooms ["
for room in self.rooms:
res += "\n "+ room
res +="\n ]\n]\n"
return res
def viewInventory(self):
""" Displays current state of Inventory"""
res = "Items in this room: "
i = ', '.join(self.inventory)
if i == '':
i = 'None'
res += i
return res
def removeItem(self, item):
self.inventory.remove(item)
def addItem(self, item):
self.inventory.append(item)
def switchRoom(self, direction): #TODO Update for Locks
"""Goes to a connected room if room is unlocked"""
direction = direction.casefold()
if direction.find("north") > 0:
direction = 0
elif direction.find("east") > 0:
direction = 1
elif direction.find("south") > 0:
direction = 2
elif direction.find("west") > 0:
direction = 3
else:
return 0
return self.rooms[direction]
class Game():
"""
A class that controls the gameplay. This class handles room changes and
other actions
startRoom: Room that the player begins in
rooms: a Dictionary of all rooms
items: a Dictionary of all items
attributes: a Dictionary of all attributes
actions: a Dictionary of all actions
"""
def __init__(self, startRoom = "1", rooms = None,items= None, attributes=
None, actions= None, notes = None):
self.player = Player()
if rooms is None:
rooms = {}
self.rooms = rooms
if items is None:
items = {}
self.items = items
if attributes is None:
attributes = {}
self.attributes = attributes
if actions is None:
actions = {}
self.actions = actions
if notes is None:
notes = {}
self.notes = notes
self.currentRoom = rooms[startRoom]
self.currentRoom.discovered = True
def switchRoom(self, direction):
"""Handles room switching at the game level"""
res = ""
if(self.currentRoom.switchRoom(direction) == 0):
res += "Not a valid Direction. Please try another command."
elif(self.currentRoom.switchRoom(direction) == ""):
res +="There's no room there!"
else:
self.currentRoom = self.rooms[self.currentRoom.switchRoom(direction)]
self.currentRoom.discovered = True
return res
def prepare_item(self,input):
"""
Checks if an item exists and then if the associated command exists
input: String input from user
"""
item = ""
command = ""
items = []
items.extend( self.player.inventory)
items.extend( self.currentRoom.inventory)
for element in items:
if input.casefold().find(element)>=0:
item = element
for attribute in self.items[item].properties:
for action in self.attributes[attribute]:
if input.casefold().find(action)>=0:
command = action
break
break
return item, command
def execute_command(self,command, item, notes):
"""Finds the appropriate reaction to command and executes it """
res = ""
if self.actions[command] == "move to inventory" :
self.currentRoom.removeItem(item)
self.player.addItem(item)
res += item + " moved to inventory"
elif self.actions[command] == "move to placeable" :
self.player.removeItem(item)
self.currentRoom.addItem(item)
res += item + " removed from Inventory"
elif self.actions[command] == "no reaction":
res += "Legit Nothing Happens"
elif self.actions[command] == "examine _":
# Record note has been viewed
if not item in notes:
notes[item] = 1
note = self.notes[item]
res += "\n" + item.upper()+ "\n********\n"
res += note['title'] + "\n"
res += "Day " + str(note['day']) + '\n'
res += note['text'] + "\n********\n"
else:
res+="Sorry that command doesn't do anything"
return res
def help(self):
"""Displays all possible commands"""
res= "These are all the recognized commands in Adventured Unlocked\n"
for attribute in self.attributes:
if not self.attributes[attribute] == []:
res += ', '.join(self.attributes[attribute])
res += '\n'
res += "go north\n"
res += "go east\n"
res += "go south\n"
res += "go west\n"
res += "view\n"
res += "view inventory"
return res
def helpitem(self, item):
"""Displays all possible commands associated with an item"""
res = "These are all the way to interact with " + item + "\n"
for attribute in self.items[item].properties:
res += ', '.join(self.attributes[attribute])
res += '\n'
return res
def handleInput(self, input, notes):
"""First point of contact for user input. Parses user input resing and
responds with appropriate reaction
input: user input
"""
res = []
item,command = self.prepare_item(input)
if(input.casefold().find("go ")>=0):
s = self.switchRoom(input)
if s:
res.append(s)
elif(input.casefold().find("view")>=0):
if(input.casefold().find("inventory")>=0):
res.append(self.player.viewInventory())
else:
res.append( self.currentRoom.viewInventory())
elif item and (input.casefold().find("help")>=0):
res.append(self.helpitem(item))
elif (input.casefold().find("help")>=0):
res.append(self.help())
elif not item:
res.append("This item is not in this room")
elif not command:
res.append("You can't do that to this item")
elif item and command:
res.append(self.execute_command(command, item, notes))
else:
res.append( "Sorry this action is not supported just yet")
res.append("You are in the " + self.currentRoom.name)
res.append("Around you are the following rooms:")
if self.currentRoom.rooms[0]:
room = self.currentRoom.rooms[0]
if self.rooms[room].discovered:
res.append("North: "+ room)
else:
res.append("North: ?")
if self.currentRoom.rooms[1]:
room = self.currentRoom.rooms[1]
if self.rooms[room].discovered:
res.append("East: "+ room)
else:
res.append("East: ?")
if self.currentRoom.rooms[2]:
room = self.currentRoom.rooms[2]
if self.rooms[room].discovered:
res.append("South: "+ room)
else:
res.append("South: ?")
if self.currentRoom.rooms[3]:
room = self.currentRoom.rooms[3]
if self.rooms[room].discovered:
res.append("West: "+ room)
else:
res.append("West: ?")
res.append( "What do you do?")
return clean_output(res)
def clean_output(res):
out = []
wrap_len = 125
for chunk in res:
arr = chunk.split("\n")
for line in arr:
while len(line) > wrap_len:
out.append(line[:wrap_len])
line = line[wrap_len:]
out.append(line)
# out.append("")
return out
def load_attibutes(attributeFile):
"""Loads attributes file"""
with open(attributeFile, 'r') as file:
data = file.read().replace('"', '\"')
adata = json.loads(data)
attributes = {}
actions = {}
for attribute in adata:
attributes[attribute] = []
if 'prompts' in adata[attribute]:
for i, actionset in enumerate(adata[attribute]['prompts']):
attributes[attribute].extend(actionset)
for action in actionset:
actions[action] = adata[attribute]['reactions'][i]
else: #TODO handle non prompts case
pass
return attributes, actions
def load_items(itemsFile):
"""Loads items file"""
with open(itemsFile, 'r') as file:
data = file.read().replace('"', '\"')
itemsdata = json.loads(data)
items = {}
for item in itemsdata:
items[item] = Item(item,itemsdata[item])
return items
def load_rooms(roomsFile):
"""Loads rooms file"""
with open(roomsFile, 'r') as file:
data = file.read().replace('"', '\"')
roomsdata = json.loads(data)
rooms = {}
for i,room in enumerate(roomsdata):
if i == 0:
startRoom = room
rooms[room] = Room(str(room),False, roomsdata[room]["directions"],
roomsdata[room]["items"], None) #roomsdata[room]["locks"]
return rooms, startRoom
def load_notes(notesFile):
with open(notesFile, 'r') as file:
data = file.read().replace('"', '\"')
notesdata = json.loads(data)
return notesdata
class MusicThread(threading.Thread):
"""
Class to handle creation of music class. Creates a seperate thread to run
parallel to game
"""
def run(self):
song = music.Song()
game = True
text = 'asdf'
temp = text
while song.sonic_is_open and game:
if temp != text:
song.update_song()
song.play_phrase()
temp = text
song.close_sonicpi()
def startGame():
"""
Method to set up game Object for gameplay and start music thread
"""
mythread = MusicThread(name = "Thread-{}".format(1)) # ...Instantiate a thread and pass a unique ID to it
mythread.start()
attributes, actions = load_attibutes("content/attributes.json")
items = load_items("content/items.json")
rooms, startRoom = load_rooms("content/rooms.json")
notes = load_notes("content/notes.json")
game = Game(startRoom,rooms,items, attributes, actions, notes)
res = []
res.append("You are in the " + game.currentRoom.name)
res.append("Around you are the following rooms:")
if game.currentRoom.rooms[0]:
res.append("North: ?")
if game.currentRoom.rooms[1]:
res.append("East: ?")
if game.currentRoom.rooms[2]:
res.append("South: ?")
if game.currentRoom.rooms[3]:
res.append("West: ?")
res.append( "What do you do?")
return game, res
if __name__ == '__main__':
game, res = startGame()
for stuff in res:
print(stuff)
while True:
for stuff in game.handleInput(input("")):
print(stuff)
|
68a6a5ca27fc3cf859d5c622a5b8f615f24eaf81 | FelixZFB/Python_advanced_learning | /02_Python_advanced_grammar_supplement/001_2_高级语法(装饰器-闭包-args-kwargs)/011-语法糖之装饰器_3_带固定参数的装饰器.py | 905 | 3.671875 | 4 | # 带有固定参数的装饰器函数
# 011-语法糖之装饰器_2.py中函数中加入参数
import time
# 定义一个装饰函数,函数的参数是一个函数
def deco(func):
# 定义一个内部函数,实现具体的功能,
# 原始函数带有参数,该处传入参数到该内部函数
def wrapper(a, b):
startTime = time.time()
func(a, b)
endTime = time.time()
msecs = (endTime - startTime) * 1000
print("原函数获得的拓展功能,原始函数func_a运行耗时:%d ms" % msecs)
# 装饰函数的返回值是内部函数的执行结果
return wrapper
# 使用@符号拓展函数功能,func_a就具有了deco函数的功能
@deco
def func_a(a, b):
print("带有固定参数的装饰器演示:")
time.sleep(2)
print("传入的参数求和:%d" % (a + b))
if __name__ == '__main__':
func_a(1, 2)
|
4cc49b7f0676ec486460bd6305609c94400bf804 | JuliaBelskaya/test_repo | /Lessons/lesson9.py | 2,898 | 3.9375 | 4 | # 9.1 Дан список слов.
# Сгенерировать новый список с перевернутыми словами
list_b = ['papa', 'asd']
list_a = [word[::-1] for word in list_b]
print(list_a)
# 9.2 Дан список словарей.
# Каждый словарь описывает машину
# (серийный номер и год выпуска).
# Создать новый список со всеми машинами,
# год выпуска которых больше n
n = int(input('Enter a year'))
list_a = [
dict(number='01', year=1996),
dict(number='02', year=1999),
dict(number='03', year=1998),
]
list_b = [car for car in list_a if car['year'] > n] #для car в списке, если год в car больше n, возвращаем взначение car
print(list_b)
# Создание матрицы
from random import randint
n = 3
matrix = [[randint(1, 9) for j in range(n)] for i in range(n)]
print(matrix)
# Генератор словарей
old_dict = {"aa": 1, "b": 2, "cccc": 3}
new_dict = {key + str(len(key)): value for key, value in old_dict.items()}
print(new_dict)
# 9.3 Дан словарь, создать новый словарь,
# поменяв местам ключ и значение
old_dict = {"aa": 1, "b": 2, "cccc": 3}
new_dict = {value: key for key, value in old_dict.items()}
print(new_dict)
# 9.4 Создать lambda функцию, которая
# принимает на вход имя и выводит его в формате “Hello, {name}”
print((lambda name: f"Hello, {name}")("Mark"))
# 9.5
#Создать lambda функцию, которая
# принимает на вход список имен
# и выводит их в формате “Hello, {name}”
print((lambda names: [f'Hello, {name}' for name in names])(['aa', 'bb']))
# 9.6 Написать декоратор, который
# будет выводить время выполнения функции
from datetime import datetime
from time import sleep
import functools
def time_decorator(func):
@functools.wraps(func)
def do_some_staff(*args, **kwargs):
start = datetime.now()
result = func(*args, **kwargs)
end = datetime.now()
print(f'Func time is: {end - start}')
return result
return do_some_staff
@time_decorator
def sleep_func(n):
sleep(n)
return 'a'
@time_decorator
def count(a, b):
return a + b
print(sleep_func(2))
print(count(5,6))
print(sleep_func.__name__)
#another task
def bread(func):
def wrapper():
print "</------\>"
func()
print "<\______/>"
return wrapper
def ingredients(func):
def wrapper():
print "#помидоры#"
func()
print "~салат~"
return wrapper
def sandwich(food="--ветчина--"):
print food
|
ac8e4c67dbf674ad592bdac7672fc4e4b559413e | yhamoudi/heatEquation | /cornebize-hamoudi/generator.py | 996 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
import random
if __name__ == "__main__":
"""
Generate randomly a file following the specification.
Width, height, p and t must be given as argument (in this order).
"""
if len(sys.argv) != 5:
print("Syntax: {0} <width> <height> <p> <t>".format(sys.argv[0]))
sys.exit()
random.seed()
width = int(sys.argv[1])
height = int(sys.argv[2])
p = float(sys.argv[3])
t = int(sys.argv[4])
print(width)
print(height)
print(p)
print(t)
nb_input = random.randint(0,width*height)
nb_request = random.randint(0,width*height)
for z in range(0,nb_input):
i = random.randint(0,height-1)
j = random.randint(0,width-1)
x = random.uniform(0,1)
print("0 {0} {1} {2}".format(str(i),str(j),str(x)))
for z in range(0,nb_request):
i = random.randint(0,height-1)
j = random.randint(0,width-1)
print("2 {0} {1} 0".format(str(i),str(j)))
|
25001f7d5bbbc1b7d4234653652400a946381c1f | janvozar/engeto_codebrew_hackathon_2019 | /longest_word.py | 526 | 4.15625 | 4 | words = ['Python', 'is', 'a', 'widely', 'used',
'high-level', 'programming', 'language',
'for', 'general-purpose', 'programming,',
'created', 'by', 'Guido', 'van', 'Rossum',
'and', 'first', 'released', 'in', '1991.']
longest = ()
def longest_word(words):
longest = words[0]
for i in range (0, len(words)-1):
if len(longest)<len(words[i]):
longest = words[i]
print(longest)
print('(' +longest + ', ' + str(len(longest)) + ')')
longest_word(words) |
432376630eb3c87f975ae955df1e364936686f92 | hi2gage/csci127 | /Week 3/Random.py | 295 | 3.859375 | 4 | import random
def main():
number_guesses = 0
answer = random.randint(1,10)
guess = 0
while (guess != answer):
guess = int(input("Enter your guess[1,10}"))
number_guesses += 1
print("congratulations! It took you", number_guesses, "guesses")
main()
|
2bb058faa3e55b2f8af6e463bd9c5cc625f5e276 | thangduong3010/Python | /ThinkPython/my_code/chapter9.py | 1,019 | 3.828125 | 4 | file = r"F:\Github\Python\ThinkPython\code\words.txt"
def has_no_e(word):
if 'e' not in word:
return True
def avoids(word, forbidden_string):
for char in word:
if char in forbidden_string:
return False
return True
def uses_only(word, allowed_string):
for char in word:
if char not in allowed_string:
return False
return True
if __name__ == "__main__":
count = 0
total = 0
with open(file, 'r') as fin:
for line in fin:
word = line.strip()
if has_no_e(word):
#print word
count += 1
total += 1
print "{} % of the list have no letter 'e'.".format(round(float(count)/float(total), 4) * 100)
forbidden_string = raw_input("Enter your mighty string\n> ")
with open(file, 'r') as fin:
for line in fin:
word = line.strip()
if avoids(word, forbidden_string):
print word
allowed_string = raw_input("Enter your mighty string\n> ")
with open(file, 'r') as fin:
for line in fin:
word = line.strip()
if uses_only(word, allowed_string):
print word |
c1e3c9275ee8ea9563729d354e64603ea42a2eb1 | pro-pedropaulo/estudo_python | /executaveis/01-desconto.py | 365 | 3.9375 | 4 | nome = input('Digite o nome da pessoa: ')
salario = float(input('Digite o Salario da pessoa: '))
desconto = float(input('Digite a porcertagem de desconto do salario: '))
salario_final = salario - (salario / desconto)
print('{}, tem o Salário de R${:.2f}, mas houve desconto de {}%, o salario final do mes foi R${:.2f}'.format(nome,salario,desconto,salario_final)) |
6f9ec527cb7eb479111bdd1922fbd9f72d424980 | LuckyLi0n/prog_golius | /Turtle/frac 2 Koch line.py | 355 | 3.8125 | 4 | import turtle
t = turtle.Turtle()
t.shape("turtle")
def alignment():
t.penup()
t.back(350)
t.pendown()
def draw(size, n):
if n == 0:
t.fd(size)
return
a = size / 3
draw(a, n - 1)
t.left(60)
draw(a, n - 1)
t.right(120)
draw(a, n - 1)
t.left(60)
draw(a, n - 1)
alignment()
draw(800, 0)
|
876ca46a0a4082416ff498029c358166be55a02f | considerxzh/JZoffer | /offer21.py | 1,379 | 3.609375 | 4 | '''
输入两个整数序列,第一个序列表示栈的压入顺序,
请判断第二个序列是否为该栈的弹出顺序。假设压
入栈的所有数字均不相等。例如序列1,2,3,4,5是
某栈的压入顺序,序列4,5,3,2,1是该压栈序列对
应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
(注意:这两个序列的长度是相等的)
#out of time
def IsPopOrder(pushV, popV):
# write code here
if not pushV:
return False
stack = []
stack.append(pushV[0])
pushV.pop(0)
for i in range(len(popV)):
while stack[-1] != popV[i]:
if pushV:
stack.append(pushV[0])
pushV.pop(0)
if stack[-1]==popV[i]:
stack.pop(-1)
else:
return False
if stack:
return True
else:
return False
'''
#others
def IsPopOrder( pushV, popV):
# write code here
if not pushV or len(pushV) != len(popV):
return False
stack = []
for i in pushV:
stack.append(i)
while len(stack) and stack[-1] == popV[0]:
stack.pop()
popV.pop(0)
if len(stack):
return False
return True
def main():
pushV = [1, 2, 3, 4, 5]
popV = [4, 5, 3, 2, 1]
IsPopOrder(pushV, popV)
main() |
c149f496a41779feaebb669c1d9c34c09305a95c | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/621fccbf4b754e60a78d068b06af69b7.py | 177 | 3.578125 | 4 | def difference(n):
return square_of_sum(n) - sum_of_squares(n)
def square_of_sum(n):
return (n*(n+1))**2/4
def sum_of_squares(n):
return n*(n+1)*(2*n+1)/6
|
1588191af0cb33e9c61af6ea1f186f0bee437cb4 | MKolman/list-partiotioner | /partitions.py | 4,004 | 4 | 4 | # Only using numpy to calculate standard deviation
import numpy
def make_partitions(data, min_size=2, max_size=-1, multiplier=0):
"""Partitions data into multiple bins.
Args:
data (list<float/int>): data to be partitioned
min_size (int): Minimum number of elements in a single partition; must
be at least 2
max_size (int): Maximum number of elements in a single partition; must
be at least min_size or -1 for unlimited
multiplier (float): a number that helps determine how many partitions we
end up with. If less than 0 it means more partitions, if more than
0 it means we want less partitions
Returns:
list<list<float/int>>: partitioned data
"""
# Set max_size to maximum if left to -1
if max_size < 0:
max_size = len(data)
# Assertions to check input parameters
assert 2 <= min_size <= len(data), \
"min_size must be at least 2 but not bigger than all of data"
assert min_size <= max_size, "max_size must be at least min_size"
# Memoization here to make sure the algorithm is fast by saving
# already calculated data of the form:
# memo [i] = what is the best partition of `data[i:]` (from i to the end)
# Set them to False, so we know we did nothing yet
memo = [False for _ in data]
# Return the (score, partition) combo of `data[i:]` with the minimum score,
# where score is the sum of standard deviations.
# e.g. such [[x11, x12, x13, ...], [x21, x22, x23, ...], ...] that
# together they yield `data` but have a minimum
# sum(i) STD(xi1, xi1, xi3, ...)
def scoring(i):
# If we reached the end of the list make sure to end the recursion
if i == len(data):
return 0, [i]
# Check if we already calculated this and if so return it
if memo[i]:
return memo[i]
# Start with infinite score and empty partition
best_score = float("inf")
best_partition = []
# Iterate through all possible sizes of the next partition `data[i:j]`
# for j in range(i+min_size, min(len(data)+1, i+max_size+1)):
for j in range(min(len(data), i+max_size), i+min_size-1, -1):
# Get the best partition of what's left
score, part = scoring(j)
score += numpy.std(data[i:j])
score += multiplier * len(part)
# Check if this is the new best partition
if score < best_score:
best_score = score
best_partition = [i] + part
# Save the calculated result and return it
memo[i] = [best_score, best_partition]
return memo[i]
# Calculate the partition and check the score
score, part = scoring(0)
assert score != float("inf"), "I could't make the partitions. :("
# ~~ Uncomment this line if you only want indeces of edges ~~
# return part
# The function scoring only returns indexes of edges, now lets
# change them into actual tables
partitioned_data = [data[part[i]:part[i+1]] for i in range(len(part)-1)]
partitioned_data = [data[i:j] for i, j in zip(part, part[1:])]
return partitioned_data
if __name__ == "__main__":
# Set the data
data = [1, 1, 1, 5, 6, 111, 122, 999, 1002]
print("default ".ljust(30, "-"), make_partitions(data))
print("default with mult. 1.5 ".ljust(30, "-"),
make_partitions(data, multiplier=1.5))
print("default with mult. 100 ".ljust(30, "-"),
make_partitions(data, multiplier=100))
print("default with mult. 1000 ".ljust(30, "-"),
make_partitions(data, multiplier=1000))
print("max_size=3 with mult. 1000 ".ljust(30, "-"),
make_partitions(data, max_size=3, multiplier=1000))
print("====================")
data = [1, 1, 1, 5, 6, 1110, 1220, 999, 1002]
print("default ".ljust(30, "-"), make_partitions(data))
print("min_size=3 ".ljust(30, "-"), make_partitions(data, 3))
|
7bd34a665c3c70c730d241bb75ef16a1deedbdaf | Jayesh598007/Python_tutorial | /Chap5_dictionary/09_prac4_len_of_set.py | 213 | 3.953125 | 4 | s = {12, "45", 12.0} # here, it will read 12 and 12.0 as a single element
s1 = {12, "45", 12.1}
print(s)
print(len(s)) # thus here, output length is 2
print(s1)
print(len(s1))
s = { 2, 7 ,(2, 4), 3}
print(s) |
ff69de771640aaee6e928cfcc934e111f1254459 | snaveen1856/Python_Revised_notes | /Core_python/_16_Generator/_01_ListComprehension.py | 3,033 | 4.96875 | 5 | # https://www.programiz.com/python-programming/list-comprehension
"""
List Comprehension :
-------------------
=> List comprehensions provide a concise way to create lists
For loop vs List Comprehension :
REQ : Separate the letters of the word human and add the letters as items of a list.
"""
# Example 1: Iterating through a string Using for Loop
h_letters = [] # 1. CREATE A EMPTY LIST
for letter in 'human': # 2. ITERATE THROUGH SEQUENCE
h_letters.append(letter) # 3. APPENDING EACH ELEMENT INTO LIST
print("--Using for loop--------------", h_letters)
# Example 2: Iterating through a string Using List Comprehension
h_letters = [letter for letter in 'human']
print("--Using list comprehension----", h_letters)
val = [x ** x for x in range(5)]
print("--Using list comprehension----", val)
'''
Syntax of List Comprehension : [<output expression> <for item in sequence> <Conditions>]
Ex: [ letter for letter in 'human' ]
List comprehension can identify when it receives a string or a tuple and work on it like a list.
'''
# Using if with List Comprehension :
print("=========IF with List Comprehension==============")
number_list = [x for x in range(20) if x % 2 == 0] # x
# for x in range(20)
# if x % 2 == 0
print("MAD=", number_list)
print("-------------OR--------------")
number_list = []
for x in range(20):
if x % 2 == 0:
number_list.append(x)
# Nested IF with List Comprehension
print("=========Nested IF with List Comprehension==============")
num_list = [y ** 2 for y in range(100) if y % 2 == 0 if y % 5 == 0] # y
# for y in range(100)
# if y % 2 == 0
# if y % 5 == 0
print("Using comprehension : ", num_list)
print("-------------OR--------------")
number_list = []
for y in range(100):
if y % 2 == 0:
if y % 5 == 0:
number_list.append(y ** 2)
print("Using for loop : ", number_list)
# if...else With List Comprehension
print("========= if...else with List Comprehension==============")
obj = ["Even" if i % 2 == 0 else "Odd" for i in range(10)]
print(obj)
print("-------------OR--------------")
obj = []
for i in range(10):
if i % 2 == 0:
obj.append("Even")
else:
obj.append("Odd")
print(obj)
print("----List comprehension with expression------------")
list1 = [3, 4, 5]
multiplied = [item * 5 for item in list1]
print(multiplied)
square = [item * item for item in list1]
print(square)
'''
Key Points :
============
1.List comprehension is an elegant way to define and create lists based on existing lists.
2.List comprehension is generally more compact and faster than normal functions and
loops for creating list.
3.However, we should avoid writing very long list comprehensions in one line to ensure.
that code is user-friendly.
4.Every List comprehension can be rewritten in for loop but vice versa is not true.
'''
|
90781aa162bb5205df9c6616eff447ed7ca0682b | kajal1810/ideal-spoon | /if statement.py | 318 | 4.25 | 4 | #if stmt
str =raw_input("enter pass: ") #raw_input function is used to string take input from user
if str!="devanshi":
print "pass is incorrect"
else:
print "pass is correct"
age=input("enter age: ")
if age==18: #input() function used to take no input from user
print "you can vote"
|
ad13aba2b60c3fe276a82d1013121640c0f73ed2 | Asunqingwen/LeetCode | /easy/N-ary Tree Level Order Traversal.py | 1,221 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/8/22 0022 10:51
# @Author : 没有蜡笔的小新
# @E-mail : [email protected]
# @FileName: N-ary Tree Level Order Traversal.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example, given a 3-ary tree:
We should return its level order traversal:
[
[1],
[3,2,4],
[5,6]
]
Note:
The depth of the tree is at most 1000.
The total number of nodes is at most 5000.
"""
from typing import List
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
def levelOrder(root: 'Node') -> List[List[int]]:
res_list = []
pre_stack = [[root]]
while pre_stack:
root = pre_stack.pop(0)
child_list = []
val_list = []
for r in root:
if r:
val_list.append(r.val)
if r.children:
child_list.extend(r.children)
if len(child_list):
pre_stack.append(child_list)
if len(val_list):
res_list.append(val_list)
return res_list
if __name__ == '__main__':
input = Node(1, 1)
output = levelOrder(input)
print(output)
|
72cd3838146b193963ddabb7fa828bebd4f83053 | lyj238Gmail/server-dt5 | /备用test/py2/版本说明/版本说明.py | 4,750 | 3.65625 | 4 | 版本:基于“undefined”的优先级决策树,使用python3运行main.py,该代码的数据集原子German,好坏比例1:1,坏状态使用了距离概念
版本说明:在原有的决策树(ID3)中加入了优先级概念。这里的优先级指某属性的样本数据中包含undefined的概率,
含有undefined概率越底的属性优先级越高。在决策树中,优先级概念被应用于选择属性以分裂数据集。原算法中,选择属性的依据
是“信息增益”,“信息增益”大的属性将会被选中。在基于“undefined”的优先级决策树中,选择属性被分为三种情况,第一种情况为
“当前属性的优先级大于最佳属性”,该情况下会直接替换现有属性为最佳属性。第二种情况为“当前属性的优先级与最佳属性相等”,
该情况下会对比当前属性与最佳属性的“信息增益”,“信息增益”大者为最佳属性。第三种情况为“当前属性的优先级小于于最佳属性”
这种情况不做任何处理。
新加入的函数
1.def percentage(csvfile): 用于计算各个属性的数据中包含undefined的概率
伪代码:位于main.py
def percentage(csvfile): #输入为 csv文件
获得表头与训练数据
undefined_percentage_dict = {} #用于返回的字典
获取训练数据大小
for 每个属性:
undefined_counter = 0 #初始化计数器
for 属性对应的每个样本数据:
if 样本值 == 'undefined':
undefined_counter = undefined_counter + 1 #进行计数
undefined_percentage_dict[属性名称] = undefined_counter/训练数据总数 #保存属性对应的undefined概率
return undefined_percentage_dict
新加入包:import package_pre.pre
说明:整合了之前的预处理代码,以package_pre.pre包的形式出现
对原版本函数的修改
1.def teacher(origin_csv,atom_txt,atom_csv,tree_save_file): #teacher模块
伪代码:位于main.py
def teacher(origin_csv,atom_txt,atom_csv,tree_save_file):
生成以原子公式为表头的训练数据 #new
计算训练数据的优先级字典,即函数percentage得出的结果 #new
对训练数据进行预处理,对“undefined”项进行随机赋值 #new
使用预处理过的数据生成决策树 #new
存储决策树
打印决策树
return 决策树
2.def createTree(atom_csv,undefined_percentage): #teacher中生成决策树的函数
说明:位于main.py。修改调用函数id3.createTree的代码,加入新参数undefined_percentage
3.def createTree(dataSet,labels,undefined_percentage): #0706 加入优先级判定依据undefined_percentage
说明:该函数位于id3.py
修改调用函数chooseBestFeatureToSplit的代码,加入新的参数,更新为 chooseBestFeatureToSplit(dataSet,labels,undefined_percentage)
修改调用自身的代码,加入新参数,修改为createTree(temp,subLabels,undefined_percentage)
4.def chooseBestFeatureToSplit(dataSet,labels,undefined_percentage): #修改选择用于分裂数据集的属性的方法,加入优先级的判定
伪代码:
def chooseBestFeatureToSplit(dataSet,labels,undefined_percentage):
numFeatures = len(dataSet[0]) - 1 #找到特征的数量,减一是为了排除最后一项(数据的分类项)
#baseEntropy = calcShannonEnt(dataSet) #使用香农熵算法计算未分类时数据集的熵,并将其作为基础熵,用于信息增益的判断
baseEntropy = 100
bestInfoGain = 0.0; bestFeature = -1 #最大信息增益基础值(初始化)为0,最佳特征基础值为-1
best_priority = 1 #定义优先级,优先级越小,优先程度越高,初始化为1,这里指undefined率 NEW!!
for i in range(numFeatures): #遍历所有的特征
featList = [example[i] for example in dataSet] #使用列表解析,将数据集中的每个元素的特征值(i对应的)加入列表中
uniqueVals = set(featList) #获得没用重复的取值,也就是所有可能取值的列表
newEntropy = 0.0 #用于记录按特征划分后的熵,初始化为0
for value in uniqueVals: #对于每种取值
subDataSet = splitDataSet(dataSet,i,value) #找出所有符合取值的元素
prob = len(subDataSet)/float(len(dataSet))
newEntropy += prob * calcShannonEnt(subDataSet)
infoGain = baseEntropy - newEntropy #信息增益的计算
#注意!!!上方代码与原算法一样,除了加入最佳优先级best_priority,下方为新代码的伪代码
if(当前属性的优先级大于最佳属性的优先级):
替换最佳属性为当前属性
if(当前属性与最佳属性的优先级相同):
选择信息增益大的属性为最佳属性
返回最佳属性
|
72ede0f208ff75514a656f1462a36b1162e09a01 | ikonstantinov/python_everything | /test web app/classs.py | 733 | 3.875 | 4 | class A(object):
def __init__(self):
print "A"
super(A, self).__init__()
def f(self):
super(A, self).f()
class B(object):
def __init__(self):
print "B"
super(B, self).__init__()
def f(self):
#super(B, self).f()
class C(object):
def __init__(self):
print "C"
super(C, self).__init__()
class D(A, B):
def __init__(self):
print "D"
super(D, self).__init__()
def f(self):
super(D, self).f()
class E(D, C):
def __init__(self):
print "E"
super(E, self).__init__()
class H(A, C):
def __init__(self):
print "H"
super(H, self).__init__()
|
46a56ed7f4f865044bd2da5ad10ed723cf1c1ef6 | xwang322/Coding-Interview | /uber/uber_algo/SortedArraySquareSorted_UB.py | 687 | 3.5625 | 4 | /*
* 第一题是将一个有序数组乘方后返回import bisect
**/
def SortedSquareArray(array):
left = right = bisect.bisect_left(array, 0)
print left, right
answer = []
while right-left < len(array):
if right == len(array):
while left > 0:
answer.append(array[left-1]**2)
left -= 1
return answer
if abs(array[left-1]) < abs(array[right]):
answer.append(array[left-1]**2)
left -= 1
else:
answer.append(array[right]**2)
right += 1
return answer
answer = SortedSquareArray([-9, -7, -1, 0, 1, 3, 9])
print answer
|
8f5b82646e16e6e84aece66e0e4c9e3e84955893 | csulva/Coding_Nomads_Python_201_Labs | /03_file-input-output/03_03_writing.py | 411 | 3.84375 | 4 | # Write a script that reads in the contents of `words.txt`
# and writes the contents in reverse to a new file `words_reverse.txt`.
with open('words.txt', 'r') as new_open:
words = new_open.read()
# words = words.split()
reverse_word = words[::-1]
print(reverse_word)
reverse_out = open('words_reverse.txt', 'w')
reverse_out.write(str(reverse_word))
reverse_out.write('\n')
reverse_out.close() |
1f86d634e5c2e82c3bb5e28e47deefbb3ca9291d | EdisonCristovao/Graph-estructure | /main.py | 5,270 | 3.796875 | 4 | #OK = G.adicionaVértice(v) "Adiciona um novo vértice em G"
#OK = G.removeVértice(v) "Remove um vértice de G, juntamente com todas as conexões"
#OK = G.conecta(v1,v2) "Conecta os vértices v1 e v2 em G"
#OK = G.desconecta(v1,v2) "Desconecta os vértices v1 e v2 em G"
#OK = G.ordem Inteiro "Retorna o número de vértices de G"
#OK = G.umVértice Vertice "Retorna um vértice qualquer de G"
#OK = G.grau(v)Inteiro "Retorna o número de vértices adjacentes a v em G" Ações Derivadas
#OK = G.vértices Conjunto "Retorna um conjunto contendo os vértices de G"
#OK = G.adjacentes(v)Conjunto "Retorna um conjunto contendo os vértices adjacentes a v em G"
#G.éRegularBoolean "Verifica se todos os vértices de G possuem o mesmo grau"
#G.éCompletoBoolean "Verifica se cada vértice de G está conectados a todos os outros vértices"
#G.fechoTransitivo(v)Conjunto "Retorna um conjunto contendo todos os vértices de G que são transitivamente alcancáveis partindo-se de v"
#G.éConexoBoolean "Verifica se existe pelo menos um caminho que entre cada par de vértices de G"
#G.éÁrvoreBoolean "Verifica se não há ciclos em G"
from GraphEstructure import GraphEstructure
def main():
g = buildGraph()
g.showGraph()
g.removeVertice("INE5404")
print("")
g.showGraph()
print("")
print("")
print("Seu grafo tem {} vertices".format(g.ordem()))
print("")
verticeQulquer = g.umVertice().name
print("Um vertice qualquer --> {}".format(verticeQulquer))
print("Grau do vertice qualquer --> {}".format(g.grau(verticeQulquer)))
print("")
print("{}".format(g.copyVertices()))
print("")
print("Adjacentes a {} são => {}".format(verticeQulquer, g.adjacentes(verticeQulquer)))
def buildGraph():
g = GraphEstructure()
g.adicionaVertice("EEL5105") # v1
g.adicionaVertice("EEL5105") # v1
g.adicionaVertice("INE5401") # v2
g.adicionaVertice("INE5402") # v3
g.adicionaVertice("INE5403") # v4
g.adicionaVertice("MTM3100") # v5
g.adicionaVertice("MTM3101") # v6
g.adicionaVertice("INE5404") # v7
g.adicionaVertice("INE5405") # v8
g.adicionaVertice("INE5406") # v9
g.adicionaVertice("INE5407") # v10
g.adicionaVertice("MTM3102") # v11
g.adicionaVertice("MTM5512") # v12
g.adicionaVertice("INE5408") # v13
g.adicionaVertice("INE5409") # v14
g.adicionaVertice("INE5410") # v15
g.adicionaVertice("INE5411") # v16
g.adicionaVertice("MTM5245") # v17
g.adicionaVertice("INE5412") # v18
g.adicionaVertice("INE5413") # v19
g.adicionaVertice("INE5414") # v20
g.adicionaVertice("INE5415") # v21
g.adicionaVertice("INE5416") # v22
g.adicionaVertice("INE5417") # v23
g.adicionaVertice("INE5418") # v24
g.adicionaVertice("INE5419") # v25
g.adicionaVertice("INE5420") # v26
g.adicionaVertice("INE5421") # v27
g.adicionaVertice("INE5422") # v28
g.adicionaVertice("INE5423") # v29
g.adicionaVertice("INE5424") # v30
g.adicionaVertice("INE5425") # v31
g.adicionaVertice("INE5426") # v32
g.adicionaVertice("INE5427") # v33
g.adicionaVertice("INE5430") # v34
g.adicionaVertice("INE5453") # v35
g.adicionaVertice("INE5428") # v36
g.adicionaVertice("INE5429") # v37
g.adicionaVertice("INE5431") # v38
g.adicionaVertice("INE5432") # v39
g.adicionaVertice("INE5433") # v40
g.adicionaVertice("INE5434") # v41
g.conecta("MTM3100","MTM3101");
g.conecta("MTM3100","MTM3101");
g.conecta("INE5402","INE5404");
g.conecta("MTM3101","INE5405");
g.conecta("EEL5105","INE5406");
g.conecta("MTM3101","MTM3102");
g.conecta("INE5404","INE5408");
g.conecta("MTM5512","INE5409");
g.conecta("MTM3102","INE5409");
g.conecta("INE5404","INE5410");
g.conecta("INE5406","INE5411");
g.conecta("MTM5512","MTM5245");
g.conecta("INE5410","INE5412");
g.conecta("INE5411","INE5412");
g.conecta("INE5403","INE5413");
g.conecta("INE5408","INE5413");
g.conecta("INE5404","INE5414");
g.conecta("INE5403","INE5415");
g.conecta("INE5408","INE5415");
g.conecta("INE5408","INE5416");
g.conecta("INE5408","INE5417");
g.conecta("INE5412","INE5418");
g.conecta("INE5414","INE5418");
g.conecta("INE5417","INE5419");
g.conecta("MTM3102","INE5420");
g.conecta("INE5408","INE5420");
g.conecta("MTM5245","INE5420");
g.conecta("INE5415","INE5421");
g.conecta("INE5414","INE5422");
g.conecta("INE5408","INE5423");
g.conecta("INE5412","INE5424");
g.conecta("INE5405","INE5425");
g.conecta("INE5421","INE5426");
g.conecta("INE5417","INE5427");
g.conecta("INE5405","INE5430");
g.conecta("INE5413","INE5430");
g.conecta("INE5416","INE5430");
g.conecta("INE5417","INE5453");
g.conecta("INE5407","INE5428");
g.conecta("INE5403","INE5429");
g.conecta("INE5414","INE5429");
g.conecta("INE5414","INE5431");
g.conecta("INE5423","INE5432");
g.conecta("INE5453","INE5433");
g.conecta("INE5427","INE5433");
g.conecta("INE5433","INE5434");
return g
if __name__ == '__main__':
main()
|
a2d6bc8eb1c65527699c6415d40991ba83c4a821 | shubham261996/vip-app-service | /automation/test-cron.py | 927 | 3.53125 | 4 | from datetime import datetime
import traceback
import os
def write_file(filename,data):
try:
if os.path.isfile(filename):
with open(filename, 'a') as f:
f.write('\n' + data)
else:
with open(filename, 'w') as f:
f.write(data)
except Exception as e:
traceback.print_exc()
print(str(e))
def print_time():
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
data = "Current Time:- " + current_time + ":-" + basePath
return data
os.chdir(os.path.dirname(os.path.abspath(__file__)))
basePath = os.getcwd() + '/test-new-02.txt'
print(basePath)
print('basename: ', os.path.basename(__file__))
print('dirname: ', os.path.dirname(__file__))
print('[change directory]')
print('getcwd: ', os.getcwd())
#print(newPath + "tere")
write_file(basePath , print_time()) |
d680a5813f3a39069c7e7b6fba39442aa828fc67 | apena19/exercism | /python/change/change.py | 687 | 3.828125 | 4 | from itertools import combinations_with_replacement
from typing import List
def find_fewest_coins(coins: List[int], total_change: int) -> List:
if not total_change:
return []
if total_change < 0:
raise ValueError('Change can\'t be negative')
if not coins:
raise ValueError('No coins left.')
if total_change < min(coins):
raise ValueError('No suitable coins for change.')
for i in range(1, total_change + 1):
for combination in combinations_with_replacement(coins, i):
if sum(combination) == total_change:
return sorted(list(combination))
raise ValueError('No suitable coins for change.')
|
ff74cb2822e9435dd270e4b807bd5c1727133b29 | Karthik-bhogi/Infytq | /Part 2/Assignment Set 7/Question5.py | 378 | 3.53125 | 4 | '''
Created on Jul 30, 2021
@author: Karthik
'''
#lex_auth_01269443664174284882
def reverse(num):
return str(num)[::-1]
def nearest_palindrome(number):
#start writitng your code here
while(1):
number += 1
if str(number)==reverse(number):
return number
break
number=99
print(nearest_palindrome(number)) |
507822a674fb289bdb4e6d150a49d4b642f8204d | rojannti/dpt-courses | /Python3_MukeshRanjan/14-Classes And Object In Python.py | 274 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 29 08:02:02 2019
@author: mranjan4
"""
class Car:
def __init__(self, year,make):
self.__year = year
self.__make = make
beetel = Car(2019,"Beetel")
mini = Car(2019,"Mini")
polo = Car(2019,"Polo")
|
f5c23323fe40e33f38335dcb722ee8d539bf974e | konradbondu/CodeWars-solutions | /how_much.py | 1,945 | 3.546875 | 4 | # I always thought that my old friend John was rather richer than he looked, but I never knew exactly how much money
# he actually had. One day (as I was plying him with questions) he said:
#
# "Imagine I have between m and n Zloty..." (or did he say Quetzal? I can't remember!)
# "If I were to buy 9 cars costing c each, I'd only have 1 Zloty (or was it Meticals?) left."
# "And if I were to buy 7 boats at b each, I'd only have 2 Ringglets (or was it Zloty?) left."
# Could you tell me in each possible case:
#
# how much money f he could possibly have ? the cost c of a car? the cost b of a boat? So, I will have a better idea
# about his fortune. Note that if m-n is big enough, you might have a lot of possible answers.
#
# Each answer should be given as ["M: f", "B: b", "C: c"] and all the answers as [ ["M: f", "B: b", "C: c"],
# ... ]. "M" stands for money, "B" for boats, "C" for cars.
#
# Note: m, n, f, b, c are positive integers, where 0 <= m <= n or m >= n >= 0. m and n are inclusive.
#
# Examples:
# howmuch(1, 100) => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"]]
# howmuch(1000, 1100) => [["M: 1045", "B: 149", "C: 116"]]
# howmuch(10000, 9950) => [["M: 9991", "B: 1427", "C: 1110"]]
# howmuch(0, 200) => [["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"], ["M: 163", "B: 23", "C: 18"]]
# Explanation of the results for howmuch(1, 100):
#
# In the first answer his possible fortune is 37:
# so he can buy 7 boats each worth 5: 37 - 7 * 5 = 2
# or he can buy 9 cars worth 4 each: 37 - 9 * 4 = 1
# The second possible answer is 100:
# he can buy 7 boats each worth 14: 100 - 7 * 14 = 2
# or he can buy 9 cars worth 11: 100 - 9 * 11 = 1
def how_much(m, n):
f_min = min(m, n)
f_max = max(m, n)
result = []
for i in range(f_min, f_max + 1):
if i % 7 == 2 and i % 9 == 1:
result.append(["M: " + str(i), "B: " + str(i // 7), "C: " + str(i // 9)])
return result
|
117e070a4bd6a3e92b9637cdbec510465d235b74 | Aasthaengg/IBMdataset | /Python_codes/p02596/s544677997.py | 120 | 3.5625 | 4 | k=int(input())
if k%2==0 or k%5==0:
print(-1)
else:
s=1
a=7
while a%k!=0:
a=(10*a+7)%k
s+=1
print(s)
|
1abf1c5e17e49bcb0413e6f6c11ae4b8a4d94b8c | kvkumar049/test-Repo | /floyds.py | 200 | 3.953125 | 4 | x=input("Enter a NUmber :")
for i in range(1,x+1) :
for j in range(1,i+1) :
print j,
print
for i in range(-1,x):
for j in range(1,x-i-1):
print j,
print
|
25f9c4ed6f273185e4e18f135da3c187099a0ed0 | agrawalshivam66/python | /lab3/q13.py | 427 | 4 | 4 | def raman():
n=eval(input("enter a number "))
for i in range(1,n+1):
for j in range(1,int((i**(1/3)))+1):
for k in range(j,int((i**(1/3)))+1):
if (j**3)+(k**3)==i:
for l in range(j+1,int((i**(1/3)))+1):
for m in range(l,int((i**(1/3)))+1):
if i==(l**3)+(m**3):
print(i)
raman()
|
f816ce5b754f93eb688bc8b695adda84ef47d3d4 | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc068/B/4961106.py | 71 | 3.6875 | 4 | n = int(input())
two = 2
while n >= two:
two = two*2
print(two//2) |
5adf7e8a1e1c58921dd8a2ca0d3d051e6d57b086 | mdopearce/MIT-Intro-Problem-sets | /Problemset 3 complete for MIT intro course to python.py | 1,501 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 23 13:30:09 2019
@author: User-PC
"""
#####
"""
mistaken code piece, could be useful though
"""
def isLetterGuessed1(secretWord, lettersGuessed):
check=0
for range in lettersGuessed:
if range in secretWord==False:
return False
else:
check+=1
return check==len(secretWord)
####
"""
problem 1
"""
def isWordGuessed(secretWord, lettersGuessed):
sword=[]
for letter in secretWord:
sword.append(letter)
for check in lettersGuessed:
while check in sword:
sword.remove(check)
if len(sword)==0:
return True
else:
return False
"""
problem 2
"""
def getGuessedWord(secretWord, lettersGuessed):
sword=[]
printout=[]
for letter in secretWord:
sword.append(letter)
for check in sword:
n=0
for letter in lettersGuessed:
if check==letter:
n+=1
if n>=1:
printout.append(check+' ')
else:
printout.append('_ ')
return ''.join(printout)
"""
Problem 3
"""
def getAvailableLetters(lettersGuessed):
a=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for k in a:
if k in lettersGuessed:
a.remove(k)
return ''.join(a)
"""
Problem 4
"""
|
4a89186f6b3dab8bc854ae66d2890a31e9d46231 | yongseongCho/python_201911 | /day_08/function_04.py | 954 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# return 키워드의 동작 방식
# 1. 함수의 실행을 종료하고, 함수를 호출한 지점으로
# 돌아가는 동작
# (리턴되는 값이 없는 경우)
# 2. return 값 의 형태로 사용되는 경우
# 함수의 실행을 종료하고, 함수를 호출한 지점으로
# 우항의 값을 반환하는 동작
# 반환하는 값이 없이 return을 활용하는 함수
# - 함수의 실행 중 강제로 종료하는 경우에 활용
def printNumber(num) :
# 매개변수의 값이 100보다 작은 경우
# 함수를 실행하지 않고 호출한 지점으로 돌아감
if num <= 100 :
return
print(f'num -> {num}')
# 매개변수의 값이 100보다 작기때문에
# 출력되지 않고 돌아옴
printNumber(90)
# 매개변수의 값이 100보다 크기때문에
# 출력된 후, 돌아옴
printNumber(200)
|
fdcea7416a09419989ceb066cf7348439c1b883b | mrpandrr/My_scripts | /Past Code/16.py | 787 | 4.1875 | 4 | # import turtle module
import turtle as trtl
# create turtle object
painter = trtl.Turtle()
# add code here for a circle
painter.circle(40)
# move the turtle to another part of the screen
painter.penup()
painter.goto(-100,-100)
painter.pendown()
# add code here for an arc
painter.circle(30,180)
# move the turtle to another part of the screen
painter.penup()
painter.goto(190,100)
painter.pendown()
# add code here for an arc that is greater than 90 degrees and has 5 steps
painter.circle(40,120,5)
# move the turtle to another part of the screen
painter.penup()
painter.goto(-100,100)
painter.pendown()
# add code here to create a polygon of your choice using the circle method
painter.circle(30,360,6)
# create screen object and make it persist
wn = trtl.Screen()
wn.mainloop() |
bf3c34c214fe610c3fe5ecb920e4867393d717a2 | pratheeknagaraj/project_euler | /problem124.py | 731 | 3.78125 | 4 | from math import *
import operator
def rad( num ):
product = 1
for i in primesList:
if num == 1:
break
elif num%i == 0:
product *= i
while num%i == 0:
num = int(num/i)
return product
def isPrime( num ):
for i in range( 2, int(sqrt(num)) + 1 ):
if num%i == 0:
return False
return True
primesList = []
for i in range(2, 100001):
if isPrime(i) == True:
primesList.append(i)
totalList = []
totalList.append([1,1])
for i in range(2,100001):
totalList.append( [i, rad(i)] )
totalList = sorted( totalList, key=operator.itemgetter(1) )
print( totalList[10000-1] )
|
189113b53e10bdec35ff0577dd130c1cabb9f779 | Abinmorth/rosalind | /Bioinformatics Stronghold/FIB.py | 365 | 3.78125 | 4 | def rabbits(n, k):
if n == 1:
return (0,1)
elif n == 2:
return (1,0)
else:
(adult1, young1) = rabbits(n-2,k)
(adult2, young2) = rabbits(n-1,k)
adult3 = adult2 + young2
young3 = adult2 * k
return (adult3, young3)
n = 33
k = 3
(adult, young) = rabbits(n,k)
print(adult + young)
|
1a925cf7eeab0e117ebf18868d2437fd43581879 | wusui/pentomino_redux | /tree_utils.py | 1,179 | 3.71875 | 4 | """
Tree utilities
"""
from functools import reduce
def extract_path(node, tree):
"""
Give a node, recursively generate a path of nodes
back to the root of the tree, effectively generating
the figure corresponding to this leaf node.
"""
if node['point'] == [0, 0]:
return []
return [node['point']] + extract_path(tree[node['prev_gen']], tree)
def fig_comp(fig_pts):
"""
Add numbers together to form unique figure number
"""
return reduce(_do_sum, _comp_pow_numb(fig_pts))
def _do_sum(info1, info2):
"""
reduce function used by fig_comp
"""
return info1 + info2
def _comp_pow_numb(fig_pts):
"""
Convert each figure into a number unique for that shape
"""
return map(_math_func, fig_pts)
def _math_func(coord):
"""
Calculate an index based on the distance a square is from 0,0
"""
return _do_func(abs(coord[0]) + abs(coord[1]))(coord)
def _do_func(indx):
"""
Form integer based on base 2 locations of each of the numbers
mapped to a point
"""
def _innerf(coord):
return 2 ** ([0, 0, 2, 6, 12][indx] + indx + coord[1] - 1)
return _innerf
|
c23a5139c62a1614c5ae55608cbebcc8cc18376b | MaryLivingston21/IndividualProject | /Volunteer.py | 1,216 | 3.59375 | 4 | from Walk import WALK
from PlayTime import PLAYTIME
class VOLUNTEER:
s_next_volunteer_number = 0
def __init__(self, name):
self.name = name
VOLUNTEER.s_next_volunteer_number = VOLUNTEER.s_next_volunteer_number + 1
self.volunteer_number = VOLUNTEER.s_next_volunteer_number
self.walks = set()
self.play_times = set()
def to_string(self):
return self.name + ': volunteer number = ' + str(self.volunteer_number) + ' number of walk(s) = ' + \
str(len(self.walks)) + '; number of playtime(s) = ' + \
str(len(self.play_times)) + '\n'
def get_volunteer_number(self):
return self.volunteer_number
def get_name(self):
return self.name
def get_walks(self):
return list(self.walks)
def get_play_times(self):
return list(self.play_times)
def __eq__(self, other):
return self.name == other.name and self.volunteer_number == other.volunteer_number
def __hash__(self):
return hash((self.name, self.volunteer_number))
def walk_animal(self, animal):
self.walks.add(animal)
def play_w_animal(self, animal):
self.play_times.add(animal)
|
c75f7c1452c0967f557e7f2f0023e5c26706f6b0 | ankyy307000/Helloworld | /number.py | 612 | 4.1875 | 4 | a=int(input("Enter your number:"))
if a%2==0 :
print("Your number is even")
else:
print("Your number is odd")
for i in range(2,a):
if(a%i==0):
print("Your number is Not Prime")
break
else:
print("Your number is Prime")
rev=0
x=a
while a>0:
d=a%10
a=a//10
rev=rev*10+d
if x==rev :
print("Your number is pallindrome")
else:
print("Your number is not pallindrome")
arm=0
y=x
while x>0:
d=x%10
x=x//10
arm=arm+(d**3)
if y==arm:
print("Your number is armstrong")
else:
print("Your number is not armstrong") |
4016f28e4874617f759f1a68a0eb26121b851245 | kumar2056/begi | /prime.py | 111 | 3.640625 | 4 | c=int(input())
d=0
for x in range(1,c+1):
if(c%x==0):
d=d+1
if(d==2):
print("yes")
else:
print("no")
|
46c357f97e5859faae15cb1cc71169cb0ac9cf06 | nbrown273/du-python-fundamentals | /modules/module6_json/exercise6.py | 1,791 | 4.0625 | 4 | from json import load
# Example of reading from JSON file
def loadJSON(fileName):
"""
Parameters: fileName -> str
Loads JSON data from a specified file
Returns: dict / Error Message
"""
try:
with open(fileName, "r") as r:
data = load(fp=r)
return data
except FileNotFoundError as err:
return f"Error in loadJSON: { err }"
# Example of recursively finding all keys in a dict
def nestedKeys(dictObj, keys):
# Loop through each key value
for key, val in dictObj.items():
keys.append(key)
# Check for iterable
if(type(val) is list or type(val) is tuple):
for item in val:
# Find nested keys
if(type(item) is dict):
nestedKeys(dictObj=item, keys=keys)
# Find nested keys
if(type(val) is dict):
nestedKeys(dictObj=val, keys=keys)
################################################################################
"""
TODO: Write a function that follows the criteria listed below
The purpose of this function is to loop through list of page objects in the
"wiki.json" file and find the count of given substrings on each page
* Function should take in a parameter "substrings", where substring
is a list of strings
* Function should return a dict object, mapping the page titles
to a dict, mapping the given substrings counts on the page
Example
* Inputs: substrings=["a", "b"]
* Returns: {'Pear': {'a': 1394, 'b': 232},
'Apple': {'a': 4239, 'b': 848},
'Banana': {'a': 8626, 'b': 1671},
'Pumpkin': {'a': 2094, 'b': 415},
'Pitaya': {'a': 923, 'b': 148}}
"""
|
1fb2d7ac1bffe76e5c31c6bf23a2d22c9e612cda | 2648226350/Python_learn | /pych-eleven/pych-test/test.survey.py | 691 | 3.671875 | 4 | import unittest
from survey import AnonymousSurvey
class TestAnonymouSurvey(unittest.TestCase):
def setUp(self):
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English','Chinese','Franch']
def test_store_single_response(self):
self.my_survey.store_responses('English')
self.assertIn('English',self.my_survey.responses)
def test_store_three_responses(self):
for response in self.responses:
self.my_survey.store_responses(response)
for response in self.responses:
self.assertIn(response,self.my_survey.responses)
unittest.main()
|
b6b30b578a47ff0594cdec2577b820c132265d3e | Slendercoder/LCC-ejemplo | /Tableaux-solo.py | 9,601 | 3.921875 | 4 | #-*-coding: utf-8-*-
##############################################################################
# Definicion de objeto tree y funciones
##############################################################################
class Tree(object):
def __init__(self, label, left, right):
self.left = left
self.right = right
self.label = label
def Inorder(f):
# Imprime una formula como cadena dada una formula como arbol
# Input: tree, que es una formula de logica proposicional
# Output: string de la formula
if f.right == None:
return f.label
elif f.label == '-':
return f.label + Inorder(f.right)
else:
return "(" + Inorder(f.left) + f.label + Inorder(f.right) + ")"
def StringtoTree(A, letrasProposicionales):
# Crea una formula como tree dada una formula como cadena escrita en notacion polaca inversa
# Input: A, lista de caracteres con una formula escrita en notacion polaca inversa
# letrasProposicionales, lista de letras proposicionales
# Output: formula como tree
conectivos = ['O', 'Y', '>']
pila = []
for c in A:
if c in letrasProposicionales:
pila.append(Tree(c, None, None))
elif c == '-':
formulaAux = Tree(c, None, pila[-1])
del pila[-1]
pila.append(formulaAux)
elif c in conectivos:
formulaAux = Tree(c, pila[-1], pila[-2])
del pila[-1]
del pila[-1]
pila.append(formulaAux)
return pila[-1]
def imprime_tableau(tableau):
cadena = '['
for l in tableau:
cadena += "{"
primero = True
for f in l:
if primero == True:
primero = False
else:
cadena += ", "
cadena += Inorder(f)
cadena += "}"
return cadena + "]"
def imprime_hoja(H):
cadena = "{"
primero = True
for f in H:
if primero == True:
primero = False
else:
cadena += ", "
cadena += Inorder(f)
return cadena + "}"
def obtiene_literales(cadena, letrasProposicionales):
literales = []
contador = 0
while contador < len(cadena):
if cadena[contador] == '-':
l = cadena[contador] + cadena[contador+1]
literales.append(l)
contador += 1
elif cadena[contador] in letrasProposicionales:
l = cadena[contador]
literales.append(l)
contador += 1
return literales
def Tableaux(lista_hojas, letrasProposicionales):
# Algoritmo de creacion de tableau a partir de lista_hojas
# Imput: - lista_hojas: lista de lista de formulas
# (una hoja es una lista de formulas)
# - letrasProposicionales: lista de letras proposicionales del lenguaje
# Output: - String: Satisfacible/Insatisfacible
# - interpretaciones: lista de listas de literales que hacen verdadera
# la lista_hojas
print "Trabajando con: ", imprime_tableau(lista_hojas)
marcas = ['x', 'o']
interpretaciones = [] # Lista para guardar interpretaciones que satisfacen la raiz
while any(x not in marcas for x in lista_hojas): # Verifica si hay hojas no marcadas
# Hay hojas sin marcar
# Crea la lista de hojas sin marcar
hojas_no_marcadas = [x for x in lista_hojas if x not in marcas]
print u"Cantidad de hojas sin marcar: ", len(hojas_no_marcadas)
# Selecciona una hoja no marcada
hoja = choice(hojas_no_marcadas)
print "Trabajando con hoja: ", imprime_hoja(hoja)
# Busca formulas que no son literales
formulas_no_literales = []
for x in hoja:
if x.label not in letrasProposicionales:
if x.label != '-':
# print Inorder(x) + " no es un literal"
formulas_no_literales.append(x)
break
elif x.right.label not in letrasProposicionales:
# print Inorder(x) + " no es un literal"
formulas_no_literales.append(x)
break
# print "Formulas que no son literales: ", imprime_hoja(formulas_no_literales)
if formulas_no_literales != []: # Verifica si hay formulas que no son literales
# Hay formulas que no son literales
print "Hay formulas que no son literales"
# Selecciona una formula no literal
f = choice(formulas_no_literales)
if f.label == 'Y':
# print u"Fórmula 2alfa" # Identifica la formula como A1 y A2
hoja.remove(f) # Quita a f de la hoja
A1 = f.left
if A1 not in hoja:
hoja.append(A1) # Agrega A1
A2 = f.right
if A2 not in hoja:
hoja.append(A2) # Agrega A2
elif f.label == 'O':
# print u"Fórmula 2beta" # Identifica la formula como B1 o B2
hoja.remove(f) # Quita la formula de la hoja
lista_hojas.remove(hoja) # Quita la hoja de la lista de hojas
B1 = f.left
if B1 not in hoja:
S1 = [x for x in hoja] + [B1] # Crea nueva hoja con B1
lista_hojas.append(S1) # Agrega nueva hoja con B1
B2 = f.right
if B2 not in hoja:
S2 = [x for x in hoja] + [B2] # Crea nueva hoja con B2
lista_hojas.append(S2) # Agrega nueva hoja con B2
elif f.label == '>':
# print u"Fórmula 3beta" # Identifica la formula como B1 > B2
hoja.remove(f) # Quita la formula de la hoja
lista_hojas.remove(hoja) # Quita la hoja de la lista de hojas
noB1 = Tree('-', None, f.left)
if noB1 not in hoja:
S1 = [x for x in hoja] + [noB1] # Crea nueva hoja con no B1
lista_hojas.append(S1) # Agrega nueva hoja con no B1
B2 = f.right
if B2 not in hoja:
S2 = [x for x in hoja] + [B2] # Crea nueva hoja con B2
lista_hojas.append(S2) # Agrega nueva hoja con B2
elif f.label == '-':
if f.right.label == '-':
# print u"Fórmula 1alfa" # Identifica la formula como no no A1
hoja.remove(f) # Quita a f de la hoja
A1 = f.right.right
if A1 not in hoja:
hoja.append(A1) # Agrega la formula sin doble negacion
elif f.right.label == 'O':
# print u"Fórmula 3alfa" # Identifica la formula como no(A1 o A2)
hoja.remove(f) # Quita a f de la hoja
noA1 = Tree('-', None, f.right.left)
if noA1 not in hoja:
hoja.append(noA1) # Agrega no A1
noA2 = Tree('-', None, f.right.right)
if noA2 not in hoja:
hoja.append(noA2) # Agrega no A2
elif f.right.label == '>':
# print u"Fórmula 4alfa" # Identifica la formula como no(A1 > A2)
hoja.remove(f) # Quita a f de la hoja
A1 = f.right.left
if A1 not in hoja:
hoja.append(A1) # Agrega A1
noA2 = Tree('-', None, f.right.left)
if noA2 not in hoja:
hoja.append(noA2) # Agrega no A2
elif f.right.label == 'Y':
# print u"Fórmula 1beta" # Identifica la formula como no(B1 y B2)
hoja.remove(f) # Quita la formula de la hoja
lista_hojas.remove(hoja) # Quita la hoja de la lista de hojas
noB1 = Tree('-', None, f.right.left)
if noB1 not in hoja:
S1 = [x for x in hoja] + [noB1] # Crea nueva hoja con no B1
lista_hojas.append(S1) # Agrega nueva hoja con no B2
noB2 = Tree('-', None, f.right.right)
if noB2 not in hoja:
S2 = [x for x in hoja] + noB2 # Crea nueva hoja con no B2
lista_hojas.append(S2) # Agrega nueva hoja con no B2
else: # No hay formulas que no sean literales
# print "La hoja contiene solo literales!"
lista = list(imprime_hoja(hoja))
# print lista
literales = obtiene_literales(lista, letrasProposicionales)
# print literales
hojaConsistente = True
for l in literales: # Verificamos que no hayan pares complementarios en la hoja
if '-' not in l: # Verifica si el literal es positivo
if '-' + l in literales: # Verifica si el complementario esta en la hoja
print "La hoja " + imprime_hoja(hoja) + " es inconsistente!"
lista_hojas.remove(hoja)
# lista_hojas.append('x') # Marca la hoja como inconsistente con una 'x'
hojaConsistente = False
break
elif l[1:] in literales: # Verifica si el complementario esta en la hoja
print "La hoja " + imprime_hoja(hoja) + " es inconsistente!"
lista_hojas.remove(hoja)
# lista_hojas.append('x') # Marca la hoja como inconsistente con una 'x'
hojaConsistente = False
break
if hojaConsistente: # Se recorrieron todos los literales y no esta el complementario
print "La hoja " + imprime_hoja(hoja) + " es consistente :)"
interpretaciones.append(hoja) # Guarda la interpretacion que satisface la raiz
lista_hojas.remove(hoja)
# lista_hojas.append('o') # Marca la hoja como consistente con una 'o'
# Dice si la raiz es inconsistente
print "Hay " + str(len(interpretaciones)) + u" interpretaciones que satisfacen la fórmula"
if len(interpretaciones) > 0:
print u"La fórmula es satisfacible por las siguientes interpretaciones: "
# Interpreta como string la lista de interpretaciones
INTS = []
for i in interpretaciones:
aux = [Inorder(l) for l in i]
INTS.append(aux)
print aux
return "Satisfacible", INTS
else:
print(u"La lista de fórmulas dada es insatisfacible!")
return "Insatisfacible", None
##############################################################################
# Fin definicion de objeto tree y funciones
##############################################################################
from random import choice
# Crea letras proposicionales
letrasProposicionales = ['p', 'q']
# Crea formula de prueba
cadena = 'p-pO-'
A = StringtoTree(cadena, letrasProposicionales)
print Inorder(A)
# Las hojas son conjuntos de formulas o marcas 'x' o 'o'
lista_hojas = [[A]] # Inicializa la lista de hojas
print(Tableaux(lista_hojas, letrasProposicionales))
|
410a3a43c8f27eb419408475ada71bbdcf8b5ed4 | colinkelleher/Python | /File_Search/File_Contents_Search.py | 1,369 | 4.28125 | 4 | '''
Write a function definition for the following function and then invoke the function to test it
works. The function search_file(filename, searchword) should accept a
filename (a file fields.txt has been provided) and a user specified search
word. It searches every line in the file for an occurrence of the word and if it exists it prints
out the line preceded by the line number. Importantly it also writes the same output out to a
file called 'Inputfile'Modified.txt. This examines iteration, string examination,
accumulators, files and functions. Example test case below:
search_file("Fields-of-Athenry", "watched") ==>
9 - Where once we watched the small free birds fly.
21 - Where once we watched the small free birds fly.
26 - She watched the last star falling
33 - Where once we watched the small free birds fly.
'''
def search_file():
x = input("Please enter the '.txt' filename excluding extension>>>")
y = x + '.txt'
search_file = open(y,'r')
search_file1=open( x +'modified.txt','w')
line_num = 0
search_phrase = input("Please enter your keyword:")
for line in search_file.readlines():
line_num += 1
if line.find(search_phrase) >= 0:
print("%s - %s"%(line_num,line))
search_file1.writelines("%s - %s"%(line_num,line))
print("Result written out to",x+"modified.txt")
search_file()
|
10d5d4d2d85a39db74fdcbe7d7280029fbcb2a19 | imriven/coding_challenges | /sort_descending.py | 300 | 3.65625 | 4 | # https: // edabit.com/challenge/yaXQvCzAXJLe37Qie
def sort_descending(num):
num_array = []
for i in str(num):
num_array.append(i)
num_array.sort(reverse=True)
return int("".join(num_array))
print(sort_descending(123))
print(sort_descending(1254859723))
print(sort_descending(73065))
|
2650cfb2ba052748824e2d65eaf2850845d99540 | chicochico/exercism | /python/twelve-days/twelve_days.py | 987 | 3.515625 | 4 | DAYS = [
'first',
'second',
'third',
'fourth',
'fifth',
'sixth',
'seventh',
'eighth',
'ninth',
'tenth',
'eleventh',
'twelfth',
]
PRESENTS = [
'a Partridge in a Pear Tree',
'two Turtle Doves',
'three French Hens',
'four Calling Birds',
'five Gold Rings',
'six Geese-a-Laying',
'seven Swans-a-Swimming',
'eight Maids-a-Milking',
'nine Ladies Dancing',
'ten Lords-a-Leaping',
'eleven Pipers Piping',
'twelve Drummers Drumming'
]
def verse(day_number):
first_verse = f'On the {DAYS[day_number-1]} day of Christmas my true love gave to me'
presents = [PRESENTS[n] for n in range(day_number-1, 0, -1)]
first_present = f'and {PRESENTS[0]}' if day_number > 1 else PRESENTS[0]
return ', '.join([first_verse, *presents, first_present]) + '.\n'
def verses(start, end):
return '\n'.join([verse(day) for day in range(start, end+1)]) + '\n'
def sing():
return verses(1, 12)
|
64a2de3909c7e56497af0110802e3c33a8cd0781 | jayc0b0/Projects | /Python/Security/caesarCypher.py | 1,540 | 3.890625 | 4 | # Jacob Orner (jayc0b0)
# Caesar Cypher script
def main():
# Declare variables and take input
global alphabet
alphabet = ['a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x',
'y', 'z']
global messageArray
messageArray = []
choice = int(input("Enter 1 to encode. 2 to decode.\n>> "))
if choice == 1:
encode()
elif choice == 2:
pass # Implement decode() and add here
else:
print "Invalid choice"
main()
def encode():
message = raw_input("Enter a string to encode (letters only):\n>> ")
cypherShift = int(input("Enter an integer from 1-25 for the shift:\n>> "))
# Verify input
if not message.isalpha():
print "Please enter only letters into your message."
main()
else:
pass
if cypherShift < 1 or cypherShift > 25:
print "Invalid number. Please enter a valid shift value."
main()
else:
pass
# Break string into an array of letters and shift
messageArray = list(message)
for letter in messageArray:
if alphabet.index(letter) + cypherShift < 25:
messageArray[letter] = alphabet[alphabet.index(letter) + cypherShift]
else:
letter = alphabet[(alphabet.index(letter) + cypherShift) % 25]
# Output cyphered text
message = " ".join(messageArray)
print "Your cyphered message is:"
print message
main()
|
72db825341b95819cb5fd6171b4eb2bda4580079 | mpott2300/Rock-Paper-Scissors | /rps.py | 4,949 | 4.09375 | 4 | #!/usr/bin/env python3
# This program plays a game of Rock, Paper, Scissors between two Players,
# and reports both Player's scores each round."""
# The Player class is selected at random for the computer.
# Select the number of rounds and enjoy.
import random
moves = ['rock', 'paper', 'scissors']
class Player:
def __init__(self):
self.score = 0
def move(self):
return moves[0]
def learn(self, my_move, their_move):
pass
class RandomPlayer(Player):
def move(self):
return random.choice(moves)
class ReflectPlayer(Player):
def __init__(self):
Player.__init__(self)
self.move_temp = "rock"
def move(self):
return self.move_temp
def learn(self, my_move, their_move):
self.move_temp = their_move
class CyclePlayer(Player):
def __init__(self):
Player.__init__(self)
self.step = 0
def move(self):
throw = None
if self.step == 0:
throw = moves[1]
self.step = self.step + 1
elif self.step == 1:
throw = moves[2]
self.step = self.step + 1
else:
throw = moves[0]
self.step = self.step + 1
return throw
class HumanPlayer(Player):
def move(self):
throw = input('rock, paper, scissors: ')
while throw != 'rock' and throw != 'paper' and throw != 'scissors':
print('Throw again')
throw = input('rock, paper, scissors: ')
return throw
def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
# Game mechanics
class Game:
p1_score = 0
p2_score = 0
def __init__(self, p2):
self.p1 = HumanPlayer()
self.p2 = p2
def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
print(f"Player 1: {move1} <> Player 2: {move2}")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
if beats(move1, move2):
self.p1_score += 1
print('* Player 1 wins! *')
else:
if move1 == move2:
print('* Tie *')
else:
self.p2_score += 1
print('* Player 2 wins! *')
print(f"Player:{self.p1.__class__.__name__}, Score:{self.p1_score}")
print(f"Player:{self.p2.__class__.__name__}, Score:{self.p2_score}")
# This will call a tourney
def play_game(self):
print("Game Start!")
for round in range(3):
print(f"Round {round}:")
self.play_round()
if self.p1_score > self.p2_score:
print('** Congrats! Player 1 WINS! **')
elif self.p2_score > self.p1_score:
print('** Sadly Player 2 WINS! **')
else:
print('** The match was a tie! **')
print('The final score is: ' + str(self.p1_score) + ' TO ' +
str(self.p2_score))
print("Game over!")
# This will call a singe game.
def play_single(self):
print("Single Game Start!")
print(f"Round 1 of 1:")
self.play_round()
if self.p1_score > self.p2_score:
print('** Congrats! Player 1 WINS! **')
elif self.p1_score < self.p2_score:
print('** Sadly Player 2 WINS! **')
else:
print('** The game was a tie! **')
print('The final score: ' + str(self.p1_score) + ' TO ' +
str(self.p2_score))
if __name__ == '__main__':
p2 = {
"1": Player(),
"2": RandomPlayer(),
"3": CyclePlayer(),
"4": ReflectPlayer()
}
# Selecting Opponent
while True:
try:
p2 = int(input("Select the strategy "
"you want to play against: "
"1 - Rock Player "
"2 - Random Player "
"3 - Cycle Player "
"4 - Reflect Player: "))
# input("Select strategy: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if p2 > 4:
print("Sorry, you must select [1-4]: ")
continue
else:
break
# Slecting 1 or 3 games
rounds = input('Enter for [s]ingle game or [f]ull game: ')
Game = Game(p2)
while True:
if rounds == 's':
Game.play_single()
break
elif rounds == 'f':
Game.play_game()
break
else:
print('Please select again')
rounds = input('Enter [s] for a single'
'game and [f] for a full game: ')
|
65b28fe26d2e876ba4bbc59247e68174ab1b702e | yooncheawon-1234/test-repo | /연습문제4장_2.py | 1,300 | 3.796875 | 4 | #1
def is_odd():
if num%2==1:
return 'odd'
else:
return 'not odd'
#2
def ave(s):
sMean=sum(s)/len(s)
print('평균:', sMean)
print(ave([1,2,3]))
#3
input1 = int(input("첫번째 숫자를 입력하세요:"))
input2 = int(input("두번째 숫자를 입력하세요:"))
total = input1 + input2
print("두 수의 합은 %s 입니다" % total)
#4
print('정답은 3번 이유는 +가 아닌 ,로 연결되면 띄어쓰기가 적용됨')
#5
f1 = open("test.txt", 'w') #write 버전으로 파일열기
f1.write("Life is too short!") #그 파일에 뭐라고 쓸지 적어줌
f1.close() #파일 다시 닫아줌
f2 = open("test.txt", 'r') # read 버전으로 파일열기
print(f2.read()) #f2의 내용 전체 읽기
f2.close() #파일닫기
#6
user_input = input("저장할 내용을 입력하세요:") # 새로운 객체에 질문 input해주기
f = open('test.txt', 'a') #append버전으로 파일열기
f.write(user_input) #아까 인풋받은 내용을 파일에 추가하기
f.write("\n") # 인풋받은 내용을 추가할 때 줄바꾸기
#7
f = open('test.txt', 'r')
body = f.read() #새로운 객체에 파일 전체 읽히기
f.close()
body = body.replace('java', 'python')
f = open('test.txt', 'w')
f.write(body)
f.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.