blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
863b67f297862f0f51ed0065fff66861e79684dc | rcarrasco3652/PythonParaPrincipiantes | /tiposVariables.py | 1,090 | 4.1875 | 4 | #Variables
#Una variable es un nombre simbolico para un valor
nombre = "Roberto Carrasco" #Forma mas comun de declarar una varibale
book = "Libro genial"
print(nombre)
#En una variable puedes guardar cualquier tipo de datos
nombre2, numBook = "Rosa Jaramillo", 19 #Otra manera de declarar variables
print(nombre2, numBook) #Los valores se imprimen juntos pero es una manera de imprimirlos
#Convecciones
#se les llama asi por que los programadores eligen su propia manera de declarar sus variables
#o incluso a veces la misma empresa lo elige, y declarar tus variables de alguna de estas maneras
#entra dentro de las buenas practicas
nombre_completo = "Faustino Medina" #snake_case
nombreCompleto = "Citlallic Sotomayor" #camelCase
NombreCompleto = "Juan Perez" #PascalCase
#Sabias que: Los lenguajes de programacion tienen una caracteristica llamada case sensitive.
#Case sensitive ayuda al lenguaje de programacion a distinguir entre letras mayusculas y minusculas
#es decir: que no es lo mismo una variable llamada Hola con mayuscula que una variable llamada hola
#con minuscula al inicio. |
6299ae3438ab1ff9c2ca1831ad9aa9d762371c1e | EstherOA/PythonNDataScience | /files/q1.py | 387 | 3.6875 | 4 |
user_in = input('Enter some text and END to quit:')
try:
f = open('userInput.txt', 'a')
while user_in != 'END':
f.write(user_in + '\n')
user_in = input('Enter some text and END to quit:')
finally:
f.close()
try:
fr = open('userInput.txt', 'r')
i = 0
for line in fr:
print(i, ":", line, end='')
i += 1
finally:
f.close()
|
060e6f73a5fe3c47bf19284bad2a664f216e5a7a | aroraakshit/coding_prep | /reverse_words_string_2.py | 924 | 3.515625 | 4 | class Solution: # 228ms
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if s == [] or ' ' not in s:
return
for j in range(len(s)//2):
s[j], s[len(s)-j-1] = s[len(s)-j-1], s[j]
prev = 0
for i in range(len(s)):
if s[i] == " ":
for k in range(prev, prev+(i-prev)//2):
s[k], s[prev+i-k-1] = s[prev+i-k-1], s[k]
prev = i + 1
i += 1
for k in range(prev, prev+(i-prev)//2):
s[k], s[prev+i-k-1] = s[prev+i-k-1], s[k]
class Solution: # 188ms, in-place, Credits - LeetCode
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
rev_word = "".join(s).split(" ")[::-1]
s[:]= list(" ".join(rev_word)) |
4e78bb6e62beeeda164c6d1a9df12951485beca0 | krsatyam20/pythonApr | /FirstDayQ2.py | 499 | 3.78125 | 4 | a=input ("Roll No.")
b= raw_input ("Student Name")
c=input ("Marks in Maths")
d=input ("Marks in Science")
e=input ("Marks in English")
f=input ("Marks in Hindi")
g=input ("Marks in SST")
print ("==================")
print ("Roll No %d"%(a))
print ("Roll No %s"%(b))
print ("Roll No %d"%(c))
print ("Roll No %d"%(d))
print ("Roll No %d"%(e))
print ("Roll No %d"%(f))
print ("Roll No %d"%(g))
h=(c+d+e+f+g)
print ("Total Marks %d"%(h))
i=(h/5)
print ("Average Marks %d"%(i))
|
c8f1c4ef75718a50296f6d7ea7b0b3779e8a6a20 | arshadumrethi/Python_practice | /list_comprehension.py | 1,272 | 4.71875 | 5 | #List Comprehension syntax is used to build lists easily
#Example 1
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print even_squares
#Example 2
cubes_by_four = [x ** 3 for x in range(1, 11) if (x ** 3) % 4 == 0]
print cubes_by_four
#Example 3
threes_and_fives = [x for x in range(1, 16) if x % 3 == 0 or x % 5 == 0]
print threes_and_fives
#List Slicing is used if only want part of the list
#List Slicing Syntax [start:end:stride]
#Example
l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print l[2:9:2]
# Omitting Indices
# If you don't pass a particular index to the list slice,
# Python will pick a default.
to_five = ['A', 'B', 'C', 'D', 'E']
print to_five[3:]
# prints ['D', 'E']
print to_five[:2]
# prints ['A', 'B']
print to_five[::2]
# prints ['A', 'C', 'E']
my_list = range(1, 11) # List of numbers 1 - 10
print my_list[::2]
#A negative stride progresses through the list from right to left.
letters = ['A', 'B', 'C', 'D', 'E']
print letters[::-1]
backwards = my_list[::-1]
print backwards
to_one_hundred = range(101)
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens
#Another Example
garbled = "!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI"
message = garbled[::-2]
print message
|
d9fa529280e41fe064c7df4f58abd41e93ba325a | lostsquirrel/python_test | /checkio/elementary/pangram.py | 1,962 | 4 | 4 | # -*- coding:utf-8 -*-
'''
Created on 2015-03-17
@author: lisong
pangram:字母表所有的字母都出现(最好只出现一次)的句子
A pangram (Greek:παν γράμμα, pan gramma,
"every letter") or holoalphabetic sentence for a given
alphabet is a sentence using every letter of the alphabet
at least once. Perhaps you are familiar with the well
known pangram "The quick brown fox jumps over the lazy dog".
For this mission, we will use the latin alphabet (A-Z).
You are given a text with latin letters and punctuation symbols.
You need to check if the sentence is a pangram or not. Case does not matter.
Input: A text as a string.
Output: Whether the sentence is a pangram or not as a boolean.
Example:
check_pangram("The quick brown fox jumps over the lazy dog.") == True
check_pangram("ABCDEF.") == False
1
2
How it is used: Pangrams have been used to display typefaces,
test equipment, and develop skills in handwriting, calligraphy, and keyboarding for ages.
Precondition:
all(ch in (string.punctuation + string.ascii_letters + " ") for ch in text)
0 < len(text)
'''
def check_pangram(text):
show_letter = list()
res = False
for letter in text:
if letter.isalpha():
letter = letter.lower()
if not(letter in show_letter):
show_letter.append(letter)
if len(show_letter) == 26:
res = True
# print show_letter, res
return res
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert check_pangram("The quick brown fox jumps over the lazy dog."), "brown fox"
assert not check_pangram("ABCDEF"), "ABC"
assert check_pangram("Bored? Craving a pub quiz fix? Why, just come to the Royal Oak!"), "Bored?"
'''
from string import ascii_lowercase
def check_pangram(text):
return set(ascii_lowercase).issubset(set(text.lower()))
''' |
693e69f8d1d1414147c30b6e738b70993ced0c87 | Klaus-Analyst/Python-Programs | /SQLITE3/002.py | 392 | 3.953125 | 4 | import sqlite3 as sql
conn=sql.connect("PWG.sqlite3")
curs=conn.cursor()
idno=int(input("Enter id no"))
name=input("Enter name")
salary=float(input("Enter the salary"))
try:
curs.execute("insert into employee values(?,?,?)",(idno,name,salary))
conn.commit()
print("Data Stored Successfully")
except sql.IntegrityError:
print("Data already Exists")
conn.close()
print("Thanks") |
6265ba1033c3c6b6aacf6f0b9c90fef1eaef6242 | prateek1404/AlgoPractice | /Strings/allspace.py | 192 | 3.796875 | 4 | def allspace(word,i):
if i==len(word)-1:
print word
return
aword = word[:i+1]+" "+word[i+1:]
allspace(aword,i+2)
allspace(word,i+1)
word = raw_input()
allspace(word,0)
|
07b66aa28faa4c26de29487e2e8cc5e1476779ca | dan-mcm/python-practicals | /P14/p14p4.py | 753 | 4.09375 | 4 | # Psuedocode
# for number in range (2,20)
# let the variable x = 1 // this will act as a semaphore
# for i in range (2,number):
# if number has no remainder:
# print number equal to number 1 by number 2
# let x = 0 //switch semaphore state - forces program to run though entire range first.
# else
# if semaphore value is 1...
# print its a prime number
#
# print finished at end of program.
#
for number in range (2,20):
x = 1
for i in range (2,number):
if number %i == 0:
print(number, 'equals', i, '*', number//i)
x = 0
else:
if x == 1:
print(number, 'is a prime number')
print ('Finished!')
|
e2600edcdf2213c3495a2b63148c339fbcfec8eb | mihailruskevich/rosalind | /bioinformatics_stronghold/signed_permutation/permutations.py | 935 | 3.578125 | 4 | def permutations(a, index, res):
if index < len(a):
i = index
while i < len(a):
b = a.copy()
b[index], b[i] = b[i], b[index]
i = i + 1
permutations(b, index + 1, res)
else:
res.append(a)
def signed_combinations(p, index, res):
if index < len(p):
k = p.copy()
k[index] *= -1
signed_combinations(p, index + 1, res)
signed_combinations(k, index + 1, res)
else:
res.append(p)
def signed_permutations(n):
values = list(range(1, n + 1))
res = []
permutations(values, 0, res)
total = []
for p in res:
signed_p = []
signed_combinations(p, 0, signed_p)
total.extend(signed_p)
return total
def print_result(values):
print(len(values))
for v in values:
print(*v)
length = 5
signed_values = signed_permutations(length)
print_result(signed_values)
|
2096b01a725336df0eb8a8fd54ca2e124f5f480d | rublaman/Python-Course | /exercices/ej62.py | 211 | 3.84375 | 4 |
# Crea un programa que imprima "Hola". Cada iteración va a aumentar
# en un segundo el tiempo de espera para volver a imprimir
import time
i = 2
while 1 < 2:
print("Hola")
time.sleep(i)
i += 1
|
43a95259a2cf5e5e7bd87da80875f3dc87f1658e | chanheum/Practice-Python- | /자료구조/해시테이블/close_hash.py | 2,080 | 3.640625 | 4 | # close hashing
class CloseHash:
def __init__(self, table_size):
self.size = table_size
self.hash_table = [0 for a in range(self.size)]
def getKey(self, data):
self.key = ord(data[0])
return self.key
def hashFunction(self, key):
return key % self.size
def getAddress(self, key):
myKey = self.getKey(key)
hash_address = self.hashFunction(myKey)
return hash_address
def save(self, key, value):
hash_address = self.getAddress(key)
if self.hash_table[hash_address] != 0:
for a in range(hash_address, len(self.hash_table)):
# 특정 addr에 데이터가 들어가 있지 않으면
if self.hash_table[a] == 0:
self.hash_table[a] = [key, value]
return
# 같은 key값을 가진거라면 덮어쓴다
elif self.hash_table[a][0] == key:
self.hash_table[a][1] = value
return
return None
else:
self.hash_table[hash_address] = [key, value]
def read(self, key):
hash_address = self.getAddress(key)
for a in range(hash_address, len(self.hash_table)):
if self.hash_table[a][0] == key:
return self.hash_table[a][1]
return None
def delete(self, key):
hash_address = self.getAddress(key)
for a in range(hash_address, len(self.hash_table)):
if self.hash_table[a] == 0:
continue
if self.hash_table[a][0] == key:
self.hash_table[a] = 0
return
return False
# Test Code
h_table = CloseHash(8)
data1 = 'aa'
data2 = 'ad'
print(ord(data1[0]), ord(data2[0]), "← 같은 addr를 지칭하고 있음")
h_table.save('aa', '3333')
h_table.save('ad', '9999')
h_table.save('aa', '1777')
h_table.save('af', '888')
print(h_table.hash_table)
h_table.read('ad')
h_table.delete('aa')
print(h_table.hash_table)
h_table.delete('ad')
print(h_table.hash_table)
|
f9032cbdb7f46eeb5f9a1eb2b8417c76f6e5eb73 | THUZLB/leetcode_python | /048_Retate_Image.py | 889 | 3.875 | 4 | # -*- coding: utf-8 -*-
# author: THUZLB
# GitHub: https://github.com/THUZLB
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n):
for j in range(i+1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in range(n):
l = 0
r = n-1
while l < r:
matrix[i][l], matrix[i][r] = matrix[i][r], matrix[i][l]
l += 1
r -= 1
# 此解法空间复杂度非O(1)
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
matrix[::] = zip(*matrix[::-1]) |
6a29d30ce126ffbae27a3e6e74b5538e614ba589 | JustinLee32/cai_niao_shua_ti | /按题号/1161 最大层内元素和.py | 1,822 | 3.625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
from collections import defaultdict
self.level_sum_dict = defaultdict(int)
ans = 1
def _recursion(father: TreeNode, level: int):
if not father:
return
else:
self.level_sum_dict[level] += father.val
_recursion(father.left, level + 1)
_recursion(father.right, level + 1)
_recursion(root, 1)
temp = self.level_sum_dict[1]
for key, value in self.level_sum_dict.items():
if value > temp:
ans = key
temp = value
return ans
def stringToTreeNode(input):
input = input.strip()
input = input[1:-1]
if not input:
return None
inputValues = [s.strip() for s in input.split(',')]
root = TreeNode(int(inputValues[0]))
nodeQueue = [root]
front = 0
index = 1
while index < len(inputValues):
node = nodeQueue[front]
front = front + 1
item = inputValues[index]
index = index + 1
if item != "null":
leftNumber = int(item)
node.left = TreeNode(leftNumber)
nodeQueue.append(node.left)
if index >= len(inputValues):
break
item = inputValues[index]
index = index + 1
if item != "null":
rightNumber = int(item)
node.right = TreeNode(rightNumber)
nodeQueue.append(node.right)
return root
if __name__ == '__main__':
s = input()
root = stringToTreeNode(s)
sol = Solution()
print(sol.maxLevelSum(root))
|
7c2e45ec864f2257bc40f34c1b51d996991fa025 | PengZhang2018/LeetCode | /algorithms/python/BinaryTreePreorderTraversal/BinaryTreePreorderTraversal.py | 920 | 3.9375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# recursive
class Solution1:
def preorderTraversal(self, root: TreeNode):
if not root:
return []
result = []
result.append(root.val)
result += self.preorderTraversal(root.left)
result += self.preorderTraversal(root.right)
return result
# iteration
class Solution2:
def preorderTraversal(self, root: TreeNode):
current = root
stack = []
result = []
while True:
if current is not None:
result.append(current.val)
stack.append(current.right)
current = current.left
elif len(stack):
current = stack.pop()
else:
break
return result |
13abb7c305e92b959ca13470cf65630a28240c2a | georgegoglodze/python | /stock_trading/get_monthly_data.py | 406 | 3.515625 | 4 | import sqlite3
# Function to get stock trading data
def get_monthly_data(month):
connection = sqlite3.connect("stock.db")
cursor = connection.cursor()
#cursor.execute("SELECT * FROM stock")
#cursor.execute("select * from stock where trade_date < date('now','-0 days')")
cursor.execute(f"SELECT * FROM stocks WHERE strftime('%m', trade_date) = '{month}'")
return cursor.fetchall()
|
c4ff84c39a7a1aab9cb70411f497b2e68eac4886 | acehu970601/Motors-Temperature-Prediction | /src/util.py | 2,172 | 3.703125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def add_intercept(x):
"""Add intercept to matrix x.
Args:
x: 2D NumPy array.
Returns:
New matrix same as x with 1's in the 0th column.
"""
new_x = np.zeros((x.shape[0], x.shape[1] + 1), dtype=x.dtype)
new_x[:, 0] = 1
new_x[:, 1:] = x
return new_x
def load_dataset(csv_path, input_col, label_col):
"""Load dataset from a CSV file.
Args:
csv_path: Path to CSV file containing dataset.
label_col: Name of column to use as labels (should be 'y' or 't').
add_intercept: Add an intercept entry to x-values.
Returns:
xs: Numpy array of x-values (inputs).
ys: Numpy array of y-values (labels).
"""
# Load headers
with open(csv_path, 'r') as csv_fh:
headers = csv_fh.readline().strip().split(',')
# Load features and labels
x_cols = [i for i in range(len(headers)) if headers[i] in input_col]
l_cols = [i for i in range(len(headers)) if headers[i] in label_col]
inputs = np.loadtxt(csv_path, delimiter=',', skiprows=1, usecols=x_cols)
labels = np.loadtxt(csv_path, delimiter=',', skiprows=1, usecols=l_cols)
if inputs.ndim == 1:
inputs = np.expand_dims(inputs, -1)
return inputs, labels
def plot(x, y, theta, x_name, y_name, save_path):
"""Plot dataset and fitted logistic regression parameters.
Args:
x: Matrix of training examples, one per row.
y: Vector of labels in {0, 1}.
theta: Vector of parameters for logistic regression model.
save_path: Path to save the plot.
correction: Correction factor to apply, if any.
"""
# Plot dataset
plt.figure()
plt.plot(x, y, 'go', linewidth=0.5)
# Plot fitting line
x_min = min(x)
x_max = max(x)
y_min = min(y)
y_max = max(y)
line_x = np.linspace(x_min, x_max, 10)
line_y = theta[0] + theta[1] * line_x
plt.plot(line_x, line_y, 'b-', linewidth=2)
plt.xlim(x_min-.1, x_max+.1)
plt.ylim(y_min-.1, y_max+.1)
# Add labels and save to disk
plt.xlabel(x_name)
plt.ylabel(y_name)
plt.savefig(save_path) |
ae83ddacb88098fb1db1447ae0bb97af0dbe9b09 | gmauricio/game-of-life | /tests.py | 2,636 | 3.5625 | 4 | import unittest
from game import World, Cell
class WorldTest(unittest.TestCase):
def test_counting_0_corner_cell_neighbours(self):
world = World(2, 2)
world.set([
[Cell(0), Cell(0)],
[Cell(0), Cell(0)]
])
self.assertEqual(0, world.get_neighbourhoods()[0][0])
def test_counting_3_corner_cell_neighbours(self):
world = World(2, 2)
world.set([
[Cell(0), Cell(1)],
[Cell(1), Cell(1)]
])
self.assertEqual(3, world.get_neighbourhoods()[0][0])
def test_counting_4_center_cell_4_neighbours(self):
world = World(3, 2)
world.set([
[Cell(1), Cell(1), Cell(1)],
[Cell(1), Cell(1), Cell(0)]
])
self.assertEqual(4, world.get_neighbourhoods()[0][1])
def test_that_cell_dies_with_0_alive_neighbours(self):
world = World(2, 2)
world.set([
[Cell(1), Cell(0)],
[Cell(0), Cell(0)]
])
world.evolve()
self.assertEqual(0, world.world[0][0].status)
def test_that_cell_dies_with_1_alive_neighbours(self):
world = World(2, 2)
world.set([
[Cell(1), Cell(1)],
[Cell(0), Cell(0)]
])
world.evolve()
self.assertEqual(0, world.world[0][0].status)
def test_that_cell_lives_with_2_alive_neighbours(self):
world = World(2, 2)
world.set([
[Cell(1), Cell(1)],
[Cell(1), Cell(0)]
])
world.evolve()
self.assertEqual(1, world.world[0][0].status)
def test_that_cell_keeps_death_with_2_alive_neighbours(self):
world = World(2, 2)
world.set([
[Cell(0), Cell(1)],
[Cell(1), Cell(0)]
])
world.evolve()
self.assertEqual(0, world.world[0][0].status)
def test_that_cell_lives_with_3_alive_neighbours(self):
world = World(2, 2)
world.set([
[Cell(1), Cell(1)],
[Cell(1), Cell(1)]
])
world.evolve()
self.assertEqual(1, world.world[0][0].status)
def test_that_death_cell_lives_with_3_alive_neighbours(self):
world = World(2, 2)
world.set([
[Cell(0), Cell(1)],
[Cell(1), Cell(1)]
])
world.evolve()
self.assertEqual(1, world.world[0][0].status)
def test_that_cell_dies_with_4_alive_neighbours(self):
world = World(3, 2)
world.set([
[Cell(1), Cell(1), Cell(1)],
[Cell(1), Cell(1), Cell(0)]
])
world.evolve()
self.assertEqual(0, world.world[0][1].status)
def test_that_cell_keeps_death_4_alive_neighbours(self):
world = World(3, 2)
world.set([
[Cell(1), Cell(0), Cell(1)],
[Cell(1), Cell(1), Cell(0)]
])
world.evolve()
self.assertEqual(0, world.world[0][1].status)
class WorldMakeTest(unittest.TestCase):
def test_that_worlds_get_created_with_expected_size(self):
world = World(10, 10)
world.generate()
self.assertEqual(10, len(world.world))
self.assertEqual(10, len(world.world[0]))
|
4628cb33312da7e7024301c5fdef2c367470c542 | marcos-mpc/CursoEmVideo-Mundo-2 | /ex061.py | 146 | 3.78125 | 4 | termo = int(input('TERMO: '))
razao = int(input('RAZÃO: '))
cont = 0
while cont < 10:
print(termo, end=' ')
termo += razao
cont += 1
|
dbb78a2c764277eef5797c29e67b57017d9e1e3c | ColorfulCodes/Algo-Grind | /Random/newspiral.py | 1,350 | 3.546875 | 4 | #
# def printSpiral(matrix):
# result = []
# rows = len(matrix)
# topRow = 0
# btmRow = rows -1
# leftCol = 0
# rightCol = len(matrix[0]) -1
#
# if rows == 0:
# return result
#
# while (topRow <= btmRow and leftCol <= rightCol):
# for i in range(leftCol, rightCol +1):
# result.append(matrix[topRow][i])
# topRow += 1
#
# for i in range(topRow, btmRow+1):
# result.append(matrix[i][rightCol])
# rightCol -= 1
#
# if topRow <= btmRow:
# for i in range(rightCol, leftCol-1,-1):
# result.append(matrix[btmRow][i])
# btmRow -= 1
#
# if leftCol <= rightCol:
# for i in range(btmRow, topRow-1,-1):
# result.append(matrix[i][leftCol])
# leftCol += 1
#
# return result
def printSpiral(matrix):
result = []
while matrix:
result += matrix.pop(0)
if matrix and matrix[0]:
for row in matrix:
result.append(row.pop())
if matrix:
result += matrix.pop()[::-1]
if matrix and matrix[0]:
for row in matrix[::-1]:
result.append(row.pop(0))
return result
print printSpiral([ [1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20] ])
|
08b9736de5ded403a6f41e0a8bd019729b8dcfea | mikebentley15/sandbox | /python/multiplicative-permanence/multperm.py | 6,620 | 4.25 | 4 | #!/usr/bin/env python3
import argparse
import sys
import itertools
def populate_parser(parser=None):
if not parser:
parser = argparse.ArgumentParser()
parser.description = 'Calculate multiplicative permanence'
group = parser.add_mutually_exclusive_group()
group.add_argument('num', type=int, default=277777788888899, nargs='?',
help='''
Show the calculations of multiplicative permanence
of this number. The default is the smallest one of
permanence 11 (i.e., 277,777,788,888,899).
''')
group.add_argument('-s', '--search', action='store_true',
help='''
Search infinitely instead of the one number. Press
CTRL-C when you want to exit. Otherwise, it will
run forever.''')
parser.add_argument('--print-bigger', type=int, default=3,
help='''
For --search. Only print numbers with depth higher
than this.
''')
parser.add_argument('--start-length', type=int, default=1,
help='''
For --search, start with this many factors instead
of starting from the beginning.
''')
group.add_argument('--reverse-search', type=int,
help='''
Search infinitely looking for numbers that generate
a number with the same digit factors as the given
number here. For example, if 8 is given, it will
look for numbers whose digits produce 8, 24, 222,
42, 18, 81, 124, ... This is useful for looking
for the next higher multiplicative permanence from
a high one you've found.
''')
return parser
# TODO: is it faster to do collections.Counter instead of list?
# TODO- product would be prod *= factor**power for factor, power in digits.items()
def to_digits(num):
'Convert a number to a list of digits'
if num <= 0:
return [0]
digits = []
while num > 0:
digits.append(num % 10)
num = num // 10
digits = list(reversed(digits))
return digits
def digits_to_string(digits):
return ''.join(str(d) for d in digits)
def product(array):
prod = 1
for x in array:
prod *= x
return prod
def per(digits, quiet=True):
'''
Calculates the depth of multiplicative permanence until a single digit.
@param digits (list(int)): list of digits of the current number, each
between 0 and 9.
@param quiet (bool): False means to print the numbers as they are found
@return (int) multiplicative permanence.
'''
depth = 0
if not quiet:
print('00: {}'.format(digits_to_string(digits)))
while len(digits) > 1:
depth += 1
num = product(digits)
if not quiet:
print(f'{depth:02}: {num}')
digits = to_digits(num)
return depth
def generate_draws(choices, start_len=1):
'''
An infinite generator of lists of draws with replacement starting from one
draw and methodically working up to more and more samples.
'''
for count in itertools.count(start=start_len):
yield from itertools.combinations_with_replacement(choices, count)
def prime_digits(digits):
assert all(0 < x < 10 for x in digits)
pdigits = []
for x in digits:
if x < 2:
pass
elif x == 4: pdigits.extend([2, 2])
elif x == 6: pdigits.extend([2, 3])
elif x == 8: pdigits.extend([2, 2, 2])
elif x == 9: pdigits.extend([3, 3])
else: pdigits.append(x)
pdigits.sort()
return pdigits
def prime_digits_to_string(pdigits):
s = ''
for factor in (2, 3, 5, 7):
if factor in pdigits:
if s:
s += ' '
s += '{}^{}'.format(factor, pdigits.count(factor))
return s
def digit_combos(pdigits):
'Create all unique unordered combos equivalent to the given prime digits'
pdigits = prime_digits(pdigits) # just to be sure they're prime
combos = set([tuple(pdigits)])
# combine twos to make fours
new_combos = list(combos)
for combo in combos:
num_twos = combo.count(2)
remaining = [x for x in combo if x != 2]
def main(arguments):
parser = populate_parser()
args = parser.parse_args(arguments)
if args.search:
best_match = (0, 0, 0)
last_tested = 0
current_len = 0
try:
#for factors in generate_draws([2, 3, 5, 7]):
for factors in generate_draws([2, 3, 7], start_len=args.start_length):
if len(factors) > current_len:
current_len = len(factors)
print('starting length', current_len)
last_tested = factors
depth = per(factors, quiet=True)
if depth > args.print_bigger:
current = prime_digits_to_string(factors)
print(f' {current}: {depth}')
if depth > best_match[2]:
best_match = (len(factors), prime_digits_to_string(factors), depth)
except KeyboardInterrupt:
last_tested_str = prime_digits_to_string(last_tested)
print()
print()
print(f'best match: ({best_match[0]}) {best_match[1]} '
f'@ {best_match[2]}')
print(f'last tested: ({len(last_tested)}) {last_tested_str} '
f'@ {per(last_tested, quiet=True)}')
print()
elif args.reverse_search:
print(f'reverse search of {args.reverse_search}')
digits = to_digits(args.reverse_search)
if digits.count('0'):
print(f' Error: {args.reverse_search} has a zero in it, exiting')
pdigits = prime_digits(digits)
print(f' prime digits: {prime_digits_to_string(pdigits)}')
pdigit_combos = prime_digit_combos(pdigits)
print(f' # 1-digit factor combos: {len(pdigit_combos)}')
#print('reverse search not yet implemented')
#print(args)
#return 1
else:
per(to_digits(args.num), quiet=False)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
6b72d449b6da8c8d94e2fd10f1e22bb44f677d9a | hamburgcodingschool/L2CX-January_new | /lesson 6/homework_7.py | 263 | 4.03125 | 4 | # 7 - Write a program that prints the names on odd positions in an array of names.
l2cClass = ["Helder", "Fabia", "Leonie", "Carina", "Lexie"]
for i in range(0, len(l2cClass)):
name = l2cClass[i]
if i % 2 != 0:
print("{}: {}".format(i, name))
|
01f47b93c0902270904803a7e9d1e180743ccc4a | Ivan-yyq/livePython-2018 | /day9/demon8.py | 723 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/20 20:06
# @Author : yangyuanqiang
# @File : demon8.py
# 阶乘的和
class JinCinCount(object):
def __init__(self, n):
self.n = n
def jc(self, n):
result = 1
if n == 0:
return result
else:
for i in range(1, n+1):
result *= i
return result
def count(self):
count = 0
for i in range(0, int(self.n) + 1):
count += self.jc(i)
print("count = {0}".format(count))
def main():
n = input("Please inpurt a number: ")
jinCinCount = JinCinCount(int(n))
jinCinCount.count()
if __name__ == "__main__":
main()
|
52a69fc9e91c94f9dfebaeb5ad6024f955150e41 | s1td1kov/Basics-in-Python | /Week2/Утренняя пробежка.py | 96 | 3.5 | 4 | x, y = int(input()), int(input())
k = 0
while x < y:
x = x * 1.1
k = k + 1
print(k + 1)
|
52c4bd26be8b0ea375966e187462c7945b60caaf | parthjoshi09/ner | /nerv1.py | 867 | 4.46875 | 4 | #Identify person names in a given piece of text, using dictionaries.
import re
regex = "[a-zA-Z]+" #Defining regex for tokenizer.
with open("female.txt") as f:
female_names = f.readlines() #Read names line by line and store them in a list.
female_names = [w.strip() for w in female_names] #Remove \n or newline character from the end of each name.
with open("male.txt") as f:
male_names = f.readlines()
male_names = [w.strip() for w in male_names]
person_names = female_names + male_names #Concatenate both the lists to form one big list. Python cool :)
text = input("Enter some text: ")
tokenized_words = re.findall(regex,text)
ne = [word for word in tokenized_words if word in person_names] #You have seen the use of this last week. Check if given word is NE.
print("NEs in the given text are: ")
print(ne)
|
da52d941e3fb1025e2cb2cd72dfdcda0b4b1f6bf | thaistlsantos/Python-FIT | /1º Semestre/Aula 12 - 05_11/Aula_11_lista_range.py | 200 | 3.609375 | 4 | lista = [1, 5, 7, 6, 9]
for x in lista:
print(x)
lista.append(x**2)
if cont == 10:
break
cont += 1
n = len(lista)
for i in range(len(lista)):
lista.append(lista[i] ** 2)
|
e8e881cece87d6937f1cd5bf4a5dbdc7913de454 | brandonhumphries/week-1-python-exercises | /blastoff4.py | 443 | 3.9375 | 4 | starting_number = int(raw_input("Number under 21 to start counting from? "))
counter = 0
while starting_number > 20:
starting_number = int(raw_input("Number under 21 to start counting from? "))
numbers = range(0, starting_number + 1)
while abs(counter) < len(numbers):
print numbers[counter - 1]
counter -= 1
if numbers[counter - 1] == 0:
print numbers[counter - 1]
print "End of the line."
counter -= 1 |
583860109443f4a61026711896d8fe132973bbdd | jiushibushuaxie/my_leetcode_path | /python/9回文数.py | 809 | 4.03125 | 4 | """
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
输入: 121
输出: true
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
所以负数肯定不是回文数
注意事项:'int' object has no attribute 'copy' int不能用copy()
暂时存储x的值
"""
class Solution:
def isPalindrome(self, x):
if x < 0:
return False
y = 0
z = x # 暂存x的值
while x:
y = y*10 + x%10
x = x//10
if y == z:
return True
else:
return False
num = 12321
solver = Solution()
print(solver.isPalindrome(num)) |
ab7fbb0138a26f4f0ba3979df5c008289263b258 | Rohit-83/TODO | /dbhelper.py | 1,251 | 4.0625 | 4 | import sqlite3
#for creation of data base
conn = sqlite3.connect('test.db')
#creation of table if not exists
conn.execute(''' CREATE TABLE IF NOT EXISTS todo(
id INTEGER PRIMARY KEY,
task TEXT NOT NULL
)
''')
#DATA INSERTION
#query = "INSERT INTO todo(task) VALUES('Reecord');"
#conn.execute(query)
#conn.commit()
def insertdata(newtask):
query = "INSERT INTO todo(task) VALUES(?);"
conn.execute(query,(newtask,))
conn.commit()
#now we will make a function which delete task by id
def deletedata(newid):
query = "DELETE FROM todo WHERE id = ?;"
conn.execute(query,(newid,))
conn.commit()
def deletedatatask(newtask):
query = "DELETE FROM todo WHERE task = ?;"
conn.execute(query,(newtask,))
conn.commit()
#now we will make a function which update the data by id and task
def updatedata(newtask,newid):
query = "UPDATE todo SET task =? WHERE id =?;"
conn.execute(query,(newtask,newid))
conn.commit()
def show():
query = "SELECT * FROM todo;"
return conn.execute(query)
#insertdata("Sleeping")
#deletedata(3)
#updatedata("Eatiing",2)
#query = "SELECT * FROM todo;"
#for rows in conn.execute(query):
#print(rows)
#print("database connected")
#conn.close()
#always close the data base |
4a377c66981ff01dc8afe447b591f9681c955b35 | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | /problems/LC257.py | 830 | 3.8125 | 4 | # O(n*log(n))
# n = numberOfNodes(root)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res = []
self.explore(root, [], True, res)
return res
def explore(self, node, path, isRoot, res):
if node is None:
return
if isRoot:
path.append(str(node.val))
else:
path.append("->" + str(node.val))
if node.left is None and node.right is None:
res.append("".join(path))
else:
self.explore(node.left, path, False, res)
self.explore(node.right, path, False, res)
path.pop() |
40e47a034eb1eafaf5d5ee7cf97165a0b375a447 | ivenn/ready | /basics/sorting/merge_sort.py | 810 | 3.8125 | 4 | def merge(arr, l, m, r):
big_int = 100
size_l = m - l + 1
size_r = r - m
larr = [0] * size_l
rarr = [0] * size_r
for i in range(size_l):
larr[i] = arr[l + i]
for j in range(size_r):
rarr[j] = arr[m + j + 1]
larr.append(big_int)
rarr.append(big_int)
i = 0
j = 0
for k in range(l, r + 1):
if larr[i] <= rarr[j]:
arr[k] = larr[i]
i += 1
else:
arr[k] = rarr[j]
j += 1
def merge_sort(arr, l, r):
if l < r:
m = (l + r) / 2
merge_sort(arr, l, m)
merge_sort(arr, m + 1, r)
merge(arr, l, m, r)
def main():
arr = [6, 0, 5, 1, 8, 2, 9, 4, 3, 7]
print(arr)
merge_sort(arr, 0, 9)
print(arr)
if __name__ == '__main__':
main()
|
d0f9a755e18f163ac4ea71a841604069caa1c1c9 | javargas510-bit/Python_stack | /_python/python_fundamentals/basic_functions.py | 1,368 | 3.875 | 4 | #1 prints number 5
def a():
return 5
print(a())
#2 prints number 10
def a():
return 5
print(a()+a())
#3 prints number 5
def a():
return 5
return 10
print(a())
#4 prints 5
def a():
return 5
print(10)
print(a())
#5 prints 5
def a():
print(5)
x = a()
print(x)
#6 print 3 , 5 and error
def a(b,c):
print(b+c)
print(a(1,2) + a(2,3))
#7 prints str 25
def a(b,c):
return str(b)+str(c)
print(a(2,5))
#8 prints 100 and 10
def a():
b = 100
print(b)
if b < 10:
return 5
else:
return 10
return 7
print(a())
#9 prints 7 ,14, and 21
def a(b,c):
if b<c:
return 7
else:
return 14
return 3
print(a(2,3))
print(a(5,3))
print(a(2,3) + a(5,3))
#10 print 8
def a(b,c):
return b+c
return 10
print(a(3,5))
#11 print 500 , 500 , 300, 500
b = 500
print(b)
def a():
b = 300
print(b)
print(b)
a()
print(b)
#12 print 500 , 500 ,300 , 500
b = 500
print(b)
def a():
b = 300
print(b)
return b
print(b)
a()
print(b)
#13 print 500 , 500 , 300 , 300
b = 500
print(b)
def a():
b = 300
print(b)
return b
print(b)
b=a()
print(b)
#14 print 1 ,3 ,2
def a():
print(1)
b()
print(2)
def b():
print(3)
a()
#15 print 1 , 3 , 5, 10
def a():
print(1)
x = b()
print(x)
return 10
def b():
print(3)
return 5
y = a()
print(y)
|
df88a4dbe442d59b1c4454b4b6152b54730c9a9c | DaianeFeliciano/python-fatec | /ATV78.py | 2,290 | 4 | 4 | n1 = int(input("Digite o primeiro número inteiro: "))
n2 = int(input("Digite o segundo número inteiro: "))
n3 = int(input("Digite o terceiro número inteiro: "))
n4 = int(input("Digite o quarto número inteiro: "))
if (n1 > n2 and n2 > n3 and n3 > n4):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n4,n3,n2,n1))
elif (n2 > n1 and n1 > n3 and n3 > n4 ):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n4,n3,n1,n2))
elif (n3 > n1 and n1 > n2 and n2 > n4):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n4,n2,n1,n3))
elif (n4 > n1 and n1> n2 and n2 > n3):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n3,n2,n1,n4))
elif (n1 > n2 and n2 > n4 and n4 > n3):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n3,n4,n2,n1))
elif (n1 > n3 and n3 > n4 and n4 > n2):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n2,n4,n3,n1))
elif (n1> n4 and n4 > n3 and n3 > n2):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n2,n3,n4,n1))
elif (n2 > n1 and n1 > n3 and n3 > n4):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n4, n3, n1, n2))
elif (n2 > n3 and n3 > n1 and n1 > n4):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n4, n1, n3, n2))
elif (n2 > n4 and n4 > n1 and n1 > n3):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n3, n1, n4, n2))
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n2,n3,n4,n1))
elif (n3 > n1 and n1 > n2 and n2 > n4):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n4, n2, n1, n3))
elif (n3 > n2 and n2 > n1 and n1 > n4):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n4, n1, n2, n3))
elif (n3 > n4 and n4 > n2 and n2 > n1):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n1, n2, n4, n3))
elif (n4 > n1 and n1 > n2 and n2 > n3):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n3, n2, n1, n4))
elif (n4 > n2 and n2 > n1 and n1 > n3):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n3, n1, n2, n4))
elif (n4 > n3 and n3 > n1 and n1 > n2):
print("A ordem crescente dos valores é {}, {}, {} e {}".format(n2, n1, n3, n4))
|
f5fd210cebe5e234e437235a999d31aecfac23ab | PropertyOfMan/WebServer-API-Project | /diction.py | 1,061 | 3.546875 | 4 | dictionary = {1: ('В золотом окне востока лик свой солнце показало.', 'Ромео и Джульетта'), 2: ('— Через столько лет? — Всегда.', 'Северус Снегг (Северус Снейп)'), 3: ('Ни одного правителя не поддерживают все до единого.', 'Игра престолов'), 4: ('Он коснулся пальцами ее волос, она ощутила, что к ней прикоснулась любовь.', 'Сцены из жизни за стеной'), 5: ('Воины-победители сперва побеждают и только потом вступают в битву; те же, что терпят поражение, сперва вступают в битву и только затем пытаются победить.', 'Сунь-Цзы')}
while 1:
n = input()
if n != '0':
input()
author = input()
dictionary[len(dictionary) + 1] = n, author
print('OK')
else:
break
print(dictionary) |
350d8b79396dcd705f2adb64e72db917ebed3963 | Skillicious/PythonJunk | /futval.py | 862 | 3.78125 | 4 | from graphics import*
def main():
principal = eval(input("Enter the intial principal: "))
apr = eval(input("Enter the annualized unterest rate: "))
win = GraphWin("Investment Growth Chart", 320,240)
win.setBackground("white")
Text(Point(20,230), " 0.0K").draw(win)
Text(Point(20,180), " 2.5K").draw(win)
Text(Point(20,130), " 5.0K").draw(win)
Text(Point(20,80), " 7.5K").draw(win)
Text(Point(20,30), " 10.0K").draw(win)
height = principal * 0.02
cat = Rectangle(Point(40,230), Point(65, 230-height))
cat.setFill("green")
cat.setWidth(2)
cat.draw(win)
for year in range(1,11):
principal = principal * (1 + apr)
x11 = year * 25 + 40
height = principal * 0.02
bar = Rectangle(Point(x11, 230), Point(x11+25, 230 -height))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
input("Press <Enter> to quit")
win.close()
main()
|
bc84fc11a51c42b9747e70d23a5dd7321b13d5c4 | smtamh/oop_python_ex | /student_result/2019/01_number_baseball/baseball [2-1 김A].py | 6,184 | 3.578125 | 4 | import random
# 똑바로 입력했나 판단
def fin_check(a):
# if (a == 'y' or a == 'n'):
if a in 'yn':
return True
return False
# 입력값에 따라 게임 지속 여부 판단
# 게임을 끝내겠습니까?
def which_func(a):
if a == 'y':
# 아뇨
return False
else:
# 네
return True
def make_func():
# 랜덤하게 0~9 나열 - 앞의 3개만 사용 예정
lists = list(range(10))
random.shuffle(lists)
return lists
# 숫자인지 확인하는 함수
def only_number(guess_list, ball_numb): # T. ball_numb 은 사용하지 않음.
for i in guess_list:
# if not (i == '0' or i == '1' or i == '2' or i == '3' or i == '4' or i == '5' or i == '6' or i == '7' or i == '8' or i == '9'):
if i not in "0123456789":
return False
return True
def check(guess_list, ball_numb):
# 입력한 값이 조건에 부합하나 확인
# 길이가 맞는지, 다 숫자가 맞는지 확인
if len(guess_list) == ball_numb and only_number(guess_list, ball_numb):
return True
return False
def compare_func(Ans_List, Ball_Numb):
# 추정 입력값 받기
a = 1
# 해당 while문에서는 입력을 받고, 잘못된 방법으로 값을 입력시 똑바로 할떄까지, 12번까지만 다시 시킵니다.
while True:
guess_list = input().split()
# 요기에서 check를 통해 확인합니다
if not check(guess_list, Ball_Numb):
a += 1
print("똑바로 찍어")
else:
# 문자로 입력받은 guess_list 이기에 정수 리스트로 바꿉니다(이러지 않으면 이후 비교가 힘듭니다)
guess_list = list(map(int, guess_list))
break
if a == 4:
print('')
print("너 대머리")
if a == 8:
print('')
print("너 친구들도 대머리")
if a == 12:
print("접어 그냥")
print("다 아웃")
return 0, 0
# 확인하기
# strike
s = 0
# ball
b = 0
# 추정 값과 정답을 하나하나 대조
for i in range(0, Ball_Numb):
for j in range(0, Ball_Numb):
# 만약 대조한 값이 같을 때
if Ans_List[i] == guess_list[j]:
# 자리도 같으면 스트라이크
if i == j:
s += 1
# 자리는 다르면 볼
else:
b += 1
return s, b
def expl_rule(chance_numb):
print('*' * 80)
print("저는 0 ~ 9 까지의 숫자 중에서 세개의 숫자를 머릿속에 떠올렸습니다.")
print("앞으로 %d번의 기회가 주어지며," % chance_numb)
print("그 안에 제가 생각하는 숫자의 종류와 위치를 전부 맞추어야 승리할 수 있습니다.")
print("시도를 한번 할때마다 추측이 답에 얼마나 근접했는지 알려드리겠습니다.")
print("")
print("strike는 당신의 추측에서 숫자의 '종류', 그리고 '위치'가 전부 맞은 추측의 개수입니다.")
print("ball은 당신의 추측에서 숫자의 '종류'는 맞았으나, '위치'가 틀린 추측의 개수입니다.")
print("out은 당신이 추측한 숫자 중 '위치', '종류'가 다 틀린 추측의 개수입니다.")
print("이떄, '한 자리 숫자' 세개를 하나씩 '띄어쓰기로' 분리해서 입력하세요. 그렇지 않으면 화가 날 것 같습니다.")
print("시작 하자마자 enter누르지도 말고요")
print("계속 실수하시면 그에 합당한 저주가 있을 것입니다.")
print("아무튼 행운을 빕니다.")
print('*' * 80)
def IQ_Test(i):
if i in range(1, 4):
print("우와 정말 똑똑하다... 솔직히 찍은 거죠?")
elif i in range(4, 6):
print("음... 실력은 그럭저럭. 다시 시도해 보세요")
elif i in range(6, 10):
print("오늘 좀 상태가 안좋은 모양이네요... %d번은 좀 심했다." % i)
elif i == 10:
print("겨우 맞췄네요..")
else:
print("우와... 바보다... 다시 해도 안될 것 같으니까 포기하세요. 뭐... 그래도 예의상 묻기는 할게요.")
# 추측하는 숫자의 개수와 시도 횟수 설정
# ball_numb는 수정할 수 없습니다.
ball_numb = 3
# chance_numb는 바꿀 수 있습니다.
chance_numb = 10
# 규칙을 설명하는 함수
expl_rule(chance_numb)
# 코드 시작!
while True:
# 사용한 기회를 저장하는 변수
chance = 1
# 정답이 입력되는 리스트, 다만 이 리스트는 길이가 10이지만, 앞의 3개만 사용할 것입니다.
ans_list = []
# make_func에서 정답 랜덤 생성
ans_list = make_func()
# 아래 주석을 제거하면 정답을 보고 플레이 할 수 있습니다.-앞 3 수가 답입니다.
# print(ans_list)
while True:
# 시도 횟수가 다 차면 끝내는 부분
if chance > chance_numb:
break
# 아래로는 s, b, o 계산 후 결과 산출
print("%s번째 시도" % chance)
S, B = compare_func(ans_list, ball_numb)
O = 3 - S - B
# 스트라이크 3개면 만점
if S == 3:
print("정답!")
break
# 그 외 결과
else:
print("strike = %s, ball = %s, out = %s" % (S, B, O))
# 시도 횟수 1 증가
chance += 1
# 10 번 시도시
if chance == chance_numb + 1:
print("그만 해요 끝났어요")
print("정답은 %d, %d, %d 였답니다." % (ans_list[0], ans_list[1], ans_list[2]))
# 지능을 판단하는 함수
IQ_Test(chance)
print("다시 하고 싶어요?")
print("다시 하려면 y, 포기하려면 n '글씨만' 입력하세요.")
a = input()
# 입력 값이 y, n 이 아니면 강제 종료
if not fin_check(a):
print("쯧... 그냥 관두세요\n글씨를 못 읽는 사람인가..")
break
# n 이라고 입력해도 종료
elif which_func(a):
break
|
9917e44fbc0fc3f37018739d2858e289e8675e7a | arparker95/Learn-to-Program-Activities | /directory.py | 1,238 | 4.03125 | 4 | import csv
def menu():
print "A) Add to Directory"
print "B) Diplay Directory"
print "X) Exit Directory Program"
selection = raw_input()
if selection == "A":
addToDirectory()
elif selection == "B":
displayDirectory()
elif selection == "X":
quit()
else:
print "Invalid Selection"
menu()
def addToDirectory():
print "Add to Directory"
firstName = raw_input("First Name: ")
lastName = raw_input("Last Name: ")
email = raw_input("Email: ")
phone = raw_input("Phone: ")
directory = open("directory.csv", "a")
outstring = firstName + "," + lastName + "," + email + "," + phone + "\n"
directory.write(outstring)
directory.close()
print (firstName + " " + lastName + " " + "added to directory.")
menu()
def displayDirectory():
print "Display Directory"
directory = open("directory.csv", "r")
try:
rowtext = ""
reader = csv.reader(directory)
for row in reader:
for item in row:
rowtext = rowtext + " " + item
print rowtext
rowtext = ""
finally:
directory.close()
menu()
menu()
|
c79141e6c0c99141fd38b5368d47f6b0981124a5 | alvindrakes/python-crashcourse-code | /Chapter 4/foods.py | 809 | 4.4375 | 4 | # copying list in python
my_food = ['veggies', 'tomatoes', 'apple']
friend_food = my_food[:] # just omit the indexes to copy the entire list
print('This is my food')
print(my_food)
print('\n')
print('This is my friend''s food')
print(friend_food)
my_food.append('cheese')
friend_food.append('nugget') # as you can see, the 2 lists are seperated
print('\nThis is my food')
print(my_food)
print('\nThis is my friend''s food')
print(friend_food)
# THIS DOESN'T WORK (if we want seperate copy of lists, we need to use slices)
my_food = friend_food
my_food.append('cheese')
friend_food.append('nugget')
print('\nThis is my food')
print(my_food) # as both my_food and friends_food print the same things
print('\nThis is my friend''s food')
print(friend_food)
|
ba0748f72652df6dddcb7180d4fb5dfe587de720 | addtheletters/laddersnakes | /graphs/bellmanford.py | 956 | 3.765625 | 4 | # Bellman-Ford algorithm.
# Find shortest paths from a source to elsewhere in a graph.
# Slower than Dijkstras, but works with negative edge weights.
# https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
import testgraph as tg
def bellmanford(graph, src):
edges = tg.edgeList(graph)
dist = {}
path = {}
dist[src] = 0
def relax(v, w):
if (v in dist) and ((w not in dist) or (dist[v] + graph[v][w] < dist[w])):
dist[w] = (dist[v] + graph[v][w])
path[w] = v
for i in range(len(graph.keys()) - 1):
for edge in edges:
relax(edge[0][0], edge[0][1])
for edge in edges:
if dist[edge[0][1]] > dist[edge[0][0]] + edge[1]:
print("Negative weight cycle with edge " + str(edge[0]))
return dist, path
print( bellmanford(tg.adjList(), "A") )
print( bellmanford(tg.adjNegative(), "O"))
print( bellmanford(tg.adjNegative(True), "O")) # with cycles
|
b95d390fe5fc34cac1a79275684bb64d415ef83b | Solvi/statsmodels | /examples/example_interaction_categorial.py | 779 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""Plot Interaction of Categorical Factors
"""
#In this example, we will vizualize the interaction between
#categorical factors. First, categorical data are initialized
#and then plotted using the interaction_plot function.
#
#Author: Denis A. Engemann
print __doc__
import numpy as np
from statsmodels.graphics.factorplots import interaction_plot
from pandas import Series
np.random.seed(12345)
weight = Series(np.repeat(['low', 'hi', 'low', 'hi'], 15), name='weight')
nutrition = Series(np.repeat(['lo_carb', 'hi_carb'], 30), name='nutrition')
days = np.log(np.random.randint(1, 30, size=60))
fig = interaction_plot(weight, nutrition, days, colors=['red', 'blue'],
markers=['D', '^'], ms=10)
import matplotlib.pylab as plt
plt.show()
|
faef581455d52a27a5e405e2192229a8b2a12dd9 | Muslum10cel/HackerRankPY | /com/mathematics/fundamentals/HalloweenParty.py | 183 | 3.578125 | 4 | import math
T = int(input())
for _ in range(T):
K = int(input())
if K % 2 == 0:
print(K // 2 * K // 2)
else:
print((math.ceil(K / 2) * math.floor(K / 2))) |
649f9722c554371994007ca67553e0297970ad59 | zhouyuhangnju/freshLeetcode | /3SumClosest.py | 1,055 | 3.765625 | 4 | def threeSumClosest(nums, target):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
maxdiff = 2**31-1
nums = sorted(nums)
print nums
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
l, r = i + 1, len(nums) - 1
while l < r:
# print i, l, r
s = nums[i] + nums[l] + nums[r]
diff = s - target
if diff < 0:
diff = -diff
# print diff, maxdiff
if diff < maxdiff:
result = s
maxdiff = diff
if s >= target + maxdiff:
r -= 1
elif s <= target - maxdiff:
l += 1
elif s > target and s < target + maxdiff:
l += 1
elif s < target and s > target - maxdiff:
r -= 1
else:
assert s == target
return target
return result
if __name__ == '__main__':
print threeSumClosest([0,2,1,-3], 1)
|
7d10db3f652923241d5779ba250d7e6c28334b38 | Android-Ale/PracticePython | /mundo2/lerNomePreçoDoProdutoComWhile.py | 941 | 3.671875 | 4 | print('-'*20)
print('LOJA BARATÃO')
print('-'*20)
fim = 'a'
totalpreço = contadorpreço = menor = contador = 0
menorproduto = ''
while True:
produto = str(input('Nome do produto:'))
preço = float(input('Preço: R$'))
totalpreço += preço
contador += 1
if preço > 1000:
contadorpreço += 1
if contador == 1:
menor = preço
else:
if preço < menor:
menor = preço
menorproduto = produto
'''print(totalpreço)'''
while True:
escolha = str(input('Quer continuar ? [S/N]')).lower()
if escolha == 'n':
fim = escolha
if escolha in 'sn':
break
if fim == 'n':
break
print('-'*10,'FIM DO PROGRAMA','-'*10)
print(f'O total da compra foi R${totalpreço:.2f}')
print(f'Temos {contadorpreço} produtos custando mais de R$1000.00')
print(f'O produto mais barato foi {menorproduto} que custa R${menor:.2f} ') |
b85a99807f08dc7e96a64151026e10594f8ff60e | severinkrystyan/CIS2348-Fall-2020 | /Homework 1/1.20 zyLab_Krystyan Severin_CIS2348.py | 392 | 3.859375 | 4 | """Name: Krystyan Severin
PSID: 1916594"""
user_num1 = int(input('Enter integer:\n'))
print('You entered:', user_num1)
print(user_num1, 'squared is', user_num1**2)
print(f'And {user_num1} cubed is {user_num1**3} !!')
user_num2 = int(input('Enter another integer:\n'))
print(f'{user_num1} + {user_num2} is {user_num1+user_num2}')
print(f'{user_num1} * {user_num2} is {user_num1*user_num2}')
|
80dc46160aa39078add57d1b0de9614bb1033f55 | chaozc/leetcode | /python/p110.py | 613 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def height(self, root):
if root == None:
return True, 0
bl, hl = self.height(root.left)
br, hr = self.height(root.right)
if bl and br and abs(hl-hr) < 2:
return True, max(hl, hr)+1
return False, max(hl, hr)+1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.height(root)[0] |
74255c438de37d22da51070c23c7a7ee876a5135 | zxl-python/- | /day5/new的认识.py | 280 | 3.65625 | 4 | #__new__ 魔术方法
# 实例对象的时候触发,负责对象的创建与否
class Human:
def __new__(cls,limit):
if isinstance(limit,int):
return super().__new__(cls)
def __init__(self,limit):
print("哈哈哈哈")
a = Human('he')
print(a)
|
d49200c51c1b0d3b41b756c2f4f5615945a72883 | jjcenturion/ej21 | /main.py | 279 | 3.84375 | 4 | cont_letra = 0
cont_palabra = 0
cadena = None
while cadena !='.':
cadena = input('Ingresar letra, termina con"."')
cont_letra += 1
if cadena == '' or cadena == '.':
if cont_letra > 1:
cont_palabra +=1
cont_letra = 0
print('Cantidad de palabras:', cont_palabra ) |
a90b203e64385c2f1b09cb96069e50a05bf0b4dd | edu-sense-com/OSE-Python-Course | /SP/Modul_07/funkcje_python.py | 1,346 | 3.859375 | 4 | # przykłady definiowania i wywoływania funkcji w Python
def just_print():
print("Just printing some text.")
def just_return():
return "Just returning some text"
def parameter_print(some_value):
print(f"You pass value: {some_value}")
def parameter_return(some_value):
return f"You pass value: {some_value}"
def more_parameters(first, second):
print(f"First parameter: {first}")
print(f"Second parameter: {second}")
def quadrat_area(side_length):
return side_length * side_length
# przykłady wywołania w trybie REPL - zwracamy uwagę na funkcje zwracające wartość
# >>> just_print()
# Just printing some text.
# >>> just_return()
# 'Just returning some text'
# >>> parameter_print(1234)
# You pass value: 1234
# >>> parameter_return("Something")
# 'You pass value: Something'
# >>> more_parameters(123, "Some value")
# First parameter: 123
# Second parameter: Some value
# >>> quadrat_area(10)
# 100
# funkcja wywołana bez nawiasów nie uruchamia się
# >>> just_print
# <function just_print at 0x7fa340ab89d0>
# dla chętnych
def parameters_return(first, second):
return first, second
# przykłady wywołania w trybie REPL - dziwnie wyglądające zwrócone dane to typ Tuple
# https://docs.python.org/3/library/stdtypes.html#tuples
# >>> parameters_return(123, "Some value")
# (123, 'Some value')
|
a5f2c62d0ad6a52f6c084eca308dab633042ac11 | honwenle/pygit | /fibs.py | 286 | 3.78125 | 4 | def fib1(n):
result=[0,1]
for i in range(n-2):
result.append(result[-2]+result[-1])
return result
def fib2(n):
a, b = 0, 1
result=[]
while b < n:
result.append(b)
a, b = b, a+b
return result
a1 = fib1(10)
a2 = fib2(100)
print(a1,a2) |
92b76e85bd05d4c0da375aaa98ae6da54d45a1a1 | ovch-antonina/tokenizer | /test_tokenizer.py | 2,394 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import unittest
from tokenizer import Token, Tokenizer
class TokenizerTest(unittest.TestCase):
'''tests for tokenizer.py'''
def test_regular(self):
'''
tests a string with mixed alphabetical symbols, numbers, and whitespaces
'''
tokens = Tokenizer.tokenize('3fff dsl f')
self.assertEqual(len(tokens), 3)
self.assertEqual(tokens[0].position, 1)
self.assertEqual(tokens[0].substring, 'fff')
self.assertEqual(tokens[2].position, 9)
self.assertEqual(tokens[2].substring, 'f')
def test_typeError(self):
'''
tests how the tokenizer handles receiving an integer instead of a string
as input
'''
with self.assertRaises(TypeError):
Tokenizer.tokenize(123)
def test_whitespaces(self):
'''
tests a string that starts and ends with a whitespace and has multiple
whitespaces in a row
'''
tokens = Tokenizer.tokenize(' white space ')
self.assertEqual(len(tokens), 2)
self.assertEqual(tokens[0].position, 1)
self.assertEqual(tokens[0].substring, 'white')
self.assertEqual(tokens[1].position, 8)
self.assertEqual(tokens[1].substring, 'space')
def test_punctiation(self):
'''
tests a string with several puctuation marks
'''
tokens = Tokenizer.tokenize(';.^punctuation!:)')
self.assertEqual(len(tokens), 1)
self.assertEqual(tokens[0].position, 3)
self.assertEqual(tokens[0].substring, 'punctuation')
def test_noLetters(self):
'''
tests a string that contains no alphabetical symbols
'''
tokens = Tokenizer.tokenize('1...2! 3?')
self.assertEqual(len(tokens), 0)
def test_accentedLetters(self):
'''
tests a string that contains accented letters
'''
tokens = Tokenizer.tokenize('ˇ... 勀!')
self.assertEqual(len(tokens), 2)
self.assertEqual(tokens[0].position, 0)
self.assertEqual(tokens[0].substring, 'Àá')
self.assertEqual(tokens[1].position, 6)
self.assertEqual(tokens[1].substring, '勀')
if __name__ == '__main__':
unittest.main()
|
29fcfa072bd8a12d022ec0ea963a2ecd033c81d8 | Jaraiz91/Javier_Araiz_TheBridge | /ML_Project/src/utils/mining_data_tb.py | 5,521 | 4 | 4 | import pandas as pd
import numpy as np
import os, sys
def merge_csv(base_name, range_number, column_name, file_name, path, start_number= 0):
"""" The function saves a csv file with all the csv files you want to join
arguments:
base_name: base name that share all the files in order to make the loop inside the function
start_number: this number is used in case the file number must start from a number other than one. Default value is 0
range_number: list or tuple with the start and end numbers to the loop
column_name: list with the names of the columns
file_name : desired name for the new file you want to save
path: path to folder where the new_file must be stored
Returns:
a new merged csv file
"""
for i in range(range_number[0], range_number[1]):
if i == 1:
data = pd.read_csv(base_name + str(start_number + i) + '.csv', header= None)
df = pd.DataFrame(data)
df.columns = column_name
data1 = pd.read_csv(base_name + str(start_number + i + 1) + '.csv', header = None)
df1 = pd.DataFrame(data1)
df1.columns = column_name
merged_df = pd.concat([df, df1])
else:
data = pd.read_csv(base_name + str(start_number + i + 1) + '.csv', header= None)
df = pd.DataFrame(data)
df.columns = column_name
df1 = merged_df
merged_df = pd.concat([df1, data])
path_to_file = path + os.sep + file_name + '.csv'
merged_df.to_csv(path_to_file, header= True, index= False)
return
def save_merged_csv(csv1, csv2, file_name, path):
"""This function concatenates 2 csv that already have same column names and
saves the new file in the given path as parameter"""
data1 = pd.read_csv(csv1)
df1 = pd.DataFrame(data1)
data2 = pd.read_csv(csv2)
df2 = pd.DataFrame(data2)
concat_df = pd.concat([df1, df2])
path_to_file = path + os.sep + file_name + '.csv'
concat_df.to_csv(path_to_file, header= True, index= False)
return
def add_short_features(df, file_name, path):
""" This function add the features needed for trading time series
arguments:
df : Dataframe to be used for adding the features
returns:
A saved file of csv modified with the new features
"""
df['SMA_5'] = df['Bar CLOSE Bid Quote'].rolling(window=5).mean()
df['SMA_20'] = df['Bar CLOSE Bid Quote'].rolling(window=20).mean()
df['EMA_20'] = df['Bar CLOSE Bid Quote'].ewm(span=20, min_periods=20, adjust=True).mean()
path_to_file = path + os.sep + file_name + '.csv'
df.to_csv(path_to_file, header= True, index= False)
return
def add_features(df, file_name, path):
""" This function add the features needed for trading time series
arguments:
df : Dataframe to be used for adding the features
returns:
A saved file of csv modified with the new features
"""
df['SMA_5'] = df['Bar CLOSE Bid Quote'].rolling(window=5).mean()
df['SMA_20'] = df['Bar CLOSE Bid Quote'].rolling(window=20).mean()
df['SMA_200'] = df['Bar CLOSE Bid Quote'].rolling(window=200).mean()
df['EMA_20'] = df['Bar CLOSE Bid Quote'].ewm(span=20, min_periods=20, adjust=True).mean()
path_to_file = path + os.sep + file_name + '.csv'
df.to_csv(path_to_file, header= True, index= False)
return
def final_add_short_features(df):
""" This function add the features needed for trading time series
arguments:
df : Dataframe to be used for adding the features
returns:
A saved file of csv modified with the new features
"""
df['SMA_5'] = df['Close price'].rolling(window=5).mean()
df['SMA_20'] = df['Close price'].rolling(window=20).mean()
df['EMA_20'] = df['Close price'].ewm(span=20, min_periods=20, adjust=True).mean()
return df
def final_add_features(df):
""" This function add the features needed for trading time series
arguments:
df : Dataframe to be used for adding the features
returns:
A saved file of csv modified with the new features
"""
df['SMA_5'] = df['Close price'].rolling(window=5).mean()
df['SMA_20'] = df['Close price'].rolling(window=20).mean()
df['SMA_200'] = df['Close price'].rolling(window=200).mean()
df['EMA_20'] = df['Close price'].ewm(span=20, min_periods=20, adjust=True).mean()
return df
def put_features(df):
df['SMA_5'] = df['Bar CLOSE Bid Quote'].rolling(window=5).mean()
df['SMA_20'] = df['Bar CLOSE Bid Quote'].rolling(window=20).mean()
df['SMA_200'] = df['Bar CLOSE Bid Quote'].rolling(window=200).mean()
df['EMA_20'] = df['Bar CLOSE Bid Quote'].ewm(span=20, min_periods=20, adjust=True).mean()
return df
def parser(x):
""" function to parse object into datetime when reading a csv file"""
return datetime.strptime(x, '%Y.%m.%d')
def x_dict_y_dict(data, step):
""" Function designed to check if LSTM_preprocessing is doing changes in data as desired"""
copy_last = data[-1:]
LSTM_df = data[-1:]
for i in range(step-1):
LSTM_df = pd.concat([LSTM_df, copy_last])
LSTM_df = pd.concat([data, LSTM_df])
x_list = []
y_list = []
for i in range(len(data)):
D = i + step
x_list.append([LSTM_df[x][i:D] for x in data.columns[:]])
y_list.append({'date': LSTM_df['Date'][D:D+1], 'time': LSTM_df['Time'][D:D+1], 'close price': LSTM_df['Close Price'][D:D+1]})
return x_list, y_list |
aefbbb52913be3b602cbfda29debc69bd7612ac8 | suilin0432/DataStructurePratice | /树/BinarySearchTree.py | 5,227 | 3.921875 | 4 | import collections
class BinarySearchTree(object):
def __init__(self):
self.root = None
def clear(self):
self.root = None
def insert(self, node):
if not self.root:
self.root = node
return
root = self.root
while True:
if node.val >= root.val:
if root.right == None:
root.right = node
break
else:
root = root.right
elif node.val < root.val:
if root.left == None:
root.left = node
break
else:
root = root.left
def remove(self, key):
"""
分三种情况:
1. 删除节点没有子节点, 那么直接删除就可以了
2. 如果删除节点只有一个子节点, 那么用这个子节点代替就可以了
3. 如果删除节点有两个子节点, 这时候找到右子节点树的最小节点, 然后把左子节点挂在这个节点左子树位置上, 然后将右子树挂在父节点上
但是要考虑删除的是不是父节点...
"""
father = self.root
node = father
while node:
if node.val < key:
father = node
node = node.right
elif node.val > key:
father = node
node = node.left
else:
break
# 防止遇到没找到的情况
assert node and node.val == key
# 1. 找到的节点没有子节点
if not node.left and not node.right:
# node == father是表示删除的是根节点
if father == node:
self.root = None
else:
if node == father.right:
father.right = None
elif node == father.left:
father.left = None
else:
raise "Delete Error 1"
# 2. 找到的节点只有一个子节点
# 只有左子树
elif node.left and not node.right:
if father == node:
self.root = node.left
else:
if father.right == node:
father.right = node.left
elif father.left == node:
father.left = node.left
else:
raise "Delete Error 2-1"
elif node.right and not node.left:
if father == node:
self.root = node.right
else:
if father.right == node:
father.right = node.right
elif father.left == node:
father.left = node.right
else:
raise "Delete Error 2-2"
# 3. 找到的节点有两个子节点
else:
# 首先找到右子节点的直接后继
right = node.right
rightLeft = right
while rightLeft.left:
rightLeft = rightLeft.left
# 然后开始移动
if father == node:
self.root = node.right
rightLeft.left = node.left
else:
left = node.left
rightLeft.left = left
if node == father.left:
father.left = node.right
elif node == father.right:
father.right = node.right
else:
raise "Delete Error 3"
def find(self, key):
root = self.root
if root.val == key:
return root
while root:
if root.val < key:
root = root.right
elif root.val > key:
root = root.left
else:
return root
return None
def isEmpty(self):
return self.root == None
def queueTravel(self):
if not self.root:
print("None")
return
root = self.root
queue = collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
print(node.val, end=" ")
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
print()
def postTravel(self):
if self.root:
self.travelP(self.root)
print()
else:
print("None")
def travelP(self, node):
if not node:
return
self.travelP(node.left)
self.travelP(node.right)
print(node.val, end=" ")
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def testBinarySearchTree():
l = [6, 3, 8, 1, 5, 3, 4]
T = BinarySearchTree()
for i in l:
T.insert(TreeNode(i))
T.queueTravel()
T.postTravel()
print("Begin remove:")
T.remove(6)
T.queueTravel()
T.postTravel()
while not T.isEmpty():
T.remove(T.root.val)
T.queueTravel()
T.postTravel()
testBinarySearchTree() |
67c83d04cc00e3d9acb024ace11f211e080c11ef | microainick/high_low_game2 | /MyBBcomGuess.py | 4,240 | 4.15625 | 4 | #import
import random
#make ran be a random integer between 1 and 128)
ran = random.randint(1, 128)
int(ran)
#it probably was an integer but that was to ensure it.
#Print eplanation
#spacing for readability
#i like the formatting this way with spaces
print(" ")
print("If the computer has 7 chances to calculate the Secret Number then our range can excede 100")
print(" ")
print("To go above and beyond we will allow the Secret Number to be bewteen 1 and 128")
print(" ")
print("Certainly this can still be done in 7 turns")
print(" ")
print(" ")
#print secret number to the screen, to show the user the computers goal
#use .format
print("The Secret number randomly generated is {}".format(ran))
#create a function to generate computer guesses
#ran is the secret number
#previous com guess is cg1
#change is half the interval remaining
#cg2 is the next guess
#if ran is greater than cg1, then cg2 is cg1 plus change
#if ran is less than cg1, then cg2 is cg1 minus change
#then print higher or lower respectively
#return next guess as cg2
def Eval(cg1, change):
if ran > cg1:
cg2 = cg1 + change
print("The Secret number is Higher")
if ran < cg1:
cg2 = cg1 - change
print("The Secret number is Lower")
return cg2
#make variable for solution found (solfnd)
#set solfnd to false and use to conitue
#change solfnd to true if computer completes task
solfnd = False
#first guess will always be 64
#make that an integer
#print the round #
#display the next guess
cg1 = 64
int(cg1)
print("Round 1")
print("Computer selects {}".format(cg1))
#if computer gets the secret number then print computer wins
#if computer wins, change solfnd to true
if ran == cg1:
print("Computer wins")
solfnd = True
#as long as solution is not found continue
#generate next com guess with 32 as the plus or minus
#display the round number
#show com guess with .format
#end game if computer is right
if solfnd == False:
cg2 = Eval(cg1, 32)
input("press enter to continue")
print("Round 2")
print("Computer selects {}".format(cg2))
if ran == cg2:
print("Computer wins")
solfnd = True
#as long as solution is not found continue
#generate next com guess with 16 as the plus or minus
#display the round number
#show com guess with .format
#end game if computer is right
if solfnd == False:
cg3 = Eval(cg2, 16)
input("press enter to continue")
print("Round 3")
print("Computer selects {}".format(cg3))
if ran == cg3:
print("Computer wins")
solfnd = True
#as long as solution is not found continue
#generate next com guess with 8 as the plus or minus
#display the round number
#show com guess with .format
#end game if computer is right
if solfnd == False:
cg4 = Eval(cg3, 8)
input("press enter to continue")
print("Round 4")
print("Computer selects {}".format(cg4))
if ran == cg4:
print("Computer wins")
solfnd = True
#as long as solution is not found continue
#generate next com guess with 4 as the plus or minus
#display the round number
#show com guess with .format
#end game if computer is right
if solfnd == False:
cg5 = Eval(cg4, 4)
input("press enter to continue")
print("Round 5")
print("Computer selects {}".format(cg5))
if ran == cg5:
print("Computer wins")
solfnd = True
#as long as solution is not found continue
#generate next com guess with 2 as the plus or minus
#display the round number
#show com guess with .format
#end game if computer is right
if solfnd == False:
cg6 = Eval(cg5, 2)
input("press enter to continue")
print("Round 6")
print("Computer selects {}".format(cg6))
if ran == cg6:
print("Computer wins")
solfnd = True
#as long as solution is not found continue
#generate next com guess with 1 as the plus or minus
#display the round number and that it is the last
#show com guess with .format and that it must be right
#end game because the computer will be right!
if solfnd == False:
cg7 = Eval(cg6, 1)
input("press enter to continue")
print("Final Round; Round 7!")
print("The Computer says your number must be {}".format(cg7))
keepitgoing = False
|
e7f2b44f135a6bc488adc96c27b0686b522c4b62 | wow01022634/udemy_python_quickstart | /6_Class/6-1_class.py | 171 | 3.578125 | 4 | class Customer:
def __init__(self, name, city):
self.name = name
self.city = city
p1 = Customer("peter","Austin")
print(p1.name)
print(p1.city) |
ac1eaa54f645a7b2d5fee018d5b6720fb7e8b9a7 | xinshuoyang/algorithm | /src/86_BinarySearchTreeIterator/solution.py | 1,325 | 3.890625 | 4 | #!/usr/bin/python
################################################################################
# NAME : solution.py
#
# DESC :
#
# AUTH : Xinshuo Yang
#
# DATE : 20181229
#
################################################################################
"""
Definition of TreeNode:
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class BSTIterator:
"""
@param: root: The root of binary tree.
"""
def __init__(self, root):
# do intialization if necessary
self.stack = []
while root:
self.stack.append(root)
root = root.left
"""
@return: True if there has next node, or false
"""
def hasNext(self, ):
# write your code here
return len(self.stack)
"""
@return: return next node
"""
def next(self, ):
# write your code here
node = self.stack.pop()
n = node.right
while n:
self.stack.append(n)
n = n.left
return node
if __name__ == "__main__":
root = TreeNode(10)
root.left = TreeNode(1)
root.right = TreeNode(11)
root.left.right = TreeNode(6)
root.right.right = TreeNode(12)
obj = BSTIterator(root)
while obj.hasNext():
print(obj.next().val)
|
c3c1feafa7e3962240985ded734dd3a6192ee4ab | slavamirovsky/The-tasks-Python- | /task_8.py | 890 | 4.65625 | 5 | ## 8. Volume of a Spherical Shell
## The volume of a spherical shell is the difference between the enclosed volume
## of the outer sphere and the enclosed volume of the inner sphere:
##
## Create a function that takes r1 and r2 as arguments and returns the volume of
## a spherical shell rounded to the nearest thousandth.
##
## Notes
## The inputs are always positive numbers. r1 could be the inner radius or the
## outer radius, don't return a negative number.
def vol_shell (r1, r2):
import math
R = abs (r1)
r = abs (r2)
if R < r:
R, r = r, R
v_betw_sph = 4 / 3 * math.pi * (R ** 3 - r ** 3)
if v_betw_sph >= 0:
return print ("The volume of a spherical shell is %.3f" %v_betw_sph)
r1 = int (input ("Input the radius of outer-sphere "))
r2 = int (input ("Input the radius of inner-sphere "))
vol_shell (r1, r2)
|
05a17191a8f890f24811ef6ab7d2128fce7a96d4 | humachine/AlgoLearning | /leetcode/Done/416_PartitionEqualSubsetSum.py | 2,698 | 3.53125 | 4 | #https://leetcode.com/problems/partition-equal-subset-sum/
# There also exists a bitset solution which uses O(max possible sum of all numbers) space and O(N) time
"""
Inp: [1, 5, 11, 5]
Out: True (can be partitioned into 11 and the rest)
Inp: [1, 2, 3, 5]
Out: False (no equal partition of the array possible)
Inp: [1, 2, 3, 4, 5, 6, 7, 8]
Out: True (1, 8, 3, 6 and the rest is an equal partition)
"""
from bisect import bisect_left
class Solution(object):
def canPartition(self, nums):
if not nums:
return True
if len(nums) == 1:
return False
arraySum = sum(nums)
if arraySum & 1 == 1:
return False
# If we have to partition the array, we have to find a subset of the array that adds up to arraySum/2
nums = sorted(nums)
target = arraySum/2
n = len(nums)
# li1 is a set which contains all the unique sums obtained until now
# At each step, we take all the possible sums and add the current element to it and update li1
li1 = {0}
li2 = []
for i in xrange(1, n):
li2 = [nums[i] + x for x in li1]
li1.update(li2)
# If arraySum/2 exists in li1, then there exists SOME subset of nums which can split the array
return target in li1
def canPartitionDP(self, nums):
if not nums: return True
if len(nums) == 1: return False
arraySum = sum(nums)
target = arraySum/2
if arraySum & 1:
return False
nums = sorted(nums)
#DP represents a list which contains whether a particular sum can be achieved using a subset of nums
dp = [False]*(target+1)
dp[0] = True
"""
For each number x, we begin from sum and loop down until x
For each number we loop across, we check if number-x is True. If so, we assign that number to be True too.
nums = [2, 3, 5]
Eg: 0 is True
While looping down, 2 is set to True (2-2=0 is True)
While looping down, 5, 3 is set to True (5-3=2 is True & 3-3=0 is True)
Note:
Had we looped up from x until sum, we would have had incorrect answers
nums = [1, 2, 5]
First iteration, 1 is set to True (Since 1-1=0 is True). Then 2 is set to True (2-1=1 is True) and so on ...
"""
for i in xrange(len(nums)):
for j in xrange(target, nums[i]-1, -1):
dp[j] |= dp[j-nums[i]]
return dp[target]
s = Solution()
print s.canPartitionDP([1, 5, 11, 5])
print s.canPartitionDP([1, 2, 3, 5])
print s.canPartitionDP([1, 2, 5])
print s.canPartition(range(8))
|
812682b6cb8efc47ba3eddab3eba16234bc46927 | mayrazan/exercicios-python-unoesc | /comparação/1.py | 317 | 4.15625 | 4 | numero1 = input("Informe um número: ")
numero2 = input("Informe um número: ")
if numero1 > numero2:
print("O maior numero é %s." % numero1)
elif numero1 < numero2:
print("O maior numero é %s." % numero2)
elif numero1 == numero2:
print("O numero %s e o numero %s são iguais." % (numero1, numero2)) |
979c8644423e6650c10f19eae1ec31589f251ecf | poornachandrakashi/OOPs-in-Python | /Employee.py | 579 | 3.796875 | 4 | class Employess():
#Definiing the initializers
def __init__(self,ID=None,salary=None,department=None):
self.ID=ID
self.salary=salary
self.department=department
def tax(self):
return(self.salary*0.2)
def salaryperday(self):
return(self.salary/30)
#Initializing the object to the Employess class
poorna=Employess(2525,20000000,"Artificial intelligence")
print("Id=",poorna.ID)
print("Salary=",poorna.salary)
print("Department=",poorna.department)
print("Tax=",poorna.tax())
print("Salary per Day=",poorna.salaryperday())
|
4209dae8f28831a9b2f8a1a90971830c7ec3d161 | Quantanalyst/SoftwareEngineeringNotes | /Data Structure and Algorithms/Popular Questions/toptal test.py | 2,851 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 7 16:46:47 2020
@author: saeed
"""
def solution(N,K):
if N < 2:
return 0
else:
if K == 0:
return N - 1
elif (K !=0) & ((N // (2**K)) > 0):
X = N // (2**K)
res = N % (2**K)
return (X-1) + K + res -1
else:
for k in range(0,K):
if (N//(2**k)) == 1:
idx = k
X = N // (2**idx)
res = N % (2**idx)
return (X-1) + idx + res -1
solution(18,2)
def solution(A):
numcountries = 1
N = len(A) # number of rows
M = len(A[0]) # number of columns
arr = [i for i in range(M*N)]
if (M == 1) & (N ==1):
return 1
# else:
# uniquecolor = A[0][0]
# arr.remove(0)
# for i in range(1, M*N):
# if i in arr:
# row = i//M
# col = i % M
# if A[row][col] != uniquecolor:
# numcountries +=1
# uniquecolor = A[row][col]
# arr.remove(i)
#
# else:
# pass
#
A = [[2,3,4],[6,3,8],[9,5,1]]
## # Python3 program for finding the maximum number
# of trailing zeros in the product of the
# selected subset of size k.
MAX5 = 100
# Function to calculate maximum zeros.
def maximumZeros(arr, n, k):
global MAX5
# Initializing each value with -1
subset = [[-1] * (MAX5 + 5) for _ in range(k + 1)]
subset[0][0] = 0
for p in arr:
pw2, pw5 = 0, 0
# Calculating maximal power
# of 2 for arr[p].
while not p % 2 :
pw2 += 1
p //= 2
# Calculating maximal power
# of 5 for arr[p].
while not p % 5 :
pw5 += 1
p //= 5
# Calculating subset[i][j] for maximum
# amount of twos we can collect by
# checking first i numbers and taking
# j of them with total power of five.
for i in range(k-1, -1, -1):
for j in range(MAX5):
# If subset[i][j] is not calculated.
if subset[i][j] != -1:
subset[i + 1][j + pw5] = (
max(subset[i + 1][j + pw5],
(subset[i][j] + pw2)))
# Calculating maximal number of zeros.
# by taking minimum of 5 or 2 and then
# taking maximum.
ans = 0
for i in range(MAX5):
ans = max(ans, min(i, subset[k][i]))
return ans
# Driver function
arr = [ 50, 4, 20 ]
k = 2
n = len(arr)
print(maximumZeros(arr, n, k))
# This code is contributed by Ansu Kumari.
|
700ee9093a2dbd55ebf6fb1028ca1c44eee76a9f | Ldarrah/edX-Python | /PythonII/3.3.3 Coding Problem sumloop.py | 947 | 4.125 | 4 | mystery_int = 7
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#Use a loop to find the sum of all numbers between 0 and
#mystery_int, including bounds (meaning that if
#mystery_int = 7, you add 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7).
#
#However, there's a twist: mystery_int might be negative.
#So, if mystery_int was -4, you would -4 + -3 + -2 + -1 + 0.
#
#There are a lot of different ways you can do this. Most of
#them will involve using a conditional to decide whether to
#add or subtract 1 from mystery_int.
#
#You may use either a for loopor a while loop to solve this,
#although we recommend using a while loop.
#Add your code here!
sumnum = 0
if mystery_int <= 0:
for i in range(mystery_int,0):
sumnum = sumnum + i
print (sumnum)
else:
for i in range(0, mystery_int +1):
sumnum += i
print(sumnum) |
029a2b40b859a6282eef809474756486f8ef2ec9 | JDHProjects/AOC-2020 | /day3/day3.py | 452 | 3.515625 | 4 | def getTreeCount(inData, x, y):
treeCount = 0
xOffset = 0
for i in range(0,len(inData),y):
if(xOffset >= len(inData[i])):
xOffset -= len(inData[i])
if(inData[i][xOffset] == "#"):
treeCount += 1
xOffset += x
return treeCount
def multiSlope(inData, slopeList):
total = 1
for slope in slopeList:
total = total * getTreeCount(inData,slope[0],slope[1])
return total |
1f3cb8e812212b5bf2d29ae765db38b553691436 | Kent1004/Python_1try | /Krivykh_Mikhail_dz_3/task3_5.py | 1,996 | 3.671875 | 4 |
from random import choice,choices,shuffle, randint, sample
nouns = ["автомобиль", "лес", "огонь", "город", "дом"]
adverbs = ["сегодня", "вчера", "завтра", "позавчера", "ночью"]
adjectives = ["веселый", "яркий", "зеленый", "утопичный", "мягкий"]
"""Функция - генератор шуток из заданных списков"""
def get_jokes(number):
jokes=[]
jokes.append(','.join(f'"{choice(nouns)} {choice(adverbs)} {choice(adjectives)}"' for i in range(number)))
print(jokes)
"""repeat принимает значение 1 или 2 ( 1 - генерация с повторами, 2 - генерация без повторов"""
def get_jokes_adv (number, repeat):
jokes_adv=[]
"""Проверка на флаг повтора"""
if repeat == 2 :
"""Проверка сравнения аргумента количества шуток и макс длины списка, тк возможно вывести 5 шуток без повторов"""
if number > len(nouns):
"""Промежуточные списки без повторов"""
nounsNR = sample(nouns, 5)
adverbsNR = sample(adverbs, 5)
adjectivesNR = sample(adjectives, 5)
jokes_adv.append(','.join(f'"{nounsNR[i]} {adverbsNR[i]} {adjectivesNR[i]}"' for i in range(5)))
print('Возможно сгенерировать только 5 шуток без потворов\n',jokes_adv)
else:
nounsNR = sample(nouns, number)
adverbsNR = sample(adverbs, number)
adjectivesNR = sample(adjectives, number)
jokes_adv.append(','.join(f'"{nounsNR[i]} {adverbsNR[i]} {adjectivesNR[i]}"' for i in range(number)))
print(jokes_adv)
else:
get_jokes(number)
get_jokes(6)
get_jokes_adv(8,1)
get_jokes_adv(6,2)
get_jokes_adv(3,2)
|
cc48b26bdd1934e2407c91cf227b0d1c63492a9a | boboalex/LeetcodeExercise | /leetcode_105.py | 1,089 | 3.875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, preorder, inorder) -> TreeNode:
def myBuildTree(preLeft, preRight, inLeft, inRight):
if preLeft > preRight:
return None
preRoot = preLeft
node = TreeNode(preorder[preRoot])
inRoot = index_dict[preorder[preRoot]]
sub_left_size = inRoot - inLeft
node.left = myBuildTree(preLeft + 1, sub_left_size + preLeft, inLeft, inRoot - 1)
node.right = myBuildTree(sub_left_size + preLeft + 1, preRight, inRoot + 1, inRight)
return node
index_dict = {element: index for index, element in enumerate(inorder)}
N = len(preorder)
return myBuildTree(0, N - 1, 0, N - 1)
if __name__ == '__main__':
preorder = [3, 9, 20, 15, 7]
inorder = [9, 3, 15, 20, 7]
s = Solution()
res = s.buildTree(preorder, inorder)
print(res)
|
91e6486cc3ed3f523f2c72bba9ee34f278176da0 | nmanley03/final_project | /Python.py | 891 | 3.703125 | 4 | import pandas as pd
import numpy as np
#import csv file
data = pd.read_csv(r"/Users/niallmanley/Downloads/Final_Project/202021Football1.csv")
avgage = data['age'].mean()
print(avgage)
#Some players ages appearing as 0, as well as birthday field. Clean data and replace 0 in age with avg age of 23
data.loc[data['birthday'] == 0, 'age'] = 23
#Function to filter data to Current Club column, and drop duplicates in order to print each different team
teams = data['Current Club']
print(teams)
unique_teams = teams.drop_duplicates()
#Convert list of teams without duplicates into dictionary
allteams = unique_teams.to_dict()
print('Number of teams in the top 4 divisions of English football:')
print(len(allteams))
#Convert unique_teams into numpy array and print the list of teams
ary = unique_teams.to_numpy()
print(ary.shape)
print(type(ary))
print('The teams are as follows:')
print(ary) |
a10dbaba77a40d21bab0182a3dfadeaed29bbbff | mittsahl/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 378 | 3.828125 | 4 | #!/usr/bin/python3
"""MyInt class"""
class MyInt(int):
""" Canging equality attributes of int class"""
def __eq__(self, other):
"""Chagnes equality artributes form equal to not equal"""
return int.__ne__(self, other)
def __ne__(self, other):
"""changes equality attributes from not equal to equal"""
return int.__eq__(self, other)
|
ff0b73331098958831e435fdef6b67432f6efb39 | mischief901/nyt_unscrambler | /unscramble.py | 672 | 3.53125 | 4 | import sys
import getopt
import bisect
def main(letters, center) :
words = open("/usr/share/dict/american-english", "r")
for word in words :
word = word.lower().strip()
if center not in word :
continue
if len(word) < 4 :
continue
lets = "".join(sorted(set(word)))
valid = True
for l in lets :
if l not in letters :
valid = False
if valid :
print(word)
if __name__ == "__main__" :
args = sys.argv
letters = "".join(sorted(args[1].lower()))
center = args[2].lower()
if len(letters) is not 7 or len(center) is not 1 :
exit(1)
print(letters)
print(center)
main(letters, center)
|
be1c8e737259555b7e78550e1097609e01c4badf | chitreshd/puzzles | /hackerrank/findPossibleSentences.py | 1,314 | 4.03125 | 4 | # For a given string and dictionary, how many sentences can you make from the string, such that all the words are contained in the dictionary.
# // eg: for given string -> "appletablet"
# // "apple", "tablet"
# // "applet", "able", "t"
# // "apple", "table", "t"
# // "app", "let", "able", "t"
# // "applet", {app, let, apple, t, applet} => 3
# // "thing", {"thing"} -> 1
def findPossiSent(string, start, end, dictionary):
print 'input: {0} start: {1} end: {2}'.format(string[start:end], start, end)
if start >= end:
return 1
possibilities = 0;
for i in range(start, end + 1):
left_str = string[start:i]
print 'Checking {0} from {1} to {2} [exclusive]'.format(left_str, start, i)
if left_str in dictionary:
right = findPossiSent(string, i, end, dictionary)
possibilities += right
return possibilities
dictionary = ['ab', 'c', 'd']
string = 'abcd'
print findPossiSent(string, 0, len(string), set(dictionary))
dictionary = ['app', 'let', 'apple', 't', 'applet']
string = 'applet'
print findPossiSent(string, 0, len(string), set(dictionary))
dictionary = ['thing']
string = 'thing'
print findPossiSent(string, 0, len(string), set(dictionary))
dictionary = ['app', 'let', 'apple', 't', 'applet']
string = 'applets'
print findPossiSent(string, 0, len(string), set(dictionary))
|
328b17bc68ccbe85cc8e5125c1a6edc5e7c1b2a3 | jackHorwell/automatedChessBoard | /main.py | 13,828 | 3.5 | 4 | # Imports modules to control raspberry pi GPIO
import RPi.GPIO as GPIO
import time
import charlieplexing
# Sets up Stockfish engine
from stockfish import Stockfish
stockfish = Stockfish("/home/pi/Downloads/a-stockf")
stockfish = Stockfish(parameters={"Threads": 2, "Minimum Thinking Time": 30})
stockfish.set_skill_level(1)
# 97 is the ASCII code for a, using this we can reduce this down to a numeric form
asciiA = 97
# Class to store piece attributes like colour and type
class Piece:
def __init__(self, colour, pieceType, icon):
self.colour = colour
self.pieceType = pieceType
self.icon = icon
# Class to group together piece initialisation
class Pieces:
def initialisePieces(self):
# Initalises the piece objects and passes their attributes
self.wp = Piece("white", "pawn", "♙")
self.wr = Piece("white", "rook", "♖")
self.wkn = Piece("white", "knight", "♞")
self.wb = Piece("white", "bishop", "♗")
self.wq = Piece("white", "queen", "♕")
self.wk = Piece("white", "king", "♔")
self.bp = Piece("black", "pawn", "♟")
self.br = Piece("black", "rook", "♜")
self.bkn = Piece("black", "knight", "♞")
self.bb = Piece("black", "bishop", "♝")
self.bq = Piece("black", "queen", "♛")
self.bk = Piece("black", "king", "♚")
# Class to store the current state and last known legal state of the board
class BoardRecord:
def __init__(self, p):
# Stack to store previous move
self.previousMoves = []
# Dictionaries linking the name of a piece with its object
self.whitePieceObjects = {"q": p.wq, "k": p.wk, "r": p.wr, "n": p.wkn, "b": p.wb, "p": p.wp}
self.blackPieceObjects = {"q": p.bq, "k": p.bk, "r": p.br, "n": p.bkn, "b": p.bb, "p": p.bp}
# Creates a 2D array to store piece locations
self.board = [[p.wr,p.wkn,p.wb,p.wq,p.wk,p.wb,p.wkn,p.wr],
[p.wp,p.wp,p.wp,p.wp,p.wp,p.wp,p.wp,p.wp],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[p.bp,p.bp,p.bp,p.bp,p.bp,p.bp,p.bp,p.bp],
[p.br,p.bkn,p.bb,p.bq,p.bk,p.bb,p.bkn,p.br]]
# Getter for board variable
def getBoard(self):
# Prints each row and converts objects into their assigned icons
for row in range(7, -1, -1):
rowToPrint = []
for square in self.board[row]:
if square != 0:
rowToPrint.append(square.icon)
else:
rowToPrint.append("0 ")
print("".join(rowToPrint))
return self.board
# Setter for board variable
# Takes two coordinates and moves a piece to it's new position
def setBoard(self, pieceFrom, pieceTo, move):
self.board[pieceTo[1]][pieceTo[0]] = self.board[pieceFrom[1]][pieceFrom[0]]
self.board[pieceFrom[1]][pieceFrom[0]] = 0
# Adds move made to the previousMoves array
if move != "castle":
self.previousMoves.append(move)
# Updates the moves made for the engine
stockfish.set_position(self.previousMoves)
# Function to change a piece type on the board
def promotePiece(self, position, colour, promoteTo):
if colour == "w":
self.board[position[1]][position[0]] = self.whitePieceObjects[promoteTo]
elif colour == "b":
self.board[position[1]][position[0]] = self.blackPieceObjects[promoteTo]
# Stores the pin numbers used for the rows and columns
# Index + 1 is the row number
rowPins = [23, 18, 11, 9, 10, 22, 27, 17]
columnPins = [21, 20, 16, 12, 7, 8, 25, 24]
# Sets the pins to be inputs or outputs
def pinSetup():
GPIO.setmode(GPIO.BCM)
for pin in rowPins:
GPIO.setup(pin, GPIO.OUT)
for pin in columnPins:
GPIO.setup(pin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
# Function to turn off all the row pins to make sure none are accidently left on
def resetRowPins():
for pin in rowPins:
GPIO.output(pin, 0)
# Function to return the position of pieces in a 2D array
def scanCurrentBoard():
board = []
# Provides power to rows one by one and checks columns for input
# Stores the output to board array
for row in range(8):
board.append([])
GPIO.output(rowPins[row], 1)
for column in range(8):
board[row].append(GPIO.input(columnPins[column]))
GPIO.output(rowPins[row], 0)
return board
'''
Used for development purposes, delete in final
'''
for i in range(7, -1, -1):
print(" ".join(map(str,board[i])))
print("\n\n")
# Takes the current state of the board and repeatedly checks
# for a change. Once found will return the position of the change
# Takes an optional paramater if we are checking for movement to a square
# to prevent the piece being detected twice
"""
Could optimise with wait for edge?
"""
def reportChange(moveFrom = None):
resetRowPins()
oldBoard = scanCurrentBoard()
while True:
newBoard = scanCurrentBoard()
if newBoard != oldBoard:
for row in range(8):
if newBoard[row] != oldBoard[row]:
for column in range(8):
if newBoard[row][column] != oldBoard[row][column]:
if moveFrom != [column, row]:
resetRowPins()
return [column, row]
# Function that waits for a square to turn from on to off
def detectFallingAtPosition(coordinates):
GPIO.output(rowPins[coordinates[1]], 1)
GPIO.add_event_detect(columnPins[coordinates[0]], GPIO.FALLING)
numberRows = [8, 7, 6, 5, 4, 3, 2, 1]
numberCols = [9, 10, 11, 12, 13, 14, 15, 16]
while True:
# Lights up position
charlieplexing.turnOn(numberRows[coordinates[1]])
charlieplexing.turnOn(numberCols[coordinates[0]])
# Breaks loop once piece is picked up
if GPIO.event_detected(columnPins[coordinates[0]]):
GPIO.remove_event_detect(columnPins[coordinates[0]])
charlieplexing.turnOn(0)
break
#GPIO.wait_for_edge(columnPins[coordinates[0]], GPIO.FALLING)
GPIO.output(rowPins[coordinates[1]], 0)
# Function that waits for a square to turn from off to on
def detectRisingAtPosition(coordinates):
GPIO.output(rowPins[coordinates[1]], 1)
GPIO.add_event_detect(columnPins[coordinates[0]], GPIO.RISING)
numberRows = [8, 7, 6, 5, 4, 3, 2, 1]
numberCols = [9, 10, 11, 12, 13, 14, 15, 16]
while True:
# Lights up position
charlieplexing.turnOn(numberRows[coordinates[1]])
charlieplexing.turnOn(numberCols[coordinates[0]])
# Breaks loop once piece is placed down
if GPIO.event_detected(columnPins[coordinates[0]]):
GPIO.remove_event_detect(columnPins[coordinates[0]])
charlieplexing.turnOn(0)
break
#GPIO.wait_for_edge(columnPins[coordinates[0]], GPIO.FALLING)
GPIO.output(rowPins[coordinates[1]], 0)
# Will return True if there is currently a piece at the given coordinates
def isOccupied(coordinates):
board = currentBoard.getBoard()
if board[coordinates[1]][coordinates[0]] != 0:
return True
else:
return False
# Function to take a move generated by the computer
# and update the board if there has been a promotion
def checkForPromotion(move, toMove):
if len(move) == 5:
currentBoard.promotePiece(toMove, computerColour, move[-1])
print(f"Piece is now {move[-1]}")
# Function to determine if a player can promote a piece, if true then
# the player is asked to which piece he would like to promote
# Input is then returned
def checkForPromotionOpportunity(moveTo, moveFrom):
board = currentBoard.getBoard()
promoteTo = ""
# Checks for white pawns in black back line
if moveTo[1] == 7 and board[moveFrom[1]][moveFrom[0]].pieceType == "pawn":
promoteTo = input("What would you like to promote to: ")
# Checks for black pawns in white back line
if moveTo[1] == 0 and board[moveFrom[1]][moveFrom[0]].pieceType == "pawn":
promoteTo = input("What would you like to promote to: ")
# If promotion is not available then "" is returned
return promoteTo
# Function to detect if AI or player has castled and tells the user to move the castle
def checkForCastle(move, fromMove):
board = currentBoard.getBoard()
if board[fromMove[1]][fromMove[0]].pieceType == "king":
# Detects which castling move has been made and moves castle
if move == "e1c1":
currentBoard.setBoard([0, 0], [3, 0], "castle")
moveComputerPieces([0, 0], [3, 0], "a1c1")
elif move == "e1g1":
currentBoard.setBoard([7, 0], [5, 0], "castle")
moveComputerPieces([7, 0], [5, 0], "h1f1")
elif move == "e8c8":
currentBoard.setBoard([0, 7], [3, 7], "castle")
moveComputerPieces([0, 7], [3, 7], "a8c8")
elif move == "e8g8":
currentBoard.setBoard([7, 7], [5, 7], "castle")
moveComputerPieces([7, 7], [5, 7], "h8f8")
# Function to make sure that the pieces are where they're meant to be
# Recursively calls itself until all pieces are in the correct position
def checkBoardIsLegal():
board = currentBoard.getBoard()
for row in range(8):
resetRowPins()
GPIO.output(rowPins[row], 1)
for column in range(8):
# First checks for pieces where no pieces should be
if board[row][column] == 0 and GPIO.input(columnPins[column]) == 1:
print(f"Remove piece from: {convertToChessNotation([column, row])}")
detectFallingAtPosition([column, row])
resetRowPins()
checkBoardIsLegal()
return
# Then checks for empty spaces where pieces should be
elif board[row][column] != 0 and GPIO.input(columnPins[column]) == 0:
print(f"Place {board[row][column].colour.capitalize()} {board[row][column].pieceType.capitalize()} on {convertToChessNotation([column, row])}")
detectRisingAtPosition([column, row])
resetRowPins()
checkBoardIsLegal()
return
resetRowPins()
# Function to tell player where to move pieces
def moveComputerPieces(moveFrom, moveTo, move):
# Tells user which piece to pick up, checks for piece removal
print(f"Move piece from {move[0:2]}")
detectFallingAtPosition(moveFrom)
# Checks if moveTo position is already occupied, if so tells user to remove it
if isOccupied(moveTo):
print(f"Remove piece from {move[2:]}")
detectFallingAtPosition(moveTo)
# Tells user where to move piece
print(f"Move piece to {move[2:]}")
detectRisingAtPosition(moveTo)
print("Thank you!")
resetRowPins()
# Function to convert move to chess notation (for Stockfish)
# Example: "a2"
def convertToChessNotation(move):
return chr(ord('a') + move[0]) + str(move[1] + 1)
# Function to convert chess notation to move
# Example: [1, 1]
def convertToMove(chessNotation):
return [ord(chessNotation[0]) - asciiA, int(chessNotation[1]) - 1]
# Function to obtain the move a player makes
def getPlayerMove():
moveFrom = reportChange()
print(f"From: {moveFrom}")
moveTo = reportChange(moveFrom)
print(f"To {moveTo}")
# Checks if a pawn can be promoted
promotion = checkForPromotionOpportunity(moveTo, moveFrom)
if isOccupied(moveTo):
print("Place down piece")
detectRisingAtPosition(moveTo)
# Adds the from move, to move and promotion if available so the AI can understand it
move = convertToChessNotation(moveFrom) + convertToChessNotation(moveTo) + promotion
# Checks if player has castled
checkForCastle(move, moveFrom)
if stockfish.is_move_correct(move):
print("legal shmegle")
currentBoard.setBoard(moveFrom, moveTo, move)
# If player has promoted a piece then board is updated
if promotion != "":
promotePiece(moveTo, playerColour, promotion)
currentBoard.getBoard()
else:
print("Not a legal move")
charlieplexing.allFlash()
checkBoardIsLegal()
getPlayerMove()
return
# Function to get the AI to generate a move
def generateMove():
move = stockfish.get_best_move()
# Splits move into where it's moving from and where it's moving to
# Converts letters into their corresponding alphabet
# Both arrays have: column then row
fromMove = convertToMove(move[0:2])
toMove = convertToMove(move[2:4])
moveComputerPieces(fromMove, toMove, move)
# Checks if player has castled
checkForCastle(move, fromMove)
# Updates board
currentBoard.setBoard(fromMove, toMove, move)
checkForPromotion(move, toMove)
p = Pieces()
p.initialisePieces()
currentBoard = BoardRecord(p)
computerColour = "b"
playerColour = "w"
pinSetup()
m = input("")
resetRowPins()
checkBoardIsLegal()
while True:
getPlayerMove()
checkBoardIsLegal()
evaluation = stockfish.get_evaluation()
print(evaluation)
if evaluation["type"] == 'mate' and evaluation["value"] == 0:
while True:
charlieplexing.slide("fast")
generateMove()
checkBoardIsLegal()
evaluation = stockfish.get_evaluation()
print(evaluation)
if evaluation["type"] == 'mate' and evaluation["value"] == 0:
while True:
charlieplexing.slide("fast")
|
9ae8aeb122efb8a83f9004157b5a62d684a35b07 | ShamiliS/Java_Backup | /SimplePython/callFunction.py | 462 | 3.609375 | 4 | '''
Created on 4 Apr 2018
@author: SHSRINIV
'''
import math
import SampleFunction
import var_len_arg
# module1
var_len_arg.printinfo(56, 20, 10)
# module2
prntval = SampleFunction.samplefun("Shamili")
for val in prntval:
print(val)
content = dir(math)
print(content)
def sum(a, b):
"Adding the two values"
print("Printing within Function")
print(a + b)
return a + b
total = sum(10, 20)
print("Printing Outside:", total)
|
12c54f72446d434e9cb8a9f758e0b1955d378568 | Joelciomatias/programming-logic-python | /3-if-elif.py | 913 | 3.875 | 4 | """
Escreva um programa que leia um nome e idade
e no final escrever no terminal,
se for igual ou maior que 18: é obrigatório o voto,
se for igual ou menor que 16: ainda não tem idade para votar,
se for igual ou maior que 16 e menor que 18: voto é facultativo.
Exemplo 1:
Entradas:
> José
> 20
Saída:
José tem 20 anos e é obrigatório o voto
Exemplo 2:
Entradas:
> Maria
> 15
Saída:
Maria tem 15 anos e ainda não tem idade para votar
Exemplo 3:
Entradas:
> João
> 17
Saída:
Maria tem 15 anos e o voto é facultativo
"""
print('#### início programa ####\n')
##################################
##################################
print('\n#### fim programa #######')
"""
Utilize o espaço demarcado
Utilizar se possível a espressão 'elif'(atalho para else if )
Refência:
https://www.w3schools.com/python/ref_keyword_elif.asp
""" |
fd679b56155868bd0dbfc3bc2bbb28d98d477d08 | gschen/where2go-python-test | /1906101009肖文星/ago/实验5.2.py | 234 | 3.75 | 4 | def isPrime(q):
if type(q)==int:
for i in range(2,q):
if q%i==0:
print("False")
break
else:
print("Ture")
else:
print("你输入的不是整数")
|
5c00e3e6e4c3385d79b8c82c53a23e02a6949758 | gozelalmazovna/Caesar-Cipher-Code-in-Python | /caesar-code.py | 1,646 | 3.796875 | 4 | def num_offset(num):
"""Checking offset number to be in range of A to Z code values
Preconditions:
num = int
Result:
boolean
"""
if 90 >= num >= 65: #Conditions for offset from A = 65 to Z = 90
return True
else:
return False
def turn_around(num):
""" To turn around the alphabet when offset in negative or positive
Preconditions:
num = int
Result
num = int value for the new letter
"""
if num > 90:
num = 64 + (num - 90)
return num
elif num < 65:
num = 90 - (64 - num)
return num
else:
return num
def caesar(string,offset):
"""The two inputs are the string in upper-case letters and the integer offset.
Each character is replaced by the character offset positions away in the alphabet.
Preconditions:
string = str UPPERCASE only
offset = int
Result:
new_string = str with new letters
"""
new_string = "" #Initialization of the new_string
val = 0 #Code value of a character
for char in string: #For every character in string
val = ord(char) #Save code number of the character in val
new_string = new_string + chr(turn_around(val + offset)) #New string with new values
return new_string
def test_caesar(): #Test function with different results to test caesar code
assert caesar("C" , 1) == "D"
assert caesar("CAT" , 1) == "DBU"
assert caesar("AZ" , 1) == "BA"
assert caesar("ZAZA" , -1) == "YZYZ"
test_caesar() #Calling the test fuction , if true no output should be given
|
7ccc1dd6c4921265a1ef958836dec8a2ba52e260 | danicon/MD2-Curso_Python | /Aula13/ex14.py | 352 | 3.765625 | 4 | maior = 0
menor = 0
for p in range(1,6):
peso = float(input(f'Peso da {p+1}ª pessoa: '))
if p == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor = peso
print(f'O maior peso lido foi de {maior}Kg')
print(f'O menor peso lido foi de {menor}Kg') |
2ab1814bcc20c3bd07306af940aeab246b22fa26 | Ovilia/ProjectEuler | /014.py | 251 | 3.703125 | 4 | def collatz_step(n):
i = 1
while n != 1:
n = n / 2 if n % 2 == 0 else 3 * n + 1
i += 1
return i
steps = 1
n = 1
for i in range(1, 1000000):
c = collatz_step(i)
if c > steps:
steps = c
n = i
print n
|
6499201c407f5ab70911c2555df8bdebed725bce | richardbowden/pyhelpers | /tests/test_date_tools.py | 1,473 | 3.515625 | 4 | import unittest
from datetime import datetime
import pyhelpers.date_tools as date_tools
class LengthOfTimeCalc(unittest.TestCase):
def test_should_return_1_year_and_0_months(self):
start_date = datetime(2001,1,1)
end_date = datetime(2002,1,1)
years, months = date_tools.get_length_of_time(start_date, end_date)
self.assertEqual(years, 1, msg="Years should = 1")
self.assertEqual(months, 0, msg="Months should = 0")
def test_should_return_2_years_and_4_months(self):
start_date = datetime(2001,1,1)
end_date = datetime(2003,5,1)
years, months = date_tools.get_length_of_time(start_date, end_date)
self.assertEqual(years, 2, msg="Years should = 1")
self.assertEqual(months, 4, msg="Months should = 0")
def test_start_and_end_date_are_equal_should_return_0_0(self):
start_date = datetime(2001,1,1)
end_date = datetime(2001,1,1)
years, months = date_tools.get_length_of_time(start_date, end_date)
self.assertEqual(years, 0, msg="Years should = 0")
self.assertEqual(months, 0, msg="Months shold = 0")
def test_raise_execption_if_start_date_is_greater_than_end_date(self):
start_date = datetime(2001,1,1)
end_date = datetime(2000,1,1)
with self.assertRaises(Exception):
years, months = date_tools.get_length_of_time(start_date, end_date=end_date)
if __name__ == '__main__':
unittest.main()
|
9ba2a0957d65a59b659cb5084cabbdb2da90cf4e | gengwg/Python | /extract_emails.py | 202 | 3.890625 | 4 | # find all email addresses between <>
st = "Anurag Gupa <AGupta10@example.com>; Fezal Miza <FMirza@example.com>; Donld Slvia Jr. <Donad.Sivia@xyz.com>; Lar Gln <lary.glnn@jht.com>"
import re
emails = re.findall("\<(.*?)\>", st)
for email in emails:
print email
|
5504541c2672295a644f211b0056710c34ee9b6a | joyonto51/Programming_Practice | /Python/Old/Python Basic/Problem/22-08-17/Problem-1.1.3.py | 408 | 3.921875 | 4 | inp=input("Please Enter an year:")
n=int(inp)
if n%4==0 and (n%400==0 or n%100!=0):
print(str(n)+" is a Leap year")
print("The next Leap year is:"+str(n+4))
else:
print(str(n)+" is not leap year")
a=n+(4-n%4)
b=a+(4-a%4)
if(a%4==0 and (a%400==0 or a%100!=0)):
print("The next Leap year is:"+str(a))
elif(b%4==0 and (b%400 or b%100!=0)):
print("The next leap year is:",b)
|
bd71f0d44308bf49741559bb2ed1dcee4214a7b4 | zainul45/Rangkuman-Materi-PBO | /Rangkuman Materi/Tugas Praktikum/Tugas Praktikum/no_4.py | 570 | 3.6875 | 4 | class mahasiswa:
def __init__(self):
self.nama = input("Nama :")
self.npm = input("NPM :")
class matakuliah:
def __init__(self):
self.kode = input("Kode :")
self.namamatkul = input("Nama Mata Kuliah :")
class pengambilanmatkul(mahasiswa,matakuliah):
def __init__(self):
mahasiswa.__init__(self)
matakuliah.__init__(self)
self.tambahannilai = float(input("Tambahan Nilai :"))
def main(self):
print(self.nama, self.npm, self.namamatkul, self.tambahannilai)
pm = pengambilanmatkul()
pm.main()
|
06ba8b7f6637cd9e4d8121cebd673eb8cd823d99 | udaykumarbpatel/HackerRankKit | /FileRead.py | 495 | 3.96875 | 4 | import sys
def num_of_words_in_file(filename):
file_obj = open(filename, 'r')
count = 0
max_w = -sys.maxint
max_word = ""
for line in file_obj:
words = line.split()
for w in words:
if len(w) > 1 and w[0] == w[-1]:
if len(w) > max_w:
max_word = w
max_w = len(w)
if words:
count += len(words)
print max_word
print count
num_of_words_in_file("bubble_sort.py")
|
11ba5e49e0f10e028060a65dcb41f1f21d2460b1 | aruimk/ud_pyintro | /lesson18.py | 554 | 3.78125 | 4 | i = [1, 2, 3, 4, 5]
j = i
j[0] = 100
print(i)
print(j)
# 上記の様にリストを = でコピーすると、C言語での参照渡しの様なイメージで実態が②つあるわけではなくなる。
# 同じものを二種類の名前で見ているだけ。
# 以下の様に実態を別として二つにしたい場合はcopy メソッドを使用したり、スライスで最初から最後までをコピーしたりする必要がある
x = [1, 2, 3, 4, 5]
y = x.copy()
# y = x[:]
y[0] = 100
print('X = ', x)
print('y = ', y)
|
c64afeb0fc3f49603966b25a711bfd099e1cba88 | vladlemos/lets-code-python | /Aula_5/01.py | 570 | 4.0625 | 4 | '''
crie um dicionario cujas chaves
sao os meses do ano e os valores sao a duracao em dias de cada mes
'''
dicionario = {
'janeiro':31,
'fevereiro':28,
'marco': 30,
'abril': 31,
'maio': 30,
'junho': 30,
'julho': 31,
'agosto': 31,
'setembro': 30,
'outubro': 30,
'novembro': 30,
'dezembro': 31
}
''' imprima cada resultado '''
print(dicionario)
for mes in dicionario.items():
print (mes)
for mes in dicionario.items():
print(mes[0], '-', mes[1])
for mes, dias in dicionario.items():
print(mes, dias) |
ed60d64e3958bf86537d5c965a21e4b164f303af | NNishkala/PESU-IO-SUMMER | /coding_assignment_module1/w1q5.py | 107 | 4.0625 | 4 | a=input("Enter string")
if a.isnumeric():
print("String is numeric")
else:
print("String is not numeric") |
6aa461004bb2293047fa2c6459cba2c9e21bfb4f | KBerUX/OODPy | /customer.py | 406 | 3.75 | 4 | class Customer:
#__init__ is constructor/initializer
# self is like this.
def __init__(self, name, membership_type):
self.name = name
self.membership_type = membership_type
customers = [Customer("Caleb", "Gold"), Customer("Brad", "Bronze")]
# finish tomorrow 9:47 https://www.youtube.com/watch?v=MikphENIrOo
# finish this as well https://www.youtube.com/watch?v=JeznW_7DlB0
|
79ad57ed8bff6f2f7616dd32ef6fa75e1057108c | AnastasiiaDm/Python_Hillel_Nickisaev | /06-mydict.py | 582 | 3.5 | 4 | from pprint import pprint
team = dict(
Colorado='Rockies',
Boston='Red Sox',
Minnesota='Twins',
Milwaukee='Brewers',
Seattle='Mariners'
)
print(team)
print(team['Colorado'])
team['Colorado'] = 'Spartak'
print(team)
team['Kiev'] = 'Dinamo'
pprint(team)
P = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
}
print(P[1])
# p = {
# [1, 5]: 'r'
# }
# print(p)
d = {'a': 10, 'b': 20, 'c': 30}
print(d) # {'a': 10, 'b': 20, 'c': 30}
print(d.get('b')) # 20
print(d.get('z', 0)) |
851634ba29c99a5086d6b254078d21203df41c21 | PeterChain/simpleorgs | /apps/members/utils.py | 537 | 3.625 | 4 |
class NumberRange(object):
"""
Number range operations
"""
FILL_LENGTH = 5
def __init__(self, number):
"""
Constructor which receives the original number
"""
self.old_number = number
def next(self, step):
"""
Increase the original number (string) by step
units and returns it's string value
"""
int_num = int(self.old_number)
int_num += step
result_str = str(int_num).zfill(self.FILL_LENGTH)
return result_str |
0fa19d36567502e1d6ce2fc6e6af7cd3e839ea2f | prattaysanyal/Assign3 | /Assign10.py | 1,720 | 4 | 4 | #question1
class animal():
def attribute(self):
print("carnivore animal")
class tiger(animal):
pass
obj=tiger()
obj.attribute()
#question2
#print a.f(),b.()->A,B
#print a.g(),b.g()->A,B
#question3
class Cop():
def __init__(self,n,a,w,e,z):
self.name=n
self.age=a
self.work=w
self.exp=e
self.des=z
def add(self):
self.age=self.age+self.exp
print("after adding %d" %(self.age))
def display(self):
print("name of cop is %s age is %d works as a %s experience of %d designation is %s"%(self.name,self.age,self.work,self.exp,self.des))
def update(self,new_age):
self.age=new_age
class Mission(Cop):
def add_mission_details(self):
if(self.exp>5):
print("available for mission")
else:
print("not available")
name=input("enter the name of cop")
age=int(input("enter age of cop"))
work=input("enter work of cop")
exp=int(input("enter experince of cop"))
des=input("enter designation")
x=Mission(name,age,work,exp,des)
x.display()
new_age=int(input("enter new age"))
x.update(new_age)
x.display()
x.add_mission_details()
#question 4
class Shape():
def __init__(self,l,b):
self.length=l
self.breadth=b
def area(self):
if(self.length==self.breadth):
print("area of square is %d"%(self.length*self.breadth))
else:
print("area of rectangle is %d"%(self.length*self.breadth))
class Rectangle(Shape):
pass
class Square(Shape):
pass
ln=int(input("enter first side"))
br=int(input("enter second side"))
x=Rectangle(ln,br)
x.area()
|
68613423fb66781998bd48b4b2d8f60964d4f67b | Mr-BYK/Python1 | /generators/generators.py | 532 | 4.09375 | 4 | def cube():
for i in range(5000):
yield i ** 10 #bellek üzerinde yer kaplamadan işlem yaptırırız.İkinci kez ulasılmaz bir kereye masustur
for i in cube():
print(i)
##mesela bellek üstüned nasıl yer kaplar
#def cube():
# result=[]
# for i in range(5):
# result.append(i**3)
# return result
#print(cube())
generator=(i**3 for i in range(5))
print(generator)
#print(next(generator))
#print(next(generator))
#print(next(generator))
for i in generator:
print(i) |
8b28b40a52bad250743a0ad54520f464bc511a89 | umairkhan1154/Machine-Learning | /polynomial_regression.py | 835 | 3.921875 | 4 | #import the libraries
import numpy as py
import matplotlib.pyplot as plt
import pandas as pd
#Import the data set from Desktop
dataset = pd.read_csv('M_Regression.csv')
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,3].values
#Training and Testing Data (divide the data into two part)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test =train_test_split(X,y,test_size=0.3, random_state=0)
#multiple regression linear reg s b huskti hai
from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(X_train,y_train)
#for predict the test values
y_prdict=reg.predict(X_test)
#Visualize the Traing data
#ku k hamary pas 3 independent variable hain or ik output to it is not
#possible k hm inky graph plot kren(hr axis p ik hi attribute asakta haina :D) |
aa39dcbab4800749fa260e8a2b057336cc644c6d | YXRSs/myrepo | /2017_final_mangled_code.py | 2,133 | 3.953125 | 4 | def build_marks_dict(input_file):
student_to_marks = {}
input_line = input_file.readline()
while(not input_line.startswith("---")):
course_to_grade = {}
input_line = input_line.strip()
(student, course, grade) = input_line.split(',')
if(student in student_to_marks):
course_to_grade = student_to_marks[student]
course_to_grade[course] = float(grade)
else:
student_to_marks[student] = course_to_grade
course_to_grade[course] = float(grade)
input_line = input_file.readline()
return student_to_marks
def calculate_averages(student_to_marks):
course_to_average = {}
course_to_marks_list = {}
for next_student in student_to_marks:
course_to_grade = student_to_marks[next_student]
for next_course in course_to_grade:
next_grade = course_to_grade[next_course]
if(next_course in course_to_marks_list):
course_to_marks_list[next_course].append(next_grade)
else:
course_to_marks_list[next_course] = [next_grade]
for next_course in course_to_marks_list:
marks_list = course_to_marks_list[next_course]
average = sum(marks_list)/len(marks_list)
course_to_average[next_course] = average
return course_to_average
if(__name__ == "__main__"):
input_file = open("grades.txt")
student_to_marks = build_marks_dict(input_file)
course_to_average = calculate_averages(student_to_marks)
input_file.close()
class Vehicle:
def __init__(self,max_passengers, num_wheels, max_speed):
self._max_passengers = max_passengers
self._num_wheels = num_wheels
self._max_speed = max_speed
class Car(Vehicle):
def __init__(self,max_passengers, max_speed):
CAR_WHEELS = 4
Vehicle.__init__(self,max_passengers, CAR_WHEELS, max_speed)
class SportsCar(Car):
def __init__(self,max_passengers, num_wheels, max_speed):
SPORTS_CAR_SEATS=2
SPORTS_CAR_MAX_SPEED=300
Car.__init__(self,SPORTS_CAR_SEATS,SPORTS_CAR_MAX_SPEED)
|
b775df43bf988a866f9633821770b289e39c5adb | AdmiralGallade/GUI-file-explorer-python | /test.py | 245 | 3.53125 | 4 | input_string="Name1: Han Age: 23 Guns: 2"
print(list(map(str,input_string.split())))
print('\n',list(map(str,input_string.split(':'))))
print('\n',list(map(str,input_string.strip())))
print('\n',list(map(str,input_string.strip().split()))) |
9a2dd61443207a5c8e033175318e177101760701 | mottaquikarim/pydev-psets | /pset_pandas_ext/101problems/p73.py | 288 | 3.640625 | 4 | """
74. How to get the frequency of unique values in the entire dataframe?
"""
"""
Difficulty Level: L2
"""
"""
Get the frequency of unique values in the entire dataframe df.
"""
"""
Input
"""
"""
df = pd.DataFrame(np.random.randint(1, 10, 20).reshape(-1, 4), columns = list('abcd'))
"""
|
4070e1709cd1f689878bd718e7af3d586a77704c | git-mih/Learning | /python/04_OOP/polymorphism/08__format__.py | 1,678 | 4.65625 | 5 | # __format__ method
# is just yet another representation... We know we can use the format() function
# to precisely format certain types like: floats, dates, etc.
format(0.1, '.2f') # 0.10
format(0.1, '.25f') # 0.1000000000000000055511151
from datetime import datetime
datetime.utcnow() # 2021-07-14 23:32:07.957151
format(datetime.utcnow(), '%a %Y-%m-%d %I:%M %p') # Wed 2021-07-14 11:32 PM
# we can also support it in our custom classes by implementing the __format__ method.
# we call the Python builtin function: format(value, format_spec) passing the
# value and the format specification that we want.
# if format_spec isnt supplied, it defaults to an empty string. and in this case,
# Python will then use: str(value)
# which in turn may fall back to the: repr(value) if the __str__ isnt defined.
# implementating our own format specification is difficult.
# so we frequently delegates formatting back to another type that already supports it.
class Person:
def __init__(self, name, dob):
self.name = name
self.dob = dob
def __format__(self, date_format_spec):
# delegating back to the default: format(value, format_specification)
# passing an object that does implement an formatting. (datetime object)
dob = format(self.dob, date_format_spec)
return f"Person('{self.name}', '{dob}')"
from datetime import datetime, date
p = Person('Fabio', date(1995, 4, 20))
# without passing the format_specification argument:
format(p) # Person('Fabio', '1995-04-20')
# passing the format_specification argument:
format(p,'%a %Y-%m-%d %I:%M %p')
# Person('Fabio', 'Thu 1995-04-20 12:00 AM') |
8e701e1d02be276def933cd411e3f9aa0655dedc | marloncalvo/BuggyJavaJML | /Macros/time.py | 6,461 | 3.796875 | 4 | from datetime import date, datetime, timedelta
from util import test_case
def get_time_string(time: datetime, var="time"):
return f"Time {var} = new Time({time.hour}, {time.minute}, {time.second});"
def get_time():
print("getting time...")
second, minute, hour = input("second: "), input("minute: "), input("hour: ")
return datetime.strptime(f"{hour}:{minute}:{second}", "%H:%M:%S")
def time_options():
pass
def difference_times(a, b, var="diff"):
if b > a:
a = b
c = a - b
c = datetime.min + c
return f"""assertEquals({c.hour}, {var}.getHour());
assertEquals({c.minute}, {var}.getMinute());
assertEquals({c.second}, {var}.getSecond());"""
def difference():
time = get_time()
a = get_time()
b = get_time()
if b > a:
c = a
a = b
b = c
c = a - b
c = datetime.min + c
return f"""{get_time_string(time, "time")}
{get_time_string(a, "a")}
{get_time_string(b, "b")}
Time diff = time.difference(a, b);
{difference_times(a,b)}"""
def equals():
a = get_time()
b = get_time()
body = f"""{get_time_string(a, "a")}
{get_time_string(b, "b")}
"""
if a == b:
body += f"assertEquals(a, b);"
else:
body += f"assertNotEquals(a, b);"
return body
def decr():
print("input time")
time = get_time()
new_time = time - timedelta(seconds=1)
return f"""{get_time_string(time)}
time.decr();
assertEquals({new_time.hour}, time.getHour());
assertEquals({new_time.minute}, time.getMinute());
assertEquals({new_time.second}, time.getSecond());"""
def timer():
return f"""fail("Cannot test timer()");"""
def set_second():
second = int(input("second: "))
if second < 0 or second >= 60:
return f"""Time time = new Time(-1, -1, -1);
assertThrows(IllegalArgumentException.class, () -> {{
time.setSecond({second});
}});"""
else:
return f"""Time time = new Time(-1, -1, -1);
assertDoesNotThrow(() -> {{
time.setSecond({second});
}});
assertEquals({second}, time.getSecond());"""
def set_minute():
minute = int(input("minute: "))
body = f"Time time = new Time(-1, -1, -1);"
if minute < 0 or minute >= 60:
body += f"""
assertThrows(IllegalArgumentException.class, () -> {{
time.setMinute({minute});
}});"""
else:
body += f"""
assertDoesNotThrow(() -> {{
time.setMinute({minute});
}});
assertEquals({minute}, time.getMinute());"""
return body
def set_hour():
hour = int(input("hour: "))
body = f"Time time = new Time(-1, -1, -1);"
if hour < 0 or hour >= 24:
body += f"""
assertThrows(IllegalArgumentException.class, () -> {{
time.setHour({hour});
}});"""
else:
body += f"""
assertDoesNotThrow(() -> {{
time.setHour({hour});
}});
assertEquals({hour}, time.getHour());"""
return body
def is_time_zero():
time = get_time()
body = f"{get_time_string(time)}"
ret = "\n"
if datetime.hour == datetime.minute and datetime.minute == datetime.second and datetime.hour == 0:
ret += f'assertTrue(time.isTimeZero());'
else:
ret += f'assertFalse(time.isTimeZero());'
return body + ret
def later_than():
a = get_time()
b = get_time()
c = a > b
return f"""{get_time_string(a, "time")}
{get_time_string(b, "start")}
{"assertTrue" if c else "assertFalse"}(time.later_than(start));"""
def gettime():
time = get_time()
return f"""{get_time_string(time, "time")}
Time res = time.getTime();
assertEquals(time.getHour(), res.getHour());
assertEquals(time.getMinute(), res.getMinute());
assertEquals(time.getSecond(), res.getSecond());"""
def time_option():
time = get_time()
start = get_time()
end = get_time()
sel = int(input("sel: "))
body = f"""{get_time_string(time, "time")}
{get_time_string(time, "__timeOld")}
{get_time_string(start, "start")}
{get_time_string(start, "__startOld")}
{get_time_string(end, "end")}
{get_time_string(end, "__endOld")}
int sel = {sel};
Time res = time.timeOptions(start, end, sel);"""
if sel == 4:
body += difference_times(start, end, "res")
elif sel == 3:
if start == end:
body += f"""
assertEquals(0, res.getHour());
assertEquals(0, res.getMinute());
assertEquals(0, res.getSecond());
assertEquals(0, start.getHour());
assertEquals(0, start.getMinute());
assertEquals(0, start.getSecond());
assertEquals(__endOld.getHour(), end.getHour());
assertEquals(__endOld.getMinute(), end.getMinute());
assertEquals(__endOld.getSecond(), end.getSecond());"""
else:
body += f"""
assertEquals(__timeOld.getHour(), res.getHour());
assertEquals(__timeOld.getMinute(), res.getMinute());
assertEquals(__timeOld.getSecond(), res.getSecond());"""
elif sel >= 0 and sel <= 2:
body += f"""assertEquals(0, res.getHour());
assertEquals(0, res.getMinute());
assertEquals(0, res.getSecond());
assertEquals(__startOld.getHour(), start.getHour());
assertEquals(__startOld.getMinute(), start.getMinute());
assertEquals(__startOld.getSecond(), start.getSecond());
assertEquals(__endOld.getHour(), end.getHour());
assertEquals(__endOld.getMinute(), end.getMinute());
assertEquals(__endOld.getSecond(), end.getSecond());"""
return body
def not_testable():
return f"""fail("The function {input("function_name: ")} is not testable for this case");"""
print("select function to generate test for")
func = int(input("""
0: equals
1: difference
2: later_than
3: time_options
4: set_second
5: get_time
6: set_minute
7: is_time_zero
8: set_hour
Default: Generate uncreatable fail test
func: """))
if func == 0:
func = equals
elif func == 1:
func = difference
elif func == 2:
func = later_than
elif func == 3:
func = time_option
elif func == 4:
func = set_second
elif func == 5:
func = gettime
elif func == 6:
func = set_minute
elif func == 7:
func = is_time_zero
elif func == 8:
func = set_hour
else:
func = not_testable
body = func()
print(test_case(body, index)) |
57c93992da7f50a1c2e7c9e02eac1204df8d32ce | kira-Developer/python | /107_OOP_Part_5_Class_Attributes.py | 1,437 | 4.0625 | 4 | # -----------------------------------------------------
# -- Object Oriented Programming => Class Attributes --
# -----------------------------------------------------
# Class Attributes: Attributes Defined Outside The Constructor
# -----------------------------------------------------------
class member :
not_allowed = ['hell' , 'shit' ,'baloot']
users_num = 0
def __init__(self, first_name, middle_name, last_name, gender):
self.fname = first_name
self.mname = middle_name
self.lname = last_name
self.gender = gender
member.users_num += 1 # member.users_num = member.users_num + 1
def full_name(self):
if self.fname in member.not_allowed :
raise ValueError('name not allowed')
else :
return f'{self.fname} {self.mname} {self.lname}'
def name_with_title(self):
if self.gender == 'male':
return f'hello mr {self.fname}'
elif self.gender == 'female':
return f'hello miss {self.fanme}'
else:
return f'hello {self.fname}'
def get_all_info(self):
return f'{self.name_with_title()}, your full name is : {self.full_name()}'
def delete_user(self):
member.users_num -= 1
return f'user {self.fname} deleted'
member_one = member('abdullh', 'bander', 'alosami', 'male')
print(member.users_num)
print(member_one.delete_user())
print(member.users_num)
|
65207cd2c9982587bf76a269221b1f1cc7ece594 | aleuli/PythonPY100 | /Занятие3/Лабораторные_задания/task2_1/main.py | 249 | 3.625 | 4 | def task(str1, str2, k):
if str1[:k + 1] == str2[:k + 1]:
print("Да")
else:
print("Нет")# TODO проверка совпадения строк
return
if __name__ == "__main__":
print(task("Hello", "Herry", 0))
|
8f70dfb3d59b18a4b41c1b67e7cfb4635a06dd3b | Darkxiete/leetcode_python | /107.py | 1,650 | 3.59375 | 4 | from DataStructure.BinaryTree import BinaryTree as TreeNode, create_btree
from typing import List
class Solution:
def levelOrderBottom1(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
queue = [root]
level, ans = [], []
while queue:
level = queue[:]
tmp = []
for node in level:
tmp.append(node.val)
ans.append(tmp)
queue = []
for node in level:
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return ans[::-1]
def levelOrderBottom2(self, root: TreeNode) -> List[List[int]]:
"""
recursive
:param root:
:return:
"""
def dfs(root, level, res):
if root:
if len(res) < level + 1:
res.insert(0, []) # O(N)
res[-(level + 1)].append(root.val)
dfs(root.left, level + 1, res)
dfs(root.right, level + 1, res)
res = []
dfs(root, 0, res)
return res
def levelOrderBottom3(self, root: TreeNode) -> List[List[int]]:
res, queue = [], [root]
while queue:
res.append([node.val for node in queue if node])
queue = [child for node in queue
if node for child in (node.left, node.right)]
return res[-2::-1]
if __name__ == '__main__':
s = Solution()
nums = [3, 9, 20, None, None, 15, 7]
bt = create_btree(nums)
print(s.levelOrderBottom3(bt))
|
7e04eba92c71430cc1b104df4a302130eaf09f37 | WeiNyn/TrieTree | /build_corpus.py | 989 | 3.828125 | 4 | import pandas as pd
df = pd.read_csv("new_merged_csv.csv")
def check_input(words: str) -> str:
texts = words.replace("\r", " ") \
.replace("\n", " ") \
.replace("- ", "-") \
.replace(" -", "-") \
.split(",")
new_texts = []
for text in texts:
if not text.strip().isdigit() and 3 < len(text.strip()) < 50 \
and "hs code" not in text.lower() \
and "phone" not in text.lower() \
and "fax" not in text.lower() \
and "no." not in text.lower() \
and "tax" not in text.lower() \
and "hs-code" not in text.lower():
new_texts.append(text)
return ",".join(new_texts)
print(df.size)
df["DESC_BKG"] = df["DESC_BKG"].apply(check_input)
print(df.head(5))
df = df[df["DESC_BKG"].map(len) > 0]
print(df.size)
print(df.head(10))
print(check_input("NECTARINES\nHS CODE: 080930"), "----------")
df.to_csv("new_merged_csv_removed.csv")
|
19433aa6384dd496f808121f8a36c2dd7cd764b6 | blitzwolfz/nextgencoder_cc-35 | /PyChallenge.py | 595 | 3.921875 | 4 | #Made by Samin Q
def Add_Per(number):
first_step = 0
for x in range(len(number)):
first_step += int(number[x])
second_step = int(str(first_step)[0]) + int(str(first_step)[1])
return second_step
def Multi_Per(number):
first_step = 1
for x in range(len(number)):
first_step *= int(number[x])
second_step = int(str(first_step)[0]) * int(str(first_step)[1])
return second_step
x = str(input("Please enter a number: "))
print("The addition persistence is", Add_Per(x))
print("The multipication persistence is", Multi_Per(x))
|
9847109288eb59761847c7597dd81541a87df572 | RaulMyron/URIcodes-in-py-1 | /URI/1073.py | 100 | 3.78125 | 4 | X = int(input())
Z = 0
for i in range(1, X+1):
if i%2 == 0:
print("%d^2 = %d" %(i, pow(i,2))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.