blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
7fc3b38afab512d2ee77cfd3114b1ac856da5738 | dgpllc/leetcode-python | /learnpythonthehardway/super-palindrome-906.py | 4,985 | 4.03125 | 4 | # Let's say a positive integer is a superpalindrome if it is a palindrome, and it is also the square of a palindrome.
#
# Now, given two positive integers L and R (represented as strings), return the number of superpalindromes in the
# inclusive range [L, R].
#
#
#
# Example 1:
#
# Input: L = "4", R = "1000"
# Output: 4
# Explanation: 4, 9, 121, and 484 are superpalindromes.
# Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.
#
#
# Note:
#
# 1 <= len(L) <= 18
# 1 <= len(R) <= 18
# L and R are strings representing integers in the range [1, 10^18).
# int(L) <= int(R)
import math
class Solution(object):
def superpalindromesInRange_tle(self, L, R):
"""
:type L: str
:type R: str
:rtype: int
"""
def isPalindrome(t):
s, n = 0, t
while t:
s = s * 10 + t % 10
t /= 10
return s == n
res = 0
start, end = int(int(L) ** .5), int(int(R) ** .5)
for i in xrange(start - 1, end + 1):
if isPalindrome(i) and isPalindrome(i * i) and int(L) <= i * i <= int(R):
print i
res += 1
return res
def superpalindromesInRange(self, L, R):
"""
:type L: str
:type R: str
:rtype: int
"""
res = 0
start, end = int(int(L) ** .5), int(int(R) ** .5)
def isPalindrome(t):
s, n = 0, t
while t:
s = s * 10 + t % 10
t /= 10
return s == n
# yield n digits palindrom, if n is 3, produce 121, 212, etc.
def genPalindrome(lower, upper):
# if n is odd
# check how many digit of lower and upper sqare root boundary have, for ex, if lower = 100
# then it should have at least 3 digit, if upper is 10000, then it should have 5 digits
# if lower is 0, it should have at least 1 digit
n1, n2, res = int(math.log10(lower)) + 1 if lower > 0 else 1, int(math.log10(upper)) + 1, []
for n in xrange(n1, n2 + 1):
# if n is odd, then we should have something like 12321
if n & 1:
# if t == 1, we can choose 1->9
t = n / 2
if not t:
res.extend(range(1, 10))
continue
# a is the mid
for a in xrange(0, 10):
# assume n == 7, then t = 3, so we can choose from 100 - 999, for ex, 8742478
# so lower : 10 **(3-1) = 100, upper : 10 * 3 = 1000
for m in xrange(10 ** (t - 1), 10 ** t):
s = int(str(m) + str(a) + str(m)[::-1])
if lower <= s <= upper:
res.append(s)
else: # if n is even, so should have 123321
t = n / 2
for m in xrange(10 ** (t - 1), 10 ** t):
s = int(str(m) + str(m)[::-1])
if lower <= s <= upper:
res.append(s)
return res
cans = genPalindrome(start - 1, end + 1)
for i in cans:
k = i * i
if int(L) <= k <= int(R) and isPalindrome(k):
res += 1
return res
def superpalindromesInRange2(self, L, R):
"""
:type L: str
:type R: str
:rtype: int
"""
L, R = int(L), int(R)
# since Len(L) < 18 and len(R) < 18, its sqaure root is 10**9, assume k is the half palindrome, k||K' = P,
# it could be something like
# 1234321 or 12344321 , k = 1234, k would be < 10 ** 5, this is how the MAGIC comes from
MAGIC = 100000
def reverse(x):
ans = 0
while x:
ans = 10 * ans + x % 10
x /= 10
return ans
def is_palindrome(x):
return x == reverse(x)
ans = 0
# count odd length
for k in xrange(MAGIC):
s = str(k) # Eg. s = '1234'
t = s + s[-2::-1] # t = '1234321'
v = int(t) ** 2
if v > R: break
if v >= L and is_palindrome(v):
ans += 1
# count even length
for k in xrange(MAGIC):
s = str(k) # Eg. s = '1234'
t = s + s[::-1] # t = '12344321'
v = int(t) ** 2
if v > R: break
if v >= L and is_palindrome(v):
ans += 1
return ans
if __name__ == '__main__':
# print Solution().superpalindromesInRange("4", "1000")
# print Solution().superpalindromesInRange("1020762146323", "142246798855636")
print Solution().superpalindromesInRange("1", "2")
# print Solution().superpalindromesInRange_tle("1020762146323", "142246798855636")
|
38f55a70feb3ef71930733972666bbe890eeaaf6 | thieslei/python_labs_scripts | /calc_seconds_to_hourminsec.py | 607 | 4.15625 | 4 | ### This script will:
# - Convert seconds, into hours, minutes and seconds.
#
#
def convert(seconds):
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return "%d:%02d:%02d" % (hour, minutes, seconds)
# Driver program
n = float(input('Please type the seconds you want to convert: '))
#n = 60
print (' ')
print ('###############################')
print('Convert to hh:mm:ss == ',(convert(n)))
#print (f'You are {age:.0f} years old.')
print ('###############################')
print (' ')
### Autor thieslei@gmail.com |
57761486ed59ad7665cf62440b34a02eb22c6294 | skosantosh/python | /function_scope_legb.py | 962 | 4.03125 | 4 | # Local, Enclosing Function Locals, Globe, Built-In
# Globle Name
x = 'Globle NameX'
def my_func():
x = 'JohnX'
return x
print(f"Printed at Outside: {my_func()} ")
print(f"Printed at Outside: {x} \n")
#############################################
y = 'Globle NameY'
def my_func():
y = 'JohnY'
z = 'DanZ'
def diff_func():
y = 'SmithY'
print(f"Printed at Inside: {y} and {z}")
diff_func()
return y
print(f"Printed at Outside: {my_func()} ")
print(f"Printed at Outside: {y} \n")
#######################################
a = 50
def func(a):
print(f"Print a at top of Fuction {a}")
a = 5005
print(f"Print a at after a = 5005 of Fuction {a}")
func(a)
print(f"Pring outside the Function {a}\n")
###################################
b = 50
def func():
global b # for test commet this line look the out put.
b = 5000
print(f"Before Function Call {b} ")
func()
print(f"After Function Call {b} ")
|
d1652a3fc54f45acad689f30dc09e24516108d0f | asperaa/back_to_grind | /Binary_Search/1060. Missing Element in Sorted Array_Clean.py | 475 | 3.734375 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""1060. Missing Element in Sorted Array [Clean]
"""
class Solution:
def missingElement(self, nums, k):
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) // 2
if nums[mid] - nums[0] - mid >= k:
right = mid
else:
left = mid + 1
return nums[0] + left - 1 + k |
a3903c2adddba30d75e169e882a8610543aa26e0 | aayushinamdeo31/Python_Intern-SecurityBrigade | /task_2.py | 652 | 4.5 | 4 | # Task 2
# Write a program (using functions!) that asks the user for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
# My name is Michele
# Then I would see the string:
# Michele is name My
# shown back to me.
# Function to reverse the order of the string array
def reverse_sentence(word):
word.reverse() # Reversing the sentence list
return word
# Driver Program
sentence = list(input("Enter a sentence - ").split()) # Take input of string with multiple words
answer = reverse_sentence(sentence)
print(' '.join(answer)) |
48f1a23d44bc87febccf851c4ba968a417c07589 | wangshanmin/leetcode | /125. Valid Palindrome/isPalindrome.py | 827 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 17:07:30 2018
@author: wangshanmin
"""
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
m = 0
n = len(s) - 1
s = s.upper()
while m <= n:
if (s[m].isdigit() or s[m].isalpha()) and (s[n].isdigit() or s[n].isalpha()):
if s[m] != s[n]:
return False
else:
m = m+1
n = n-1
elif not (s[m].isdigit() or s[m].isalpha()):
m = m+1
elif not (s[n].isdigit() or s[n].isalpha()):
n = n-1
return True
if __name__ == '__main__':
print(Solution().isPalindrome("race a car"))
|
991bfafa3b6b1e90cd70c2867d701f04780f5c4b | nogand/py0220 | /Fibonacci/fibonacci.py | 1,083 | 3.875 | 4 | """
Módulo Fibonacci
2020-04-22
Greencore - PY0220
Módulo de ejemplo con la serie de Fibonacci implementada de múltiples maneras.
"""
def fibo(n):
# Recibe un número n, entero mayor a cero, y devuelve el elemento n-ésimo de la serie de Fibonacci
if n <= 2:
return 1
else :
return fibo(n-1)+fibo(n-2)
"""
fibo(1) -> 1
fibo(2) -> 1
fibo(3) -> fibo(2)+fibo(1) -> 1+1 -> 2
fibo(4) -> fibo(3)+fibo(2) -> (fibo(2)+fibo(1))+1 -> (1+1)+1 -> 3
fibo(5) -> fibo(4)+fibo(3) -> (fibo(3)+fibo(2))+(fibo(2)+fibo(1)) -> ((fibo(2)+fibo(1))+1)... -> 5
"""
def fiblist(n):
# Recibe un número n, entero mayor a cero, y devuelve una lista de los elementos de la serie de Fibonacci hasta ese número.
if n == 1 :
return [ 1 ]
else :
return fiblist(n-1)+[ fibo(n) ]
"""
fiblist(1) -> [ 1 ]
fiblist(2) -> fiblist(1)+[ fibo(2) ] -> [ 1 ] + [ 1 ] -> [1, 1]
fiblist(3) -> fiblist(2)+[ fibo(3) ] -> [1, 1] + [ 2 ] -> [1, 1, 2]
fiblist(4) -> fiblist(3)+[ fibo(4) ] -> [1, 1, 2] + [ 3 ] -> [1, 1, 2, 3]
"""
|
025b672bbf605a215c427a4a5f82c02d2553eec7 | RahulBendre1/Competitive-Programming | /oddities.py | 167 | 4.09375 | 4 | for i in range(int(input().strip())):
x = int(input().strip())
if x%2==0:
print("{} is even".format(x))
else:
print("{} is odd".format(x))
|
bd6b34c77fd3635347e0897de717b90e3565b188 | Sankarb475/LeetCode-HackerRank | /HackerRank_Challenges/day_of_the_programmer.py | 875 | 3.703125 | 4 | # solution of https://www.hackerrank.com/challenges/day-of-the-programmer/problem
def dayOfProgrammer(year):
dict1 = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
sum = 0
for key,value in dict1.items():
sum = sum + value
if sum>256:
day = 256 - (sum - value)
output = [day, key]
break
if year >= 1919:
if year%400 == 0 or (year%4 == 0 and year%100!=0):
return str(output[0]-1)+".0"+str(key)+"."+str(year)
else:
return str(output[0])+".0"+str(key)+"."+str(year)
elif year <= 1917:
if year%4 == 0:
return str(output[0]-1)+".0"+str(key)+"."+str(year)
else:
return str(output[0])+".0"+str(key)+"."+str(year)
elif year == 1918:
return str(output[0]+13)+".0"+str(key)+"."+str(year)
|
aa82e4e6efeed757e6d13213ec37fb453343f319 | Upgwades/K-Means | /kmeans.py | 4,611 | 3.5625 | 4 | """
Author: Will Irwin
Date: 11/13/2017
Inputs:
valid file location
number of clusters
attributes to ignore
Outputs:
the centroids of the clusters
the number of instances in each class
the total square error
the number iterations that were used to get this result
Notes:
Runs in python 2.x
"""
import os
import csv
import random
import numpy as np
import math
import copy
def input():
f = raw_input("Enter file location: ")
data, headers = processFile(f)
nclusters = int(raw_input('Enter the number of desired clusters: '))
for x in range(0,len(headers)):
string = str(x) + " ,"
print(str(x) + " - " + headers[x])
ignoreString = raw_input('Enter the numbers (comma seperated) of the attributes you would like to ignore: ')
ignore = [x.strip() for x in ignoreString.split(',')]
ignore = map(int, ignore)
return data, headers, nclusters, ignore
def processFile(f):
with open(f, 'rb') as f:
reader = csv.reader(f)
headers = next(reader)
data = list(reader)
return data, headers
def kmeans(data, headers, nclusters, ignore):
isStillMoving = True
ignore = sorted(ignore, key=int, reverse=True)
for row in data:
for x in ignore:
del row[x]
data = np.array(data,dtype=np.float32)
clusterIDs = np.empty(int(len(data)),dtype=np.int)
clusterIDs = np.random.randint(low=0, high=nclusters, size=len(data))
centroids = initCentroids(data, nclusters)
centroids = np.array(centroids,dtype=np.float32)
centroids = centroids[0]
iterations = 1
instances = []
while(isStillMoving):
centroids = calcCentroid(centroids,data,nclusters,clusterIDs)
clusterIDs,isStillMoving = calcClusters(centroids,data,nclusters,clusterIDs)
iterations += 1
unique, instances = np.unique(clusterIDs, return_counts=True)
tse = calcTSE(data,centroids,clusterIDs,unique)
return instances, centroids, tse, iterations, unique, clusterIDs
def calcTSE(data,centroids,clusterIDs,unique):
tse = 0.0
dist = 0.0
sqError = 0.0
for x in range(0,len(centroids)):
for y in range(0,len(clusterIDs)):
if(clusterIDs[y] == unique[x]):
dist = calcDistance(data[y],centroids[x])
sqError += math.pow(dist,2)
tse += sqError
return tse
def initCentroids(data,nclusters):
centroids = []
centroids.append(random.sample(data, nclusters))
return centroids
def calcCentroid(centroids,data,nclusters,clusterIDs):
totals = np.zeros(len(data[0]),dtype=np.float32)
totalInCluster = 0
for j in range(0,nclusters):
for k in range(len(data)):
if(clusterIDs[k] == j):
for x in range(0,len(totals)):
totals[x] += data[k][x]
totalInCluster += 1
if(totalInCluster > 0):
for x in range(0,len(totals)):
centroids[j][x] = totals[x] / totalInCluster
return centroids
def calcClusters(centroids,data,nclusters,clusterIDs):
isStillMoving = False
originalClusterIDs = clusterIDs
for i in range(0,len(clusterIDs)):
bestMinimum = math.pow(10, 10)
currentCluster = 0
for j in range(0,nclusters):
distance = calcDistance(centroids[j], data[i])
if(distance < bestMinimum):
bestMinimum = distance
currentCluster = j
if(clusterIDs[i] != currentCluster):
clusterIDs[i] = currentCluster
isStillMoving = True
return clusterIDs,isStillMoving
def calcDistance(array1, array2):
# Calculate Euclidean distance.
distance = float(np.linalg.norm(array1-array2))
return distance
def main():
data, headers, nclusters, ignore = input()
originalData = copy.deepcopy(data)
instances, centroids, tse, iterations, unique, clusterIDs = kmeans(data, headers, nclusters, ignore)
print("Here is the associated raw data:")
for x in range(0,len(originalData)):
print(str(clusterIDs[x]) + " - " + str(originalData[x]))
print("")
for x in range(0,nclusters):
print("For cluster " + str(x) + ":")
print("It had " + str(instances[x]) + " instances")
print("and a final centroid at" + str(centroids[x]) + "\n")
print("The algorithm took " + str(iterations) + " iterations and had a total square error of " + str(tse))
main()
|
3133ae49135fee723dad6c5a2cfbaf834ca16fa8 | tomatocat/interview-sites | /leetcode/min-stack.py | 842 | 3.890625 | 4 | # https://leetcode.com/problems/min-stack/
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.arr = []
self.m = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.arr.append(x)
if self.m:
self.m.append(min(self.m[-1], x))
else:
self.m.append(x)
def pop(self):
"""
:rtype: None
"""
if self.arr:
self.arr.pop()
self.m.pop()
def top(self):
"""
:rtype: int
"""
if self.arr:
return self.arr[-1]
return None
def getMin(self):
"""
:rtype: int
"""
if self.arr:
return self.m[-1]
return None
|
c8aa1d2de2efb4f053482f60bc638a2726283500 | DavidOsioHerrera/Torres-Hanoi-Iterativo | /HanoiIterative.py | 2,605 | 3.9375 | 4 | # autor: David Osio Herrera
def reco(x):
# Funcion encaragda de recorrer los discos en los arreglos#
r = len(x)
for j in range(0, r - 1):
# Elimina el primera dato del arreglo y mueve todos los demas una posicion adelante
x[j] = x[j + 1]
# (Deja el utlimo dato repetido)
if r >= 1:
# Elimina el ultimo dato del arreglo mientras exista
x.pop()
def swapDisco(y, z):
# Funcion encargada de hacer el movimiento legal necesario entre dos postes
if len(y) == 0:
# Si el poste Y esta vacio mueve el disco superior de Z a Y
print("Mueve el disco", z[0], "de manera legal")
temp = z[0]
y.insert(0, temp)
reco(z)
elif (len(z) == 0) or (y[0] < z[0]):
# Si el poste Z esta vacio o el disco superior en Y es menor que el de Z mueve el disco superior de Y a Z
print("Mueve el disco", y[0], "de manera legal")
temp = y[0]
z.insert(0, temp)
reco(y)
else: # Para cualquier otro escenario mueve el disco superor de Z a Y
print("Mueve el disco", z[0], "de manera legal")
temp = z[0]
y.insert(0, temp)
reco(z)
def hanoiSol(a, b, c):
# Funccion encargada de solucionar el problema para cualquier caso
print("Torre inicial A =", a)
print("Torre final C =", c)
print()
if n % 2 != 0:
# Soluciona los casos de discos impares
for j in range(1, movs):
if j % 3 == 1:
swapDisco(a, c)
if j % 3 == 2:
swapDisco(a, b)
if j % 3 == 0:
swapDisco(b, c)
print("A=", a)
print("B=", b)
print("C=", c)
print()
if n % 2 == 0:
# Soluciona los casos de discos impares
for j in range(1, movs):
if j % 3 == 1:
swapDisco(a, b)
if j % 3 == 2:
swapDisco(a, c)
if j % 3 == 0:
swapDisco(c, b)
print("A=", a)
print("B=", b)
print("C=", c)
print()
print('Hecho!')
print()
print("Torre inicial A =", a)
print("Torre final C =", c)
n = int(input('Numero de discos: ')) # Numero de discos
A = [] # Torre A
B = [] # Torre B
C = [] # Torre C
movs = pow(2, n) # Moviemtos necesarios para resolver el problema (2^n)
for i in range(1, n + 1):
# Crea el numero de discos necesarios en la torre A
A.append(i)
hanoiSol(A, B, C)
|
7b7924948f0443af3feaeb9bfc275d5664c8d0b5 | NeilWangziyu/Leetcode_py | /subsets.py | 1,108 | 3.8125 | 4 | class Solution:
"""
所有的子集和排列
"""
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def bfs(depth, start, value_list):
res.append(value_list)
if depth == len(nums):
return
for i in range(start, len(nums)):
bfs(depth+1, i+1, value_list+[nums[i]])
res = []
bfs(0, 0, [])
return res
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
print ('nums', nums)
if len(nums) <= 1:
return [nums]
ans = []
for i, num in enumerate(nums):
n = nums[:i] + nums[i+1:]
# n:没有某一个数,剩余的全排列
for temp_list in self.permute(n):
# temp_list:剩余的排列结果
ans.append([num] + temp_list)
print ('-----End-----')
return ans
s = Solution()
print(s.subsets([12,4,5,6]))
print('\n')
print(s.permute([12,4,5,6]))
|
225012fa79b0fddbe15e8108b8fb45b5d665a7bb | Farro178/Python-Shell | /shell.py | 2,553 | 3.578125 | 4 | from cmd import Cmd
import os
import sys
class MyPrompt(Cmd):
def do_hello(self, args):
if len(args) == 0:
name = "stranger"
else:
name = args
print ("Hello, " + name)
def do_quit(self, args):
"""Quits the program."""
print ("Quitting")
raise SystemExit
def do_dir(self, args):
try:
path = "."
if len(args) == 0:
path = "."
else:
path = args
files = os.listdir(path)
for name in files:
print(name)
except NotADirectoryError:
print("Error: This is not a directory: " + path)
except FileNotFoundError:
print("Error: File or Directory not found: " + path)
def do_cd(self, args):
try:
if len(args) == 0:
print(os.getcwd())
else:
path = args
os.chdir(path)
prompt.prompt = "~" + os.getcwd() + ": >"
except NotADirectoryError:
print("Error: This is not a directory: " + path)
except FileNotFoundError:
print("Error: File or Directory not found: " + path)
def do_clr(self, args):
"""Clears the screen"""
print("\033c")
def do_environ(self, args):
"""should print out the same as the env command"""
for key in os.environ.keys():
print("{} : {}".format(key, os.environ[key]) + "\n")
def do_echo(self, args):
words = args.split()
new_word = ""
for word in words:
new_word = new_word + " " + word
print(new_word[1:])
def do_pause(self, args):
input("Program is paused, press enter to continue.")
def do_help(self, args):
if args == "":
print("These commands are defined within the shell.")
print("For more information on each command type: help <command>")
commands = {
"echo" : "Echoes the arguement.",
"environ" : "Should print out the same as the env command.",
"clr" : "Clears the screen.",
"hello" : "Says hello. If you provide a name, it will greet you with it.",
"dir" : "Names files and directories in current directory.",
"cd" : "Changes the current directory",
"pause" : "Pauses the terminal until the enter key is pressed."
}
maxi = 0
for key in commands:
if len(key) > maxi:
maxi = len(key)
for keys, values in commands.items():
leng = maxi - len(keys)
print(keys + (" " * (leng + 5) + values))
if __name__ == '__main__':
prompt = MyPrompt()
prompt.prompt = "~" + os.getcwd() + "/myshell: >"
if len(sys.argv) == 2:
with open(sys.argv[1], "r") as f:
lines = f.readlines()
for line in lines:
line = line.strip("\n")
print(line)
MyPrompt().onecmd(line)
else:
prompt.cmdloop("Starting prompt") |
ae89694e7b855148eb644acd25b1119cc45d7f3c | valeriacavalcanti/IP-2020.2---R | /semana_12/exercicios/funcoes.py | 920 | 3.6875 | 4 | def index(lista, elem):
for i in range(len(lista)):
if (lista[i] == elem):
return i
return -1
def count(lista, elem):
qtde = 0
for l in lista:
if (l == elem):
qtde += 1
return qtde
def upper(st):
aux = ''
for s in st:
if (s >= 'a') and (s <= 'z'):
aux += chr(ord(s) - 32)
else:
aux += s
return aux
def isNum(st):
for s in st:
if (s < '0') or (s > '9'):
return False
return True
def vogais(st):
letras = 'aeiouAEIOU'
qtde = 0
for s in st:
if (s in letras):
qtde += 1
return qtde
# Programa Principal
numeros = [10,20,30,40,50,60,20,40]
frase = 'Instituto Federal - 2021'
print(index(numeros, 20))
print(index(numeros, 200))
print(count(numeros, 20))
print(count(numeros, 200))
print(upper(frase))
print(isNum(frase))
print(vogais(frase))
|
4bdcdf2f577c40babde4516fe06e6ad325c178d8 | tomkooij/AdventOfCode | /aoc2016/day7b.py | 1,573 | 3.515625 | 4 | def split_string_brackets(s):
""" abc[xyz]ghf --> abc, xyz, ghf """
try:
first, next_part = s.split('[', 1)
second, third = next_part.split(']', 1)
return first, second, third
except ValueError:
return s, '', None
def split_hypernet_sequence(s):
A, B = [], []
while s is not None:
first, second, third = split_string_brackets(s)
A.append(first)
B.append(second)
s = third
return A, B
def is_aba(s):
return s[0] != s[1] and s[0] == s[2]
def find_bab(aba, list):
bab = aba[1]+aba[0]+aba[1]
for item in list:
if item.find(bab) != -1:
return True
return False
def test_hypernet_sequence(s):
outside, inside = split_hypernet_sequence(s)
for string in inside:
for idx in range(len(string)-2):
aba = string[idx:idx+3]
if is_aba(aba):
if find_bab(aba, outside):
return True
for string in outside:
for idx in range(len(string)-2):
aba = string[idx:idx+3]
if is_aba(aba):
if find_bab(aba, inside):
return True
return False
def testcases():
print(test_hypernet_sequence('aba[bab]xyz'))
print(test_hypernet_sequence('xyx[xyx]xyx'))
print(test_hypernet_sequence('aaa[kek]eke'))
print(test_hypernet_sequence('zazbz[bzb]cdb'))
with open('input/input7.txt') as f:
testcases()
supports_ssl = [test_hypernet_sequence(line) for line in f.readlines()]
print(sum(supports_ssl))
|
475507c70ad8c3da2470171b68e6beac33393e65 | mehhdiii/ODE-solver | /solver.py | 1,448 | 3.921875 | 4 | import matplotlib.pyplot as plt
def solver():
print("enter step size: ", end = '')
step_size = float(input())
loop_range = int(10/step_size)
#Enter speratble ODE's coefficients
print("Enter ODE: dxdt = ", end = '')
ODE_t = list(map(int, input('Enter numbers: ').split()))
print("enter initial condition: ", end = '')
init_x = int(input())
x=[]
T = []
dxdt = 0
t = 0
#using euler method to solve the given ODE
for loop in range(0,loop_range):
T.append(t)
dxdt_temp = 0
for index in range(len(ODE_t)):
dxdt_temp += ((t**(len(ODE_t) - index - 1))*ODE_t[index])
dxdt = dxdt_temp
if(t == 0):
x.append(dxdt*step_size + init_x)
else:
x.append(dxdt*step_size + x[len(x)-1])
t+=step_size
ODE_print = printer(ODE_t)
plt.plot(T, x)
plt.yscale('linear')
plt.title(ODE_print)
plt.show()
def printer(ODE_t):
#for printing purposes:
ODE_print = "ODE: dxdt = "
for i in range(len(ODE_t)):
if i!=len(ODE_t) -1:
if(len(ODE_t) - i - 1!=1):
ODE_print = ODE_print + str(ODE_t[i]) + "x^" + str(len(ODE_t) - i - 1) + "+"
else:
ODE_print = ODE_print + str(ODE_t[i]) + "x" + "+"
else:
ODE_print+= str(ODE_t[i])
return ODE_print
solver() |
16fd6015b25dc117054b0aef9ba85e187422f4b1 | yuninje/Algorithm_Solve | /Baekjoon/[ 14499 ] 주사위 돌리기.py | 1,583 | 3.625 | 4 | # https://www.acmicpc.net/problem/14499
def left_move(cube):
temp = cube[3][1]
cube[3][1] = cube[1][2]
cube[1][2] = cube[1][1]
cube[1][1] = cube[1][0]
cube[1][0] = temp
def right_move(cube):
temp = cube[3][1]
cube[3][1] = cube[1][0]
cube[1][0] = cube[1][1]
cube[1][1] = cube[1][2]
cube[1][2] = temp
def up_move(cube):
temp = cube[3][1]
cube[3][1] = cube[2][1]
cube[2][1] = cube[1][1]
cube[1][1] = cube[0][1]
cube[0][1] = temp
def down_move(cube):
temp = cube[0][1]
cube[0][1] = cube[1][1]
cube[1][1] = cube[2][1]
cube[2][1] = cube[3][1]
cube[3][1] = temp
N, M, r, c, K = list(map(int, input().split()))
cube = [[0 for _ in range(0,3)] for __ in range(0,4)]
area = [[-1 for _ in range(0,M+2)]]
for n in range(0,N):
area.append([-1] + list(map(int, input().split())) + [-1])
area.append([-1 for _ in range(0,M+2)])
orders = list(map(int, input().split()))
# 1 : 우
# 2 : 좌
# 3 : 위
# 4 : 아래
dir = [[],[0,1], [0,-1], [-1,0],[1,0]]
now = [r+1,c+1]
for o in orders:
if area[now[0]+dir[o][0]] [now[1]+dir[o][1]] != -1:
now[0] += dir[o][0]
now[1] += dir[o][1]
if o == 1:
right_move(cube)
elif o == 2:
left_move(cube)
elif o == 3:
up_move(cube)
elif o == 4:
down_move(cube)
if area[now[0]][now[1]] != 0:
cube[1][1] = area[now[0]][now[1]]
area[now[0]][now[1]] = 0
else:
area[now[0]][now[1]] = cube[1][1]
print(cube[3][1]) |
7d9a38a34abf2cc203d0097d10b49ed62aa338a8 | briansbotlab/python_project | /python_project/20180823/20180823.py | 456 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 12:27:29 2018
@author: superuser
"""
import csv
# 開啟 CSV 檔案
with open('test.csv', newline='') as csvfile:
# 讀取 CSV 檔案內容
rows = csv.reader(csvfile)
# 以迴圈輸出每一列
for row in rows:
print(row)
'''
讀取特定行
'''
import csv
f = open('test.csv', 'r')
for row in csv.DictReader(f):
print (row['num'])
f.close()
|
9d59dc781ce76f2ec35fe92a8cf3f6930e300b08 | zhou-jia-ming/leetcode-py | /interview_01_07.py | 1,216 | 4.03125 | 4 | # coding:utf-8
# Created by: Jiaming
# Created at: 2020-04-07
# 矩阵旋转90度
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix) # 行
# 以x=y为轴翻转
# [[1,2,3],
# [4,5,6],
# [7,8,9]]
# 变为
# [1 4 7]
# [2 5 8]
# [3 6 9]
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# 以中点为轴翻转
for i in range(n):
for j in range(n // 2):
matrix[i][j], matrix[i][n - j - 1] = matrix[i][n - j - 1], \
matrix[i][j]
# 非原地修改写法,先上下翻转,再以x=y为轴复制对应数字
# n = len(matrix)
# r = list(zip(*matrix[::-1]))
# for i in range(n):
# for j in range(n):
# matrix[i][j] = r[i][j]
if __name__ == "__main__":
s = Solution()
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
s.rotate(m)
print(m)
|
6ffd864a31ac44990e6a2d8333865ec2be73aac2 | fanniestar0/tax-school-hb | /common/handle_02readexcel.py | 1,116 | 3.515625 | 4 | # 封装读取测试用例的类
import openpyxl
class ReadExcel(object):
def __init__(self, filename, sheet_name):
self.filename = filename
self.sheet_name = sheet_name
def openfile(self):
self.wb = openpyxl.load_workbook(self.filename)
self.sh = self.wb[self.sheet_name]
def read_data(self):
self.openfile()
data = list(self.sh.rows)
title = list(i.value for i in data[0])
cases = []
for i in data[1:]:
values = list(a.value for a in i)
case = dict(zip(title, values))
cases.append(case)
return cases
def write_data(self, row, column, value):
self.openfile()
self.sh.cell(row=row, column=column, value=value)
self.wb.save(self.filename)
# 表单需与封装的读取表达的类在同一目录下, 才可读取成功数据
# excel = ReadExcel("api_cases_hb.xlsx", "login") # 通过定义的类名创建个对象
# case_datas = excel.read_data() # 对象调用方法
# print("读取出来的数据为:", case_datas)
|
4ce4c3f671e5fa1b1188da4c21b66f5c27e6f88b | mksime/gerador_senha | /senha.py | 835 | 3.640625 | 4 | import string
import random
sinais = string.punctuation
maiusculas = string.ascii_uppercase
minusculas = string.ascii_lowercase
numeros = string.digits
for i in sinais:
if i in r"'\\/_=^`\|~\"":
sinais = sinais.replace(i, "")
total = sinais + maiusculas + minusculas + numeros
while True:
senha = ""
sinal = False
maiuscula = False
minuscula = False
numero = False
for i in range(8):
senha += random.choice(total)
for char in senha:
if char in sinais:
sinal = True
elif char in maiusculas:
maiuscula = True
elif char in minusculas:
minuscula = True
elif char in numeros:
numero = True
if sinal == True and maiuscula == True and minuscula == True and numero == True:
break
print(senha) |
fd8da3208067253d6485bc86127a62d4953d99b0 | AppallingFiend/MyProfile | /DefHelm.py | 1,233 | 3.515625 | 4 | #Протокол Деффи-Хелмана
import random
def chif(p,g):
z=int(input("Введите количество участников чата"))
print("Изначально всем участникам извстны следующее числа p = %d и g = %d"%(p,g))
priv=[]
print("Каждая сторона выберает свое уникальное число")
for i in range(z):
e=random.randint(1,p-1)
priv.append(e)
print(priv)
print("Все игроки поделились своеми публичными ключами, теперь на основе полученых ключей они расчитают")
outzn=[]
for i in range(z):
b=g
for j in range(z):
if i==j:
None
else:
b=b**priv[j]%p
outzn.append(b)
print("Учистник %d выбрал параметр %d и после того как расчитали получили участник %d получил следующее число %d"%(i+1,priv[i],i+1,b))
print(outzn)
print("Теперь каждый считает ключ который должен быть у всех одинаковый")
rez=[]
for i in range(z):
pp=(outzn[i]**priv[i])%p
rez.append(pp)
print(rez)
p=3011
g=random.randint(1,p-1)
chif(p,g)
|
aee22eee0b4ac419dbf27d1e9bfc4dba6702e004 | pramod-karkhani/codechef_beginner | /ATM.py | 887 | 4.125 | 4 | '''Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is
a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including
bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account balance
after an attempted transaction.
Input
Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw.
Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance.
Output
Output the account balance after the attempted transaction, given as a number with two digits of precision.
If there is not enough money in the account to complete the transaction, output the current bank balance.
'''
a = list(input().split(' '))
x=int(a[0])
y=float(a[1])
if x<=y-.50 and x%5==0:
y=y-x-0.5
print("%.2f" %y)
|
3f045f23774b09f0d816c4a2ae7d76ad05be15c2 | EduardoAlbert/python-exercises | /Mundo 3 - Estruturas compostas/107-112 Módulos e Pacotes/ex110module/coin.py | 919 | 3.625 | 4 | def coin(value):
return f'R${value:>.2f}'.replace('.', ',')
def half(x, formatCoin=False):
result = x / 2
return coin(result) if formatCoin else result
def double(x, formatCoin=False):
result = x * 2
return coin(result) if formatCoin else result
def increase(x, inc, formatCoin=False):
result = x + (x * inc/100)
return coin(result) if formatCoin else result
def decrease(x, dec, formatCoin=False):
result = x - (x * dec / 100)
return coin(result) if formatCoin else result
def resume(value, inc, dec):
print('-'*30)
print(f'RESUMO DO VALOR'.center(30))
print('-'*30)
print(f'Preço analisado: \t{coin(value)}')
print(f'Dobro do preço: \t{double(value, True)}')
print(f'Metade do preço: \t{half(value, True)}')
print(f'{inc}% de aumento: \t{increase(value, inc, True)}')
print(f'{dec}% de aumento: \t{decrease(value, dec, True)}')
|
572e79837b8ea5840aa3b92ab1cbb9da998ea0fb | XiaoLing941212/Summer-Leet-Code | /7.12 - Prefix Sum(848)/848. Shifting Letters.py | 1,216 | 4.09375 | 4 | '''
We have a string S of lowercase letters, and an integer array shifts.
Call the shift of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').
For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.
Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times.
Return the final string after all such shifts to S are applied.
Example 1:
Input: S = "abc", shifts = [3,5,9]
Output: "rpl"
Explanation:
We start with "abc".
After shifting the first 1 letters of S by 3, we have "dbc".
After shifting the first 2 letters of S by 5, we have "igc".
After shifting the first 3 letters of S by 9, we have "rpl", the answer.
Note:
1. 1 <= S.length = shifts.length <= 20000
2. 0 <= shifts[i] <= 10 ^ 9
'''
#Prefix Sum
class Solution:
def shiftingLetters(self, S: str, shifts: List[int]) -> str:
res = ''
s = sum(shifts) % 26
#index start from 1st element, and going to last
for i, num in enumerate(S):
index = ord(num) - ord('a')
res = res + chr(ord('a') + (index + s) % 26)
s = (s - shifts[i]) % 26
return res
|
7f4d1acb8fb56f7dbe23875c84ab825f57292ac5 | Nicolas-Reyland/metalang | /out/calc.py | 267 | 3.703125 | 4 |
"""La suite de fibonaci"""
def fibo(a, b, i):
out_ = 0
a2 = a
b2 = b
for j in range(0, i + 2):
print("%d" % j, end='')
out_ += a2
tmp = b2
b2 += a2
a2 = tmp
return out_
print("%d" % fibo(1, 2, 4), end='')
|
20bb2ef0d244b45c99e8c642ebdd2c56576fadf5 | ericbrowne/PythonScripts | /max_profit.py | 463 | 3.53125 | 4 | ### Max Profit ###
def MaxProfit(A):
""" Given a list of A of stock prices, find the buy and sell times that max profit"""
best,buy,sell = 0,0,-1
n=len(A)
for i in range(0,n):
for j in range(i,n):
profit = A[j] - A[i]
if profit > best:
best,buy,sell = profit, i, j
return best, buy, sell
## Has complexity class: T(n) = theta(n^2)
A= [50,30,66,19,345,89]
print(MaxProfit(A))
|
edd86eeb66b4129c2c1f32d36b5a16da8374199a | tieberghien/bootcamp_python | /d00/ex06/recipe.py | 709 | 3.703125 | 4 | def del_recipe(recipe):
del recipe
def print_recipe(recipe):
res = {key: recipe[key] for key in recipe.keys()}
print(res)
if __name__ == '__main__':
cookbook = { 'sandwich': {'ingredients': ['ham', 'bread', 'cheese', 'tomatoes'], 'meal': 'lunch', 'prep_time': 10},
'cake': {'ingredients': ['flour', 'sugar', 'eggs'], 'meal': 'dessert', 'prep_time': 60},
'salad': {'ingredients': ['avocado', 'arugula', 'tomatoes','spinach'], 'meal': 'lunch', 'prep_time': 15} }
# for k, v in cookbook.items():
# for k1, v1 in v.items():
# print(k1, v1)
print_recipe(cookbook['sandwich'])
del_recipe(cookbook['sandwich'])
print_recipe(cookbook['sandwich']) |
375eaefed5ef05907c91437b89100d1468a81e3e | shbz1690/basic-Bioinfo-Problem-Python- | /Reverse complement of input DNA sequence is pallindrome or not.py | 597 | 3.96875 | 4 | # Reverse complement is a pallindrome of input DNA sequence or not.
import sys
input_codon=sys.argv[1]
def comp(nuc):
if nuc=='A':
comp='T'
elif nuc=='T':
comp='A'
elif nuc=='G':
comp='C'
elif nuc=='C':
comp='G'
else:
comp=nuc
return comp
def rev_comp(nucl):
nucl=nucl.upper()
rev_comp=''
for i in nucl:
compl=comp(i)
rev_comp = compl+rev_comp
return rev_comp
rev_complement=rev_comp(input_codon)
print "reverse complement is a pallindrome of original sequence :",rev_complement==input_codon
|
cd9ee84a0ac0591dab1f10f4126c88d600f87dcc | bkuhlen73/udemy | /python/challenges/find_greater_numbers.py | 440 | 4.0625 | 4 | '''
find_greater_numbers([1,2,3]) # 3
find_greater_numbers([6,1,2,7]) # 4
find_greater_numbers([5,4,3,2,1]) # 0
find_greater_numbers([]) # 0
'''
def find_greater_numbers(arr):
count = 0
i = 0
j = 1
while i < len(arr):
while j < len(arr):
if arr[j] > arr[i]:
count += 1
j += 1
j = i+1
i += 1
return count
print(find_greater_numbers([6, 1, 2, 7])) # 4
|
cddc4d596242f4445250c1708becb00503bf0f1d | kromadown/FarrasYamin_ITP2017_Excercise | /Excercise 4/4.2.py | 163 | 3.78125 | 4 | animals = ['cat','rabbit','hamster']
for i in animals:
print (i)
for i in animals:
print ('A ' + i + ' would make a great pet')
print ('They have 4 legs')
|
9b205913301b28375a991b08c349395ea210dc5d | ArmandSongisepp/cooditund | /te1.py | 195 | 3.734375 | 4 | from time import sleep
def countdown(n):
for i in range(n):
print(n)
n-=1
sleep(1)
loendus = int(input("Sisestage taimeri sekundid"))
print(countdown(loendus))
|
b68fa224a13241bbcfd15aa1ce209df8fa06cf50 | KashishChanana/Promotions-Analysis-ML | /utils/featureSelection.py | 1,364 | 3.6875 | 4 | import matplotlib.pyplot as plt
import seaborn as sns
def plot_multicollinearity(df):
"""
Plots multicollinearity plot for the dataframe df.
:param df: master Dataframe containing feature and target columns
:return: None; displays plot
"""
plt.figure(figsize=(9, 6))
sns.heatmap(df.corr(), annot=True, vmin=-1, vmax=1, fmt=".2f", cmap="coolwarm")
plt.title("Feature Multicollinearity", fontsize="x-large")
plt.xticks(rotation=45, ha="right");
plt.show()
target = ["success"]
features = ["USER_ID", "SELLER_RESIDENCE_COUNTRY_ID", "IS_BUSINESS_SELLER",
"IS_DIRECT_CHARITY_SELLER", "TOP_SELLER_LEVEL", "SUBS_TIER",
"SELLER_SPS_LEVEL", "IS_P20_SELLER",
"pre_dec_promo_discount", "pre_dec_base_charge", "pre_dec_list_items"]
def split_features_target(df, features_col=features, target_col=target):
"""
Method for filtering features and target Series from master dataframe
:param df: master Dataframe containing feature and target columns
:param features_col: list with selected features column names
:param target_col: list with selected target column name
:return X: DataFrame with selected feature columns
:return y: Series with selected target column
"""
plot_multicollinearity(df)
X = df[features_col]
y = df[target_col]
return X, y
|
c6abbe4c07ea394469c204b9b38a28363c6ea825 | vikasjoshis001/Python-Course | /64_itertools.py | 402 | 3.6875 | 4 | from itertools import product
A = input()
B = input()
A = A.split(" ")
B = B.split(" ")
list1 = []
list2 = []
print(A[0])
print(A)
for i in range(0,len(A)):
integer = int(A[i])
list1.append(integer)
for j in range(0,len(B)):
integer = int(B[j])
list2.append(integer)
print(list1)
print(list2)
C = list(product(list1,list2))
print(C)
for k in range(0,len(C)):
print (C[k],end=" ") |
f953b698376405826ec52639b6b5d318d3452954 | zeroam/TIL | /codeit/algorithm/greedy_course_selection.py | 601 | 4.09375 | 4 | def course_selection(course_list):
sorted_course_list = sorted(course_list, key=lambda x: (x[1], x[0]))
best_courses = [sorted_course_list[0]]
for course in sorted_course_list:
if course[0] > best_courses[-1][1]:
best_courses.append(course)
return best_courses
if __name__ == '__main__':
print(course_selection([(6, 10), (2, 3), (4, 5), (1, 7), (6, 8), (9, 10)]))
print(course_selection([(1, 2), (3, 4), (0, 6), (5, 7), (8, 9), (5, 9)]))
print(course_selection([(4, 7), (2, 5), (1, 3), (8, 10), (5, 9), (2, 5), (13, 16), (9, 11), (1, 8)]))
|
b9535673d3886b433e2422d0c99f5d240ac0ca60 | kishanpolekar/kishanpolekar.github.io | /folder/p7_1.py | 731 | 4.03125 | 4 | from Rectangle import Rectangle
def main():
rec1=Rectangle(4,40)
rec2=Rectangle(3.5,35.7)
print('The area of the rectangle with width {} units and height {} units is {:.2f} square units.'.format(rec1.width, rec1.height, rec1.getArea()))
print('The perimeter of the rectangle with width {} units and height {} units is {:.2f} square units.'.format(rec1.width, rec1.height, rec1.getPerimeter()))
print('The area of the rectangle with width {} units and height {} units is {:.2f} square units.'.format(rec2.width, rec2.height, rec2.getArea()))
print('The perimeter of the rectangle with width {} units and height {} units is {:.2f} square units.'.format(rec2.width, rec2.height, rec2.getPerimeter()))
main()
|
69d1996b6c5b0fc19daf11cb83f512a23615e95e | palladine/edu_python | /multytable.py | 327 | 4.03125 | 4 | print("""---------------------------
Таблица умножения
---------------------------""", end="")
for x in range(1, 10):
print("", end="\n")
for y in range(1,10):
_unit = str(x*y)
if len(_unit) == 1:
_unit = " "+_unit
print(_unit, end=" ")
print("\n---------------------------", end="")
|
289ad870d9b27a3c965ecddb55df557d65b01d03 | eclairsameal/TQC-Python | /第2類:選擇敘述/PYD203.py | 883 | 3.953125 | 4 | y = int(input())
if y % 4 ==0 and y % 100 != 0 or y % 400 == 0:
print("{} is a leap year.".format(y))
else :
print("{} is not a leap year.".format(y))
# version: elif
year = int(input('Please input year:'))
if( year % 400 == 0):
print('{} is a leap year.'.format(year))
elif( year % 100 == 0):
print('{} is a normal year.'.format(year))
elif( year % 4 == 0):
print('{} is a leap year.'.format(year))
else:
print('{} is a normal year.'.format(year))
# version: nest if
year = int(input('Please input year:'))
if( year % 400 == 0):
print('{} is a leap year.'.format(year))
else:
if( year % 100 == 0):
print('{} is a normal year.'.format(year))
else:
if( year % 4 == 0):
print('{} is a leap year.'.format(year))
else:
print('{} is a normal year.'.format(year))
|
376b00985a179441873af09e1021cdbc101ee8a6 | NunoMars/PurBeurre | /body/meeting_user.py | 425 | 3.59375 | 4 | from .first import main_menu
def meeting():
while True:
user_name = input(
"BIENVENUE\n Je peut vous aider à trouver un produit équivalent.\n\
Faisons d'habord connaiscance, quel est votre nom? :")
if user_name == '' or user_name == ' ':
continue
else:
main_menu(user_name)
break
if __name__ == "__main__":
meeting_user()
|
969cacd92449e4ffcc02adfca39152a7109b76af | bopopescu/Py_projects | /Py_op/py_dataStruc/zipMapLambda_test.py | 3,628 | 3.75 | 4 | import time
import sys
import os
# os.system("pause")
###################################################################################################
####
# zip, map, and filter all return an iterator
# zip takes tuple of iterables and return an iterable of tuples
dic1 = {'wifi': 1, 'bt': 2}
dic2 = {'abgn': 3, 'ax': 4}
merg1 = zip(dic1, dic2, dic2, dic2)
# [('wifi', 'abgn', 'abgn', 'abgn'), ('bt', 'ax', 'ax', 'ax')]
merg = zip(dic1, dic2)
print(list(merg)) #[('wifi', 'abgn'), ('bt', 'ax')]
#
list1 = ['Alpha', 'Beta', 'Gamma', 'Sigma']
list2 = ['one', 'two', 'three', 'six']
# zip returns an iterator
test = zip(list1, list2) # zip the values # test is an iterator
try:
while True:
item_a, item_b = next(test)
print(item_a, item_b)
except:
print("done")
# time.sleep(1000)
# ('Alpha', 'one'), ('Beta', 'two'), ('Gamma', 'three'), ('Sigma', 'six')
test = zip(list1, list2)
testList = list(test)
#
list1 = ['Alpha', 'Beta', 'Gamma', 'Sigma']
list2 = ['one', 'two', 'three', 'six']
iter_zip = zip(list1, list2)
print(f"type(iter_zip) is {type(iter_zip)}") # type(iter_zip) is <class 'zip'>
a, b = zip(*iter_zip)
print(f"type(a) is {type(a)}, and a is {a}\ntype(b) is {type(b)}")
# type(a) is <class 'tuple'>, and a is ('Alpha', 'Beta', 'Gamma', 'Sigma')
print(list(a))
# ['Alpha', 'Beta', 'Gamma', 'Sigma']
list1 = ['Alpha', 'Beta', 'Gamma', 'Sigma']
# list is iterable, but not iterator
# iter(list) turn a list to an iterator
# print(next(list1))
list1 = iter(list1)
try:
while True:
item_a = next(list1)
print(item_a, end=", ")
except:
print("\ndone")
# Alpha, Beta, Gamma, Sigma,
# done
####
x = lambda a : a + 10
print(x(5))
t = lambda a, b : a+ b
print(t(100, 1))
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
#@@
Input: ["23:59", "00:00"]
def findMinDifference(self, timePoints):
"""
:type timePoints: List[str]
:rtype: int
"""
tp = sorted(map(int, p.split(':')) for p in timePoints)
tp += [[tp[0][0] + 24, tp[0][1]]]
return min((tp[x+1][0] - tp[x][0]) * 60 + tp[x+1][1] - tp[x][1]
for x in range(len(tp) - 1))
#map returns an iterator
def multiply2(x):
return x * 2
a = map(multiply2, [1, 2, 3, 4]) # Output [2, 4, 6, 8]
print(type(a), a, sep=", ")
for i in a:
print(i, sep=", ")
#
def to_upper_case(s):
return str(s).upper()
def print_iterator(it):
for x in it:
print(x, end=' ')
print('') # for new line
# map returns an map object, which is an iterator
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)
#
def print_iterator(it):
for x in it:
print(x, end=' ')
print('') # for new line
list_numbers = [1, 2, 3, 4]
map_iterator = map(lambda x: x * 2, list_numbers)
print_iterator(map_iterator)
#
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)
# filter returns an iterator
list_of_dict = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
map(lambda x: x['name'], list_of_dict) # Output: ['python', 'java']
map(lambda x: x['points'] * 10, list_of_dict) # Output: [100, 80]
map(lambda x: x['name'] == "python", list_of_dict) # Output: [True, False]
a = [1, 2, 3, 4, 5, 6]
b=filter(lambda x : x % 2 == 0, a) # Output: [2, 4, 6]
list_of_dict = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
b = filter(lambda x : x['name'] == 'python', list_of_dict) # Output: [{'name': 'python', 'points': 10}]
|
c7eb7b753035b15336d490168b21e1d986d7254c | happybt/rad | /class_in/MyClass.py | 229 | 3.96875 | 4 | # -*- coding: UTF-8 -*-
class MyClass:
"""This is a simple class"""
i = 12345
def f(self):
return 'hello world'
x = MyClass()
print('MyClass attribute i is : ', x.i)
print('MyClass method f is : ', x.f())
|
f2b1ca4fb7c6ef986541e150ae903eb0e34b8860 | jmeln/Uberair-Green | /Python/Passenger.py | 991 | 3.859375 | 4 | #Author: Jarrett Melnick
#Class to stroe data relating to individual passengers.
class Passenger:
def __init__(self, fname, lname, locS, locE):
self.fname = fname #Passenger's firstname
self.lname = lname #Passenger's lastname
self.locS = locS #starting location of class City
self.locE = locE #ending location of class City
self.distanceTraveled = Distance(self.locS, self.locE) #Total distance traveled by the passenger
self.price = CalcPrice(distanceTraveled) #Price the passenger will pay
def Distance(locS, locE):
#fucntion to calculate the distance the passenger will travel.
d = 0.0
a1 = math.radians(locS.Latitude)
a2 = math.radians(locE.Latitude)
b1 = math.radians(locS.Longitude)
b2 = math.radians(locE.Longitude)
d = ((1 - math.cos(2*((a2-a1)/2)))/2) + math.cos(a1)*math.cos(a2)*((1 - math.cos(2*((b2-b1)/2)))/2)
d = ((2*6373)*(math.asin(math.sqrt(d))))
return d
def CalcPrice(distT):
#Calculates the price the passenger will pay
return (distT*1.25)
|
0e6f150ec7f68fa839aa33c6fec46db353a52a0f | alexandraback/datacollection | /solutions_5709773144064000_0/Python/eduardische/B.py | 323 | 3.515625 | 4 | T = int(input())
for iT in list(range(0,T)):
lim = input().split()
C = float(lim[0])
F = float(lim[1])
X = float(lim[2])
tm = 0.0
R = 2.0
res = X / R
while (tm < res):
tm += C / R
R += F
if ((tm + (X / R)) < res):
res = tm + X / R
print("Case #" + str(iT+1) + ": " + "{0:.7f}".format(res))
|
0e93901800ab0517d4d87d9fa3857242fbb3e0c5 | ccdle12/Code-Wars-Solutions | /Reversing Strings 6 Kyu.py | 391 | 3.578125 | 4 | #Reversing String Algorithm 6 Kyu
def spin_words(sentence):
lst = []
for i in sentence.split():
if len(i) >= 5:
lst.append(''.join(list(i)[::-1]))
else:
lst.append(i)
print ' '.join(lst)
#Best Practice
#return " ".join([x[::-1] if len(x) >= 5 else x for x in sentence.split(" ")])
spin_words("hey fellow warriors")
|
98234ba71713428c93099402cefb56c25814b84f | ZainebPenwala/Python-practice-problems | /Length of words.py | 232 | 4.3125 | 4 | # A program that maps a list of words into a list of integers representing the lengths of the correponding words.
li=['hello','wonderful','beauty','watermeleon']
length=[]
for elem in li:
length.append(len(elem))
print(length)
|
3541262d6c84769fee55d2f7c887ac2e5da834dd | sowmyapunuru143/Career-Guidance | /career.py | 5,481 | 4.0625 | 4 | '''
This functions returns the greeting message according to the tym
'''
from datetime import datetime
import random
def current_time():
current_time=datetime.now()
greeting="Good morning"
if current_time.hour>12 and current_time.hour<17:
greeting="Good afternoon"
elif current_time.hour>=17 and current_time.hour<22:
greeting="Good evening"
elif current_time.hour>=22:
greeting="Hi,its too late"
return greeting
'''
This function gives the welcome message
'''
def welcome(name):
message=[
"How can i help you?",
"Is there anything i can help with?"
]
print(f"{current_time()}!{name},{random.choice(message)}")
def career_guidance():
print("1.Science")
print("2.Arts")
print("3.Commerce")
try:
return(int(input("Enter your option:")))
except:
print("Invalid input")
return 0
def type1_Science():
print("Select any one option from 1 to 3")
def Science_option():
print("1.Science subjects")
print("2.Science career options")
print("3.Go back")
try:
return(int(input("Enter your choice:")))
except:
print("Invalid input")
return 0
def Science_subjects():
print("This subjects you should choose according to your goal or interest in science")
print("Mathematics")
print("English")
print("Biology")
print("Physics")
print("Chemistry")
print("Computer Science")
def Science_career__options():
print("Engineering")
print("Doctor")
print("Scientist")
print("Astronauts")
print("Pharmacists")
print("Software Programmers")
print("Web Developers and lot more")
def print_option():
option=Science_option()
while option !=3:
if option == 1:
Science_subjects()
elif option == 2:
Science_career__options()
else:
print("Sorry!Invalid input")
option=Science_option()
print_option()
def type2_Arts():
print("Select any one option from 1 to 3")
def Arts_option():
print("1.Arts subjects")
print("2.Arts career options")
print("3.Go back")
try:
print(int(input("Enter your choice:")))
except:
print("Invalid input")
return 0
def Arts_subjects():
print("This subjects you should choose according to your goal or interest in arts")
print("English")
print("Economics")
print("History")
print("Geography")
print("Political Science")
print("Hindi")
print("Sanskrit")
print("Home Science")
def Arts_career_options():
print("Journalism")
print("Teaching")
print("Lawyer")
print("Graphic Designer")
print("Mass Communication and Journalism")
print("Hotal Management and Many more")
def print_option():
option=Arts_option()
while option!=3:
if option==1:
Arts_subjects()
elif option==2:
Arts_career_options()
else:
print("Sorry!Invalid input")
option=Arts_option()
print_option()
def type3_commerce():
print("Select any one option from 1 to 3")
def commerce_option():
print("1.commerce subjects")
print("2.commerce career options")
print("3.Go back")
try:
print(int(input("Enter your Choice:")))
except:
print("Invalid input")
return 0
def commerce_subjects():
print("Among this subjects you should choose accoring to your goal or interest in commerce")
print("Business Studies")
print("Accountancy")
print("Econamics")
print("Mathematics")
print("English")
print("Informatics Practices(if nor maths)")
def commerce_career_options():
print("Chartered Accountants(CA)")
print("Company Secretaries(CS)")
print("Chief Finacial Accountant(CFA)")
print("Finacial planner")
print("Lawyer")
print("Bank PO and many more")
def print_option():
option=commerce_option()
while option!=3:
if option==1:
commerce_subjects()
elif option==2:
commerce_career_options()
else:
print("Sorry!Invalid input")
option=commerce_option()
print_option()
def chatbot():
print("This chatbot helps you to choose best career ")
name=input("Enter your name:")
welcome(name)
print("Select any one of the below stream to know the subjects and career options")
choice=career_guidance()
while choice!=4:
if choice==1:
type1_Science()
elif choice==2:
type2_Arts()
elif choice==3:
type3_commerce()
else:
print("Please enter the number between 1 to 5")
choice=career_guidance()
chatbot()
|
d3fcea8cc411ac6ed84812fdb66cf5b51fa756a4 | murali-kotakonda/PythonProgs | /PythonBasics1/basics/conditions/Ex2.py | 261 | 4.125 | 4 |
"""
write a program to take two strings as input check if two strings are equal or not
"""
n1 = input("enter str1 :")
n2 = input("enter str2 :")
if n1 == n2 :
print("strings are equal")
else:
print("strings are not equal")
|
60e318ca1923e87db29a2d56c738314fb89c282f | SangWoo9734/TIL | /Python/p_chapter06_02.py | 1,997 | 3.546875 | 4 | # Chapter06-02
# 병행성(Concurrency) : 한 컴퓨터가 여러 일을 동시에 수행 -> 단일 프로그램안에서 여러일을 쉽게 해결
# 병렬성(Parallelism) : 여러 컴퓨터가 여러 작업을 동시에 수행 -> 속도
# Generator Ex1
def generator_ex1():
print('Start')
yield 'A Point' # yield : 어디 까지 진행했는지 알고있다!
print('Continue')
yield 'B Point'
print('End')
temp = iter(generator_ex1())
# # print(temp)
# print(next(temp)) # Start A Point
# print(next(temp)) # Start A Point Continue B Point
# print(next(temp))
for v in generator_ex1():
pass
# print(v)
# Generator Ex2
temp2 = [x*3 for x in generator_ex1()]
temp3 = (x*3 for x in generator_ex1())
print(temp2)
print(temp3)
for i in temp2:
print(i)
for x in temp3:
print(x)
print()
# Generator Ex3(중요 함수)
# count, takewhile, filterfalse, accumulate, chain, product, groupby
import itertools
gen1 = itertools.count(1, 2.5)
print(next(gen1))
print(next(gen1))
print(next(gen1))
print(next(gen1))
print(next(gen1))
print(next(gen1))
print(next(gen1))
# ... 무한
# 조건
gen2 = itertools.takewhile(lambda n : n < 1000, itertools.count(1, 2.5))
# for i in gen2 :
# print(i) 1에서 1000 까지 2.5 씩 증가하면서 출력해준다.
# 필터 반대
gen3 = itertools.filterfalse(lambda n : n < 3, [1,2,3,4,5])
for v in gen3:
print(v)
print()
# 누적 합계
gen4 = itertools.accumulate([x for x in range(1, 101)])
for v in gen4 :
print(v)
# 연결1
gen5 = itertools.chain('ABCDE', range(1,11,2))
print(list(gen5))
# 연결2
gen6 = itertools.chain(enumerate('ABCDE'))
print(list(gen6))
# 개별
gen7 = itertools.product("ABCDE")
print(list(gen7))
# 연산 (경우의 수)
gen8 = itertools.product("ABCDE", repeat=2) # 원소를 두개씩 묶음 (중복 포함)
print(list(gen8))
# 그룹화
gen9 = itertools.groupby('AAABBBCCCCCDDE')
# print(list(gen9))
for chr, group in gen9:
print(chr, ' : ', list(group)) |
c823176be79e9679717fddba675d411117d3e978 | makimaliev/BIL622 | /HW1/euler1.py | 823 | 3.703125 | 4 | import numpy as np
import matplotlib.pyplot as plt
# limits: 0.0 <= t <= 2.0
a = 0.0
b = 2.0
# steps
N = 10
# step-size
h = (b-a)/N
# initial value: y(0.0) = 0.5
IV = (0.0,0.5)
# ordinary differential equation
def f( t, y ):
#return (t*y*y+t)/(y-t*t*y)
return y - t**2 + 1
# make arrays to hold t, and y
t = np.arange( a, b+h, h )
w = np.zeros((N+1,))
# set the initial values
t[0], w[0] = IV
# apply Euler's method
for i in range(1,N+1):
w[i] = w[i-1] + h * f( t[i-1], w[i-1] )
# exact solution
def y( t ):
return (t+1.0)**2.0-0.5*np.exp(t)
plt.plot( t, w, label='approximation' )
plt.plot( t, y(t), label='exact' )
plt.title( "Euler's Method Example, N="+str(N) )
plt.xlabel('t')
plt.ylabel('y(t)')
plt.legend(loc=4)
plt.grid()
plt.savefig( 'euler_example.eps', fmt='EPS', dpi=100 )
|
1397e176aa17d16447ac246cd634c069b47ab866 | joshjpark/leetcode | /oddCells.py | 943 | 3.796875 | 4 | '''
Question 1252: Cells with Odd Values in a Matrix: Easy
URL: https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/
'''
class Solution:
def oddCells(self, n, m, indices):
# create 2D array with n * m dimensions
matrix = []
for i in range(0, n):
matrix.append([0]*m)
for index in indices:
x, y = index
matrix = self.incrementMatrix(matrix, x, y)
counter = 0
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if matrix[row][col] % 2 == 1:
counter += 1
return counter
def incrementMatrix(self, matrix, row, col):
# increment row
for i in range(len(matrix[0])):
matrix[row][i] += 1
# increment column
for j in range(len(matrix)):
matrix[j][col] += 1
return matrix
|
59ac2fd8205bf14798e35eb4e7fc48b39fa72e2e | acsutt0n/TradingStategies | /send_email.py | 1,846 | 4.125 | 4 | # send an email with contents from a txt file in format below with python
# called: python send_email.py email.txt pfile.txt
# email.txt is as below; pfile.txt is simply the email psw for fromaddr
"""
# Message must obey this template::
To: toaddress
From: fromaddress
Msg: Message as long as you want it
"""
import smtplib
def load_emailfile(emailFile):
with open(emailFile, 'r') as fIn:
for line in fIn:
splitLine = line.split(None)
if splitLine[0] == 'To:':
if len(splitLine) > 2:
print('To: line should be only: To: toaddress')
toaddr = splitLine[1]
elif splitLine[0] == 'From:':
if len(splitLine) > 2:
print('From: line should be only: From: fromaddress')
fromaddr = splitLine[1]
elif splitLine[0] == 'Msg:':
msg = ' '.join(splitLine[1:])
return toaddr, fromaddr, msg
def load_pfile(pfile):
with open(pfile, 'r') as pIn:
for line in pIn:
splitLine = line.split(None)
p = splitLine[0]
return p
def send_email(toaddr, fromaddr, p, msg):
print('Connecting to gmail server...')
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
try:
server.login(fromaddr, p)
except:
print('Bad password. Login name must be same as From: fromaddr')
server.sendmail(fromaddr, toaddr, msg)
print('Email sent.')
server.quit()
return
def emailControl(emailFile, pfile):
toaddr, fromaddr, msg = load_emailfile(emailFile)
p = load_pfile(pfile)
send_email(toaddr, fromaddr, p, msg)
return
####################################################################
if __name__ == "__main__":
import sys, os
args = sys.argv
if len(args) != 3:
print('Need 3 arguments: python send_email.py email.txt pfile.txt')
else:
emailFile = args[1]
pfile = args[2]
emailControl(emailFile, pfile)
|
bd9a8fdd5f0fb8b0b7aa02768f0ef43b3d78ae3f | alexwassel/Roman-Numerals | /roman.py | 666 | 3.84375 | 4 | # Alex Wassel
# Integer to Roman Numerals
num = int(input("Enter an integer: "))
if num < 1 or num > 3999:
print("Input must be between 1 and 3999")
ans = ""
m = num // 1000
ans += m * "M"
num -= m * 1000
c = num // 100
if c == 4:
ans += "CD"
elif c == 9:
ans += "CM"
elif c > 4:
ans += "D" + (c - 5) * "C"
else:
ans += c * "C"
num -= c * 100
x = num // 10
if x == 4:
ans += "XL"
elif x == 9:
ans += "XC"
elif x > 4:
ans += "L" + (x - 5) * "X"
else:
ans += x * "X"
num -= x * 10
i = num // 1
if i == 4:
ans += "IV"
elif i == 9:
ans += "IX"
elif i > 4:
ans += "V" + (i - 5) * "I"
else:
ans += i * "I"
print(ans)
|
65326624bc01d648646df0b1c5c256dcd8f211bb | 0xb5951/ComPro | /atcoder/ABC_167/a.py | 169 | 3.59375 | 4 | a = [input() for i in range(3)]
# print(a)
# print(T[:-1])
# s_len = len(a[0])
# a[0] = a[0].rstrip('\n')
if a[0] == a[1][:-1]:
print("Yes")
else:
print("No") |
128b3448ee8fe6aff29bf1111a8d556c1fb0448b | zdurczok/hard_way | /ex17/dictionary.py | 3,688 | 3.859375 | 4 | from dllist import DoubleLinkedList # so we can use dllist and it's methods
class Dictionary(object):
def __init__(self, num_buckets=256): # set number of bucktes to 256 ( 2 ** 8)
"""Initializes a Map with the given number of buckets."""
self.map = DoubleLinkedList() # self.map is DoubleLinkedList() with it's methods
for i in range(0, num_buckets):
self.map.push(DoubleLinkedList()) # now the parent map-dllist contains 256 child dllists
def hash_key(self, key):
"""Given a key this will create a number and then convert it to
an index for the aMap's buckets."""
return hash(key) % self.map.count() # create an index for a key - try print(states.hash_key('NY')) in test_dictionary.py
def get_bucket(self, key):
"""Given a key, find the bucket where it would go."""
bucket_id = self.hash_key(key) # get the index of the bucket we want to access
return self.map.get(bucket_id) # get the bucket (parent dllist) at the given id (created with hash_key)
def get_slot(self, key, default=None):
"""
Returns either the bucket and node for a slot, or None, None
"""
bucket = self.get_bucket(key) # find a bucket (get the index of a bucket)
if bucket: # if bucket exists
node = bucket.begin # set node to the begin of the parent dllist
i = 0 # what for?
while node: # traverse the parent dllist
if key == node.value[0]: # if key equals key stored in a node
return bucket, node # return dllist and key-value pair (node)
else: # if not, go further
node = node.next
i += 1
# fall through for both if and while above
return bucket, None
def get(self, key, default=None):
"""Gets the value in a bucket for a given key, or the default."""
bucket, node = self.get_slot(key, default=default) # get the right bucket (parent dllist) and the right node (key-value pair)
return node and node.value[1] or node # return key-value pair
def set(self, key, value):
"""Sets the key to the value, replacing any existing value."""
bucket, slot = self.get_slot(key) # find a bucket and a slot at/inside this bucket
if slot:
# the key exists, replace it
slot.value = (key, value)
else:
# the key does not, append to create it
bucket.push((key, value))
def delete(self, key):
"""Deletes the given key from the Map."""
bucket = self.get_bucket(key) # find a bucket (get the index of a bucket)
node = bucket.begin # we need to go through buckets
while node: # traverse the parent dllist
k, v = node.value # key-value pair set to the value of te node, key-value pair of the node
if key == k: # if key matches node's key
bucket.detach_node(node) # detach the node from the parent dllist
break #stop
def list(self):
"""Prints out what's in the Map."""
bucket_node = self.map.begin # start at the beginning of the parent dllist
while bucket_node: # traverse the parent dllist
slot_node = bucket_node.value.begin # we need to access a child dllist
while slot_node: # traverse a child dllist
print(slot_node.value) # prints the key-value pair stored inside a slot, which is a node of a child dllist
slot_node = slot_node.next # go further inside a child dllist
bucket_node = bucket_node.next # go further inside the parent dllist
|
68fede418275cb4b103ee86d30da06fdcb2ddbee | Ryan-R-C/my_hundred_python_exercises | /Exercises/exc86.py | 1,957 | 3.8125 | 4 | from time import sleep
# Lista principal, recebe das outras listas
# o nome do aluno, as notas dentro de uma lista e a média.
students = list()
data = list() # Guarda o nome e a nota média do aluno temporariamente.
notes = list() # Guarda as duas notas de cada aluno temporariamente.
while True:
data.append(str(input('\nName: ').title()))
notes.append(float(input('Note 1: ')))
notes.append(float(input('Note 2: ')))
data.append(notes[:])
data.append((notes[0] + notes[1]) / 2)
students.append(data[:])
# Limpa as listas para novos dados de novos alunos.
data.clear()
notes.clear()
to_continue = ' '
while to_continue not in 'YN':
to_continue = str(input('Want to continue? [Y/N] ')).upper().strip()[0]
if to_continue not in 'YN':
print('Enter "Y" do or "N" to do not.')
if to_continue == 'N':
break
# Mostra uma tabela com o índice, o nome e a média dos alunos.
print(f'\n{"=-=" * 10}\n{"Number: Name: Media:"}')
for i, student in enumerate(students):
print(f'{i:^7} {student[0]:^7} {student[2]:>9.1f}')
print(f'{"=-=" * 10}')
while True:
# Pergunta o número do aluno de acordo com a tabela para ver as notas dele.
prompt = '\nWould you like to show which student?\n'
prompt += f'{"(999 to stop)":^43}'
number = int(input(f'{prompt}\nNumber: '))
# Se o número 999 for digitado, interrompe o programa.
if number == 999:
print(f'\n{"=-=" * 5}\n{"FINALIZING..."}\n{"=-=" * 5}')
sleep(2)
break
# Percorre a lista de cada aluno com o seu índice.
for i, students in enumerate(students):
# Verifica se o número digitado é o mesmo que o índice do aluno na lista
# se for, mostra as notas em forma de lista e o nome do aluno.
if number == i:
print('=-=' * 11)
print(f'The notes of {student[0]} are {student[1]}')
print('=-=' * 11) |
ce01f0f9e4adb17bed7429d81914ef352ecbf848 | pablilloab/Python | /Guia1/ejercicio8.py | 281 | 3.78125 | 4 | monto = float(input("Ingrese el monto que desea invertir "))
interes = float(input("Ingrese el interes anual "))
anos = int(input("Ingrese cantidad de años "))
for i in range (anos):
monto += (monto*interes)/100
print (f"El monto obtenido seria de {monto} ")
#ESTE ESTA MAL |
8e4202ba9f68c258330e5e77ecae6d6e0f5dc14e | LucasElias03/CursoPython | /Exercicio_Proposto/Exe1.py | 237 | 3.90625 | 4 |
n1 = input('Digite um número inteiro: ')
try:
nu_int = int(n1)
if (nu_int % 2 == 0):
print(n1,'e um número PAR')
else:
print(n1,'e um número IMPAR')
except:
print(f'({n1}) não e um número inteiro')
|
93e2103902fbebc0c968159c447c7b06e5046952 | Rafael-Cesario/exPython | /Ex/ex061.py | 208 | 3.796875 | 4 | #leia o primeiro termo e razão PA, mostre os 10 primeiros termos
termo = int(input('Termo: '))
razao = int(input('Razão: '))
q = 0
while q != 10:
print(termo, end=' ')
termo += razao
q += 1
|
c644bb77f8249cd9f29e0ba3c55a09defbb33f77 | rg98/aoc2020 | /10/code_two.py | 924 | 3.625 | 4 | #!/usr/bin/env python3.9
import copy
def count_combinations(numbers):
numbers.append(0)
numbers.sort()
numbers.append(numbers[-1]+3)
# Cound numbers of consecutive differences of one
cc_count = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
cc_factor = {1: 1, 2: 2, 3: 4, 4: 7, 5: 12}
count = 0
_n = numbers[0]
threes = 0
for n in numbers[1:]:
if n - _n == 1:
count += 1
else:
if n - _n == 3:
threes += 1
if count > 0:
cc_count[count] += 1
count = 0
_n = n
combinations = 1
for key, value in cc_count.items():
combinations *= cc_factor[key] ** value
return combinations
# Read program
numbers = []
with open('in.txt', 'r') as fd:
for line in fd:
num = int(line[:-1])
numbers.append(num)
combinations = count_combinations(numbers)
print(combinations)
|
4311ccdec2e26c23f8f81482c9ec0e7a0317fc41 | KeithPetro/project_euler_py | /pe_27.py | 1,349 | 3.625 | 4 | #Project Euler - 27
#Keith Petro - 2016/10/21
#Problem Name: Quadratic primes
#Description: Find the product of the coefficients, a and b, for the quadratic
#expression that produces the maximum number of primes for consecutive
#values of n, starting with n = 0.
#n^2 + an + b, |a| < 1000, |b| <= 1000
#b must be prime and a must be odd
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 31] #cache of primes
def is_prime(num): #this function only works providing all previous primes are populated in the primes list
isprime = num >= 2 and 1 or 0
for prime in primes:
if prime * prime > num:
break
if(num % prime == 0):
isprime = 0
break
return isprime
def get_nth_prime(n):
i = primes[-1] #start at the last cached prime
while(len(primes) < n):
i += 1
if(is_prime(i)):
primes.append(i)
return primes[n - 1]
def get_quadratic_prime_product(a_limit, b_limit):
get_nth_prime(1000) #initialize primes list
max_length = 0
max_length_product = 0
for a in range(a_limit - 1, -a_limit + 1, -2):
for b in [i for i in primes if i <= 1000]:
n = 0
length = 0
result = 2
while(is_prime(result)):
result = n ** 2 + a * n + b
length += 1
n += 1
if(length - 1 > max_length):
max_length = length - 1
max_length_product = a * b
return max_length_product
print(get_quadratic_prime_product(1000, 1000)) |
6ae771beb9ec8644a538e8877aa7ca8f0c5c404d | wxl789/python | /Day10/2-代码/面向对象/homewo0728.py | 953 | 3.5625 | 4 | # 人射击子弹
# 默认手枪中有4发子弹,人射击4次之后就没有了,每射击一次提示目前
# 还剩几发子弹,当全部射击没之后,再执行射击的操作时,提示没有子弹了,
# 人可以再次填装n发子弹,再次射击n次之后就没有了。
class Shootingbullets():
def Person(gun):
if True:
print(input("是否射击"))
print("开始射击")
def Gun(bullentBox):
global bullet1
bullet1 = 4
while bullet1 > 0:
print("射击", "还有%s颗子弹" % (bullet1-1))
# print("还有%s颗子弹"%bullet1)
print(input(""))
bullet1 -= 1
else:
print("没子弹了,需要装弹")
def Bluuetbox(bulletCount):
print("更换弹夹")
if True:
print("装弹成功")
person1 = Shootingbullets()
person1.Person()
person1.Gun()
person1.Bluuetbox()
|
b42134688805592ccd9f550be930df90cbcd1224 | elubdynasty/CasinoGameApp | /CasinoGame.py | 1,264 | 4.21875 | 4 | from random import randint
def casino_game():
print("Make a maximum bet. If you win, the number matched will be yours. Goodluck!")
playerinp_maxnum = input() #The player enters the maxnum. Any range up to the highest one will be picked by the comp
# => Pseudocode
#There will be a while loop until it matches the player's best bet against the comp. You wanna repeat the bet?
#There will be limits on guess (4-5)
#When the player bets higher than the comp's bet, It'll say, 'Make it lower', otherwise 'make it higher
maxnum_int = int(playerinp_maxnum)
comp_pick = randint(1, maxnum_int+1)
#count_wins = 0
while True:
print("Make a guess!")
player_guess = input()
#if int(player_guess) > maxnum_int and int(player_guess) < 1:
#print(f'Sorry, enter another valid num between $1 and ${maxnum_int}')
if int(player_guess) < comp_pick:
print('Higher')
elif int(player_guess) > comp_pick:
print('Lower')
elif int(player_guess) == comp_pick:
print('Matched')
break
else:
print('Wrong input. Try again!')
#still accepts number greater than maximum number
casino_game()
|
5d9cd80baafac479ea048b9a1c6c2857962ff4e6 | MarioCSilva/Algorithm-Problems | /src/ex9.py | 878 | 3.5 | 4 | import math
def find_bin_equal(n, k):
# Calculate the interval of possible numbers
min_val = int(math.pow(2,n-1) + 1)
max_val = int(math.pow(2,n) -1)
# Find the first multiple of k
for num in range(min_val, max_val+1):
if num % k == 0:
first_mult = num
break
if first_mult == None:
return 0
# Find all possibilities
count = 0
num_steps = (max_val - first_mult) // k
for num in range(num_steps):
binary = ( bin(first_mult)[2:] )
number_0 = binary.count('0')
number_1 = binary.count('1')
if number_0 == number_1:
count += 1
first_mult += k
return count
if __name__ == "__main__":
str_input = input()
lst = str_input.split(" ")
n = int(lst[0])
k = int(lst[1])
num = find_bin_equal(n, k)
print(num) |
85c33bd570d7cbf9c6547d3a241d1d23c730a255 | ebelfer2020/hackerrank_solutions | /python/basic_data_types/runner_up.py | 303 | 3.875 | 4 | if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
my_list = list(arr)
my_list.sort()
highest_number = max (my_list)
for i in range (len(my_list)-1, -1, -1):
if my_list[i] < highest_number:
break
print (my_list[i])
|
b3d60ea278708069e515c8bc29be14bced816853 | hedayet13/practiceCoding | /try.py | 1,901 | 3.921875 | 4 |
mainBoard = ( " | | \n"
" 1 | 2 | 3 \n"
"------|-------|------\n"
" 4 | 5 | 6 \n"
"------|-------|------\n"
" 7 | 8 | 9 \n"
" | | ")
displayBoard = ( " | | \n"
" | | \n"
"------|-------|------\n"
" | | \n"
"------|-------|------\n"
" | | \n"
" | | ")
a=list(mainBoard)
b=list(displayBoard)
z=[]
for i in range(len(a)):
if a[i].isdigit()==True:
z.append(i)
print ("which one You want to choose!! \n"
"For x type 0 \n"
"For o type 1")
player = ['x','o']
number = int(input())
if number == 0 or number ==1:
player =player[number]
print(player)
print(mainBoard)
iter = 0
numberRange = list(range(1,10))
while iter<9:
if player== 'x':
print('put yout number!!! Player: X')
number = int(input())
if number in numberRange:
b.pop(z[number-1])
b.insert(z[number-1],'x')
listTostr= ''.join(map(str,b))
print(listTostr)
numberRange.remove(number)
player = 'o'
iter+=1
else:
print('Please select another number between 0 to 9')
print (numberRange)
if player== 'o':
print('put yout number!!! Player O')
number = int(input())
if number in numberRange:
b.pop(z[number - 1])
b.insert(z[number - 1], 'o')
listTostr = ''.join(map(str, b))
print(listTostr)
numberRange.remove(number)
player = 'x'
iter+=1
else:
print('Please select another number between 0 to 9')
|
3ea9eb0d1f11d8c56f3a7e87f596b0b990c05962 | jiaxuanw1/ProjectEuler | /python/Euler_005.py | 177 | 4.03125 | 4 | def is_divisible(n):
for i in range(2, 21):
if n % i != 0:
return False
return True
num = 20
while not is_divisible(num):
num += 20
print(num)
|
f9fb02f0d999a5ff6ec141956bf2bad0e9af1fd3 | yamauk/checkio | /scientific expedition/Digit Stack.py | 842 | 3.90625 | 4 | def digit_stack(commands):
stack = []
sum = 0
for command in commands:
param = command.split()
if param[0] == 'PUSH':
stack.append(int(param[1]))
if param[0] == 'POP':
sum += stack.pop() if stack else 0
if param[0] == 'PEEK':
sum += stack[-1] if stack else 0
return sum
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
assert digit_stack(["PUSH 3", "POP", "POP", "PUSH 4", "PEEK",
"PUSH 9", "PUSH 0", "PEEK", "POP", "PUSH 1",
"PEEK"]) == 8, "Example"
assert digit_stack(["POP", "POP"]) == 0, "pop, pop, zero"
assert digit_stack(["PUSH 9", "PUSH 9", "POP"]) == 9, "Push the button"
assert digit_stack([]) == 0, "Nothing"
|
b55ba617d0fd46557692c3bb605a472801165e9c | tauovir/Nielit | /Python/day7/test0211.py | 252 | 3.828125 | 4 | class Demo:
def store(self):
self.name = input("enter name:")
self.salary= input("enter salary:")
def display(self):
print "name:",self.name
print "salary:",self.salary
s1 = Demo()
s1.store()
s1.display()
|
7be3728b7d60fdc136249518f403bdf6e38d675b | ExpoPythonist/Offensive_comment_remover_master | /modules/aesEncryption.py | 1,466 | 3.75 | 4 | from Crypto.Cipher import AES
import base64
import os
class aesEncryption:
def __init__(self):
# the block size for the cipher object; must be 16, 24, or 32 for AES
self.BLOCK_SIZE = 32
# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length. This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
self.PADDING = '{'
# generate a random secret key
# self.secret = os.urandom(self.BLOCK_SIZE)
self.secret = b'\x92\x19\x1e\xd2\xc7\xfa\x13\x1fg\x9e\x9fBc\xd0V<\xc10\xbdY+\x04n\xaa&[G\xdf<{\xdc\x80'
# create a cipher object using th random secret
self.cipher = AES.new(self.secret, AES.MODE_EAX)
# one-liner to sufficiently pad the text to be encrypted
def pad(self, s):
return s + (self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE) * self.PADDING
# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
def EncodeAES(self, s):
print('see===> ', s)
return base64.b64encode(self.cipher.encrypt(self.pad(s)))
def DecodeAES(self, e):
return str(self.cipher.decrypt(base64.b64decode(e)), 'utf-8').rstrip(self.PADDING)
if __name__ == "__main__":
# obj = aesEncryption()
# encoded = obj.EncodeAES('password')
# print('Encrypted string:', encoded)
# decoded = obj.DecodeAES(encoded)
# print('Decrypted string:', decoded)
pass
|
c0ce60493b55770acca20c65050d38f815f55d5d | sandeep-v1404/DSA | /DSA-Python/quick_sort.py | 1,039 | 4 | 4 | def swap(a, b, arr):
if a!= b:
tmp = arr[a]
arr[a] = arr[b]
arr[b] = tmp
def partition(elements, start, end):
pivot_index = start
pivot = elements[pivot_index]
while start < end:
while start < len(elements) and elements[start] <= pivot:
start += 1
while elements[end] > pivot:
end -= 1
if start < end:
swap(start, end, elements)
swap(pivot_index, end, elements)
return end
def quick_sort(elements, start, end):
if start < end:
pi = partition(elements, start, end)
quick_sort(elements, start, pi-1) # Left partition
quick_sort(elements, pi+1, end) # Right partition
if __name__ == "__main__":
tests = [
[10, 3, 15, 7, 8, 23, 98, 29],
[25, 22, -1, 21, 10, 0],
[1, 2, 3, 4, 5],
[9, 8, 7, 2],
[3],
[]
]
for elements in tests:
quick_sort(elements, 0, len(elements)-1)
print(f'Sorted array: {elements}') |
80b943fcbc48976109e6441524c23e58f3674cee | Vutsuak16/LeetCode | /algorithm-solution/even_odd_linked_list.py | 746 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
if head == None:
return head
odd=head
even=head.next
evenFirst=even
while(1):
if odd==None or even==None or even.next == None:
odd.next=evenFirst
break
odd.next=even.next
odd=even.next
if odd.next == None:
odd.next=evenFirst
even.next=None
break
even.next=odd.next
even=odd.next
return head |
dd801315b6c6249743ddc3e16dd7e45617d4cbdd | kotaonaga/python | /sand.py | 599 | 3.71875 | 4 | import datetime
import locale
isOK = False #0か3ケタだとisOKがTrueになるようにする。最初はFalseにする。
while isOK == False: #falseの間whileが回り続ける。
input_trackNum = input('追跡番号を入力してください。\n(無い場合は0を入力):')
trackNum = str(input_trackNum)
trackNumLength = len(trackNum)
print(trackNumLength)
#3ケタか0が入ったらisOKをTrueにしてループを抜ける。
if trackNumLength == 3 or trackNum == str(0):
isOK = True
else:
print("good job! 3ケタか0を入れました") |
d9fbf806f926572492cf75ab30f32289819c8b68 | brandonssipes/skewl | /IC411/lab5/sub.py | 782 | 3.5 | 4 | #!/usr/bin/env python
#Brandon Sipes lab 5
def main():
fd = open("letters.txt", "r") #open input file
navy = open("navy.txt", "w+") #open output file and create if not exist
for i in fd:
n = i.find('N') #find first occurance of each letter
a = i[n:].find('A') + n #starting at occurance of prev letter
v = i[a:].find('V') + a #add back the offset
y = i[v:].find('Y') + v
if n >= 0 and a-n >= 0 and v-a >= 0 and y-v >= 0: #subtract offset to look for -1
i = i.replace('N', 'n') #replace all occurances
i = i.replace('A', 'a')
i = i.replace('V', 'v')
i = i.replace('Y', 'y')
navy.write(i)
navy.close() #close files
fd.close()
if __name__=="__main__":
main()
|
5293dbc8da287c9e444185f2957c9b71c41be126 | c-en/AM221_Final | /Print_Towns.py | 365 | 3.734375 | 4 | for number in range(9):
print(number+1)
district=np.zeros(351)
for i in range(351):
district[i]=z[i][number].x
print(district) # Print vector indicating which towns are in district "number+1"
for i in range(351):
if district[i]==1:
print(("'"+str(TOWNS[i])+"',").strip()) # Print list of towns in district "number+1"
|
dc84f1b4384c79cb4493a863bc8bf79bedcac2ba | terasakisatoshi/pythonCodes | /dashLibrary/officialTutorial/dashAppLayout/app.py | 1,390 | 3.53125 | 4 | """
app.py
"""
"""
Generating HTML with Dash
Dash apps are composed of two parts.
The first part is "layout" of the app and it
describes what the application looks like.
The second part describes the interactivity of
the application.
Dash provides Python classes for all of the visual components of
the application. We mention a set of components in the dash_core_components
and the ```dash_html_components``` and ```dash_core_components```
library but you can also build your own with JavaScript and
React.js
"""
"""
To get started, create a file named app.py with the following code:
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
dcc.Graph(
id='example-graph',
figure={
'data': [
dict(x=[1,2,3],y=[4,1,2],type='line',name='something'),
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
],
'layout': {
'title': 'Dash Data Visualization'
}
}
)
])
def main():
app.run_server(debug=True)
if __name__ == '__main__':
main()
|
29d03ba2115174a2c7a7c97292841a93fc2bcc9a | gdribeiro/hackerrank | /more/trees/link-nodes-same-level/py/link-nodes-same-level.py | 3,555 | 4.1875 | 4 | #!/usr/bin/python3
import unittest
import queue
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.nextInLevel = None
self.data = data
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def findVal(self, val):
if val < self.data:
if self.left is None:
return str(val)+" Not Found"
return self.left.findval(val)
elif val > self.data:
if self.right is None:
return str(val)+" Not Found"
return self.right.findval(val)
else:
print(str(self.data) + ' is found')
def PrintTreeInOrder(self):
if self.left:
self.left.PrintTreeInOrder()
if self.nextInLevel:
print(self.data, self.nextInLevel.data)
else:
print(self.data)
if self.right:
self.right.PrintTreeInOrder()
# If N is the # of elements in the tree
# Runtime complexity is O(N), since the iteration passes by each node once
# The queues hold references to the elements already in the tree so no
# extra space required. If the reference is considered to have relevant
# space, then let k be the depth of the tree and Space complexity O(2**k)
# which is the most references to elements held by the queues
# The solution uses the concept of BFS to link nodes in the same level of the tree
def linkLevels(self):
self.nodesToLink = queue.Queue()
self.linked = queue.Queue()
self.nodesToLink.put(self)
while not self.nodesToLink.empty():
# Empties the Queue with nodes to link and adds each node to the liked queue
# From which the nodesToLink queue is filled again, till there is no more nodes
self.currentNode = self.nodesToLink.get()
while True:
if not self.nodesToLink.empty():
self.nextNode = self.nodesToLink.get()
self.currentNode.nextInLevel = self.nextNode
self.linked.put(self.currentNode)
self.currentNode = self.nextNode
else:
self.linked.put(self.currentNode)
break
# Adds the children of each already linked node from the previous level to the
# nodesToLink queue
while not self.linked.empty():
self.currentNode = self.linked.get()
if self.currentNode.left:
self.nodesToLink.put(self.currentNode.left)
if self.currentNode.right:
self.nodesToLink.put(self.currentNode.right)
class MyTest(unittest.TestCase):
def setUp(self):
self.root = Node(10)
self.root.insert(12)
self.root.insert(11)
self.root.insert(13)
self.root.insert(5)
self.root.insert(3)
self.root.insert(6)
self.root.insert(2)
self.root.insert(4)
self.root.insert(7)
def test_print(self):
self.root.linkLevels()
self.root.PrintTreeInOrder()
if __name__ == "__main__":
unittest.main() |
339046abfb824fade8d618bf9f5e89daea47848e | hannahhodgewaller/introduction_to_python | /solutions/chapter_2/object_type_list.py | 178 | 3.859375 | 4 | # Store at least three hobbies within a list. Choose an appropriate variable name.
hobbies = ["Swimming", "Shopping", "Golf", "Extreme Ironing"]
# Return the list
hobbies |
8dc519a4c3d3b19f0834a052cbc8b76e5a53bbfb | SimonMazzucca/ProblemsAndSolutions_Python | /leetcode/problems/lc0088_merge_sorted_array.py | 501 | 3.671875 | 4 | from typing import List
class LC0088_Merge_Sorted_Array:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
p1 = m - 1
p2 = n - 1
last = m + n - 1
for p in range(last, -1, -1):
if p2 < 0:
break
elif p1 >= 0 and nums1[p1] > nums2[p2]:
nums1[p] = nums1[p1]
p1 -= 1
else:
nums1[p] = nums2[p2]
p2 -= 1
|
3a60a3ea32fec9cea2668f08635710213a1abb1f | COSC-310-Group-13/Assignment2 | /main.py | 866 | 3.5 | 4 | from chatbot.chatbot import ChatBot
import sys
#Main class where the bot will be run from.
def __main__():
cb = ChatBot()
cb.extractQuotes('quotes.txt') #we establish the quotes in the object
exitWords = ['bye', 'quit', 'exit', 'see ya', 'good bye'] #Exit the chat bot with common greetings
while(True): #run a loop to keep prompting the user for input
print("You: ", end ='')
userInput = input() #Ask user for input
if userInput.lower() in exitWords:
print("Calm Bot: It was really nice talking to you!")
sys.exit()
else:
if cb.helloMessage(userInput) != None: #if hello returns nothing, output a quote
print("Calm Bot: " + cb.helloMessage(userInput))
else:
print("Calm Bot: " + cb.botResponse(userInput))
__main__()
|
0037533382e21c167240b26ee19a39965b751be6 | wuqingze/leetcode | /排列组合/Solution.py | 821 | 3.53125 | 4 | class Solution:
def __init__(self):
self.result = []
def isSwap(self,a, length, index):
for i in range(index+1,length):
if a[index] == a[i]:
return False
return True
def permutation(self,array,i,n):
if i == n-1:
self.result.append(list(array))
else:
for j in range(i,n):
if self.isSwap(array,n,j):
t = array[i]
array[i] = array[j]
array[j] = t
self.permutation(array,i+1,n)
t = array[i]
array[i] = array[j]
array[j] = t
s = Solution()
# s.permutation([1,1,1,1,0,0,0,0,0,0],0,10)
s.permutation([3,1,1],0,3)
print(s.result)
|
e3d8ddab4d947753ce3bf3571da84ec456b7c4b9 | Erendrgnl/pytorch_tutorials | /quickStart/02_autograd.py | 943 | 3.640625 | 4 | import torch
x = torch.randn(3,requires_grad=True)
#print(x)
y = x+2
#print(y)
z = y*y*2
"""
#print(z)
z = z.mean() ##scalar output olmazsa hata olur ve backward içine veri gödernemiz gerekir
#print(z)
z.backward() #dZ/dX
print(x.grad)
"""
"""
v = torch.tensor([1,2,1],dtype=torch.float32)
z.backward(v)
print(x.grad)
"""
#x.requires_grad(False)
#x.detach()
#with torch.no_grad():
#print(x)
#y = x.detach()
#print(y) ## no grad req
#with torch.no_grad():
# y = x+2
# print(y)
"""
weights = torch.ones(4,requires_grad=True)
for epoch in range(5): #for epoch in range(5):
model_output = (weights*3).sum()
model_output.backward()
print(weights.grad)
weights.grad.zero_() ## her iterasyonda gradyenleri sıfırlamak gerekiyor yoksa birikiyor
"""
weights = torch.ones(4,requires_grad=True)
optimizer = torch.optim.SGD(weights,lr=0.01)
optimizer.step()
optimizer.zero_grad() ## Her iterasyonda sıfırlamak gerekiyor |
41041bbdbab692bd837334537ea7d1cec52fceb4 | ReneNyffenegger/about-python | /gotchas-and-landmines/dynamic_binding.py | 354 | 4.25 | 4 | #
# http://stackoverflow.com/a/530577/180275
#
some_list = ['foo', 'bar', 'baz' ]
some_other_list = ['one', 'two', 'three']
print "some_list"
for item in some_list:
print item
# foo
# bar
# baz
print "some_other_list"
for iten in some_other_list: # note the typo: "iten" instead of "item"
print item
# baz
# baz
# baz
|
0f8f9afb087ebe34278a54cbc045b696c2d0c014 | dbgoytia/30-Days-of-Algorithms | /ReverseIntegers.py | 943 | 3.96875 | 4 |
# Given a 32-bit signed integer, reverse digits of an integer.
# Easy solution, given that to reverse a string you can use a stack and continuously push and pop the elements.
# Author: Diego Goytia
# Day number: 1
class Solution:
def reverse(self, x: int) -> int:
stack = []
res = ""
x = str(x)
# Save the sign of the number
if x[0] == '-':
res = '-'
# Append and pop operations to reverse the string
for num in x:
# Ignore the sign during pushing to stack
if (num != '-'):
stack.append(num)
while len(stack) != 0:
res = res + stack.pop()
# Check if it's a 32 bit signed integer, else return zero.
if not (-2**31)<= int(res) <= (2**31-1):
return 0
# Remove all leading zeros from the number:
return int(res)
|
21ba1cfd9a61bd7cb4998e014f56656eb2271e1a | anandviswanathan89/python-prep | /regex.py | 236 | 3.921875 | 4 | #find integers in string
import re
a = "ANAND IS 1 2 A 3 4 GOOD BOY 3243"
temp = re.findall('[0-9]+', a)
print(temp) #['1', '2', '3', '4', '3243']
#sum of all integers
b = [int(i) for i in temp]
print(sum(b)) #3253
#find if it is ip
|
be8decaccdac159dc24235492c4eed77e2f5a7f8 | cry999/AtCoder | /beginner/044/D.py | 640 | 3.828125 | 4 | import math
def f(b: int, n: int) -> int:
if b > n:
return n
return f(b, n // b) + (n % b)
def digit_sum(n: int, s: int) -> int:
if n == s:
return n + 1
sqrt = math.sqrt(n)
sqrt = math.ceil(sqrt)
for b in range(2, sqrt + 1):
if f(b, n) == s:
return b
for p in range(sqrt, 0, -1):
if (n - s) % p:
continue
b = (n - s) // p + 1
if b < 2:
continue
if f(b, n) == s:
return b
return -1
if __name__ == "__main__":
n = int(input())
s = int(input())
ans = digit_sum(n, s)
print(ans)
|
b9f2ac6043058a03bb066cbbf6291d6a81640ed7 | choicoding1026/data | /numpy/02_numpy05_색인1_1차원2_정수형_fancy색인.py | 368 | 3.796875 | 4 | '''
* numpy 색인
1) python의 기본색인 및 인덱싱 사용
2) fancy 색인 ( 정수형 색인 )
==> 리스트를 활용한 인덱싱
'''
import numpy as np
v1 = np.arange(10) # [0 1 2 8 9]
print("1. 원본 데이터:", v1)
print("2. 1, 2, 3 인덱스 선택:", v1[[1,2,3]])
print("2. 8, 0, 4 인덱스 선택:", v1[[8,0,4]])
|
732ede5d8adbd00fbd3bc5cbd845549386cbe91b | mihirverma7781/Python-Scripts | /chap3/exercise5.py | 211 | 3.6875 | 4 | name = input('enter your full name : ')
i= 0
temp =""
while i< len(name):
if name[i] not in temp:
temp = temp+name[i]
print(f"number of letter : {name[i]} = {name.count(name[i])}")
i= i+1 |
d0a543e2c8b4e1519ae0087756d68fdf6fa85d98 | ispatel/TicTacToe.py | /TicTacToe.py | 4,464 | 4.125 | 4 | import random
import sys
print("Tic Tac Toe")
#asks user if the want to play game
#if user enters an invalid response ask them to enter a valid response
i = True
while i == True:
try:
game = input('If you want to play tic tac toe then type "tic tac toe": ')
assert game == "tic tac toe" or game == "continue"
except(AssertionError):
print("try again")
continue
i = False
#program starts when user enters valid response
while game == "tic tac toe" or game == "continue":
print("How to play: ")
print("You and the computer take turns placing an X.")
print("To place an X type the corresponding number")
print("0 | 1 | 2")
print("3 | 4 | 5")
print("6 | 7 | 8")
print("The player who acheives 3 X's first wins.")
#prints board with the spaces provided
def printBoard(x_spaces,o_spaces):
for num in x_spaces:
board[num] = "X"
for num in o_spaces:
board[num] = "O"
print(board[0],"|",board[1],"|",board[2])
print(board[3],"|",board[4],"|",board[5])
print(board[6],"|",board[7],"|",board[8])
#checks if either X or O have won the game
def checkWin(board):
for i in range(3):
if board[i] == board[i+3] and board[i+3] == board[i+6] and board[i]!="_":
print("Player " + board[i] + " is the winner!")
return True
break
for i in range(7):
if i==0 or i==3 or i==6:
if board[i] == board[i+1] and board[i+1] == board[i+2] and board[i]!="_":
print("Player " + board[i] + " is the winner!")
return True
break
if board[0] == board[4] and board[4] == board[8] and board[0]!="_":
print("Player " + board[0] + " is the winner!")
return True
if board[2] == board[4] and board[4] == board[6] and board[2]!="_":
print("Player " + board[2] + " is the winner!")
return True
#checks if the board is full
def fullBoard(board):
blank_space = board.count('_')
if blank_space == 0:
print('It\'s a draw!')
return True
#laying out variables needed within the game itself
gamerun = True
x_spaces = []
o_spaces = []
board = ["_","_","_","_","_","_","_","_","_"]
while gamerun == True:
#asks user for where to mark the X
j = True
while j == True:
try:
x_move = int(input("Where do you want to mark your X? "))
assert board[x_move] == "_"
except(ValueError):
print('Enter a number from 0-8')
continue
except(IndexError):
print('Enter a number from 0-8')
continue
except(AssertionError):
print('That spot has already been taken')
continue
break
#check if user input is valid
#if user input is not valid ask for valid input
x_spaces.append(x_move)
printBoard(x_spaces,o_spaces)
print("++++++++++++++++++++")
#checks if either "O" or "X" have won
if checkWin(board) == True:
break
#checks if the game board is full
if fullBoard(board) == True:
break
#produces random spot for the computer to place the O
o_move = random.randrange(9)
#checks if spot is availabe.
#if spot is not availabe then computer randomly chooses different spot
while board[o_move] != "_" or o_move==x_move:
o_move = random.randrange(9)
if board[o_move] == "_":
o_spaces.append(o_move)
printBoard(x_spaces,o_spaces)
#checks if either "O" or "X" have won
if checkWin(board) == True:
break
#checks if the game board is full
if fullBoard(board) == True:
break
#asks user if the want to continue
print('Type "continue" if you want to play again.')
print('Type "exit" if you want to exit the game.')
endgameinput= input()
if endgameinput == "exit":
sys.exit()
if endgameinput == "continue":
game == "continue"
#if userinput is not valid ask for valid input
while endgameinput != "exit" and endgameinput != "continue":
endgameinput= input('Type either "exit" or "continue"')
|
a2fe0d3e620dfd4f5ea7c0b993df32c1a57d6dfa | nick-gerrard/RandomStateGeographyQuizGenerator | /AutomatedGrader.py | 4,477 | 3.828125 | 4 | #! usr/bin/python3
from Capitals import capitals
import re
import os
#Setting up directory names
current_directory = os.getcwd()
ungraded = current_directory + "/ungraded"
graded = current_directory + "/graded"
try:
os.makedirs(ungraded)
print("ungraded folders created")
except:
print("folders already exist")
try:
os.makedirs(graded)
print("graded folder created")
except:
print("graded folder already exists")
#Reg Ex compilations for generating lists:
nameRegEx = re.compile(r'Name: (.*)')
stateRegEx = re.compile(r'\d+\. What is the capital of (.*)\?')
studentAnswerRegEx = re.compile(r'Enter your answer here:(.*)')
aRegEx = re.compile(r'A. (.*)\.')
bRegEx = re.compile(r'B. (.*)\.')
cRegEx = re.compile(r'C. (.*)\.')
dRegEx = re.compile(r'D. (.*)\.')
#Input name of file to be graded
name_of_file_to_grade = input("Enter the name of the file to be graded: ")
full_path_of_file_to_grade = ungraded + "/" + name_of_file_to_grade
with open(full_path_of_file_to_grade, "r") as ungraded_test:
#Lists to be added to
state_list = []
student_answer_list = []
a_list = []
b_list = []
c_list = []
d_list = []
for line in ungraded_test:
name_re = nameRegEx.search(line)
state_re = stateRegEx.search(line)
student_answer_re = studentAnswerRegEx.search(line)
a_re = aRegEx.search(line)
b_re = bRegEx.search(line)
c_re = cRegEx.search(line)
d_re = dRegEx.search(line)
if name_re:
name = name_re.group(1)
elif state_re:
state = state_re.group(1)
state_list.append(state)
elif student_answer_re:
studentAnswer = student_answer_re.group(1)
student_answer_list.append(studentAnswer)
elif a_re:
a = a_re.group(1)
a_list.append(a)
elif b_re:
b = b_re.group(1)
b_list.append(b)
elif c_re:
c = c_re.group(1)
c_list.append(c)
elif d_re:
d = d_re.group(1)
d_list.append(d)
"""
print(name)
print(state_list)
print(student_answer_list)
print(a_list)
print(b_list)
print(c_list)
print(d_list)"""
#Creating a cleaned student answer list
cleaned_student_answer_list = [answer.upper().strip() for answer in student_answer_list]
#Create a name for the graded file
graded_file_name = "GradedQuizFor" + name + ".txt"
graded_file_path = graded + "/" + graded_file_name
#Create a function for returning the state from a given capital:
def get_state_from_cap(cap):
for key in capitals:
if cap == capitals[key]:
return key
return("key does not exist")
with open(graded_file_path, "w") as graded_file:
graded_file.write(name)
graded_file.write('\n\n\n')
total_correct = 0
total_incorrect = 0
for number in range(0, 50):
if cleaned_student_answer_list[number] == "A":
capital_answered = a_list[number]
elif cleaned_student_answer_list[number] == "B":
capital_answered = b_list[number]
elif cleaned_student_answer_list[number] == "C":
capital_answered = c_list[number]
elif cleaned_student_answer_list[number] == "D":
capital_answered = d_list[number]
else:
capital_answered = "N/A"
#Determine if student got question right
state_answered = get_state_from_cap(capital_answered)
if state_answered == state_list[number]:
total_correct += 1
line_to_print = str(number) + ". Correct\n"
else:
total_incorrect += 1
line_to_print = str(number) + ". Incorrect\n"
graded_file.write(line_to_print)
graded_file.write("\n\n")
total_correct_and_incorrect = "Total Correct: " + str(total_correct) + '\nTotal Incorrect: ' + str(total_incorrect) + "\n\n"
graded_file.write(total_correct_and_incorrect)
percentage = total_correct / 50 * 100
if percentage > 90:
grade = "A"
elif percentage >80 and percentage <90:
grade = "B"
elif percentage >70 and percentage < 80:
grade = "C"
elif percentage > 60 and percentage < 70:
grade = "D"
else:
grade = "F"
percent_to_write = str(percentage) + "% right."
grade_to_write = "Grade: " + grade
graded_file.write(percent_to_write)
graded_file.write("\n\n")
graded_file.write(grade_to_write)
|
9ad48ab553549b7ee1109bebe124fbf1e1045d64 | j1nn33/study | /python/conspect/FUNCTION/map_lambda_filter.py | 1,986 | 4.1875 | 4 | """
*ЗАДАЧИ НА MAP/FILTER/REDUCE (И LAMBDA, ЕСЛИ НУЖНО)
+ При помощи map посчитать остаток от деление на 5 для чисел: [1, 4, 5, 30, 99]
+ При помощи map превратить все числа из массива [3, 4, 90, -2] в строки
+ При помощи filter убрать из массива ['some', 1, 'v', 40, '3a', str] все строки
"""
#-------------------------- 1 --------------------------
# При помощи map посчитать остаток от деление на 5 для чисел: [1, 4, 5, 30, 99]
# функция map принимает два аргумента: функцию и аргумент составного типа данных, например, список. map применяет к каждому элементу списка переданную функцию
print ('task 1')
sourece_list = [1, 4, 5, 30, 99]
new_list = []
# lambda arguments: expression
# arguments передается список аргументов, разделенных запятой, после чего над переданными аргументами выполняется expression
new_list = list(map(lambda x: x%5, sourece_list ))
# lambda x: x%5 вычисляет остаток от деления на 5
print (new_list)
#-------------------------- 2 --------------------------
# При помощи map превратить все числа из массива [3, 4, 90, -2] в строки
print ('task 2')
sourece_list = [3, 4, 90, -2]
new_list = []
new_list = list(map(str, sourece_list))
print (new_list)
#-------------------------- 3 --------------------------
# При помощи filter убрать из массива ['some', 1, 'v', 40, '3a', str] все строки
print ('task 2')
sourece_list =['some', 1, 'v', 40, '3a', str]
new_list = []
new_list = list(filter(lambda a : isinstance(a, int) , sourece_list))
print (new_list)
|
d890402126ed25f492a27b96078a1077340ba322 | arthurDz/algorithm-studies | /CtCl/Linked Lists/return_kth_to_last.py | 969 | 3.84375 | 4 | # Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def kth_to_last(lis, k):
if not lis or k <= 0: return
fast = lis
pre = None
while True:
temp = fast
count = 1
while fast.next:
count += 1
fast = fast.next
if count >= k:
break
if count < k:
if not pre: return
for i in range(k - count):
pre = pre.next
return pre
else:
pre = temp
# better approach
def kth_to_last(lis, k):
runner = current = lis
for _ in range(k):
if not runner.next:
return None
runner = runner.next
while runner:
current, runner = current.next, runner.next
return current |
fc4a26d27d69572269e18e198da22bac7182caf1 | rajatmishra3108/Daily-Flash-PYTHON | /Assignment/24 aug 2020/sol.py | 691 | 3.84375 | 4 | start = int(input())
end = int(input())
if(start == end):
print("INVALID RANGE")
else:
even_sum = 0
odd_sum = 0
even = list()
odd = list()
for i in range(start, end + 1):
if(i % 2 == 0):
even_sum += i
even.append(i)
else:
odd_sum += i
odd.append(i)
if(sum(even) > sum(odd)):
for i in range(len(even)):
if((i+1) % 5 == 0):
print(even[i])
else:
print(even[i], end=" ")
else:
for i in range(len(odd)):
if((i+1) % 5 == 0):
print(odd[i])
else:
print(odd[i], end=" ") |
f7f9c66aa40c092e23b5131c5f219a70e89c716a | Hondral49/Trabalho-Python---ALYSSON-SANTIN | /exercicio_seis.py | 404 | 3.890625 | 4 | expressao = str(input('Digite uma expressao: '))
pilha = []
for simbolo in expressao:
if simbolo == '(' :
pilha.append('(')
elif simbolo == ')' :
if len(pilha) > 0:
pilha.pop()
else:
pilha.append(')')
break
if len(pilha) == 0:
print('Sua expressao esta valida! ')
else:
print('Sua expressao esta invalida! ')
|
90044bd3cf3dfafd1f71a7a2f784fc149251f5b3 | ncn-freedev/python | /progressao_aritmetica/progressao_aritmetica.py | 511 | 4.0625 | 4 | confirma = False
while confirma is False:
try:
termo = int(input("Digite o primeiro termo da PA:\n"))
razao = int(input("Digite a razão da PA:\n"))
quantidade = int(input("Digite a quantidade de termos da PA:\n"))
confirma = True
except ValueError:
print("\nVocê deve digitar apenas valores inteiros!\n".upper())
lista_PA = []
contador = 0
while contador < quantidade:
lista_PA.append(termo)
termo = termo + razao
contador += 1
print(lista_PA) |
19d1b8e71088edbe0958f8204519202c78683f73 | maryoocean/Programming | /hw6/hw6.py | 7,500 | 3.75 | 4 | import random
sentences = [] # собираю предложения, чтобы потом печатать их в произвольном порядке
def open_file(filename):
my_list = []
with open(filename, encoding="utf-8") as f:
file = f.read().split()
for element in file:
my_list.append(element)
return my_list
def noun():
#открываем файл с существительными
nouns = open_file('nouns_articles.txt')
nouns.append('') # в итальянском языке личные местоимения опускаются
our_noun = random.choice(nouns)
#выбираем случайное существительное
return our_noun
def noun_article(our_noun):
#ставим правильный артикль
if our_noun.endswith('a'):
np = 'la' + ' ' + our_noun
elif our_noun.endswith('o'):
np = 'il' + ' ' + our_noun
elif our_noun.endswith('i'):
np = 'i' + ' ' + our_noun
elif our_noun.endswith('e'):
np = 'le' + ' ' + our_noun
else:
np = ''
return np
def verb(np):
# выбираем глагол-связку
verbs = open_file ('verb_essere.txt')
if np.endswith('a') or np.endswith('o'):
vp = np + ' ' + 'è'
elif np.endswith('i') or np.endswith('e'):
vp = np + ' ' + 'sono'
else:
vp = random.choice(verbs)
return vp
def predicates(vp):
#для законченного предложения осталось выбрать только предикат
predicates = open_file('predicate.txt')
flex_all = open_file('flex.txt.')
flex_sg = open_file('flex_sg.txt')
flex_pl = open_file('flex_pl.txt')
#собственно, выбираем предикат в зависимости от выбранного выше существительного-подлежащего
if vp.endswith('ono'):
if vp == 'sono': #Я.../Они...
our_pred = random.choice(predicates) + random.choice(flex_all)
elif vp.endswith('e sono'): #Они (ж.р.)...
our_pred = random.choice(predicates) + 'e'
else: #Они (м.р.)...
our_pred = random.choice(predicates) + 'i'
elif vp.endswith('è'):
if vp == 'è': #Он/Она...
our_pred = random.choice(predicates) + random.choice(flex_sg)
elif vp.endswith('a è'): #Она...
our_pred = random.choice(predicates) + 'a'
else: #Он...
our_pred = random.choice(predicates) + 'o'
elif vp.endswith('iamo') or vp.endswith('te'): #Мы/Они...
our_pred = random.choice(predicates) + random.choice(flex_pl)
else: #Ты...
our_pred = random.choice(predicates) + random.choice(flex_sg)
return our_pred
def aff_help():
"""для построения всех остальных предложений буду использовать утвердительное из этой функции"""
my_np = noun_article(noun())
my_vp = verb(my_np)
my_pred = predicates(my_vp)
the_affirmative = my_vp.capitalize() + ' ' + my_pred + '.'
return the_affirmative
def affirmative(the_affirmative):
"""эта функция непосредственно для утвердительного предложения,
которое добавится в список только 1 раз"""
sentences.append(the_affirmative)
return sentences
def interrogative(the_affirmative): # Задается интонацией, поэтому меняем точку на знак вопроса
the_interrogative = the_affirmative.replace('.','?')
sentences.append(the_interrogative)
return the_interrogative
def negation(the_affirmative): # Отрицание - это "non" перед глаголом.
#the_affirmative = str(the_affirmative)
""" питон в какой-то момент (когда я запускала код раз в 25-ый) ругался, что the_affirmative - это
лист, я даже через type проверила это - тоже писал, что лист. перезапустила питон и ошибка исчезла,
но строчку выше оставлю на всякий случай. причины ошибки, честно, не вижу"""
words = the_affirmative.lower().split() # Разбиваем его на слова
neg_sentence = []
for word in words: # Ищем глагол в предложении
if word == 'sono' or word == 'è' or word == 'sei' or word == 'siamo' or word == 'siete':
my_negation = 'non ' + word # добавляем "non" перед ним
neg_sentence.append(my_negation)
else:
neg_sentence.append(word)
return neg_sentence
def negative(neg_sentence):
the_negative = ''
for element in neg_sentence:
the_negative = the_negative + element + ' ' # снова собираем предложение (уже отрицательное)
sentences.append(the_negative[:-1].capitalize()) # убираем лишний пробел после точки
return the_negative[:-1]
def sent(the_negative, the_affirmative): # условное предложение соберем из двух простых (например, отрицательного и утвердительного)
sent_cond = []
sent_cond.append(the_negative) # генерируем новое отрицательное предложение
del sentences[-1] # удаляем последнее предложение, чтобы в списке не было двух отрицательных
sent_cond.append(the_affirmative) #новое утвердительное
return sent_cond
def conditional(sent_cond):
the_conditional = 'Se ' + sent_cond[0].replace('.',', ').lower() + \
sent_cond[1].lower() # чтобы предложения не совпадали (а при random.choice такое возможно),
sentences.append(the_conditional) # я беру их через индексы
return the_conditional
def imperative(np):
imp_forms = open_file('imperative_forms.txt')
"""пока представляю, как использовать императив только с опущенными подлежащими-местоимениями,
поэтому код такой.
конструкция типа "сделай/приготовь/etc что-то" """
i = 0
while i < 1:
if np != '':
the_imperative = random.choice(imp_forms).capitalize() + ' ' + np + '!'
i += 1
sentences.append(the_imperative)
else:
continue
return the_imperative
def our_sentences():
affirmative(aff_help())
interrogative(aff_help())
negative(negation(aff_help()))
conditional(sent(negative(negation(aff_help())), aff_help()))
imperative(noun_article(noun()))
return sentences
def random_sentences(sentences):
i = 0
printed_sentences = []
while i < 5:
the_sentence = random.choice(sentences)
if the_sentence in printed_sentences:
continue
else:
i += 1
print(the_sentence, end=" ")
printed_sentences.append(the_sentence)
random_sentences(our_sentences())
|
c1e9967fdb243512d2d9d2d199b4ec6dad2da1ba | p3ngwen/open-notes | /Intro to CS with Python/src/homework/listing0816.py | 838 | 4.0625 | 4 | num11, num12, num13 = 436, 178, 992
num21, num22, num23 = 880, 543, 101
def smallest_of_two( n1, n2 ):
if n1 < n2:
return n1
return n2
def largest_of_two( n1, n2 ):
if n1 > n2:
return n1
return n2
def smallest( n1, n2, n3 ):
return smallest_of_two( smallest_of_two( n1, n2 ), n3 )
def middle( n1, n2, n3 ):
return n1 + n2 + n3 - smallest( n1, n2, n3 ) \
- largest( n1, n2, n3 )
def largest( n1, n2, n3 ):
return largest_of_two( largest_of_two( n1, n2 ), n3 )
print( "sum of smallest =", smallest( num11, num12, num13 ) +
smallest( num21, num22, num23 ) )
print( "sum of middle =", middle( num11, num12, num13 ) +
middle( num21, num22, num23 ) )
print( "sum of largest =", largest( num11, num12, num13 ) +
largest( num21, num22, num23 ) ) |
652a1e7a180416625999f856f078611dcb007b88 | epichardoq/DS-Course | /Analisis_Datos-Unipython/Trabajando_Big-Data-Files/pandas_accidents.py | 440 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 16 20:38:49 2019
@author: emmanuel
"""
import pandas as pd
# Read the file
data = pd.read_csv("/Users/emmanuel/Documents/curso_python/Analisis_Datos-Unipython/Trabajando_Big-Data-Files/Stats19-Data1979-2004/Accidents7904.csv", low_memory=False)
# Output the number of rows
print("Total rows: {0}".format(len(data)))
# See which headers are available
print(list(data)) |
974ae1e7106271245283bb59b697438eb398b33c | pulosez/Python-Crash-Course-2e-Basics | /#8: Functions/sandwiches.py | 244 | 3.65625 | 4 | # 8.12.
def make_sandwich(*items):
print(f"\nMaking a sandwich with the followig items:")
for item in items:
print(f"- {item}")
make_sandwich('chicken', 'egg')
make_sandwich('fish')
make_sandwich('cheese', 'chicken', 'olives')
|
9f898be1bdc141c9d96cab080f1b18ff291d9298 | e3-cerruti/AdventOfCode | /intcode_machine/test_intcodeMachine.py | 3,121 | 3.78125 | 4 | import queue
from unittest import TestCase
from intcode_machine import IntcodeMachine
DEFAULT_PROGRAM = [3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31,
1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104,
999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99]
def test_input_output(computer, input_code):
input_queue = queue.Queue()
output_queue = queue.Queue()
input_queue.put(input_code)
computer.set_queues(input_queue, output_queue)
computer.run_program(DEFAULT_PROGRAM.copy())
return output_queue.get()
class TestIntcodeMachine(TestCase):
def setUp(self):
self.computer = IntcodeMachine()
def test_addition(self):
result = self.computer.run_program([1101, 100, -1, 4, 0])
self.assertEqual(result, 1101)
def test_multiplication(self):
result = self.computer.run_program([1002, 4, 3, 4, 33])
self.assertEqual(result, 1002)
# Here's a larger example:
# 3,21,1008,21,8,20,1005,20,22,107,8,21,20,1006,20,31,
# 1106,0,36,98,0,0,1002,21,125,20,4,20,1105,1,46,104,
# 999,1105,1,46,1101,1000,1,20,4,20,1105,1,46,98,99
# The above example program uses an input instruction to ask for a single number.
# The program will then output 999 if the input value is below 8, output 1000 if the input value is equal to 8,
# or output 1001 if the input value is greater than 8.
def test_low_input(self):
self.assertEqual(test_input_output(self.computer, 7), 999)
def test_equal_input(self):
self.assertEqual(test_input_output(self.computer, 8), 1000)
def test_high_input(self):
self.assertEqual(test_input_output(self.computer, 9), 1001)
def test_relative_base(self):
program = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]
input_queue = queue.Queue()
output_queue = queue.Queue()
self.computer.set_queues(input_queue, output_queue)
result = self.computer.run_program(program)
output_program = []
while not output_queue.empty():
output_program.append(output_queue.get())
self.assertEqual(program, output_program)
def test_16bit_number(self):
program = [1102,34915192,34915192,7,4,7,99,0]
input_queue = queue.Queue()
output_queue = queue.Queue()
self.computer.set_queues(input_queue, output_queue)
result = self.computer.run_program(program)
self.assertGreater(output_queue.get(), 2**16-1)
def test_large_number(self):
program = [104,1125899906842624,99]
input_queue = queue.Queue()
output_queue = queue.Queue()
self.computer.set_queues(input_queue, output_queue)
result = self.computer.run_program(program)
self.assertEqual(output_queue.get(), 1125899906842624)
def test_load_program_from_file(self):
computer = IntcodeMachine()
computer.load_program_from_file('intcode_test_program.dat')
self.assertEqual(computer.program, {k: v for k, v in enumerate(DEFAULT_PROGRAM)})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.