blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e2e9e0822f868d43f96f7adb3e5c885159db227b | spd94/Marvellous_Infosystem_Python_ML_Assignments | /Marvellous_Infosystem_Assignment_4/Assignment4_5.py | 664 | 3.5625 | 4 | from functools import reduce
import math
def ChkPrime(n):
c=0
for i in range(2,int(math.sqrt(n))+1):
if(n%i==0):c=1
if(c==0):return(n)
def max_list(n,y):
if(n>y):return(n)
else: return(y)
def accept_N_elem(n):
ls=list()
i=0
sum=0
print("Input Elements :",end=" ")
while(i<n):
ls.append(int(input()))
i+=1
fl=list(filter(ChkPrime,ls))
print("List after filter :",end=" ")
print(fl)
ml=list(map(lambda x:x*2,fl))
print("List after map :",end=" ")
print(ml)
prd=reduce(max_list,ml)
return prd
if __name__ == "__main__":
print("Input : Number of Elements :",end=" ")
x=accept_N_elem(int(input()))
print("Output of reduce :",x,end=" ") |
d5b42355b1136deef409b9bd892ed04d7daebd8b | spd94/Marvellous_Infosystem_Python_ML_Assignments | /Marvellous_Infosystem_Assignment_3/Assignment3_3.py | 331 | 3.515625 | 4 | def accept_N_min(n):
ls=list()
i=0
print("Input Elements :",end=" ")
while(i<n):
ls.append(int(input()))
i+=1
i=0
sum=ls[0]
while(i<n):
if(sum>ls[i]):sum=ls[i]
i+=1
return(sum)
if __name__ == "__main__":
print("Input : Number of Elements :",end=" ")
x=accept_N_min(int(input()))
print("Output :",x,end=" ") |
20f4e8a0618bd5f9a0a9beeb9b7851d0af09dcdc | spd94/Marvellous_Infosystem_Python_ML_Assignments | /Marvellous_Infosystem_Assignment_2/Assingment2_7.py | 197 | 3.6875 | 4 | def print_pattern(n):
i=0
print("Output :")
while(i<n):
j=0
k=1
while(j<n):
print(k,end=" ")
k+=1
j+=1
print("")
i+=1
print("Input :",end=" ")
x=int(input())
print_pattern(x) |
cede3101dcebb7ca00c09dbf06c620664e444bc6 | farzaa/AlmostUnlimited | /FileController.py | 2,177 | 3.6875 | 4 | import json
import os
class FileController:
links = {}
def __init__(self):
self.filename = 'links.json'
FileController.links = FileController.links
def process_json(self):
"""
Processes the json file as a python dictionary for O(1) lookup
"""
if os.path.isfile(self.filename):
links_file = open(self.filename).read()
FileController.links = json.loads(links_file)
else:
open(self.filename, 'w')
FileController.links = {}
def print_uploads(self):
"""
Prints each video title that has been uploaded
"""
self.process_json()
print 'Uploaded videos:'
for title in FileController.links:
print title
def return_link(self, title):
"""
Returns the link that is mapped from the passed in title
Return None if the title is NOT in the dictionary
Args:
title: a string that represents the desired video title
"""
if title in FileController.links:
return 'https://www.youtube.com/watch?' + FileController.links[title]
return None
def write_link(self, name, link):
"""
Writes a video filename and link to the file associated
with this object
Args:
name: A string representing the file name
link: A string representing the youtube link
"""
FileController.links[name] = link
with open(self.filename, 'w') as fp:
json.dump(FileController.links, fp)
def remove_link(self, title):
"""
Removes the specified video from the json file and dict
Args:
title: The title string
"""
if title in FileController.links:
del FileController.links[title]
print 'Removed ' + title
else:
print title + ' not found'
def clear_links(self):
"""
Clears everything in the json and dict
"""
FileController.links = {}
with open(self.filename, 'w') as fp:
json.dump(FileController.links, fp)
|
b9309e29726fbdd81593c7584f10bba6b3b39e8b | Herraiz/eoi | /12-testing/learning_python.py | 1,243 | 3.890625 | 4 | import unittest
def suma(a, b):
return a + b
def resta(a, b):
return a - b
def check_equality(a, b):
if a != b:
raise Exception (str(a) + ' is not equal to ' + str(b))
print('Check equality')
def multiplicacion(a, b):
return a * b
def division(a, b):
if b == 0:
raise ArithmeticError("Divisor can't be zero")
return a / b
def expect_raises(error_type, fun, arg1, arg2):
try:
fun(arg1, arg2)
raise AssertionError(f"Excepted exception but not thrown{str(error_type)}")
except error_type as e:
pass
class Test(unittest.TestCase):
def test_suma(self):
check_equality(suma(2, 2), 4)
def test_resta(self):
resultado = resta(2,2)
self.assertEqual(resultado, 0)
def test_multiplicacion(self):
self.assertEqual(multiplicacion(2, 2), 4)
def test_division(self):
with self.assertRaises(ArithmeticError):
division(2, 0)
class PythonTestStrings(unittest.TestCase):
def text_format_replaces_variables_in_string(self):
result = "hola {0}, {1}".format("carlos", "que tal")
self.assertEqual("hola carlos, quasdasde tal", result)
if __name__ == '__main__':
unittest.main() |
dcbe358f8337658a190aa6ec199638eebd75178f | PohSayKeong/python | /practical4/q5_count_letter.py | 156 | 3.625 | 4 | def count_letter(str,ch):
if len(str) == 0:
return 0
return (str[0] == ch) + count_letter(str[1:],ch)
print (count_letter("Welcome", 'e'))
|
af36097ff4c7e7b24a376723a19a37ad652b32b6 | PohSayKeong/python | /practical3/q7_convert_ms.py | 314 | 3.859375 | 4 | import math
n = int(input("please enter time in ms: "))
def convert_ms(n):
second = math.floor(n/1000)
second_final = second % 60
minutes = second // 60
minutes_final = minutes % 60
hour = minutes // 60
print(str(hour) + ":" + str(minutes_final) + ":" + str(second_final))
convert_ms(n)
|
79445ff503849570898444870ad4881f5c9b3216 | PohSayKeong/python | /practical2/q11_find_gcd.py | 259 | 3.921875 | 4 | n1 = int(input("first integer: "))
n2 = int(input("second integer: "))
minimum = min(n1,n2)
def gcf(minimum,n1,n2):
if n1 % minimum == 0 and n2 % minimum == 0:
return minimum
else:
return gcf(minimum-1,n1,n2)
print(gcf(minimum,n1,n2))
|
5e8fe335b23c11406377182f99d4205c739b414f | oneNutW0nder/config-dns | /dnsconfig.py | 5,540 | 3.90625 | 4 | def readHeader():
"""
This function reads the "header.conf" file which is where the
dns options for the zone file
:return: (string)the contents of the "header.conf" file
"""
with open("./header.conf", "r") as fd:
header = fd.readlines()
return header
def backup(zoneFile, reverseZoneFile):
"""
This function backs up the current zoneFile and reverseZoneFile
if they exist so you can restore a previous version
:param zoneFile: The path that was specified for the forward zone
in the "host.conf" file
:param reverseZoneFile: The path that was specified for the reverse zone
in the "host.conf" file
"""
# Backup the forward zone file if it exists
if zoneFile is not None:
with open(zoneFile, "r") as fd:
zoneBackup = fd.readlines()
with open("./zoneFile.bak", "w") as fd:
fd.writelines(zoneBackup)
# Backup the reverse zone file if it exists
if reverseZoneFile is not None:
with open(reverseZoneFile, "r") as fd:
reverseZoneBackup = fd.readlines()
with open("./reverseFile.bak", "w") as fd:
fd.writelines(reverseZoneBackup)
def readConfig():
"""
This function reads the provided "host.conf" file and parses
the information contained in it. It will parse out Hosts,
Zone file, and Reverse zone file locations.
:return: (4)tuple of a (string)zoneFile location,
(string)reverseZoneFile location,
(list of (3)tuple)Hosts,
(list of (3)tuple)Domains
"""
hosts = []
domains = []
with open("./host.conf", "r") as fd:
for line in fd.readlines():
line = line.strip().split()
if line != []:
# Parse config for zone files and hosts
if line[0] == "ZONE_FILE:":
zoneFile = line[1]
if line[0] == "REVERSE_ZONE_FILE:":
reverseZoneFile = line[1]
if line[0] == "HOST:":
hosts.append((line[1], line[2], line[3]))
if line[0] == "DOMAIN:":
domains.append((line[1], line[2], line[3]))
return zoneFile, reverseZoneFile, hosts, domains
def createZoneFile(zoneFile, header, hosts, domains):
"""
This function creates the forward zone file configuration based on
the configuration provided in "host.conf"
:param zoneFile: (string) The path to the zonefile that you want to create
:param header: (string) The header to use from "./header.conf"
:param hosts: (list of (3)tuples) Contains the information for each host
:param domains: (list of (3)tuples) Contains information for each domain
"""
# Overwrite the old zoneFile with the header and host information
with open(zoneFile, "w") as fd:
fd.writelines(header)
fd.write("\n")
# Domains and Hosts should have the same number in the config
for x in range(len(domains)):
# Format for forward zone file:
# example.com. IN NS ns.example.com.
# ns.example.com. IN A 192.168.1.1
try:
lineToWrite = (
f"{domains[x][0]}\t\tIN\t{domains[x][1]}\t{domains[x][2]}\n"
)
fd.write(lineToWrite)
lineToWrite = f"{hosts[x][0]} \tIN\t{hosts[x][1]}\t{hosts[x][2]}\n"
fd.write(lineToWrite)
except IndexError as e:
print(e)
print(
"[!] Make sure HOST and DOMAIN entries are 1:1 in the 'host.conf'"
)
exit()
def createReverseZoneFile(reverseZoneFile, header, hosts, domains):
"""
This function creates the reverse zone file from the "host.conf" info
:param reverseZoneFile: (string) path to reverse zonefile to create
:param header: (string) The header to use from "./header.conf"
:param hosts: (list of (3)tuples) Contains the information for each host
:param domains: (list of (3)tuples) Contains information for each domain
"""
# Overwrite the old reverseZoneFile with the header and host information
with open(reverseZoneFile, "w") as fd:
fd.writelines(header)
fd.write("\n")
for x in range(len(hosts)):
# Format for reverse zone file:
# 1.168.192.in-addr.arpa. IN NS ns.example.com
# 1.168.192.in-addr.arpa. IN NS ns2.example.com
try:
ip = hosts[x][2].split(".")
arpa = ip[2] + "." + ip[1] + "." + ip[0] + ".in-addr.arpa."
lineToWrite = f"{arpa} \tIN \tNS \t{hosts[x][0]}\n"
fd.write(lineToWrite)
except IndexError as e:
print(e)
print(
"[!] If this error occurs please look at the \
'createReverseZoneFile()' function because this should never happen"
)
exit()
if __name__ == "__main__":
# Read the config file for the information about hosts and the current zone file
zoneFile, reverseZoneFile, hosts, domains = readConfig()
header = readHeader()
# backup the current zone files
backup(zoneFile, reverseZoneFile)
# Create new zone files
createZoneFile(zoneFile, header, hosts, domains)
createReverseZoneFile(reverseZoneFile, header, hosts, domains)
|
4e8834fd82ae0c6b78a0d134058afbdb11d2da95 | MaxiFrank/calculator-2 | /new_arithmetic.py | 1,560 | 4.28125 | 4 | """Functions for common math operations."""
def add(ls):
sum = 0
for num in ls:
sum = sum + num
return sum
def subtract(ls):
diff = 0
for num in ls:
diff = num - diff
return diff
# def multiply(num1, num2):
def multiply(ls):
"""Multiply the two inputs together."""
result = 1
for num in ls:
result = result * num
return result
def divide(ls):
"""Divide the first input by the second and return the result."""
result = 1
for num in ls:
result = num / result
return result
def square(num1):
# doesn't make sense to have a list
"""Return the square of the input."""
return num1 * num1
def cube(num1):
# doesn't make sense to have a list
"""Return the cube of the input."""
return num1 * num1 * num1
def power(ls):
"""Raise num1 to the power of num2 and return the value."""
result = ls[0]
for num in ls[1:]:
result = result ** num
return result # ** = exponent operator
def mod(num1, num2):
"""Return the remainder of num1 / num2."""
result = None
for num in ls:
result = result %num
return result
def add_mult(num1, num2, num3):
"""Add num1 and num2 and multiply sum by num3."""
# uncertain about how this one works. for for example ([1, 2, 3, 4])
return multiply(add(num1, num2), num3)
def add_cubes(ls):
"""Cube num1 and num2 and return the sum of these cubes."""
sum = 0
for num in ls:
sum = sum + cube(num)
return sum
print(divide([2,4,2])) |
cdfa4e30f49d0b3c920cad94865be8647920b54c | rashid32/python_nov_2017 | /Rashid_Ashfaq/OOP/add.py | 746 | 3.859375 | 4 | class Vehicle(object):
def __init__(self,wheels,capacity,make,model):
self.wheels=wheels
self.capacity=capacity
self.make=make
self.model=model
self.mileage=0
def drive(self,miles):
self.mileage+=miles
return self
def reserve(self,miles):
self.mileage -=miles
return self
class Bike(Vehicle):
def vehicle_type(self):
return "Bike"
class Car(Vehicle):
def set_wheel(self):
self.wheels=4
return self
class Airplane(Vehicle):
def fly(self,miles):
self.mileage+=miles
return self
v = Vehicle(8,1,'Rashidmake','Tahirmodle')
print v.make
b =Bike(2,1,'hussainmake','putarimodel')
print b.vehicle_type()
c= Car(4,3,'maker1','modelt1')
c.set_wheel()
print c.wheels
a= Airplane(23,853,'PIA','NY')
a.fly(20)
print a.mileage |
691c4a41c38d1d260cfc11e7a5ca119ec1a74159 | jerseymec/Orapy | /loop.py | 155 | 4.15625 | 4 | for i in range(1,22):
if (i % 2 != 0):
print(str(i) + " is Odd")
elif (i % 2 == 0):
print(str(i) + " is Even")
print("\n")
|
5432f1d6e0171b8ff7ff86533e4bf32f6afceef7 | jerseymec/Orapy | /DoorMat.py | 921 | 3.65625 | 4 | def draw_pattern(n,m):
for i in range(0,n//2):
for j in range(0,(m//2)- (i*3+1)):
print("-", end="")
for k in range(i*2 +1 ):
print(".", end="")
print("|" , end="")
print(".", end="")
for j in range(0,(m//2) - (i*3+1)):
print("-", end="")
print()
for l in range ((m//2)-3) :
print("-", end="")
print("WELCOME" , end="" )
for l in range ((m//2)-3) :
print("-", end="")
print()
for i in range(n // 2-1,-1,-1):
for j in range((m // 2) - (i * 3 + 1),0,-1):
print("-", end="")
for k in range(i * 2 + 1):
print(".", end="")
print("|", end="")
print(".", end="")
for j in range((m // 2) - (i * 3 + 1),0,-1):
print("-", end="")
print()
#print("\n")
draw_pattern(43,129) |
5098723d0627372bda3626de4491fde1defaf3b7 | beka1cfc/first_week | /dom.py | 4,536 | 3.734375 | 4 | #задача 1
#list: ordered, changeable, allow duplicates
#tuple: ordered, allow duplicates
#set: changeable
#dict: ordered, changeable
#задача 2
a = "HELLO I AM WRITING CODE"
b = ("HELLO" , "I" , "AM" , "WRITING" , "CODE")
print(sorted(b))
#задача 3
names = ["Beks" , "Zhenya" , "Dana" , "Alibek"]
job = ["программист"]
for a in names:
for b in job:
print(a, b)
#задача 4
with open("word.txt","a") as b:
for i in range(1000):
b.write("i am developer\n")
#задача 5
a = [1,1,2,3,5,8,13,21,34,55,89]
for b in a:
if b < 5:
print(b)
#задача 6
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []
for d in range(len(a)):
for e in range(len(b)):
if a[d] == b[e]:
c.append(a[d])
print(list(set(sorted(c))))
#задача 7
a = [2,3,4,7,237,2,2,4]
for b in a:
if b == 237:
break
elif b % 2 == 0:
print(b)
#задача 8
def check(a, b):
if not a:
return 0
elif a[0] == b:
return 1 + check(a[1:], b)
else:
return check(a[1:], b)
a = input("Введите строку:")
b = input("Введите букву для проверки:")
print("Символ " + b + " встречается:")
print(check(a, b))
#задача 9
a = input("цифры: ")
b = a.split()
c = set(b)
if len(b) == len(c):
print("true")
else:
print("false")
#задача 10
text = (input())
words = text.split()
a = max(words, key=len)
b = max(words, key=words.count)
print(a,b)
#задача 11
n = int(input("Введите 3 значное число: "))
a = n // 100
b = n // 10 % 10
c = n % 10
print(f"Число: {n} Сумма: {a+b+c} Произведение:{a*b*c}")
#задача 12
from random import random
a = round(random() * 50)
b = 1
print("Компьютер загадал число. Отгадайте его. У вас 3 попыток")
while b <= 3:
c = int(input(str(b) + '-я попытка: '))
if b > a:
print('Больше')
elif b < a:
print('Меньше')
else:
print('Вы угадали с %d-й попытки' % b)
break
b += 1
else:
print("Game Over")
#задача 13
a = int(input())
b = int(input())
c = int(input())
if a == b == c:
print(3)
elif a == b or b == c or a == c:
print(2)
else:
print(0)
#задача 14
a = input("текст: ")
a_new = a[0]
i = 1
while i < len(a):
if a[i] != ' ':
a_new += a[i]
elif a[i - 1] != ' ':
a_new += '_'
i += 1
print(a_new)
#задача 15
def fill_list(m1, m2, amount, l):
from random import randint
for i in range(amount):
l.append(randint(m1, m2))
def analysis(your_list, your_dict):
for i in your_list:
if i in your_dict:
your_dict[i] += 1
else:
your_dict[i] = 1
lst = []
dct = {}
mn = int(input('Минимум: '))
mx = int(input('Максимум: '))
qty = int(input('Количество элементов: '))
fill_list(mn, mx, qty, lst)
analysis(lst, dct)
for item in sorted(dct):
print("'%d':%d" % (item, dct[item]))
#задача 16
def sum_for_loop(a):
s = 0
for x in a:
s += x
return s
def sum_while_loop(a):
s = 0
n = len(a)
while n:
n -= 1
s += a[n]
return s
if __name__ == '__main__':
t = [5, 3, 4, 1, 7]
for f in (sum_for_loop, sum_while_loop,):
print(f(t))
#задача 17
a = input("цифра: ")
b = input("2 цифра: ")
c = a + b
d = b + a
print(max(c,d))
#задача 18
a = int(input("год: "))
if a % 4 != 0:
print("Не Високосный")
elif a % 100 == 0:
if a % 400 == 0:
print("Високосный")
else:
print("Не Високосный")
else:
print("Високосный")
#задача 19
import os
print(os.listdir())
#задача 20
from pathlib import Path
print(Path(r'C:\Users\user\Desktop\tutorPy\dom.py').suffix)
#задача 21
while True:
s = input("Знак (+,-,*,/): ")
if s == '0':
break
if s in ('+', '-', '*', '/'):
x = float(input("x="))
y = float(input("y="))
if s == '+':
print(x+y)
elif s == '-':
print(x-y)
elif s == '*':
print(x*y)
elif s == '/':
if y != 0:
print(x/y)
else:
print("Деление на ноль!")
else:
print("Неверный знак операции!") |
4c7f7cb569736ce96f619dba622cf735ac06215a | PMiskew/Python3_Turtle_Code | /TurtlePolygon.py | 200 | 3.96875 | 4 | import turtle
import math
bob = turtle.Turtle()
n = 80
side = 3
angle = (180 * (n-2))/n
print(angle)
for i in range(0,n,1):
bob.right(180 - angle)
bob.forward(side)
turtle.done()
|
be4af2cdcda36c58fc8be5211a4f09e31a26119c | ishtiaque06/problems_python | /printPascal.py | 538 | 3.78125 | 4 | """
>>> printPascal(5)
"""
def printPascal(n):
if n == 0:
return []
pascal = [[1]]
for i in range(1, n):
if i == 1:
pascal.append([1, 1])
else:
previous = pascal[-1]
new = [0] * (len(previous)+1)
new[0] = 1
new[-1] = 1
for j in range(1, len(previous)):
new[j] += previous[j] + previous[j-1]
pascal.append(new)
return pascal
if __name__ == "__main__":
import doctest
doctest.testmod() |
6d95e49a3e9aad5a1f77b435e15ae00775377f78 | shrekchan259/MyProjects | /Tic_Tac_Toe.py | 4,931 | 4.0625 | 4 | print('Welcome to Tic Tac Toe !')
def replay():
return input('Would you like to play again? y/n : ').lower()
while True:
test_board = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' ']
print('Kindly note the following positions for your choice of input\n')
print(' 1 '+'|'+' 2 '+'|'+' 3 ')
print('---|---|---')
print(' 4 '+'|'+' 5 '+'|'+' 6 ')
print('---|---|---')
print(' 7 '+'|'+' 8 '+'|'+' 9 \n')
import random
def display_board(board):
print('\n')
print(' '+board[1]+' '+'|'+' '+board[2]+' '+'|'+' '+board[3]+' ')
print('---|---|---')
print(' '+board[4]+' '+'|'+' '+board[5]+' '+'|'+' '+board[6]+' ')
print('---|---|---')
print(' '+board[7]+' '+'|'+' '+board[8]+' '+'|'+' '+board[9]+' '+'\n')
def player_input():
p1 = ''
p2 = ''
first = ''
def choose_first():
return random.randint(0,1)
first = choose_first()
if first == 0:
while p1 != 'X' and p1 != 'O':
p1 = input('Player 1, choose between X or O: ').upper()
else:
while p2 != 'X' and p2 != 'O':
p2 = input('Player 2, choose between X or O: ').upper()
if p1 == 'X':
return ('X','O')
elif p1 == 'O':
return ('O','X')
elif p2 == 'X':
return ('O','X')
else:
return ('X','O')
player1, player2 = player_input()
print('\nPlayer 1 is: ',player1)
print('Player 2 is: ',player2)
print("\nLet's start !")
display_board(test_board)
def win_check(board, mark):
return ((board[1] == board[2] == board[3] == mark) or
(board[4] == board[5] == board[6] == mark) or
(board[7] == board[8] == board[9] == mark) or
(board[1] == board[4] == board[7] == mark) or
(board[2] == board[5] == board[8] == mark) or
(board[3] == board[6] == board[9] == mark) or
(board[1] == board[5] == board[9] == mark) or
(board[3] == board[5] == board[7] == mark))
def place_marker(board, marker, position):
board[position] = marker
def space_check(board, position):
return board[position] == ' '
def full_board_check(board):
for i in range(0,10):
if space_check(board, i):
return False
return True
def player1_choice(board):
position = 1
while position in range(1,9):
try:
position = int(input('Player 1, choose position to place marker :'))
except ValueError:
print('Enter a valid number')
continue
if space_check(board, position) is False:
print('Position already filled ! Please try again.')
continue
else:
return position
def player2_choice(board):
position = 1
while position in range(1,9):
try:
position = int(input('Player 2, choose position to place marker :'))
except ValueError:
print('Enter a valid number')
continue
if space_check(board, position) is False:
print('Position already filled ! Please try again.')
continue
else:
return position
full = full_board_check(test_board)
while not full_board_check(test_board):
flip = True
result1 = False
result2 = False
while flip and result1 == False and result2 == False:
pos = player1_choice(test_board)
place_marker(test_board, player1, pos)
result1 = win_check(test_board, player1)
display_board(test_board)
if result1 == True:
print('Player 1 has won !!')
break
flip = False
if full_board_check(test_board) == True:
print('Game Drawn...')
break
if result1 == True:
break
while not flip and result1 == False and result2 == False:
pos = player2_choice(test_board)
place_marker(test_board, player2, pos)
result2 = win_check(test_board, player2)
display_board(test_board)
if result2 == True:
print('Player 2 has won !!')
break
flip = True
full = full_board_check(test_board)
if result2 == True:
break
if full_board_check(test_board) == True and result1 == False and result2 == False:
print('Game Drawn...')
break
ans = replay()
if ans == 'y':
continue
else:
break
|
2813d77e5130bafe428f16f0347b81786b4971b9 | OskarSliwinskiPK/JS-Automat-MPK | /src/mpk_exceptions.py | 931 | 3.625 | 4 | class Error(Exception):
""" Raise for an exception in this app """
pass
class NotValidCoinValue(Error):
""" When the value does not match the available ones. """
def __init__(self):
super().__init__("The value is not available")
class CoinAttributeError(Error):
""" Only Coin object available. """
def __init__(self):
super().__init__("Only COIN object available")
class CoinStorageAttributeError(Error):
""" Only CoinStorage object available. """
def __init__(self):
super().__init__("Only CoinStorage object available")
class NotEnoughMoney(Error):
""" If someone pay too little. """
def __init__(self):
super().__init__("Niewystarczająca kwota")
class AmountDeducted(Error):
""" When there are no suitable coins in the machine. """
def __init__(self, value):
super().__init__("Tylko odliczona kwota")
self._value = value
|
4d24eb2e43a3f1fc37132ab82470f0127b4535e1 | kunata928/python_functions | /leetcode_solutions(1).py | 1,194 | 3.75 | 4 | import itertools
import math
def multiply1(num1, num2) -> str:
res = str(int(num1) * int(num2))
return res
def multiply2(num1: str, num2: str) -> str:
if num1 == '0' or num2 == '0':
return '0'
num = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
'5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
n1 = 0
n2 = 0
for n in num1:
n1 = (n1 * 10) + num[n]
for n in num2:
n2 = (n2 * 10) + num[n]
return str(n1 * n2)
def getPermutation1(n: int, k: int) -> str:
arr = []
for i in range(1, n+1):
arr.append(str(i))
perm_obj = itertools.permutations(arr)
perm_list = list(perm_obj)
return "".join(perm_list[k - 1])
def getPermutation2(n: int, k: int) -> str:
nums = [str(num) for num in range(1, n+1)]
fact = [1] * n
for i in range(1, n):
fact[i] = i * fact[i-1]
k -= 1
res = []
for i in range(n, 0, -1):
id = k // fact[i - 1]
k -= id * fact[i - 1]
res.append(nums.pop(id))
return ''.join(res)
#nums '2'
#fact 1 1 2 6
#k 0
#res 1 3 4
#i 2
#id = 1
if __name__ == "__main__":
print(getPermutation2(4, 4))
#print(multiply2('15', '15')) |
e85d275232a800eb6961bced98ee841dd0fd7f5d | KevinTsaiCoding/LiveCoding | /Python/Tutorial/003_list-tuple.py | 582 | 3.96875 | 4 | # 有序可變動列表 List (列表意思類似 C語言的陣列)
grades=[12,60,15,70,90]
print(grades[0])
# 變更列表裡的值, 把 55 放到列表中第一個位置
grades[0]=55
print(grades[0])
grades[1:4]=[]
""" 列表名稱[?:!]=[] 意思是把 列表中第?個位子
到第!個位子刪除 """
print(grades)
# 有序不可動列表 Tuple (列表意思類似 C語言的陣列)
data=(3,4,5)
print(data)
print('\n') # 換行
print(data[0:2])
"""
data[0]=5 錯誤: 資料不可變動
print(data)
"""
" Tuple 小括號,不可動動;List 中括號,可變動 "
|
5e7b6a828549f431d40fa054c50450c24f6d6e79 | madara-tribe/AlphaZero_TicTacToe | /LR-algorithms/Tic-Tac-Toe/mini_max_action.py | 1,369 | 3.53125 | 4 | import random
# ミニマックス法で状態価値計算
def cal_value_by_mini_max(state):
# 負けは状態価値-1
if state.is_lose():
return -1
# 引き分けは状態価値0
if state.is_draw():
return 0
# 合法手の状態価値の計算
best_score = -float('inf')
for action in state.legal_actions():
score = -cal_value_by_mini_max(state.next(action))
if score > best_score:
best_score = score
# 合法手の状態価値の最大値を返す
return best_score
# ミニマックス法で行動選択
def mini_max_action(state):
# 合法手の状態価値の計算
best_action = 0
best_score = -float('inf')
str = ['','']
for action in state.legal_actions():
score = -cal_value_by_mini_max(state.next(action))
if score > best_score:
best_action = action
best_score = score
str[0] = '{}{:2d},'.format(str[0], action)
str[1] = '{}{:2d},'.format(str[1], score)
print('action:', str[0], '\nscore: ', str[1], '\n')
# 合法手の状態価値の最大値を持つ行動を返す
return best_action
# ランダムで行動選択
def random_action(state):
legal_actions = state.legal_actions()
return legal_actions[random.randint(0, len(legal_actions)-1)] |
df285e765e14c3e52ad754416131402c786dd4ed | brandle26/Learning | /Section 4 - Pandas/Lec 18 - Drop Entry/Drop_Entry.py | 650 | 3.796875 | 4 | import numpy as np
from pandas import Series,DataFrame
import pandas as pd
ser1=Series(np.arange(3),index=['a','b','c'])
print(ser1)
print("="*50)
#dropping an index
print(ser1.drop("b"))
print("="*50)
#dropping on dataframe
dframe1=DataFrame(np.arange(9).reshape((3,3)),index=["SF","LA","NY"],columns=["pop","size","year"])
print(dframe1)
print("="*50)
#dropping a row form dataframe
print(dframe1.drop("LA"))
print("="*50)
#note this is not permanent.
dframe2=dframe1.drop("LA")
print(dframe2)
print("="*50)
#dropping column
#axis is 0 for row and 1 for column
print(dframe1.drop("year",axis=1))
print("="*50)
|
f2f72ff26c869436946fa208fd716396f67d2b69 | brandle26/Learning | /Section 4 - Pandas/Lec 23- MIssing Data/missingData.py | 1,412 | 3.609375 | 4 | import numpy as np
from pandas import Series,DataFrame
import pandas as pd
data=Series(["one","two",np.nan,"four"])
print(data)
print("="*50)
#chekcing if there is a null value in the serices
print(data.isnull())
print("="*50)
#dropping null value
print(data.dropna())
print("="*50)
#working with dataframe
dframe=DataFrame([[1,2,3],[np.nan,5,6],[7,np.nan,9],[np.nan,np.nan,np.nan]])
print(dframe)
print("="*50)
#cleaning dframe
#dropping any row with null value
clean_dframe=dframe.dropna()
print(clean_dframe)
print("="*50)
#dropping row only if all the vlaues in them are null
print(dframe.dropna(how="all"))
print("="*50)
#dropping column
#droppping anly column with null
print(dframe.dropna(axis=1))
print("="*50)
npn=np.nan
dframe2=DataFrame([[1,2,3,npn],[2,npn,5,6],[npn,7,npn,9],[1,npn,npn,npn]])
print(dframe2)
print("="*50)
#dropping using threshold argument allows us to not drop rows with at least
#the specified number of values that is not null
print(dframe2.dropna(thresh=2))
print("="*50)
print(dframe2.dropna(thresh=3))
print("="*50)
print(dframe2)
#filling na values
print(dframe2.fillna(1))
print("="*50)
#filling diffrent valeus to diffrent column
print(dframe2.fillna({0:0,1:1,2:2,3:3}))
print("="*50)
#modifying existing object
dframe2=dframe2.fillna(1)
#or
dframe2.fillna(0,inplace=True)
print(dframe2)
|
3264f6baf0939442a45689f1746d62d6be07eece | aacampb/inf1340_2015_asst2 | /exercise2.py | 2,014 | 4.5 | 4 | #!/usr/bin/env python
""" Assignment 2, Exercise 2, INF1340, Fall, 2015. DNA Sequencing
This module converts performs substring matching for DNA sequencing
"""
__author__ = 'Aaron Campbell, Sebastien Dagenais-Maniatopoulos & Susan Sim'
__email__ = "aaronl.campbell@mail.utoronto.ca, sebastien.maniatopoulos@mail.utoronto.ca & ses@drsusansim.org"
__copyright__ = "2015 Aaron Campbell & Sebastien Dagenais-Maniatopoulos & Susan Sim"
__license__ = "MIT License"
def find(input_string, substring, start, end):
"""
Function to find a substring within a longer string.
:param input_string: phrase or string of letters
:param substring: string found within input_string
:param start: first index position of input_string
:param end: last index position of input_string
:return : index value of the first character of substring found in input_string
:raises :
"""
index = 0
input_string = input_string.lower() # correct for variations in case
substring = substring.lower()
for ch in range(start, end): # iterate through the string
if input_string[index:index + len(substring)] == substring: # compare slice from both strings
return index
index += 1
else:
return -1
# find()
def multi_find(input_string, substring, start, end):
"""
Function to find all of the instances of a substring within in a longer string.
Return a list of the index value for the first character of each found instance.
:param input_string: phrase or string of letters
:param substring: string found within input_string
:param start: first index position of input_string
:param end: last index position of input_string
:return: list of index values of first character of each instance of substring found in input_string,
returns empty string if no instances found
"""
index = 0
input_string = input_string.lower()
substring = substring.lower()
result = ""
while index < end:
for ch in range(start, end):
if input_string[index:index + len(substring)] == substring:
result += str(index) + "," # convert int
index += 1
result = result[0:-1] # return slice of all index points
return result
else:
return ""
# multi_find()
|
9e588c6baf50932fa110c6f72645a6ae2c9274b8 | jdpoints/python | /roll.py | 3,164 | 3.53125 | 4 | import sys
import re
from random import randint
pattern = (
r"^(?:(?:\[([1-9][0-9]{1,2}|[2-9])" #match.group(1) 2-999 valid
"/([1-9][0-9]{0,2})" #match.group(2) 1-999 valid
"([\+\-])?\])" #match.group(3) + or - valid
"|([1-9][0-9]{0,2}))?" #match.group(4) 1-999 valid
"d([1-9][0-9]{1,2}|[2-9])" #match.group(5) 2-999 valid
"(?:([\+\-])" #match.group(6) + or - valid
"([1-9][0-9]{0,2}))?" #match.group(7) 1-999 valid
)
result = []
final = 0
dice = 1
sides = 2
keep = 0
discarding_roll = False
def msgError():
print "Exactly one argument expected."
print "Please provide an argument of the form XdY+Z or [A/B(+/-)]dY+Z"
print "XdY+Z is a standard roll"
print "[A/B+]dY+Z is a discarding roll, A dice are rolled and B are kept"
print "\tX = the number of dice to roll"
print "\tA = number of dice to roll for a discarding roll"
print "\tB = the number of dice to keep, must be less than A"
print "\t(+/-) = if '+' highest rolls kept, if '-' then lowest, default is +"
print "\tdY = the number of sides per die, minimum 2"
print "\t+Z = (optional)any bonuses or penalties to be added/subtracted"
print "\t\tIf applying a penalty '-' can be substituted for '+'"
print "\t\tAll numbers must be between 1 and 999"
sys.exit()
def rollDie(num_sides):
roll_result = randint(1,num_sides)
return roll_result
def discardRoll(result_list,num_to_keep,keep_hi_bool):
temp = sorted(result_list)
out_val = 0
if keep_hi_bool:
out_val = sum(temp[-num_to_keep:])
else:
out_val = sum(temp[num_to_keep:])
return out_val
if len(sys.argv) != 2:
msgError()
match = re.search(pattern, sys.argv[1])
#full_grp #match.group(0) full match or None if no match
discard_roll_grp = match.group(1) #match.group(1) # of die for discard roll (2-999)
discard_keep_grp = match.group(2) #match.group(2) # of die to keep from discard roll
discard_hi_low_grp = match.group(3) #match.group(3) + keep high rolls, - keep low rolls
standard_roll_grp = match.group(4) #match.group(4) # of die for regular roll (2-999)
sides_grp = match.group(5) #match.group(5) number of sides, at least 2
bonus_add_sub = match.group(6) #match.group(6) addition or subtraction
bonus_value = match.group(7) #match.group(7) bonus or penalty
if match:
if discard_roll_grp:
dice = int(discard_roll_grp)
keep = int(discard_keep_grp)
discarding_roll = True
if keep > dice:
msgError()
elif standard_roll_grp:
dice = int(standard_roll_grp)
sides = int(sides_grp)
for i in range(dice):
result.append(rollDie(sides))
if discarding_roll:
if discard_hi_low_grp:
if str(discard_hi_low_grp) == "+":
keep_hi = True
elif str(discard_hi_low_grp) == "-":
keep_hi = False
else:
msgError()
else:
keep_hi = True
final = discardRoll(result,keep,keep_hi)
else:
final = sum(result)
if bonus_add_sub and bonus_value:
bonus = int(bonus_value)
if str(bonus_add_sub) == "+":
final = final + bonus
elif str(bonus_add_sub) == "-":
final = final - bonus
else:
msgError()
print " ".join(str(roll) for roll in result)
print "You rolled " + str(final) + "."
else:
msgError() |
313f48aadc4c94d41ee421e57984c8489d3ee4d4 | zerosai7/scenic_tourist_information_system | /test4.py | 134 | 3.53125 | 4 | import re
string=input()
result=re.search(re.compile('(.*?)/(.*)/(.*)'),string)
print(result)
print(result[1],result[2],result[3]) |
6a23fff85f3e17d471083c8b8ef6dcd64c75b329 | LiuYyunHao/PythonDemo | /Person.py | 691 | 3.734375 | 4 | class Person:
def __init__(self):
self.__age = 20
# @property
# def age(self):
# return self.__age
#
# @age.setter
# def age(self, value):
# self.__age = value
def get_age(self):
return self.__age
def set_age(self, value):
self.__age = value
age = property(get_age, set_age)
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
person = Person()
print("person=%s" % id(person))
person1 = Person()
print(id(person1))
person2 = Person()
print(id(person2))
|
a4796c4173346b3045f83184127312e5083e4b42 | ngxson/edu-insa-3a | /python/ex34.py | 1,363 | 3.59375 | 4 | print(set('totto'))
# erreur car set([iterable])
# on doit écrire set(('totto'))
print({'totto'})
# affiche {'totto'}
print({{'toto'}, {'tata'}})
# TypeError: unhashable type: 'set'
print('abcde'[-1])
# affiche 'e'
print({'abcde'}[0][1])
# erreur car 'set' n'a pas de ordre
print('abcdefg'[2:5])
# affiche 'cde'
print((list('abcdefg')*3)[2:5])
# list('abcdefg') = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# list('abcdefg')*3 = ['a', ..., 'g', 'a', ..., 'g', 'a', ..., 'g']
# affiche ['c', 'd', 'e']
print((list('abcdefg')*3)[19:22])
# on prends l'indice 19, 20, 21
# mais l'indice 21 n'existe pas
# il affiche ['f', 'g']
print('abcdefg'[-5:-2])
# affiche 'cde'
print( list(range(12))[13:5:-2] )
# on va de 13 à 6 par pas de -2
# donc on prend 11, 9, 7
# affiche [11, 9, 7]
print({0:1, None:2, False:5})
# parce que: False.__hash__() = 0
# et int(0).__hash__() = 0
# donc la valeur de 0:1 est remplacé par False:5
s = { print(i) for i in range(1,3) }
# s = {None}
# et il affiche
# 1
# 2
ss = { (i,print(i)) for i in range(1,3) }
# ss = { (1, None), (2, None) }
# et il affiche
# 1
# 2
sss = { (i,i,print(i)) for i in range(1,3) }
# sss = { (1, 1, None), (2, 2, None) }
# et il affiche
# 1
# 2
print(s,ss,sss,sep='\n')
# {None}
# { (1, None), (2, None) }
# { (1, 1, None), (2, 2, None) }
|
af799dec3e9a457c8304ed8e9a178e15b31b1782 | bboats/trabFormais | /src/menu.py | 2,332 | 3.734375 | 4 | #!Python3
import AutomataClasses
from os import system, name
###########################
##### main menu class #####
###########################
class Menu:
"""text-based menu class, receives a list of options and a title as init arguments"""
def __init__(self, options, title='|'):
self.options = options
self.title = title
def showMenu(self,title='|'):
"""showMenu: Displays a menu from a given list of options exit will always be option 0 and implicit
Receives a list of strings, each string represents an option for the menu
Can also receive a title for the menu as second parameter"""
#clears the screen#
#windows
if name == 'nt':
_ = system('cls')
#mac/linux
else:
_ = system('clear')
print('Marcos Vinicius de Oliveira Pinto - 00288560')
print(10*'#',self.title,10*'#','\n')
for index,option in enumerate(self.options):
print(index+1,':',option)
print('0 : Exit')
print()
print((22+len(self.title))*'#','\n')
return int(input('OpNumber?: '))
#########################
#### menu operations ####
#########################
def openLanguage():
#makes the user input again if file is not found (or any other error happens)
done = 0
while done == 0:
automataFileName = input('Name or PATH to the LANGUAGE file?:\n')
if automataFileName[-4:] != '.txt':
automataFileName+= '.txt'
try:
AFNFile = open(automataFileName,"r")
done = 1
except:
print('File does not exist! (press enter to try again)')
input()
lines = (AFNFile.read()).split('\n')
automataName,language = lines[0].split('=') ### original format is "automataName = {language}"
#lines[1] has no purpose other than formatting so it is useless to this program
AFNoperations = lines[2:]
afn = AutomataClasses.Afn(automataName,language,AFNoperations)
afd = AutomataClasses.Afd(*afn.determinizeOperations())
return afd
def testWordsTxt():
done = 0
while done == 0:
wordsFileName = input('Name or PATH to the WORDS file?:\n')
if wordsFileName[-4:] != '.txt':
wordsFileName+= '.txt'
try:
wordsFile = open(wordsFileName,"r")
done = 1 #if the open() does not fail then there were no errors and the while loop can end
except:
print('File does not exist! (press enter to try again)')
input()
return (wordsFile.read()).split('\n')
def testWordsKb():
return input('Word? ') |
052c75ab47504d71824eaf54d2333a6b71c5a3d3 | Sekinat95/May-30-day-leetcode | /day9.py | 308 | 3.8125 | 4 | def isPerfectSquare(self, num: int):
#using binary search
if num<2:
return True
L,R=2,num
while L<=R:
mid=(L+R)//2
if mid**2 == num:
return True
elif mid**2 > num:
R = mid-1
else:
L = mid +1
return False
|
2e4390f52c1c87a8430e3ddd099c74ce74a67b0c | RiccardoTonini/algo_think_2014 | /week1/project1.py | 2,206 | 3.78125 | 4 | """
This modules exposes 3 functions: make_complete_graph, compute_in_degrees, in_degree_distribution
"""
# Represents graph 1,2,3 as adjancency lists
EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])}
EX_GRAPH1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]),
3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}
EX_GRAPH2 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3, 7]), 3: set([7]), 4: set([1]), 5: set([2]),
6: set([]), 7: set([3]), 8: set([1, 2]), 9: set([0, 3, 4, 5, 6, 7])}
def make_complete_graph(num_nodes):
"""
Given the number of nodes num_nodes
returns a dictionary corresponding to a complete directed graph
with the specified number of nodes.
"""
try:
num_nodes = int(float(num_nodes))
except ValueError or TypeError:
return {}
if num_nodes < 0:
return {}
graph = {}
nodes = [n for n in range(num_nodes)]
for node in range(num_nodes):
graph[node] = set()
for edge in nodes:
if edge != node:
graph[node].add(edge)
return graph
def compute_in_degrees(digraph):
"""
Takes a directed graph digraph (as a dictionary) and
computes the in-degrees for the nodes in the graph.
Returns a dictionary with the same set of keys (nodes) as digraph
whose corresponding values are the number of edges whose head matches a particular node.
"""
in_degrees = {}
all_edges = digraph.values()
nodes = digraph.keys()
count = 0
for node in nodes:
for edges in all_edges:
if node in edges:
count += 1
in_degrees[node] = count
count = 0
return in_degrees
def in_degree_distribution(digraph):
"""
Takes the directed graph that represented as a dictionary.
Returns the unnormalized distribution of the in-degrees of the graph.
"""
nodes_in_degrees = compute_in_degrees(digraph)
distribution = {}
in_degrees = nodes_in_degrees.values()
for count in in_degrees:
if count not in distribution.keys():
distribution[count] = 0
distribution[count] += 1
return distribution
|
af0b765e91865a5b1ab26e54593e65af36066423 | dongso/Python-Project | /day4.py | 3,658 | 3.734375 | 4 | i = 0
while True:
print(i)
i = i+1
if i == 100:
break
for i in range(10000):
print(i)
if i==100:
break
# ****
# ****
# ****
for i in range(3):
for j in range(4):
print("*",end='')
print("\n")
# *
# **
# ***
# ****
for i in range(1,5):
for j in range(i):
print("*",end='')
print("\n")
a=[(1,2),(3,4),(5,6)]
for x in a:
print(x)
a=[(1,2),(3,4),(5,6)]
for x in a:
print(x[0]) #각 튜플의 0번 index의 값이 출력됨.
for x1, x2 in a:
print(x1+x2) #튜플로 이뤄져있을때 알아서 첫번째, 두번째 값이 x1, x2로 불려짐.
#리스트 내포(list comprehension)::리스트 내부에 for문을 포함
a=[1,2,3]
res=[ n*2 for n in a] #a의 값을 2배한것을 res에 저장.
print(res)
a=[1,2,3,4,5,6]
#a리스트의 요소 중 2의 배수인 것만 2배 해서 res 리스트를 생성
res=[ n*2 for n in a if n%2 == 0] #a리스트의 요소 n이 만약에 2의 배수이면, n*2를 해서 res리스트에 저장.
print(res) #[4,8,12]
#구문형식 -> 리스트변수명 = [표현식 for 변수 in 리스트 if 조건문]
#다중 for문 가능.
res=[x*y for x in range(2,10)
for y in range(1,10)]
print(res)
#2차원 리스트 :: 리스트 안에 리스트가 들어가있는 구조
a=[[1,2],[3,4],[5,6]]
print(a[2][1]) #세로 index:2, 가로 index:1
print("*"*50)
a=[[1,2],[3,4],[5,6]]
for k in range(len(a)):
for j in range(len(a[k])):
print(a[k][j],end=' ')
print()
i=0
print("*"*50)
a=[[1,2],[3,4],[5,6]]
while i<len(a): #3번 반복
j=0
while j<len(a[i]):
print(a[i][j],end=' ')
j=j+1
i=i+1
print("*"*50)
a = []
line=[]
for i in range(3):
# line=[] #line 초기화
for j in range(2):
line.append(0)
a.append(line)
########내 장 함 수 ##########
print(abs(-3)) #절대값
print(abs(-3.1))
print(all([1,2,3,0])) #all함수는 모든 요소가 참인가? 참 : True, 거짓: False
print(any([0,0,0,1]))
print(chr(97)) #아스키 코드값->문자
for n in enumerate(['i','j','k']):
print(n)
print(eval('1+2'))
print(eval('divmod(5,3)'))
########함수 정의 ########
def pos(x): #함수 정의 부분(단독으로 실행되지 않는다.-> 호출 필요!!)
res=[] #x리스트에서 양수값만 뽑아서 res 리스트에 넣자
for i in x:
if i > 0 :
res.append(i)
#res=[i for i in x if i>0]
print(res)
print("*"*100)
pos([1,-3,2]) #함수 실행부분
def 버스이용(): #함수정의
print("버스를 탔어요")
버스이용() #함수 호출
def 버스이용2(): # 함수정의
print("버스2를 탔어요")
버스이용2() # 함수 호출
def 버스이용3(왼쪽주머니, 오른쪽주머니): #버스 요금 1500원
잔액=왼쪽주머니-1500
print("잔액 : ", 잔액)
잔액=오른쪽주머니 -1500
print("잔액 : ", 잔액)
print("버스3을 타고 이동합니다.")
버스이용3(2000,10000)
def sub(inse):
fee=1200
rest=inse-fee
return rest
print(sub(2000))
def add(a,b):
return a+b
print(add(2,3))
def say():
print("hi")
return
res=say() #return value is None.
print(res)
def add2(a,b):
return a+b
res=add2(b=3,a=5)
print(res)
def fact(val):
res=1
for v in range(1,val+1):
res=res*v
#print(v)
return res
print(fact(5))
#1부터 data 변수로 전달된 값까지 존재하는 모든 4의 배수를 출력.
#예시: 값을 입력하세요:10
#4,8
def calc(data):
for i in range(1,data+1):
if i %4 == 0:
print(i)
myInput=int(input("값을 입력하세요 : "))
res=calc(myInput)
print(res) |
b355ffb5f1e84b9f6ec449c9fc0c6319c6e54e21 | dongso/Python-Project | /day4-prac.py | 1,817 | 3.890625 | 4 | #문제 1
print("문제 1번 ******************")
for i in range(1,6):
for j in range(0,i):
print(" ",end='')
print("*\n")
#문제 2
print("문제 2번 ******************")
for i in range(2,10) :
print("%i단 시작 -->"%i)
for j in range(1,10):
print("%s * %s = %d"%(i,j,i*j))
#문제 3
print("문제 3번 ******************")
def is_odd(num):
res=""
if num % 2 == 0: res="짝수입니다."
else: res="홀수입니다."
return res
print(is_odd(int(input("숫자를 입력해주세요: "))))
#totalListCnt //변수명 작성 규칙.. -> 합성어의 두번째 시작단어는 대문자로!!
#문제4
print("문제 4번 ******************")
sum=0
cnt=0
while True:
a=int(input())
if a==0: break
sum=sum+a
cnt=cnt+1
print(sum/cnt)
#문제5
print("문제 5번 ******************")
numbers=[1,2,3,4,5]
result=[n*2 for n in numbers if n%2 == 1]
print(result)
#문제6
print("문제 6번 ******************")
def traf(age,balance):
fare=0
if age>=7 and age<=12:
fare=650
elif age>=13 and age<=18:
fare=1050
elif age>=19:
fare=1250
else:
fare=0
return balance-fare
age=int(input("당신의 나이는? "))
print(traf(age,9000))
#문제7
print("문제 7번 ******************")
def not_three(start, stop):
for i in range(start,stop+1):
if str(i)[len(str(i))-1]=='3': #str(i)[-1]==> 마지막글자
continue
print(i,end=' ')
start,stop=map(int,input().split())
not_three(start,stop)
#추가문제
def count7(start,end):
cnt=0
for i in range(start,end+1):
for j in range(0,len(str(i))):
if str(i)[j]=='7':
cnt=cnt+1
return cnt
# for i in range(1,10000) :
# cnt+=str(i).count('7')
print(count7(1,10000)) |
d2aa07f91a4fff951d42cb84bde47fe9ae61c0d9 | dongso/Python-Project | /day6.py | 6,627 | 3.640625 | 4 | # #정규표현식 : 패턴(규칙)을 가진 문자열을 표현하는 방법
# #규칙이 있는 문자열을 추출, 변경 등의 작업을 수행하기 위해 작성
# #re module을 사용해서 정규표현식 작성.
# #re.match('패턴','문자열')을 사용.
#
import re
print(re.match('Hi', 'Hello, hi, world'))
print(re.match('hi', 'hi, world')) #문자열의 첫번째부터 비교해서 있으면 span(0,n) return
print('hello hi, world'.find('hi')) #문자열의 시작위치가 나옴
# #re.match는 find()에서 찾을 수 없는 문자열도 찾아 낼 수 있다.
#
# #search 함수
# #^문자열 : 패턴이 문자열이 맨 앞에 오는 판단
# #문자열$ : 패턴이 문자열의 마지막에 오는지 판단
print(re.search('hi','hello, hi')) #문자열에 hi가 있는가? # hi의 위치를 span(i,j)로 return
print(re.search('^hi','hi hello')) #맨 앞에 hi가 있는가?
print(re.search('hi&','hi, hello')) #맨 뒤에 hi가 있는가? None
print("***********"*10+'\n',re.match('hello|world','hello world')) #주어진 문자열에 hello || world가 포함되어 있나?
# #문자열이 숫자로 되어 있는지 판단하기 위한 정규표현식의 예
# #대괄호 안에 숫자의 범위를 기재, * 또는 + 기호를 붙임
# #*:0개이상, +:1개이상 있는지 판다.
# print(re.match("[0-9]*","1234")) #1234에는 [0-9]* 패턴이 있나?
# # [0-9]* : 0부터 9까지의 숫자가 0개 이상 존재하는 패턴이 있나?
# # 있으면 return span(i,j):: i부터 j까지 매치됨
# #match는 문자열의 시작부터 확인함
# #따라서, re.match("[0-9]*, "문자열") :: 문자열이 숫자로 시작하는지를 확인하는 것.
print(re.match("[0-9]*","1234a"))
print(re.match("[0-9b-k]*","c1b123a")) #문자열에 0-9 & c, b가 있는지 확인
print("*"*50)
print(re.match("a*b","b"))
# #a*b의 의미 :: 문자열에 a가 0개이상 나온 뒤에 이어서 b가 있는 패턴이 존재하는가?
print(re.match("a+b","b"))
# #a+b의 의미 :: 문자열에 a가 1개이상 나온 뒤에 이어서 b가 있는 패턴이 존재하는가?
print(re.match("a+b","aaacb"))
print(re.match("a+b+","aabbaabb"))
print(re.match('sab+cc','sabee'))
# #? 와 .::문자가 한 개만 있는지 판단 할 때 사용
# #? : 문자가 0개 또는 한개
# #. : 문자가 1개인지 판단.
print(re.match('H?','H'))
print(re.match('H.','IW'))
print(re.match('H.',"HHHHHHHEL"))
print("*"*50)
# #문자가 정확히 몇 개 있는지 판단.
# #문자{개수}
# #(문자열){개수}
print(re.match('h{3}','hhello')) #h가 3개 있는지 판단 , 매치 안됨
print(re.match('h{4}','hhhhhello'))
print(re.match('h{4}k','hhhhkkkkhello'))
print(re.match('h{4}k+','hhhhkkkello'))
print(re.match('h{3}k*',"hhhello"))
print(re.match('h{3}k*hel{2}','hhhhello'))
print("*"*50)
print(re.match('(he){2}k+','hehekkk'))
print(re.match('(hi){3}','hihi'))
print(re.match('[0-9]*(hi){3}b*y*e','1hihihiyye'))
print(re.match('(hi){3}b*y*e','hihihiyy')) #None::"e"가 없기 때문에
print(re.match('(hi){3}[a-z]*e','hihihiydsfaasdfy'))
#
# #특정범위의 문자/숫자가 몇 개 있는지 판단 :: [범위]{개수}
print("*"*50)
print(re.match('[0-9]{4}','010-1234'))
# pNum=input("전화번호를 입력해주세요")
# print(re.match('[0-9]{3}-[0-9]{4}-[0-9]{4}',pNum)) #전화번호 확인 할때 유용하게 사용됨.
print(re.match('[0-9]{3}-[0-9]{4}-[0-9]{4}','010-1234-5678')) #전화번호 확인 할때 유용하게 사용됨.
print("*"*50)
print("*"*50)
# #범위지정
print(re.match('[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}', '02-123-4567')) #개수의 범위도 지정 가능.
print(re.match('[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}', '032-1234-5678'))
print(re.match('[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}', '02-13-4567')) #None
#
# #문자에 대한 개수 지정
print("="*100)
# # (문자){시작개수, 끝개수}
# # (문자열){시작개수, 끝개수}
# # [0-9]{시작개수, 끝개수}
print(re.match('(a){2,3}', 'a')) #None
print(re.match('(a){2,3}', 'aa'))
print(re.match('(a){2,3}', 'aaa'))
print(re.match('(a){2,3}', 'abaaa')) #None
print(re.match('(hi){2,3}', 'hihihihello')) #None
#
#
# print("="*100)
# #숫자와 영문을 혼합
# #0-9, a-z, A-Z
print(re.match('[0-9]+','1234'))
print(re.match('[0-9o]+','o1234')) #대괄호 안에서는 순서가 없다.
print(re.match('[a-z0-9]+','aw1adf234')) #a-z and 0-9
print(re.match('[ol0-9]+','lo1234'))
print(re.match('[0-9lo]+','ello1234')) #None
print(re.match('[A-Za-z0-9가-힣]+','helloHHI홍길동'))
#특정 문자 범위에 포함되지 않는지를 판단
# [^범위]*
# [^범위]+
print(re.match('[^A-Z]+','hello가나다ABC')) #A-Z가 아닌 모든 문자열이 매치됨
#^[범위]*
#^[범위]+
print(re.match('^[A-Z]+','HELLO가나다')) #A-Z로 시작하는 문자열
print(re.match('^[A-Z]*','hello')) #A-Z로 시작하는 문자열
print(re.match('[0-9]+','1234'))
print(re.search('[0-9]+$','hello1234')) #숫자로 끝나는 경우 search함수를 사용할 것!
#특수문자판단
print(re.match("\*+","1**2")) #패턴에서 특수문자는 얖에 \를 붙여야한다.
print(re.search("\*+","1 **2")) #search 함수 : 문자열의 전체에서 패턴을 찾아줌
print(re.search("[*]+","1 **2")) #search 함수 : 문자열의 전체에서 패턴을 찾아줌
print(re.search("[*0-9]+","1** 2"))
print(re.search("[*]+","1 **2 *")) #search 함수 : 문자열의 전체에서 패턴을 찾아줌
print(re.match("[$()a-z]+","$(lunch)"))
#축약형 : \d(decimal) <-> \D(not decimal), \w
print(re.match("\d+",'1234')) # \d : 숫자([0-9])
print(re.match("\D+",'1234')) # \D : [^0-9]와 같음
print(re.match("\D+",'abc1234')) # \D : ^[0-9]와 같음
print(re.match("\w+",'1234')) # \w : [a-zA-Z0-9 ]-=> 소문자,대문자,숫자,blank까지 포함
print(re.match('\W+','.?')) # \W : [^a-zA-z0-9 ]-=> 소문자,대문자, 숫자, 빈칸을 제외한 문자
print(re.match("\w+","abcd_1234"))
print(re.match("\W+","*^^* hello *^^*"))
print(re.match('[a-zA-Z0-9\s]+','Hello 1234')) #\s ::blank
#같은 정규표현식 패턴을 자주 사용해야 하는 경우에는
#매번 match, search를 사용해서 패턴을 지정하고 매칭 테스트하는건 비효율적이다.
#compile 함수 : 같은 패턴이 반복적으로 사용되는 경우에 적합
print("--------------------compile Example----------------------------")
pat=re.compile("[0-9]+") #정규표현식 패턴 정의 및 패턴 객체 생성
print(pat.match("1234")) #문자열 "1234"에 pat을 match해본다.
#print(re.match("[0-9]+","1234")
print(pat.search("1abcd"))
emailPat=re.compile("\w*\d*@\w+.\w+.*")
print(emailPat.match("khay0311@hufs.ac.kr")) |
8dff4ae8dc22466b0feaa8abb4a1e421ea4401e8 | sesch023/Python-Uebungen | /Übung (Übersetzer Schwierigkeit 4)/Lösung.py | 479 | 4.0625 | 4 | dictionary = {
"Zug": "train",
"Hochschule": "university",
"Küche": "kitchen",
"Tisch": "table",
"Computer": "computer"
}
eingabe = input("Bitte geben sie ein Wort zum Übersetzen ein: ")
while eingabe != "ende":
if eingabe in dictionary:
print(f"{eingabe} -> {dictionary[eingabe]}")
else:
print("Wort nicht im dictionary vorhanden! Versuchen sie es nochmal!")
eingabe = input("Bitte geben sie ein Wort zum Übersetzen ein: ")
|
21b82a9809a13020bb6e3f6cec6dacb75bd638f1 | sesch023/Python-Uebungen | /Übung (Vergleich Nutzereingaben Schwierigkeit 2)/Lösung.py | 284 | 3.984375 | 4 | x = float(input("Bitte geben Sie die erste Zahl an: "))
y = float(input("Bitte geben Sie die zweite Zahl an: "))
if x < y:
print("Kleinere Zahl: " + str(x))
print("Größere Zahl: " + str(y))
else:
print("Kleinere Zahl: " + str(y))
print("Größere Zahl: " + str(x))
|
23fc2ba6008d38ce8aec051f0400efe197442efb | klfoulk16/mazes | /util.py | 13,133 | 3.78125 | 4 | import random
from PIL import Image
"""Contains the objects necessary to create and solve various mazes.
Order from top to bottom: Cell, StackFrontier, Queuefrontier, Maze"""
class Cell():
"""Structure to keep track of various cells in the maze and which cell we used to get there"""
def __init__(self, location, parent_cell, end_cell):
self.location = location
self.parent = parent_cell
# set start cell "steps" to 0. If not start cell, set it to 1 more than the parent cell's.
# This measures how many steps along a direct path we took to get to this cell.
# This also sets end cells steps to 0
if self.parent != None:
self.steps = parent_cell.steps + 1
else:
self.steps = 0
# if the cell we're initializing isn't the end cell, calculate estimated_distance
if end_cell != None:
self.estimated_distance = self.calc_distance(location, self.steps, end_cell)
else:
self.estimated_distance = 0
def calc_distance(self, location, parent, end_cell):
# calculate absolute distance away from end point
horz_distance = end_cell.location[0] - self.location[0]
vert_distance = end_cell.location[1] - self.location[1]
absolute_distance = vert_distance + horz_distance
# add steps to absolute_distance to get estimate of how 'good' a path this cell is on
total_estimated_distance = absolute_distance + self.steps
#if self.parent != None:
#print(f"New Cell location: {self.location[0]},{self.location[1]} steps: {self.steps}, abs: {absolute_distance}, total: {total_estimated_distance}")
return total_estimated_distance
class StackFrontier():
"""Last in, first out data structure. Use this for Depth First Search."""
def __init__(self):
self.frontier = []
def add(self, cell):
self.frontier.append(cell)
def return_parent(self, parent):
for cell in self.frontier:
if cell.location == parent:
return cell
def empty(self):
return len(self.frontier) == 0
def remove(self, explored_cells):
if self.empty():
raise Exception("empty frontier")
else:
cell = self.frontier[-1]
self.frontier = self.frontier[:-1]
return cell
class QueueFrontier(StackFrontier):
"""First in, first out data structure. Use this for Breadth First Search."""
def remove(self, explored_cells):
if self.empty():
raise Exception("empty frontier")
else:
cell = self.frontier[0]
self.frontier = self.frontier[1:]
return cell
class SmartFrontier(StackFrontier):
"""Returns cell with the least estimated_distance, if two have the same estimated_distance,
it returns the first one it finds. This way it explores the path that shows the most promise,
given the absolute distance of the cell to the end point and the total # of steps it took to get there."""
def remove(self, explored_cells):
if self.empty():
raise Exception("empty frontier")
else:
# distance = number larger than cell.estimated_distance could be
distance = 1000
closest_cell = None
for cell in self.frontier:
if cell.estimated_distance < distance:
distance = cell.estimated_distance
closest_cell = cell
#print(f"Closest cell: {closest_cell.location}")
# if there's two cells of equal distance away...
elif cell.estimated_distance == distance:
# if their parent is the start cell, choose randomly
if cell.parent.parent == None:
closest_cell = random.choice([closest_cell, cell])
# else follow current path
if cell.parent in explored_cells:
closest_cell = cell
self.frontier.remove(closest_cell)
#print(f"Chosen cell: {closest_cell.location}, Distance: {closest_cell.estimated_distance}")
return closest_cell
def print(self):
for cell in self.frontier:
print(cell.estimated_distance)
class Maze():
"""This is the maze you're working with. You can create, solve and print it."""
def __init__(self, width, height):
self.width = width
self.height = height
# Create set of width*height size filled with 0's (path cells)
self.board = [[0 for i in range(width)] for j in range(height)]
# Add all of the walls by changing various 0's to 1's.
self.add_borders()
self.build_walls(0, self.height, 0, self.width)
# Label start and end points. Change maze values to ensure they aren't walls.
self.end = Cell((self.width-2,self.height-2), None, None)
self.start = Cell((1,1), None, self.end)
self.board[1][1] = "Start"
self.board[self.width-2][self.height-2] = "End"
def add_borders(self):
# Add walls along the edge of the maze.
for i in range(self.width):
self.board[0][i] = 1
self.board[self.height-1][i] = 1
for i in range(self.height):
self.board[i][0] = 1
self.board[i][self.width-1] = 1
def build_walls(self, top, bottom, left, right):
"""Uses recursive division to add maze walls. Based off idea from this webpage:
http://weblog.jamisbuck.org/2011/1/12/maze-generation-recursive-division-algorithm"""
# Decide whether to add vertical or horizontal wall.
# Add horizontal if maze section's height is greater than it's width.
# Add verticle section otherwise. Random if height and width are even.
direction = None
if (right - left) < (bottom - top):
direction = "horizontal"
elif (right - left) > (bottom - top):
direction = "vertical"
else:
direction = random.choice(["horizontal", "vertical"])
# Recursively divide maze into two smaller rectangles. In each rectangle,
# add one wall that spans the entire length of the rectangle at a random
# even index (top = 0). Do this by changing the 0's to 1's. Add one
# opening through each of the walls at an even index by changing the 1 back to 0.
# Repeat for the section above/below or left/right of the wall (depending
# on whether the wall was verticle or horizontal)until the sections are
# too small to add walls to.
if direction == "horizontal":
wall = random.randrange(top + 2, bottom - 1, 2)
# go from left to right building the wall.
for x in range(left, right):
self.board[wall][x] = 1
# get odd number to be the path through the wall
path = random.randrange(left + 1, right, 2)
self.board[wall][path] = 0
# redo for top half if there's enough room to make a new wall
if wall - top > 3:
self.build_walls(top, wall, left, right)
# redo for the bottom half if there's enough room to make a new wall
if bottom - wall > 3:
self.build_walls(wall, bottom, left, right)
if direction == "vertical":
wall = random.randrange(left + 2, right - 1, 2)
for y in range(top, bottom):
self.board[y][wall] = 1
path = random.randrange(top + 1, bottom - 1, 2)
self.board[path][wall] = 0
# redo for left half if there's enough room
if wall - left > 3:
self.build_walls(top, bottom, left, wall)
# redo for right half if there's enough room
if right - wall > 3:
self.build_walls(top, bottom, wall, right)
def solve(self, frontier):
# Create an empty set to populate with the cells we explore.
self.explored_cells = set()
# Explore cells until we find the end point
self.explore_paths(self.start, frontier)
# identify the direct path. Marks cells as "P" and creates a set of the final path cells.
self.trace_final_path()
def explore_paths(self, current_cell, frontier):
"""Recursively explores neighbors of each cell along the various maze paths until it finds the end point. It marks all cells that it explores as "E" in the board and adds them to the set of explored cells."""
# shuffle the list of possible neighbor locations so that we explore the cells in random order
neighbors = (-1,0), (0,-1), (0,1), (1,0)
neighbors = list(neighbors)
random.shuffle(neighbors)
# iterate over neighbors to the current cell to see if they are either path cells or the end point
for (i,j) in neighbors:
for x,y in [(current_cell.location[0]+i,current_cell.location[1]+j)]:
if x in range(0, self.width) and y in range(0, self.height):
# 2) if one of the neighbors is the end, update the parent of the end cell
if self.board[x][y] == "End":
self.end.parent = current_cell
return True
# If cell is a path cell, add it to the frontier to be (potentially) explored
elif self.board[x][y] == 0:
new_cell = Cell((x,y), current_cell, self.end)
frontier.add(new_cell)
# 4) pop a cell off of the frontier (which cell gets removed depends on the type of frontier)
# choosing a cell:
current_cell = frontier.remove(self.explored_cells)
#print(f"Chosen cell: {current_cell.location[0]}, {current_cell.location[1]}")
# 5) add cell to explored_cells and mark it as "E" for visualization
self.explored_cells.add(current_cell)
self.board[current_cell.location[0]][current_cell.location[1]] = "E"
# 6) repeat steps 1-5 until you find the end point
self.explore_paths(current_cell, frontier)
def trace_final_path(self):
"""Works backwards to identify the path taken to get to the end cell.
Marks them as P for easy visualization."""
# create set of cells for path, starting with end cell
self.final_path = {self.end}
# loop over explored cells until we find the cell who's parent was the start point (1,1)
current_cell = self.end
while current_cell.parent.location != self.start.location:
# use cell.parent to find the cell we used to get to the current cell
for cell in self.explored_cells:
if current_cell.parent.location == cell.location:
# add to path set and switch cell value from "E" to "P"
self.final_path.add(cell)
self.board[cell.location[0]][cell.location[1]] = "P"
current_cell = cell
def print_maze_img(self, type):
"""
Creates a small img of the maze.
Usage: type is version of the maze you want to print...
Finished_path -- shows the path the algorithm found.
Finished_explored -- shows all of the cells explored.
Unfinished -- the unfinished maze.
"""
img = Image.new( 'RGB', (self.width, self.height))
pixels = img.load()
for i in range(self.height):
for j in range(self.width):
if self.board[i][j] == 1:
pixels[i,j] = (0, 0, 0)
if self.board[i][j] == 0:
pixels[i,j] = (255, 255, 255)
if self.board[i][j] == "Start":
pixels[i,j] = (0, 255, 0)
elif self.board[i][j] == "End":
pixels[i,j] = (255, 0, 0)
elif self.board[i][j] == "E":
if type in ["unfinished", "finished_path"]:
pixels[i,j] = (255, 255, 255)
else:
pixels[i,j] = (0, 0, 255)
elif self.board[i][j] == "P":
if type in ["finished_explored", "finished_path"]:
pixels[i,j] = (0, 255, 0)
else:
pixels[i,j] = (255, 255, 255)
img.show()
def print_maze_terminal(self):
"""Prints out the binary maze in the terminal."""
for row in range(self.height):
print(self.board[row])
def percent_explored(self):
"""Return percent of maze explored (not including walls)."""
total = 0
total_explored = 0
for i in range(self.height):
for j in range(self.width):
if self.board[i][j] in ["E", "P"]:
total_explored += 1
total += 1
elif self.board[i][j] == 0:
total += 1
percent = int((total_explored/total)*100)
return percent
|
1e4dfefa54c79312347a8f47d26993530358041a | graceke/TowerBlaster | /towerblaster.py | 12,324 | 3.90625 | 4 | import random
turn_count = 0
def setup_bricks():
'''sets up the game main pile with 1-60 in a list and discareded empty then return them as a tuple'''
main_bricks = list(range(1, 61))
discarded_bricks = []
return main_bricks, discarded_bricks
def shuffle_bricks(bricks):
'''shuffles bricks with random...'''
random.shuffle(bricks)
def check_bricks(main_pile, discard):
'''checks if main pile (list) is empty. If it is shuffles discard and copies it over and clears discard. Then adds the top brick to discard'''
if len(main_pile) == 0:
random.shuffle(discard)
main_pile = discard.copy()
discard.clear()
first_brick = get_top_brick(main_pile)
add_brick_to_discard(first_brick, discard)
def check_tower_blaster(tower):
'''check if player/computer tower is sorted'''
for num in range(1, 9):
if tower[num] < tower[num + 1]:
continue
else:
return True
return False
def get_top_brick(brick_pile):
'''returns top brick of either pile'''
return brick_pile.pop(0)
def deal_initial_bricks(main_pile):
'''appends bricks to each players tower from the main pile then returns both towers as a tuple'''
computer_tower = []
human_tower = []
for n in range(10):
computer_tower.append(get_top_brick(main_pile))
human_tower.append(get_top_brick(main_pile))
human_tower.reverse()
computer_tower.reverse()
return computer_tower, human_tower
def add_brick_to_discard(brick, discard):
'''inserts discarded brick to discard pile'''
discard.insert(0, brick)
def find_and_replace(new_brick, brick_to_be_replaced, tower, discard):
'''finds the brick player wants to replace if it is in the tower then replace it with the brick player wants. After adds brick to be replaced to discard'''
if brick_to_be_replaced in tower:
i = tower.index(brick_to_be_replaced)
tower[i] = new_brick
add_brick_to_discard(brick_to_be_replaced, discard)
return True
else:
return False
def computer_play(tower, main_pile, discard): # my function will check if the main_pile
'''basically my computer for the first 30 turns checks if a number is greater then a determined number by me.
It then iterates through the positions backwards for 5-9 and determines if that number is larger then the number in those given positions'''
### Summary of my strategy. Read below comments for break down of each if/elif statement. Basically this will look
###if a number is greater then the value in positions 9-5. Because if it is greater then the block at that location
### then its a more stable piece. through this it will set a strong base and replace smaller number blockes one at a time
###iterating through the positions. Making sure the block above it will not be greater then the block below
### For the 1-4 positions we do the opposite. If a block is smaller then the first position we replace it.
###If it is not we go to the next block to see if it is smaller. This will ensure a ascending tower(towards the base)
### We want to do that for the first 30 turns(15 per player) because this will set a good general tower. See the else statement for next part of stratergy.
global turn_count
print(' It is the computer turn! ', tower)
if turn_count < 30: # my computer play if it is under turn 30 it will follow the below formula
if discard[
0] > 45: # if the top discarded brick is greater then 45 it will iterate backwards form 9 to 7. If the brick is greater then them it will replace the first one it is greater then
for n in range(9, 6, -1):
if discard[0] > tower[n]:
discardBrick = get_top_brick(discard)
find_and_replace(discardBrick, tower[n], tower, discard)
turn_count += 1
break
elif discard[
0] > 30: # if the top discarded brick is greater then 30 it will iterate from 6 and 5 as index for the tower. Same as above if it is greater it will replace the given brick.
for n in range(6, 4, -1):
if discard[0] > tower[n]:
discardBrick = get_top_brick(discard)
find_and_replace(discardBrick, tower[n], tower, discard)
turn_count += 1
break
elif discard[
0] > 15: # if the brick is greather then 15 it will iterate through 3 and 4 as index for tower and if it is less then the brick at that location it will repalce
for n in range(3, 5):
if discard[0] < tower[n]:
discardBrick = get_top_brick(discard)
find_and_replace(discardBrick, tower[n], tower, discard)
turn_count += 1
break
elif discard[0] > 0 and discard[
0] < 16: # Same as above. For the given range iterate through 0,1,2 if it is less it will replace.
for n in range(0, 3):
if discard[0] < tower[n]:
discardBrick = get_top_brick(discard)
find_and_replace(discardBrick, tower[n], tower, discard)
turn_count += 1
break
else: # if the brick did not meet any of the conditions above we will come to this statement. Here we will iterate through 1-9 to see where does the tower hit a snag.
for n in range(9): # When the brick is bigger then the brick following it we go to the elif statement.
if tower[n] < tower[n + 1]:
continue
elif main_pile[0] < tower[
n]: # If the main pile brick is less then the out of position brick. we simply replace that with the smaller one.
mainBrick = get_top_brick(main_pile)
find_and_replace(mainBrick, tower[n], tower, discard)
else:
add_brick_to_discard(main_pile.pop(0), discard)
else:
###The second part of the stratergy is that after 30 turns we will look to better optimize the individual blocks of the tower
###So we check if the tower is ascending in block numbers through a for loop. When we hit a snag where the pervious block is greater then the next blocks
###we willl test to see if the discard block is less then the tower location and if it is also greater then the previous position
###if those conditions arn't met we see if the discard is bigger then the current posotion(n). If it is we check to see if it is less then the next next position(n+2)
###if it is we will put that block in. This catches the case where a small number is caught in between 2 correct blocks.
###Stratergy basically stays the same for main_pile
for n in range(9):
if tower[n] < tower[n + 1]:
continue
else:
if discard[0] < tower[n] and discard[0] > tower[n - 1]:
discardBrick = get_top_brick(discard)
find_and_replace(discardBrick, tower[n], tower, discard)
break
elif discard[0] > tower[n] and discard[0] > tower[n + 1] and discard[0] < tower[n + 2]:
discardBrick = get_top_brick(discard)
find_and_replace(discardBrick, tower[n + 1], tower, discard)
break
elif main_pile[0] < tower[n] or main_pile[0] > tower[n] and main_pile[0] < tower[n + 2]:
mainBrick = get_top_brick(main_pile)
find_and_replace(mainBrick, tower[n], tower, discard)
break
def user_play(tower, main_pile, discard):
'''used in combination with ask_yes_or_no to prompt user input if they want to use discard brick. If so ask which brick they want to replace with.
Does the same for main pile brick. Then uses find and replace function to replace that block'''
print('top discarded brick:', discard[0])
print('your current tower:', tower)
global turn_count
if ask_yes_or_no('do you want to use the top discard block?(Y/N)'): # asks if they want to use top discarded brick
discardBrick = get_top_brick(discard) # gets top brick sets it to a temp variable
brickNum = brick_number() # asks what brick number they want to change
valid = False # temp variable
while valid == False: # while it is false we try to find and replace the input. If it works we return True for valid and breaks the loop.
valid = find_and_replace(discardBrick, brickNum, tower, discard)
if valid == False:
print('Please Enter a Valid Brick')
brickNum = brick_number()
turn_count += 1
else:
print('top main pile brick:', main_pile[0])
if ask_yes_or_no('do you want to use the top main brick?(Y/N)'):
mainBrick = get_top_brick(main_pile)
brickNum = brick_number()
valid = False
while valid == False:
valid = find_and_replace(mainBrick, brickNum, tower, discard)
if valid == False:
('Please Enter a Valid Brick')
brickNum = brick_number()
turn_count += 1
print('you replaced', brickNum)
else:
mainBrick = get_top_brick(main_pile)
add_brick_to_discard(mainBrick, discard)
print('you have ended your turn')
turn_count += 1
def brick_number():
'''prompts user for brick number they want to replace with either discarded or main pile brick. Checks if its between 1 and 60. Also catches errors if they input a not int type'''
while True:
num = input('What number do you want to replace?')
try: # while loop to see if the input is integers
if 1 <= int(num) < 61:
return int(num)
break
else:
print('please enter a valid response')
except:
print('please enter a valid response')
def ask_yes_or_no(prompt):
'''While loop asking for player input. If player inputs a string starting with y it returns True. If player inputs
a string starting with n it returns False. Else we print a message'''
while True:
a = input(prompt).lower() # asks for user input and puts it into lower case
try: # while loop to see if the first letter starts with y or n. In order to return True or False
if a[0] == 'y':
return True
break
elif a[0] == 'n':
return False
else:
print('please enter a valid response')
except:
print('please enter a valid response')
def main():
playing = True
brick_pile = setup_bricks()
main_bricks = brick_pile[0]
discarded_bricks = brick_pile[1]
shuffle_bricks(main_bricks)
towers = deal_initial_bricks(main_bricks)
computer_tower = towers[0]
human_tower = towers[1]
first_brick = get_top_brick(main_bricks)
add_brick_to_discard(first_brick, discarded_bricks)
while playing == True:
print(discarded_bricks)
computer_play(computer_tower, main_bricks, discarded_bricks)
print('This is computer tower now', computer_tower)
playing = check_tower_blaster(computer_tower)
if playing == False:
print('COMPUTER WINS!!!!')
continue
check_bricks(main_bricks, discarded_bricks)
print(discarded_bricks)
user_play(human_tower, main_bricks, discarded_bricks)
playing = check_tower_blaster(human_tower)
if playing == False:
print('HUMAN WINS!!!!')
continue
check_bricks(main_bricks, discarded_bricks)
print(discarded_bricks)
if __name__ == "__main__":
main()
|
a37130786c5c2843c24c631a50f50252f46d6038 | wenima/codewars | /kyu4/Python/src/holdem.py | 2,473 | 3.78125 | 4 | """Solution for https://www.codewars.com/kata/texas-holdem-poker/python."""
from collections import Counter, defaultdict
from operator import itemgetter
CARDS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
class PokerHand(object):
def __init__(self, hand):
self.values = sorted([CARDS.index(c) for c in hand], reverse=True)
self.val_cnt = defaultdict(int)
for card in self.values:
self.val_cnt[card] += 1
self.groups = sorted(self.val_cnt.items(), key=itemgetter(1, 0), reverse=True)
@property
def score(self):
points = 0.0
if self._is_straight:
points += 7
cards = 0
for k, v in self.groups:
if cards + v > 5: continue
cards += v
points += v ** 2
if cards == 5: return points
@property
def _is_straight(self):
"""Return True if combination of board and hole cards make a straight."""
cards = [k for k in self.val_cnt.keys()]
for x in range(3):
hand = sorted(cards[x:], reverse=True)
if len(hand) < 5: return False
straight = [hand[i] for i in range(4) if hand[i] - 1 == hand[i + 1]]
if len(straight) == 4:
last_card = hand.index(straight[-1]) + 1
straight.append(hand[last_card])
self.values = straight
self.val_cnt = defaultdict(int)
for card in self.values:
self.val_cnt[card] += 1
self.groups = sorted(self.val_cnt.items(), key=itemgetter(1, 0), reverse=True)
return True
return False
def compare_with(self, villain):
"""Return the winner given 2 pokerhand objects or return tie."""
if villain.score > self.score:
return 'B'
elif villain.score < self.score:
return 'A'
else:
for i in range(0, len(self.groups)):
if villain.groups[i][0] > self.groups[i][0]:
return 'B'
elif villain.groups[i][0] < self.groups[i][0]:
return 'A'
return 'AB'
def texasHoldem(board, hole_cards_hero, hole_cards_villain):
"""Return the winning hand given board cards and 2 player's hands."""
hero = PokerHand(board + hole_cards_hero)
villain = PokerHand(board + hole_cards_villain)
return hero.compare_with(villain)
|
d01bb2f5979a27a5effb327f51e40ea9402906fa | wenima/codewars | /kyu4/Python/src/test_next_bigger.py | 846 | 3.609375 | 4 | """Tests for codewars kata https://www.codewars.com/kata/next-bigger-number-with-the-same-digits."""
import pytest
TEST_BIGGEST = [
(9, True),
(111, True),
(531, True),
(123, False),
(9998, True),
(54321, True),
]
TEST_INPUT = [
(999, -1),
(12, 21),
(513, 531),
(2017, 2071),
(12345, 12354),
(54312, 54321),
(414, 441),
(144, 414),
(1234567890, 1234567908),
]
@pytest.mark.parametrize('n, result', TEST_INPUT)
def test_next_bigger(n, result):
"""Test next_bigger returns correct next bigger number."""
from next_bigger import next_bigger
assert next_bigger(n) == result
@pytest.mark.parametrize('n, result', TEST_BIGGEST)
def test_is_biggest(n, result):
"""Test is_biggest returns -1 ."""
from next_bigger import is_biggest
assert is_biggest(n) == result
|
ffd69ed1f0ce038a4e5856193af501b38e3df2db | wenima/codewars | /kyu3/src/sudoku_solver_hard.py | 12,269 | 4.03125 | 4 | """Module to solve the code-kata https://www.codewars.com/kata/sudoku-solver."""
from math import sqrt, ceil
from itertools import islice, chain, groupby
from operator import itemgetter
from collections import defaultdict
def sudoku_solver(m):
"""Return a valid Sudoku for a given matrix.
Store all starting numbers by looping through the Sudoku square by square
Find all missing numbers by subtracting the 2 sets
Generate all starting spots and find the one with the least amount of digits missing
Generate candidates by finding all possible numbers for a given starting point
Pop the starting point from a sorted representation of the previously built list
Update Sudoku if a fit is found
Remove updated digit from all lists of missing number and as a possible candidates
Repeat with next starting point
If no immediate match is found, scrap candidated and rebuild until all digits have been
inserted.
"""
square_sides = int(sqrt(len(m)))
dicts = initialize_dicts(m, square_sides)
dicts, square_coords = populate_dicts(m, square_sides, dicts)
dicts = get_missing(dicts)
candidates = get_candidates(m, dicts, square_coords)
m, candidates = scan_sudoku(m, dicts, square_coords, candidates)
single_candidates = single_candidate(candidates, square_coords, dicts)
m, candidates = fill_fit(m, dicts, square_coords, single_candidates=single_candidates)
candidates = get_candidates(m, dicts, square_coords)
naked_sets_fields_row, naked_sets_fields_cols = find_naked_sets(candidates, dicts, setlength=2)
candidates, naked_sets = remove_naked_sets_from_candidates(candidates, naked_sets_fields_row, naked_sets_fields_cols)
candidates = get_candidates(m, dicts, square_coords, naked_sets)
naked_sets_fields_row, naked_sets_fields_cols = find_naked_sets(candidates, dicts, setlength=3)
return m
def initialize_dicts(m, square_sides):
"""Return dicts to hold information about the Sudoku."""
rows_missing = defaultdict(list)
rows_missing = initialize_d(rows_missing, square_sides)
cols_missing = defaultdict(list)
cols_missing = initialize_d(cols_missing, square_sides)
squares_missing = defaultdict(list)
squares_missing = initialize_d(cols_missing, square_sides, 1)
return rows_missing, cols_missing, squares_missing
def initialize_d(d, square_sides, offset=0):
"""Return an initialized dict so empty rows or columns in the Sudoku are
correctly handled."""
return {key:[] for key in range(offset, square_sides ** 2 + offset)}
def fill_given_numbers(square, row, col, sq_nr, dicts, squares_coords):
"""Fill dicts with given numbers number for a given square."""
rm, cm, sm = dicts
sq = squares_coords
for row_idx, sr in enumerate(square):
for col_idx, sv in enumerate(sr):
coord = (row + row_idx, col + col_idx)
if sv == 0:
sq[coord] = sq_nr
continue
rm[coord[0]].append(sv)
cm[coord[1]].append(sv)
sm[sq_nr].append(sv)
return dicts, sq
def populate_dicts(m, square_sides, dicts):
"""Return dicts holding information about fills in given Sudoku."""
sq_nr = 0
squares_coords = {}
for row in range(0, square_sides ** 2, square_sides):
for col in range(0, square_sides ** 2, square_sides):
sq_nr += 1
square = [islice(m[i], col, square_sides + col) for i in range(row, row + square_sides)]
dicts, square_coords = fill_given_numbers(square, row, col, sq_nr, dicts, squares_coords)
return dicts, square_coords
def get_missing(dicts):
"""Return dictionaries with swapped values from given numbers to missing numbers."""
for d in dicts:
for k, v in d.items():
d[k] = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) - set(v)
return dicts
def get_starting_spots(m, dicts, square_coords):
"""Return a list with coordinates as starting point for sudoku solver."""
rm, cm, sm = dicts
starting_spots = []
row = 0
col = 0
max = 20
start = -1
for col in range(9):
for row in range(9):
if m[row][col] == 0:
square = square_coords[(row, col)] - 1
missing_numbers = len(cm[col]) + len(rm[row]) + len(sm[1 if square < 1 else square])
starting_spots.append((row, col, missing_numbers))
return starting_spots
def get_candidates(m, dicts, square_coords, naked_sets=None):
"""Return a dict of candidates for all starting_spots in the Sudoko."""
starting_spots = get_starting_spots(m, dicts, square_coords)
starting_spots.sort(key=itemgetter(2))
rm, cm, sm = dicts
c = {}
for coordinate in starting_spots:
row, col, missing = coordinate
c[(row, col)] = [n for n in cm[col] if n in rm[row] and n in sm[square_coords[row, col]]]
try:
c[(row, col)] = [n for n in c[(row, col)] if n not in naked_sets[(row, col)]]
except (KeyError, TypeError):
continue
return c
def find_fit(candidates):
"""Return a tuple with coordinate and value to update from a sorted
representation of a dict. If no fit can be found, return None."""
try:
fit = sorted(candidates.items(), key=lambda x: len(x[1])).pop(0)
except AttributeError:
return None
row, col = fit[0]
n = fit[1].pop()
if len(fit[1]) == 0:
return row, col, n
return None
def update_sudoku(fit, m):
"""Return an updated Sudoku."""
row, col, n = fit
try:
if m[row][col] != 0:
raise ValueError
m[row][col] = n
except ValueError:
raise ValueError('This coordinate has already been updated.')
return m
def remove_updated_from_dicts(fit, dicts, squares_coords):
"""Return dicts with updated digit removed from missing digits."""
row, col, n = fit
rm, cm, sm = dicts
sq = squares_coords
rm[row].remove(n)
cm[col].remove(n)
sm[squares_coords[row, col]].remove(n)
del sq[(row, col)]
return dicts
def remove_from_candidates(fit, candidates):
"""Return candidates with updated digit removed from all coordinates."""
if not candidates: return candidates
row, col, n = fit
del candidates[(row, col)]
for k, v in candidates.items():
if k[0] == row or k[1] == col:
try:
v.remove(n)
except:
continue
return candidates
def fill_fit(m, dicts, squares_coords, candidates=[], single_candidates=[]):
"""Return an updated Sudoku by either finding a fit or taking a fit from a provided
list of fits and filling it in as long as a fit is found."""
while True:
try:
if single_candidates:
num, coord = single_candidates.pop()
fit = (coord[0], coord[1], num)
else:
fit = find_fit(candidates)
# print("fit: ", fit)
except IndexError:
return m, candidates
if fit:
m = update_sudoku(fit, m)
dicts = remove_updated_from_dicts(fit, dicts, squares_coords)
candidates = remove_from_candidates(fit, candidates)
else:
return m, candidates
def scan_sudoku(m, dicts, square_coords, candidates):
"""Return an updated Sudoku by using the scanning technique to find fits and
filling them in. After each scan, list of candidates is rebuild until no
further immediate fills are possible."""
while True:
if len(sorted(candidates.items(), key=lambda x: len(x[1])).pop(0)[1]) > 1: # no longer easily solvable
break
m, candidiates = fill_fit(m, dicts, square_coords, candidates=candidates)
starting_spots = get_starting_spots(m, dicts, square_coords)
starting_spots.sort(key=itemgetter(2))
candidates = get_candidates(m, dicts, square_coords)
if not candidates: break
return m, candidates
def squares_to_missing(square_coords):
"""Return a dict of square numbers as key and empty fields in the Sudoku as values."""
squares_missing = defaultdict(list)
for k, v in square_coords.items():
squares_missing[v].append(k)
return squares_missing
def single_candidate(candidates, square_coords, squares_missing):
"""Return a number which is a single candidate for a coordinate in the list of candidates:
Build a dict with square as key and empty fields as value
Go through every square and get all missing fields
For every missing field in that square, get the possible numbers
Look for a number which is only missing in one field in a square."""
out = []
coords_missing_in_square = squares_to_missing(square_coords)
for k, v in coords_missing_in_square.items():
single_candidates = defaultdict(list)
seen = set()
for coord in v:
pn = set(candidates[coord])
if pn.issubset(seen):
continue
for n in pn:
if n in seen:
continue
if single_candidates.get(n, 0):
seen.add(n)
continue
single_candidates[n] = coord
if len(seen) == len(squares_missing[k]):
continue
out.append([(k, v) for k, v in single_candidates.items() if k not in seen])
return list(chain.from_iterable(out))
def find_naked_sets(candidates, dicts, setlength=2):
"""Return a dict of naked sets mapped to coordinates. A naked set is a set of numbers
which are the only possible values for fields along a row or column."""
c = candidates
ns = build_possible_naked_sets(c, setlength=setlength)
cpns = build_coords_per_naked_set(ns)
ns = update_naked_set(ns, cpns)
rows = get_coords_naked_sets(ns, candidates, dicts, row_or_col=0, setlength=setlength)
cols = get_coords_naked_sets(ns, candidates, dicts, row_or_col=1, setlength=setlength)
return rows, cols
def build_possible_naked_sets(c, setlength=2):
"""Return a dict with coordinates and possible values with length of setlength, 2 by default."""
ns = {}
pairs = [p for p in c.values() if len(p) == setlength]
for k, v in c.items():
if v in pairs:
ns[k] = sorted(v)
return ns
def build_coords_per_naked_set(ns):
"""Return a new dict with inverted values from ns"""
cpns = defaultdict(list)
for pair in ns.values():
if cpns.get(tuple(pair), 0): continue
for k, v in ns.items():
row, col = k
if v == pair:
cpns[tuple(pair)].append(k)
return cpns
def update_naked_set(ns, cpns):
"""Return an updated dict of naked set."""
for k, v in cpns.items():
if len(v) == 1:
del ns[v.pop()]
else:
if len(set(v)) < 3:
for coord in set(v):
del ns[coord]
return ns
def get_coords_naked_sets(ns, candidates, dicts, row_or_col=0, setlength=2):
"""Return a list of coordinates where naked sets can be removed from."""
c = candidates
rm, cm, sm = dicts
group = []
out = {}
ns_sorted = {el[0]:el[1] for el in sorted(ns.items(), key=lambda x: x[0])}
for k, g in groupby(ns_sorted, lambda x: x[row_or_col]):
coords = list(g)
key = tuple(ns[coords[0]])
if len(coords) > 1: #if list has only one element, there are no naked sets for that key
if len(cm[k] if row_or_col == 1 else rm[k]) > setlength: #check missing row or col dict to see if more than given setlength is missing
out[key] = [coord for coord in c.keys() if coord[row_or_col] == k and coord not in coords]
return out
def remove_naked_sets_from_candidates(c, *args, naked_sets=defaultdict(list)):
"""Return an updated list of candidates and naked sets after removing possible numbers by looking at naked sets"""
for d in args:
for k, v in d.items():
for coord in v:
c[coord] = [n for n in c[coord] if n not in k]
naked_sets[coord].extend(list(k))
return c, dict(naked_sets)
|
e88fde32a4ed8daa66714905a4d258032ec9a473 | wenima/codewars | /kyu5/python/src/best_travel.py | 418 | 3.625 | 4 | """Module to solve the code-kata https://www.codewars.com/kata/best-travel/train/python."""
from itertools import combinations
def choose_best_sum(t, k, ls):
"""Return a value closest to, but not great than, t out of a combination of
elements in ls with size k.
"""
best = 0
for c in combinations(ls, k):
if best < sum(c) <= t:
best = sum(c)
return best if best else None
|
9b5b28301d930fefb61ae250b93fe05e7fb34bd8 | wenima/codewars | /kyu5/python/src/prime_factorization.py | 954 | 4 | 4 | """Module to solve https://www.codewars.com/kata/prime-factorization."""
from collections import defaultdict
class PrimeFactorizer(int):
def __init__(self, n):
"""Initialize a Prime object."""
def prime_factors(self):
"""Return a list of prime factors for a given number in ascending order."""
n = self
factors = []
p = 2
if n < 2:
return factors
while n >= (p * p):
if n % p:
p += 1
else:
n = n // p
factors.append(p)
factors.append(n)
return factors
@property
def factor(self):
"""Return a dict where key is the prime and value the number of occurences
in the prime factorization of n."""
prime_factors = PrimeFactorizer.prime_factors(self)
d = defaultdict(int)
for pf in prime_factors:
d[pf] += 1
return dict(d)
|
7c423e6b96739cfdfe456783f34bb3b1d95c7d07 | wenima/codewars | /kyu5/python/src/domain_name.py | 673 | 3.84375 | 4 | """Module to solve the code-kata
https://www.codewars.com/kata/extract-the-domain-name-from-a-url-1/train/python.
This is just a proof of concept/prototype. The correct solution covering all
domain names as well as private domains is alot more complicated. It would
involve getting the current viable top-level domains and parse the url looking
up valid domains under the TLD.
For example http://ag.utah.gov/ won't be found with the approach taken below.
"""
import re
def domain_name(url):
"""Return the domain name of the url."""
pattern = r'^(?:http(?:s?)://)?(?:www\.)?(.*?)\.(?:[a-z.-])'
m = re.match(pattern, url)
return m.group(1) if m else None
|
e900d08e1f44c4ca6fa0a6a451bc9d379e346c1a | SwierkKlaudia/python | /basics/lists.py | 11,112 | 3.734375 | 4 | # 1
def L1(elements):
sum_elem = 0
for list_elem in elements:
sum_elem += list_elem
return sum_elem
print("L1:",L1([1, 4, 19]))
# 2
def L2(elements):
mult_elem = 1
for list_elem in elements:
mult_elem *= list_elem
return mult_elem
print("L2:",L2([1, 4, 19]))
# 3
def L3(elements):
larg_numb = 0
for list_elem in elements:
if list_elem > larg_numb:
larg_numb = list_elem
return larg_numb
print("L3:",L3([1, 4, 19, 12, 3]))
# 5
def L4(strings):
count_str = 0
for list_str in strings:
if len(list_str) > 4 and list_str[0] == list_str[-1]:
count_str += 1
return count_str
print("L4:",L4(['abh','qwerrtyuyq','abba','qazzaq','poilp','qwertyu','asdas']))
# 6
def L5(tuples):
def keysort(n):
return n[1]
tuples.sort(key = keysort)
return tuples
print("L5:",L5([(1,4), (3,3), (14,15), (12,1)]))
# 7
def L6(strings):
no_duplic = []
for list_str in strings:
if list_str not in no_duplic:
no_duplic += [list_str]
return no_duplic
print("L6:",L6(['abh','qwertyu','abba','qazzaq','qwertyu','abba','poilp']))
# 10
def L7(strings, N):
Nlength_list = []
for list_str in strings:
if len(list_str) >= N:
Nlength_list += [list_str]
return Nlength_list
print("L7:",L7(['abh','qwerrtyuyq','abba','qazzaq','poilp','qwertyu','asdas'],5))
# 11
def L8(list1,list2):
statement = 'False'
for list_elem in list1:
if list_elem in list2:
statement = 'True'
return statement
print("L8:",L8([1, 4, 19, 12, 3],[1, 14, 19, 123, 31]))
# 12
def L9(elements):
numb = [0, 4, 5]
del_str = []
for list_elem in elements:
if list_elem not in numb:
del_str += [list_elem]
return del_str
print("L9:",L9([0, 1, 2, 3, 4, 5, 6, 7]))
# 14
def L10(elements):
del_str = []
for list_elem in elements:
if list_elem % 2 == 1:
del_str += [list_elem]
return del_str
print("L10:",L10([1, 4, 19, 12, 3]))
# 16
def L11(elements):
square_str = []
for list_elem in elements:
list_elem*= list_elem
square_str += [list_elem]
return (square_str[:5],square_str[-5:])
print("L11:",L11(range(1,15)))
# 18
def L12(elements):
permut = []
for i in elements:
for j in elements:
if j != i:
permut.append((i,j))
return permut
print("L12:",L12([1, 2, 3]))
# 19
#diff_str = set(list1) - set(list2)
#return list(diff_str)
def L13(list1,list2):
new_str = []
for elem in list1:
if elem not in list2:
new_str.append(elem)
return new_str
print("L13:",L13([1, 4, 19, 12, 3],[1, 14, 19, 123, 4]))
# 12
def L14(strings):
delet_str = []
numb_delet = [0,4,5]
for (i,x) in enumerate(strings):
if i not in numb_delet:
delet_str += [x]
return delet_str
print("L14:",L14(['zero','first','second','third','fourth','fifth','sixth']))
# 21
def L15(elements):
str_elem = ''.join(elements)
return str_elem
print("L15:",L15(['a','b','c','d']))
# 20
def L16(elements, n):
index_elem = 0
for (i,x) in enumerate(elements):
if x == n:
index_elem = i
return index_elem
print("L16:",L16([0, 1, 12, 43, 46, 53, 6, 7],12))
# 23
def L17(list1, list2):
flat_list = list1
for elem in list2:
flat_list += [elem]
return flat_list
print("L17:",L17([1, 4, 19, 12, 3],[1, 14, 19, 123, 4]))
# 27
def L18(elements):
snd_number = 0
elements.sort()
for (i,x) in enumerate(elements):
if i == 1:
snd_number = x
return snd_number
print("L18:",L18([1, 4, 19, 12, 3, -11, -3]))
# 29
def L19(elements):
new_str = []
for i in elements:
if i not in new_str:
new_str.append(i)
return new_str
print("L19:",L19([1, 4, 19, 12, 1, 12, 55]))
#31
def L20(elements, small, large):
counter = 0
for i in elements:
if i >= small and i <= large:
counter += 1
return counter
print("L20:",L20([1, 4, 19, 12, 1, 13, 55], 4, 12))
#37
def L21(list1, list2):
same_elem = []
for i in list1:
if i in list2:
same_elem.append(i)
return same_elem
print("L21:",L21([1, 4, 19, 12, 3],[1, 14, 19, 123, 4]))
#44
def L22(elements):
group = []
list_group = []
for (i,x) in enumerate(elements):
group.append(x)
if (i+1) % 3 == 0:
list_group.append(group)
group = []
if len(elements) % 3 != 0:
list_group.append(group)
return list_group
print("L22:",L22([1, 4, 19, 12, 3, 14, 191, 123, 43, 11]))
#46
def L23(elements):
new_list = []
for (i,x) in enumerate(elements):
if i % 2 == 0:
new_list.append(x)
return new_list
print("L23:",L23([1, 4, 19, 12, 3, 14, 191, 123, 43, 11]))
#51
def L24(elements,N):
group = []
list_group = []
for (i,x) in enumerate(elements):
group.append(x)
if (i+1) % N == 0:
list_group.append(group)
group = []
if len(elements) % N != 0:
list_group.append(group)
return list_group
print("L24:",L24([1, 4, 19, 12, 3, 14, 191, 123, 43, 11],4))
#56
def L25(string):
new_list = list(string)
return new_list
print("L25:",L25('ELEMENT'))
#63
def L26(list1,string):
for (i,x) in enumerate(list1):
x = string + x
list1[i] = [x]
return list1
print("L26:",L26(['aaa','bbb','ccc','ddd','eee'],'XXX'))
#64
def L27(list1,list2):
new_string = ''
for i in list1:
new_string = new_string + i
for j in list2:
new_string = new_string + j
return new_string
print("L27:",L27(['aaa','bbb','ccc','ddd','eee'],['xxx','yyy','zzz']))
#69
def L28(list1):
new_list = []
for i in list1:
if i not in new_list:
new_list.append(i)
return new_list
print("L28:",L28([[10, 20], [40], [30, 56, 25], [10, 20, 11], [33], [40],[]]))
###
def L29(list1, list2):
statement = 'True'
for (i,x) in enumerate(list1):
if x.lower() != (list2[i]).lower():
statement = 'False'
return statement
print("L29:",L29(['Aaa','bb','cCcd'],['aaa','bb','CCC']))
###
def L30a(list1, list2):
new_list = []
for i in list1:
if i in list2:
new_list.append('...')
else:
new_list.append(i)
return new_list
print("L30a:",L30a(['Aaa','bb','cCc', 'aaa'],['aaa','bb','CCC']))
###
def L30b(list1, list2):
new_list = []
for i in list1:
dots = ''
ctr = 0
if i in list2:
j = len(i)
while ctr < j:
ctr += 1
dots += '.'
new_list.append(dots)
else:
new_list.append(i)
return new_list
print("L30b:",L30b(['Aaa','bb','cCc', 'aaa'],['aaa','bb','CCC']))
###
def L30c(list1, list2):
new_list = []
floor = '_'
def appnd(oldelem,newelem,lists):
if newelem in lists:
new_list.append('...')
else:
new_list.append(oldelem)
return new_list
for i in list1:
if i.endswith('_') == 1 or i.startswith('_') == 1:
j = i.replace('_', '')
appnd(i,j,list2)
else:
appnd(i,i,list2)
return new_list
print("L30c:",L30c(['_Aaa','_bb','cCc', 'aaa'],['aaa','bb','CCC']))
###
def L30d(list1, list2):
new_list = []
for i in list1:
if i not in list2:
new_list.append(i)
return new_list
print("L30d:",L30d(['Aaa','bb','cCc', 'aaa'],['aaa','bb','CCC']))
###
def L31(list1, list2):
new_list = []
indx = -1
new_word = ''
word_len = 0
for i in list1:
word_len = len(i)
for j in list2:
if word_len == 0:
new_word = '?'
elif j.find(i) != -1:
indx = j.find(i)
new_word = j[(word_len+1):]
if indx != -1:
new_list.append(new_word)
indx = -1
else:
new_list.append('?')
return new_list
print("L31:",L31(['kot','pies','kon',''],['pies:dog','kot:cat','dom:house']))
###
def L32a(listA, animal, plant, unit):
new_list = []
for elem in listA:
if elem in animal:
new_list.append(elem + ':animal')
elif elem in plant:
new_list.append(elem + ':plant')
elif elem in unit:
new_list.append(elem + ':unit')
else:
new_list.append(elem)
return new_list
print("L32a:",L32a(['kilogram','mouse','tree','stone'],['dog','cat','mouse'],['tree','grass','flower'],['meter','kilogram','newton'],))
###
def L32b(listA, animal, mammal, pet):
new_list = []
for elem in listA:
if elem in animal:
if elem in mammal:
new_list.append(elem + ':animal:mammal')
elif elem in pet:
new_list.append(elem + ':animal:pet')
else:
new_list.append(elem + ':animal')
elif elem in mammal:
new_list.append(elem + ':mammal')
elif elem in pet:
new_list.append(elem + ':pet')
else:
new_list.append(elem)
return new_list
print("L32b:",L32b(['horse','stone','frog'],['dog','horse','frog'],['horse','dog'],['cat']))
###
def L33(list1):
new_list = []
counter = 0
new_elem = []
for elem in list1:
counter = list1.count(elem)
new_elem = [elem,counter]
if new_elem not in new_list:
new_list.append(new_elem)
return new_list
print("L33:",L33(['pies','kot','kot','zaba','kon','kon','kon','panda']))
###
def L34(string1):
new_list = string1.split(' ')
for (i,x) in enumerate(new_list):
if not x.isalpha():
new_list[i] = f'<b>{x}</b>'
new_str = ' '.join(new_list)
return new_str
print("L34:",L34('Lczba 7 dzielona przez 2 daje liczbe 3.5 a 1 przez 8 daje liczbe 0.128'))
###
def L35(string1):
numbers_float = []
precisions = []
new_list = string1.split(' ')
for (i,x) in enumerate(new_list):
if not x.isalpha():
precisions.append(len(x) - x.find('.') - 1)
numbers_float.append([i,float(x)])
for [n,flt] in numbers_float:
new_list[n] = f'{flt:.{min(precisions)}f}'
new_str = ' '.join(new_list)
return new_str
print("L35:",L35('ala 1.23456 ma 12.3456 kota 123.456'))
###
def L36(string1):
numbers_i = []
numbers = []
new_list = string1.split(' ')
for (i,x) in enumerate(new_list):
if not x.isalpha():
numbers_i.append([i,float(x)])
numbers.append(float(x))
for [n,flt] in numbers_i:
if flt == max(numbers):
new_list[n] = f'<font color=\'red\'>{flt}</font>'
elif flt == min(numbers):
new_list[n] = f'<font color=\'green\'>{flt}</font>'
new_str = ' '.join(new_list)
return new_str
print("L36:",L36('1 dzielone przez 8 daje 0.128 a 7 dzielone przez 2 daje 3.5'))
|
02bebd11b10ef4d17d530355ec86707b9057900e | ijazali5555/my-project | /loops.py | 89 | 3.5625 | 4 | for i in range (1, 10+1):
print (i)
print("Hello")
for i in range (10):
print(i)
|
dcfe8eb511f4b1a89852df183bb01fcd35d9d924 | sxhmilyoyo/Algorithm_Python | /topologicalSort.py | 1,325 | 3.53125 | 4 | class DirectedgraphNode():
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution():
def dfs(self, i, countrd, ans):
ans.append(i)
countrd[i] -= 1
for j in i.neighbors:
countrd[j] = countrd[j] - 1
if countrd[j] == 0:
self.dfs(j, countrd, ans)
def topoSort(self, graph):
countrd = {}
for v in graph:
countrd[v] = 0
for v in graph:
for nbr in v.neighbors:
#print nbr
countrd[nbr] += 1
ans = []
for i in graph:
if countrd[i] == 0:
self.dfs(i, countrd, ans)
return ans
n0 = DirectedgraphNode(0)
n1 = DirectedgraphNode(1)
n2 = DirectedgraphNode(2)
n3 = DirectedgraphNode(3)
n4 = DirectedgraphNode(4)
n5 = DirectedgraphNode(5)
n6 = DirectedgraphNode(6)
n7 = DirectedgraphNode(7)
n8 = DirectedgraphNode(8)
n0.neighbors.append(n3)
n1.neighbors.append(n3)
n2.neighbors.append(n3)
n3.neighbors.append(n4)
n3.neighbors.append(n8)
n4.neighbors.append(n6)
n5.neighbors.append(n4)
n6.neighbors.append(n7)
n8.neighbors.append(n7)
g = [n0 ,n1, n2, n3, n4, n5, n6, n7, n8]
s = Solution()
for i in s.topoSort(g):
print i.label
#print s.topoSort(g)
|
72c683ad118af4ccde4a1b82886052c2e1a06046 | sxhmilyoyo/Algorithm_Python | /parseMathExprTree.py | 2,143 | 3.671875 | 4 | from Tree import *
from Stack import *
import operator
def parseTree(expr):
exprList = expr.split()
r = Tree('')
s = Stack()
s.push(r)
currentTree = r
for i in exprList:
if i == '(':
currentTree.inserLeft('')
s.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i not in ['+', '-', '*', '/', ')']:
currentTree.setRootValue(int(i))
currentTree = s.pop()
elif i in ['+', '-', '*', '/']:
currentTree.setRootValue(i)
currentTree.inserRight('')
s.push(currentTree)
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = s.pop()
else:
raise ValueError
return r
pt = parseTree("( ( 10 + 5 ) * 3 )")
print pt.getRootValue()
def evaluate(parseTree):
opers = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
currentTree = parseTree
left = currentTree.getLeftChild()
right = currentTree.getRightChild()
if left and right:
fn = opers[currentTree.getRootValue()]
return fn(evaluate(left), evaluate(right))
else:
return currentTree.getRootValue()
print evaluate(pt)
def evaluatePostOrder(tree):
opers = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
if tree:
left = evaluatePostOrder(tree.getLeftChild())
right = evaluatePostOrder(tree.getRightChild())
if left and right:
return opers[tree.getRootValue()](left, right)
else:
return tree.getRootValue()
print evaluatePostOrder(pt)
def printMathExpr(tree):
sVal = ''
if tree and tree.getLeftChild() and tree.getRightChild():
sVal = '(' + printMathExpr(tree.getLeftChild())
sVal += str(tree.getRootValue())
sVal += printMathExpr(tree.getRightChild()) + ')'
elif tree:
sVal = printMathExpr(tree.getLeftChild())
sVal += str(tree.getRootValue())
sVal += printMathExpr(tree.getRightChild())
return sVal
print printMathExpr(pt)
|
ee72d040abf29e921923c49602687d93fb4ae955 | sxhmilyoyo/Algorithm_Python | /test.py | 2,256 | 3.546875 | 4 | def recMinCoin(availableCoins, money):
# baseline: use the penny
minNumber = money
# subproblems
# recMinCoin(money-i)
if money in availableCoins:
return 1
# choices
else:
for i in [c for c in availableCoins if c <= money]:
# recursive
number = recMinCoin(availableCoins, money-i) + 1
# topo order: from the i to money
# base case: money == i, return 1
if number < minNumber:
minNumber = number
return minNumber
#a = [1,5,10,25]
#print recMinCoin(a, 63)
# Memorization
def recMinCoin(availableCoins, money, moneyList):
# baseline: use the penny
minNumber = money
# subproblems
# recMinCoin(money-i)
if money in availableCoins:
moneyList[money] = 1
return 1
# choices
elif moneyList[money] > 0:
return moneyList[money]
else:
for i in [c for c in availableCoins if c <= money]:
# recursive
number = recMinCoin(availableCoins, money-i, moneyList) + 1
# topo order: from the i to money
# base case: money == i, return 1
if number < minNumber:
minNumber = number
moneyList[money] = minNumber
return minNumber
#a = [1,5,10,25]
#b = [0] * 64
#print recMinCoin(a, 63, b)
# dp
def recMinCoin(availableCoins, money, moneyList, usedCoinList):
# subproblems
# recMinCoin(money-i)
# topo orderL from 0 to money
for j in range(1, money+1):
# baseline
minNumber = j
usedCoin = 1
# choices
for i in [c for c in availableCoins if c <= minNumber]:
# recursive
number = moneyList[j-i] + 1
# topo order: from the i to money
# base case: money == i, return 1
if number < minNumber:
minNumber = number
usedCoin = i
moneyList[j] = minNumber
usedCoinList[j] = usedCoin
return moneyList
typeCoins = [1,5,10,21,25]
allMoney = [0] * 64
usedCoin = [0] * 64
print(recMinCoin(typeCoins, 63, allMoney, usedCoin))
rest = 63
print usedCoin
while rest > 0:
coin = usedCoin[rest]
print coin
rest = rest - coin
|
3c6dc004885df3bd3ea923b825914c23d1a5e824 | tomaswender/praktic2 | /lesson3/task_7.py | 1,005 | 3.796875 | 4 | #7. В одномерном массиве целых чисел определить два наименьших элемента.
# Они могут быть как равны между собой (оба являться минимальными), так и различаться.
import random
arr=[]
arr2=[0,0,0]
for i in range(30):
arr.append(random.randint(0, 10))
for i in range(0, len(arr)):
if arr[i]>0:
arr2[0], arr2[1]=arr[i], arr[i]
for i in range(0, len(arr)-1):
if arr[i]<arr2[0]:
arr2[0]=arr[i]
arr2[2]=i
arr.pop(arr2[2])
arr2.pop(2)
for i in range(0, len(arr)):
if arr[i]>=arr2[0] and arr[i]<arr2[1]:
arr2[1]=arr[i]
print(arr)
print(arr2)
# Второй вариант
m=100
arr=[]
arr2=[m,m]
for i in range(30):
arr.append(random.randint(0, m))
print(arr)
for i in arr:
if i<arr2[0]:
arr2[1], arr2[0] = arr2[0], i
elif (i<arr2[1] and i>=arr2[0]):
arr2[1]=i
print(arr2)
|
c7bcfb032cb28fd655e128c0438245b08d4b44b6 | tomaswender/praktic2 | /lesson3/task_1.py | 412 | 3.6875 | 4 | #1. В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9.
list1 = []
list2 = {2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
for i in range(2, 100):
list1.append(i)
for n in list1:
for i,y in list2.items():
if n%i==0:
list2[i]=list2[i]+1
print(list2) |
976fa3e3320c3f98d38e73de80a3ca7d37c3ae14 | RinatZialtdinov/Codewars | /ex14/First_nonrepeating_character.py | 371 | 3.640625 | 4 | def first_non_repeating_letter(string):
if len(string) == 0:
return ""
copy_s = list()
for i in string.lower():
if i not in copy_s:
copy_s.append(i)
else:
copy_s.remove(i)
if len(copy_s) == 0:
return ""
if copy_s[0] in string:
return copy_s[0]
else:
return copy_s[0].upper()
|
ad8fcd08ed6d77c4072cf02aa16394ba4d28ecd6 | kaamayao/AlgorithmsUN2021I | /Lab13/2_primitive_calculator/primitive_calculator.py | 899 | 3.515625 | 4 | # Uses python3
import sys
d = {}
def fillCache(cache):
for i in range(1, len(cache)):
min_operation = cache[i-1] + 1
if i % 3 == 0:
min_operation = min(cache[i // 3] + 1, min_operation)
elif i % 2 == 0:
min_operation = min(cache[i // 2] + 1, min_operation)
cache[i] = min_operation
def optimal_operation(n):
cache = [0] * (n + 1)
fillCache(cache)
last_cache_value = cache[-1]
result = [1] * last_cache_value
for i in reversed(range(1, last_cache_value)):
result[i] = n
if cache[n] == cache[n-1]+1:
n -= 1
elif (cache[n] == cache[n // 2]+1) and n % 2 == 0:
n //= 2
else:
n //= 3
return result
input = sys.stdin.read()
n = int(input)
sequence = list(optimal_operation(n))
print(len(sequence) - 1)
for x in sequence:
print(x, end=' ')
|
44909bca4f4dfb10a59c009503d9fca298f80155 | Amoghk18/AI_1BM18CS014 | /tic-tac-toe.py | 5,859 | 3.640625 | 4 | import random
import time
def printBoard(board):
print()
print("----------------------- Board ----------------------------")
print()
print()
for i in range(3):
print(" ", end="")
for j in range(3):
print(" " + str(board[i][j]) + " ", end="")
if j != 2:
print("|", end="")
print()
if i != 2:
print(" __+___+__ ")
print()
print()
print("----------------------------------------------------------")
def insertToBoard(pos, board, user, unoccupied):
row = pos // 3
col = pos % 3
if board[row][col] == 0:
board[row][col] = user
unoccupied.remove(pos)
return 0
else:
return -1
def getEmptyCells(board):
return [(i, j) for i in range(3) for j in range(3) if board[i][j] == 0]
def minimax(board, depth, isMaximizing, user, scoreLookup):
result = checkWinner(user, board)
if result != None:
return scoreLookup[result]
emptyCells = getEmptyCells(board)
if len(emptyCells) == 0:
return 0
if isMaximizing:
bestScore = -2000000
for empty in emptyCells:
board[empty[0]][empty[1]] = 9
score = minimax(board, depth+1, not isMaximizing, user, scoreLookup)
board[empty[0]][empty[1]] = 0
bestScore = max(score, bestScore)
return bestScore
else:
bestScore = 2000000
for empty in emptyCells:
board[empty[0]][empty[1]] = user
score = minimax(board, depth+1, not isMaximizing, user, scoreLookup)
board[empty[0]][empty[1]] = 0
bestScore = min(score, bestScore)
return bestScore
def makeMove(board, unoccupied, user):
# randPos = random.choice(unoccupied)
# board[randPos // 3][randPos % 3] = 9
# unoccupied.remove(randPos)
# print()
# print("Computer chooses to insert at position " + str(randPos + 1))
# print()
emptyCells = getEmptyCells(board)
bestMove = (-1, -1)
bestScore = -2000000
scoreLookup = {
user : -1,
9 : 10,
}
for move in emptyCells:
board[move[0]][move[1]] = 9
score = minimax(board, 0, False, user, scoreLookup)
board[move[0]][move[1]] = 0
if score > bestScore:
bestScore = score
bestMove = move
board[bestMove[0]][bestMove[1]] = 9
unoccupied.remove((bestMove[0] * 3) + bestMove[1])
def rowCheck(board, user):
for i in range(3):
if len(set(board[i])) == 1:
if board[i][0] == user:
return user
return -1
def colCheck(board, user):
for i,j,k in zip(board[0], board[1], board[2]):
if len(set([i,j,k])) == 1:
if i == user:
return user
return -1
def diaCheck(board, user):
dia1 = board[0][0] == board[1][1] and board[1][1] == board[2][2]
if dia1 == True:
if board[0][0] == user:
return user
dia2 = board[0][2] == board[1][1] and board[1][1] == board[2][0]
if dia2 == True:
if board[0][2] == user:
return user
return -1
def runCheck(board, user):
if rowCheck(board, user) == user:
return user
if colCheck(board, user) == user:
return user
if diaCheck(board, user) == user:
return user
return -1
def checkWinner(user, board):
for i in [user, 9]:
if runCheck(board, i) == i:
return i
def startGame():
print()
print()
print(" Welcome to Tic-Tac-Toe")
board = [[0 for _ in range(3)] for _ in range(3)]
print(" Here is your Board")
time.sleep(1)
printBoard(board)
print("Enter the your Identifier(Must Be a Number other than 9, computer is 9)")
user = int(input("Your Identifier : "))
print("Your identifier is : " + str(user))
print()
print("Let the game Begin!!!!!!!")
print()
winner = 0
count = 0
unoccupied = [i for i in range(9)]
while winner not in [user, 9] and unoccupied:
time.sleep(1)
print()
print("------------------- Make the move -------------------")
print("Enter the position in which you want to put your Identifier")
pos = int(input("Position on the board(1-9) : "))
print()
print("You choose to insert at position " + str(pos))
if insertToBoard(pos-1, board, user, unoccupied) == -1:
print()
print("SORRY!!!")
print("You cannot insert in a position where you/computer have already inserted \n (Hint : Choose a different position which is empty)")
print("Board remains the same")
print()
continue
count += 1
print()
print("Board after insertion by you is : ")
printBoard(board)
time.sleep(2)
print()
if count >= 3:
winner = checkWinner(user, board)
if winner in [user, 9] or unoccupied == []:
break
print("Now computer will make the move")
makeMove(board, unoccupied, user)
print("Board after insertion by computer is : ")
printBoard(board)
time.sleep(2)
if count >= 3:
winner = checkWinner(user, board)
if winner == user:
print(" Congratulations!!!")
print(" You Won!")
elif winner == 9:
print(" Better Luck Next Time :)")
print(" Computer Won!")
else:
print(" Try Harder Next Time!!!")
print(" It's a Draw!")
startGame() |
3c4eb1005c04b680331f97fcfb3f09e45b0b7c3d | beng0/my_python_leaning | /t01/practice.py | 2,440 | 3.640625 | 4 | #coding=utf-8
# num = 2
# if num%2 == 0:
# print '{}是偶数'.format(num)
# if num%2 == 1:
# print '%d是奇数'%(num)
# str = 'hello'
# flag = False
# list = ['apple','pear','helloo']
# for n in range(len(list)):
# if list[n] == str:
# print '有这个数了'
# flag = True
# break
# if flag == False:
# list.append(str)
# print list
#
'''
dict1 = {"apple":18,"pear":16,"orange":10}
fruit = raw_input("请输入一种水果:")
if dict1.has_key(fruit):
print '这个水果%d元'%(dict1[fruit])
else:
print '没有这种水果'
'''
# print '哈哈'
# num1 = 2.3
# print type(num1)
# str1 = raw_input('请输入:')
# if str1.isdigit() == True:
# if type(str1) == "<type 'float'>":
# print "这个数是浮点数"
# else:
# print "不是浮点数"
# l = []
# for i in range(1,100):
# if i % 2 == 1:
# l.append(i)
# print l
# for i in enumerate([1,2,3]):
# print i
# 鸡兔同笼
# 鸡i只,兔j只
# for i in range(35):
# for j in range(35):
# if i+j == 35 and i*2+j*4 == 94:
# print '鸡%d只,兔%d只'%(i,j)
# break
# 直接排序
# l = [8,0,3,9,4,2,7,1]
# for i in range(len(l)):
# index = i
# for j in range(i,len(l)-1):
# if l[index]>l[j+1]:
# index = j+1
# l[i],l[index] = l[index],l[i]
# print l
# 冒泡排序
# l = [8,0,3,9,4,2,7,1]
# for i in range(len(l)-1):
# for j in range(len(l)-1-i):
# if l[j]>l[j+1]:
# l[j],l[j+1] = l[j+1],l[j]
# print l
# import math
# for i in xrange(1,100):
# total = 8*2**i
# if total >=8848000:
# print i
# break
# 假设买公鸡n只,母鸡m只,小鸡l只
# t = 0
# for n in range(50):
# for m in range(100):
# for l in range(200):
# if 2*m+n+l/2 == 100 and m!=0 and n!=0 and l!=0 and m+n+l==100:
# # print m,n,l
# t+=1
# print t
# n=0
# for i in range(1900,2019):
# if (i%4==0 and i%100!=0) or i%400 == 0:
# n+=1
# print i
# print n
# 每次弹起的高度为 m,第n次弹起高度为m=100/(2n)
# 第i次弹起的总高度为,t=100*2+(100/(2**i))*2
# h=100
# s=0
# for i in range(0,10):
# s += h*(0.5**i)+h*(0.5**(i+1))
# print h
# # t+=0.097625
#
# print s
# 打印三角形
for i in range(1,5):
print '*'*i
for i in range(1,5):
print ' '*(4-i)+'*'*i+' '*(4-i)+'*'*i
|
c710946ade385e713a64c29018a7d3e6c131d51b | metatoaster/IdleISS | /src/idleiss/battle.py | 15,527 | 3.53125 | 4 | from __future__ import division
import random
import math
from collections import namedtuple
from idleiss.ship import Ship
from idleiss.ship import ShipAttributes
from idleiss.ship import ShipLibrary
SHIELD_BOUNCE_ZONE = 0.01 # max percentage damage to shield for bounce.
HULL_DANGER_ZONE = 0.70 # percentage remaining.
AttackResult = namedtuple('AttackResult',
['attacker_fleet', 'damaged_fleet', 'shots_taken', 'damage_taken'])
Fleet = namedtuple('Fleet',
['ships', 'ship_count'])
RoundResult = namedtuple('RoundResult',
['ship_count', 'shots_taken', 'damage_taken'])
def hull_breach(hull, max_hull, damage,
hull_danger_zone=HULL_DANGER_ZONE):
"""
Hull has a chance of being breached if less than the dangerzone.
Chance of survival is determined by how much % hull remains.
Returns input hull amount if RNG thinks it should, otherwise 0.
"""
damaged_hull = hull - damage
chance_of_survival = damaged_hull / max_hull
return not (chance_of_survival < hull_danger_zone and
chance_of_survival < random.random()) and damaged_hull or 0
def shield_bounce(shield, max_shield, damage,
shield_bounce_zone=SHIELD_BOUNCE_ZONE):
"""
Check whether the damage has enough power to damage the shield or
just harmlessly bounce off it, only if there is a shield available.
Shield will be returned if the above conditions are not met,
otherwise the current shield less damage taken will be returned.
Returns the new shield value.
"""
# really, shield can't become negative unless some external factors
# hacked it into one.
return ((damage < shield * shield_bounce_zone) and shield > 0 and
shield or shield - damage)
def size_damage_factor(weapon_size, target_size):
"""
Calculates damage factor on size. If weapon size is greater than
the target size, then only the area that falls within the target
will the damage be applied.
"""
if weapon_size <= target_size:
return damage
return (target_size ** 2) / (weapon_size ** 2)
def true_damage(damage, weapon_size, target_size, source_debuff, target_debuff):
"""
Calculates true damage based on parameters.
"""
# source_debuffs: tracking disruption
tracking_disrupt = 1 + source_debuff.get('active', {}).get(
'tracking_disruption', 0)
# target_debuffs: target painter, web
target_painter = 1 + target_debuff.get('active', {}).get(
'target_painter', 0)
web = 1 - target_debuff.get('active', {}).get(
'web', 0)
# painters gives > 1 multiplier to the target_size against target
# reason - painters expand the target to make it easier to hit.
# webbers give < 1 multiplier to the weapon_size against target
# reason - weapons can focus more damage on a webbed target
if web == 0 or weapon_size / web * tracking_disrupt <= \
target_size * target_painter:
return damage
true_weapon_size = (weapon_size / web) * tracking_disrupt
true_target_size = target_size * target_painter
damage_factor = size_damage_factor(true_weapon_size, true_target_size)
return int(math.ceil(damage_factor * damage))
def is_ship_alive(ship):
"""
Simple check to see if ship is alive.
"""
# If and when flag systems become advanced enough **FUN** things can
# be applied to make this check more hilarious.
return ship.attributes.hull > 0 # though it can't be < 0
def grab_debuffs(source, target_in):
"""
Retuns a dict of applied debufs calculated from ship schema
as well as ship attributes.
Source is ShipSchema
target_in is a Ship
"""
inactive = {}
sensor_str = target_in.schema.sensor_strength
target = target_in
# I'm sure there's a list comprehension thing that could be used
# to clean this up but I have no idea what
if source.target_painter:
if target.debuffs.get('inactive', {}).get('target_painter', 0) < \
source.target_painter:
inactive['target_painter'] = source.target_painter
if source.tracking_disruption:
if target.debuffs.get('inactive', {}).get('tracking_disruption', 0) < \
source.tracking_disruption:
inactive['tracking_disruption'] = source.tracking_disruption
if source.ECM:
if not target.debuffs.get('inactive', {}).get('ECM', 0):
if sensor_str == 0 or \
random.random() < (float(source.ECM) / sensor_str):
inactive['ECM'] = source.ECM
if source.web:
if target.debuffs.get('inactive', {}).get('web', 0) < source.web:
inactive['web'] = source.web
result = {}
if inactive:
result['inactive'] = inactive
if target.debuffs.get('active'):
result['active'] = target.debuffs.get('active')
return result
def ship_attack(attacker_ship, victim_ship):
"""
Do a ship attack.
Apply the attacker's schema onto the victim_ship as an attack
and return a new Ship object as the result.
"""
if not is_ship_alive(victim_ship):
# save us some time, it should be the same dead ship.
return victim_ship
if attacker_ship.debuffs.get('active', {}).get('ECM', 0) != 0:
# attacker is jammed can't attack or apply debuffs
return victim_ship
debuffs = grab_debuffs(attacker_ship.schema, victim_ship)
if attacker_ship.schema.firepower <= 0:
# damage doesn't need to be calculated, but debuffs do
return Ship(
victim_ship.schema,
ShipAttributes(
victim_ship.attributes.shield,
victim_ship.attributes.armor,
victim_ship.attributes.hull,
),
debuffs,
)
damage = true_damage(attacker_ship.schema.firepower,
attacker_ship.schema.weapon_size,
victim_ship.schema.size,
attacker_ship.debuffs,
victim_ship.debuffs
)
shield = shield_bounce(victim_ship.attributes.shield,
victim_ship.schema.shield, damage)
if shield == victim_ship.attributes.shield:
# it glanced off, don't need to worry about hull breaches when
# the weapon didn't even hit
return Ship(
victim_ship.schema,
ShipAttributes(
victim_ship.attributes.shield,
victim_ship.attributes.armor,
victim_ship.attributes.hull,
),
debuffs,
)
armor = victim_ship.attributes.armor + min(shield, 0)
hull = hull_breach(victim_ship.attributes.hull,
victim_ship.schema.hull, - min(armor, 0))
return Ship(
victim_ship.schema,
ShipAttributes(max(0, shield), max(0, armor), max(0, hull)),
debuffs,
)
def multishot(attacker_schema, victim_schema):
"""
Calculate multishot result based on the schemas.
"""
multishot = attacker_schema.multishot.get(victim_schema.name, 0)
return multishot > 0 and (multishot - 1.0) / multishot > random.random()
def expand_fleet(ship_count, library):
# for the listing of numbers of ship we need to expand to each ship
# having it's own value for shield, armor, and hull
# TO DO: Make sure fleet when expanded is ordered by size
# From smallest to largest to make explode chance and
# shield bounce effects work out properly.
ships = []
for ship_type in ship_count:
schema = library.get_ship_schemata(ship_type)
ships.extend([Ship(
schema, # it's just a pointer...
ShipAttributes(schema.shield, schema.armor, schema.hull),
) for i in range(ship_count[ship_type])])
return Fleet(ships, ship_count)
def prune_fleet(attack_result):
"""
Prune an AttackResult of dead ships and restore shields/armor.
Returns the pruned fleet and a count of ships.
"""
fleet = []
count = {}
damage_taken = 0
for ship in attack_result.damaged_fleet:
if not ship.attributes.hull > 0:
continue
updated_debuffs = {}
if ship.debuffs.get('inactive'):
updated_debuffs['active'] = ship.debuffs.get('inactive')
# switch the inactive debuffs to active and drop current active ones
fleet.append(Ship(
ship.schema,
ShipAttributes(
min(ship.schema.shield,
(ship.attributes.shield + ship.schema.shield_recharge)
),
min(ship.schema.armor,
(ship.attributes.armor + ship.schema.armor_local_repair)
),
ship.attributes.hull,
),
updated_debuffs,
))
count[ship.schema.name] = count.get(ship.schema.name, 0) + 1
return Fleet(fleet, count)
def logi_subfleet(input_fleet):
"""
returns two sub_fleets of logi ships that can rep
[0]: shield
[1]: armor
ships which are jammed this turn are not entered into the list
"""
logi_shield = []
logi_armor = []
for ship in input_fleet:
if ship.debuffs.get('active', {}).get('ECM', 0) != 0:
# can't target to apply repairs
continue
if ship.schema.remote_shield:
logi_shield.append(ship)
if ship.schema.remote_armor:
logi_armor.append(ship)
else:
continue
return [logi_shield, logi_armor]
def repair_fleet(input_fleet):
"""
Have logistics ships do their job and repair other ships in the fleet
"""
logistics = logi_subfleet(input_fleet)
logi_shield = logistics[0]
logi_armor = logistics[1]
if (logi_shield == []) and (logi_armor == []):
return input_fleet
damaged_shield = []
# I have a bad feeling that this function won't last longer
# than a single commit :ohdear:
# also this has a slight bug that ships can rep themselves
# and a ship might get over repped, but that's actually intended
# shield first
for x in xrange(len(input_fleet)):
if input_fleet[x].attributes.shield != input_fleet[x].schema.shield:
damaged_shield.append(x)
if damaged_shield != []:
for ship in logi_shield:
rep_target = random.choice(damaged_shield)
input_fleet[rep_target] = Ship(
input_fleet[rep_target].schema,
ShipAttributes(
min(input_fleet[rep_target].schema.shield,
(input_fleet[rep_target].attributes.shield
+ ship.schema.remote_shield)
),
input_fleet[rep_target].attributes.armor,
input_fleet[rep_target].attributes.hull,
),
input_fleet[rep_target].debuffs,
)
damaged_armor = []
#armor second
for x in xrange(len(input_fleet)):
if input_fleet[x].attributes.armor != input_fleet[x].schema.armor:
damaged_armor.append(int(x))
if damaged_armor != []:
for ship in logi_armor:
rep_target = random.choice(damaged_armor)
input_fleet[rep_target] = Ship(
input_fleet[rep_target].schema,
ShipAttributes(
input_fleet[rep_target].attributes.shield,
min(input_fleet[rep_target].schema.armor,
(input_fleet[rep_target].attributes.armor
+ ship.schema.remote_armor)
),
input_fleet[rep_target].attributes.hull,
),
input_fleet[rep_target].debuffs,
)
return input_fleet
def fleet_attack(fleet_a, fleet_b):
"""
Do a round of fleet attack calculation.
Send an attack from fleet_a to fleet_b.
Appends the hit_by attribute on the victim ship in fleet_b for
each ship in fleet_a.
"""
# if fleet b is empty
if not fleet_b.ships:
return AttackResult(fleet_a, fleet_b.ships, 0, 0)
result = []
result.extend(fleet_b.ships)
shots = 0
damage = 0
for ship in fleet_a.ships:
firing = True
# I kind of wanted to do apply an "attacked_by" attribute to
# the target, but let's wait for that and just mutate this
# into the new ship. Something something hidden running
# complexity when dealing with a list (it's an array).
while firing:
target_id = random.randrange(0, len(result))
result[target_id] = ship_attack(ship, result[target_id])
firing = multishot(ship.schema, result[target_id].schema)
shots += 1
damage = sum((
(fresh.attributes.shield - damaged.attributes.shield) +
(fresh.attributes.armor - damaged.attributes.armor) +
(fresh.attributes.hull - damaged.attributes.hull)
for fresh, damaged in zip(fleet_b.ships, result)))
return AttackResult(fleet_a.ships, result, shots, damage)
class Battle(object):
"""
Battle between two fleets.
To implement joint fleets, simply convert the attackers to a list of
fleets, and create two lists and extend all member fleets into each
one for the two respective sides. Prune them separately for results.
"""
def __init__(self, attacker, defender, rounds, *a, **kw):
self.rounds = rounds
# attacker and defender are dictionaries with "ship_type": number
self.attacker_count = attacker
self.defender_count = defender
self.attacker_fleet = self.defender_fleet = None
self.round_results = []
def prepare(self, library):
# do all the fleet preparation pre-battle using this game
# library. Could be called initialize.
self.attacker_fleet = expand_fleet(self.attacker_count, library)
self.defender_fleet = expand_fleet(self.defender_count, library)
def calculate_round(self):
defender_damaged = fleet_attack(
self.attacker_fleet, self.defender_fleet)
attacker_damaged = fleet_attack(
self.defender_fleet, self.attacker_fleet)
attacker_repaired = repair_fleet(attacker_damaged.damaged_fleet)
defender_repaired = repair_fleet(defender_damaged.damaged_fleet)
defender_results = prune_fleet(defender_damaged)
attacker_results = prune_fleet(attacker_damaged)
# TODO figure out a better way to store round information that
# can accommodate multiple fleets.
self.round_results.append((
RoundResult(attacker_results.ship_count,
attacker_damaged.shots_taken, attacker_damaged.damage_taken),
RoundResult(defender_results.ship_count,
defender_damaged.shots_taken, defender_damaged.damage_taken),
))
self.defender_fleet = defender_results
self.attacker_fleet = attacker_results
def calculate_battle(self):
# avoid using round as variable name as it's a predefined method
# that might be useful when working with numbers.
for r in xrange(self.rounds):
if not (self.defender_fleet.ships and self.attacker_fleet.ships):
break
self.calculate_round()
# when/if we implement more than 1v1 then this will need to change
self.attacker_result = self.round_results[-1][0].ship_count
self.defender_result = self.round_results[-1][1].ship_count
|
ea75860295faafad4a689deb8145f0c822b93910 | ozhatuka/oz | /python_part2B.py | 6,401 | 3.796875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
def find_most_frequent_year(df, n):
'''
:param df: pd.Dataframe
:param n: positive, integer; n'th most frequent year
:return: int; the n'th most frequent year
:raise: ValueError - if n is not a positive int
'''
if isinstance(n, int) == False or n<=0:
raise ValueError("n must be a strictly positive integer (>0)")
return (df['Year'].value_counts(sort=True, ascending=False)).keys()[n-1]
def filterby_criteria(df, criteria):
'''
The function filters all rows that do not have values
that are included in the dict criteria
:param df: pd.dataframe of in format_2
:param criteria: a dictionary mapping columns to values to keep;
key � is a column name; values is a values list
:return: a df without the rows that do not include the specified values
:raise: ValueError if key is not in dataframe
'''
if criteria=={}:
return
df_col=(sorted(list(df.columns)))
for key in criteria.keys():
if key < df_col[0] or key > df_col[len(df_col) - 1]:
raise ValueError(key, " is not a column in df")
for col in df_col:
if key<col:
raise ValueError(key, " is not a column in df")
if key==col:
break
keys_in_df= df[list(criteria.keys())].isin(criteria)
return df[keys_in_df.all(1)]
def find_extremes(df, fun=np.sum, by_item=True, by_value=True, n=5):
'''
:param df: pd.DataFrame in format_2; only including importing/exporting rows
:param by_item: If True group rows by item, otherwise by Area
:param by_value: If True should find the n most extreme items by value, otherwise by quantity
:param fun: a function to be applied, one of: np.prod(),np.std(),np.var(),
np.sum(), np.min(), np.max(), np.mean(), np.midian()
:param n: if positive get the least extreme item, otherwise, get the most
:return: list of the n least/most imported/exported items
raise: ValueError if n is not an int != 0
raise: ValueError df contains both import and export values
raise: ValueError fun is not one of the specified above functions
'''
if isinstance(n, int) == False or n==0:
raise ValueError("Error message: 'n must be an integer'")
if (df.apply(pd.Series.nunique).Element)!=1:
raise ValueError("Error message: 'The dataframe must only include Import or Export rows")
if fun not in [np.prod, np.std, np.var, np.sum, np.min, np.max, np.mean, np.median]:
raise ValueError("Invalid function! function must be one of np.prod(),np.std(),np.var(), np.sum(), np.min(), np.max(), np.mean(), np.midian()")
if by_item:
grpby=df.groupby(by=["Item"],sort=True).apply(fun)
else:
grpby=df.groupby(by=["Area"],sort=True).apply(fun)
if by_value:
if n>0:
sorted_group=grpby.sort_values(by=["Price(k,usd)"],ascending=True)[:n]
else:
sorted_group=grpby.sort_values(by=["Price(k,usd)"],ascending=False)[:n*-1]
else:
if n>0:
sorted_group=grpby.sort_values(by=["Quantity(tons)"],ascending=True)[:n]
else:
sorted_group=grpby.sort_values(by=["Quantity(tons)"],ascending=False)[:n*-1]
if by_item:
return(list(sorted_group["Item"].keys()))
else:
return(list(sorted_group["Area"].keys()))
def generate_scatter_import_vs_export(df, countries, year, output):
'''
The function produces a scatter plot of the total import/export values of the specified countries in the specified year
:param df: a dataframe in format_2
:param countries: a list of strings specifying countries
:param year: int; only rows of the specified year are used
:param output: a filename (str) to which the scatter plot is to be saved
:return: None; saves the plot to output.png
'''
df_imp = filterby_criteria(df, {"Area": countries, "Year": [year], "Element": ["Import"]})
df_exp = filterby_criteria(df, {"Area": countries, "Year": [year], "Element": ["Export"]})
imp_grp = df_imp.groupby(by=['Area'])
imp_grp = imp_grp['Price(k,usd)'].apply(sum)
exp_grp = df_exp.groupby(by=['Area'])
exp_grp = exp_grp['Price(k,usd)'].apply(sum)
zipped = list(zip(list(imp_grp), list(exp_grp)))
plt_df = pd.DataFrame(zipped, imp_grp.index, columns=["Export", "Import"])
ax = plt_df.plot.scatter("Import", "Export", alpha=0.5, logx=True, logy=True)
for i, txt in enumerate(plt_df.index):
ax.annotate(txt, (plt_df["Import"].iat[i], plt_df["Export"].iat[i]))
plt.title("Exports as function of imports")
plt.savefig(output + ".png")
if __name__ == '__main__':
LN_SEP = "\n---------------------------------------------"
df = pd.read_pickle("fixed_df.pickle")
# PART C
# C. 1
year1 = find_most_frequent_year(df, 1)
year2 = find_most_frequent_year(df, 4)
print('year1, year2:', year1, year2)
# PART C
# C. 2
df_isr75_export = filterby_criteria(df, {"Area": ["Israel"], "Year": [1975], "Element":["Export"]})
df_isr13_export = filterby_criteria(df, {"Area": ["Israel"], "Year": [2013], "Element": ["Export"]})
# PART C
# C. 3
most_items = find_extremes(df_isr75_export, by_item=True, by_value=True, n=-5)
print("most exported items from israel 2013 by value:\n", "\n".join(most_items), LN_SEP)
most_items = find_extremes(df_isr13_export, by_item=True, by_value=False, n=-5)
print("most exported items from israel 2013 by quantity:\n", "\n".join(most_items), LN_SEP)
df_exp = filterby_criteria(df, {"Element": ["Export"], "Year":[2013]})
df_imp = filterby_criteria(df, {"Element": ["Import"], "Year":[2013]})
most_exp_countries = find_extremes(df_exp, by_item=False, by_value=True, n=-12)
most_imp_countries = find_extremes(df_imp, by_item=False, by_value=True, n=-12)
countries = list(set(most_exp_countries + most_imp_countries))
print("List of countries that import and export the most by value:\n","\n".join(countries), LN_SEP)
generate_scatter_import_vs_export(df, countries=countries, year=2013, output='import_vs_export')
|
e13e24bf0755c4702df538be012150898740dc46 | lakshmivisalij/dicesimulatorpython | /dice simulator.py | 929 | 3.84375 | 4 | import random
print("Let's roll the dice!")
i = 'y'
while i == 'y':
x = random.randint(1,6)
if x==1:
print(" ---------")
print("| |")
print("| O |")
print("| |")
print(" ---------")
if x==2:
print(" ---------")
print("| |")
print("| O O |")
print("| |")
print(" ---------")
if x==3:
print(" ---------")
print("| O |")
print("| O |")
print("| O |")
print(" ---------")
if x==4:
print(" ---------")
print("| O O |")
print("| |")
print("| O O |")
print(" ---------")
if x==5:
print(" ---------")
print("| O O |")
print("| O |")
print("| O O |")
print(" ---------")
if x==6:
print(" ---------")
print("| O O O |")
print("| |")
print("| O O O |")
print(" ---------")
i = input("Press 'y' for rolling again: ")
|
5fe747190880d0c7a78641be6b47217b1584a863 | enginSacan/RobotFrameworkExample | /lib/Check_firmware_size.py | 939 | 3.84375 | 4 | """This file is created for checking file size in a specific limit for file specified."""
import os
FIRMWARE_MAX_LIMIT = 40000000
TARGET_PATH = "D:/DM/LSD/MSPS_ITEST/DAT/AutoDAT/"
def file_size(target, file_name, threshold):
"""This function is checking file size under the target folder."""
THRESHOLD = 400*1024
print("Target: ", str(target))
print("File Name: ", str(file_name))
print("Target M270: ", str(threshold))
statinfo = os.stat(TARGET_PATH+target+'/'+file_name)
file_size = statinfo.st_size
if threshold.strip() == "0":
print("Threshold: ", str(THRESHOLD))
else:
THRESHOLD = 300*1024
print("Threshold: ", str(THRESHOLD))
firmware_size_limit = FIRMWARE_MAX_LIMIT - THRESHOLD
print("file_size:", str(file_size))
print("firmware_size_limit:", str(firmware_size_limit))
if file_size > firmware_size_limit :
return False
else:
return True |
77ebd8b2998277bbe8377055c10f429680bd833a | witalomonteiro/testes-automatizados | /tests/test_dominio.py | 2,721 | 3.609375 | 4 | from unittest import TestCase
from src.leilao.dominio import Lance, Leilao, Usuario
from src.leilao.excecoes import LanceInvalido
class TestLeilao(TestCase):
def setUp(self):
self.leilao_teste = Leilao("Cavalo")
self.witalo = Usuario("Witalo", 1000)
self.witalo.propor_lance(self.leilao_teste, 500)
# 001 - Quando os lances foram realizados de forma crescente
def test_lances_ordem_crescente(self):
monteiro = Usuario("Monteiro", 1000)
monteiro.propor_lance(self.leilao_teste, 750)
menor_valor_esperado = 500
maior_valor_esperado = 750
self.assertEqual(menor_valor_esperado, self.leilao_teste.menor_lance)
self.assertEqual(maior_valor_esperado, self.leilao_teste.maior_lance)
# 002 - Quando os lances forem realizados de forma decrescente
def test_lances_ordem_decrescente(self):
with self.assertRaises(LanceInvalido):
monteiro = Usuario("Monteiro", 1000)
monteiro.propor_lance(self.leilao_teste, 250)
# 003 - Quando for realizado um unico lance
def test_um_lance(self):
menor_valor_esperado = 500
maior_valor_esperado = 500
self.assertEqual(menor_valor_esperado, self.leilao_teste.menor_lance)
self.assertEqual(maior_valor_esperado, self.leilao_teste.maior_lance)
# 004 - Quando for realizado tres lances
def test_tres_lances(self):
monteiro = Usuario("Monteiro", 1000)
jose = Usuario("José", 1000)
monteiro.propor_lance(self.leilao_teste, 750)
jose.propor_lance(self.leilao_teste, 800)
menor_valor_esperado = 500
maior_valor_esperado = 800
self.assertEqual(menor_valor_esperado, self.leilao_teste.menor_lance)
self.assertEqual(maior_valor_esperado, self.leilao_teste.maior_lance)
# 005 - Quando o leilão não tiver nenhum lance
def test_leilao_sem_lances(self):
quantidade_lances = len(self.leilao_teste.lances)
self.assertEqual(1, quantidade_lances)
# 006 - Quando o usuario anterior for diferente, permitir um novo lance
def test_lance_anterior_usuario_diferente(self):
monteiro = Usuario("Monteiro", 1000)
monteiro.propor_lance(self.leilao_teste, 750)
quantida_lances = len(self.leilao_teste.lances)
self.assertEqual(2, quantida_lances)
# 007 - Quando o usuario anterior for igual, não permitir um novo lance
def test_lance_anterior_usuario_igual(self):
with self.assertRaises(LanceInvalido):
self.witalo.propor_lance(self.leilao_teste, 500)
self.witalo.propor_lance(self.leilao_teste, 750)
|
c82c07f64dcfb548733526cdb88a990074b57520 | akshatasawhney/BFS-3 | /Problem1.py | 2,066 | 3.703125 | 4 | """
// Time Complexity : o(n)
// Space Complexity : o(n), queue
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no
// Your code here along with comments explaining your approach
"""
from collections import deque
class Solution:
def is_valid(self, s): #function to check for validity
ct = 0
for i in s:
if i == "(":
ct += 1
elif i ==")":
ct -= 1
if ct < 0:
return False
if ct == 0:
return True
return False
def removeInvalidParentheses(self, s: str) -> List[str]:#BFS approach to check for validity at each level, if valid strings found at a level, no need to proceed further
res = []
seen = set()
if not s:
return [""]
flag = False #flag to keep check if valid string found
q = deque()
q.append(s)
while q:
cur = q.popleft()
if self.is_valid(cur): #if the current string is valid, add to res and set flag to true, no children of the current string will be added to the queue, as we want the longest valid string, as we go deeper length will only decrease
flag = True
res.append(cur)
if not flag: #if valid string hasnt been found yet
for i in range(0,len(cur)):# add the children, strings formed by removing each element one by one
if cur[i].isalpha():
continue
subs = cur[:i] + cur[i+1:]
if subs not in seen: #to check for repeatitions
seen.add(subs)
q.append(subs)
if not res:#no valid string
return [""]
return res
|
70c4989fada0dd3800427c2da1038807d5abb88a | anhlh93/Techkids | /Season 4/Session4-Assignment 4.4.py | 232 | 3.765625 | 4 | from turtle import*
color("blue")
bgcolor("green")
speed(-1)
def square(length):
for i in range(4):
forward(length)
left(90)
number=20
length=100
for i in range(number):
square(length)
left(360/number)
|
67ec1c51f1bf73cf5f944ace9a89e95882e94250 | kemoelamorim/python_URI | /exercicios_URI/URI_1013.py | 667 | 3.890625 | 4 | """ Faça um programa que leia três valores e apresente o maior dos três valores lidos seguido da mensagem “eh o maior”. Utilize a fórmula:
maiorAB = (a + b + abs( a - b))/2
Obs.: a fórmula apenas calcula o maior entre os dois primeiros (a e b). Um segundo passo, portanto é necessário para chegar no resultado esperado.
Entrada
O arquivo de entrada contém três valores inteiros.
Saída
Imprima o maior dos três valores seguido por um espaço e a mensagem "eh o maior".
"""
a, b, c = input().split(" ")
a = int(a)
b = int(b)
c = int(c)
maiorAB = (a + b + abs( a - b))/2
maiorABC = int((maiorAB + c + abs(maiorAB - c))/2)
print(maiorABC,"eh o maior")
|
9faf895647e7eb6f6a0fa1f00a4b38bb5bd7ffe9 | sicou2-Archive/pcc | /python_work/part2/alien_invasion/alien_invasion/laser.py | 1,088 | 3.75 | 4 | import pygame
from pygame.sprite import Sprite
class Laser(Sprite):
"""A class to manage lasers fired from the ship."""
def __init__(self, ai_game):
"""Create a laser object at the ship's current position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.color = self.settings.laser_color
# Create a laser rect at (0, 0) and then set the correct position.
self.rect = pygame.Rect(0, 0, self.settings.laser_width,
self.settings.laser_height)
self.rect.midtop = ai_game.ship.rect.midtop
# Store the laser's position as a decmial value.
self.y = float(self.rect.y)
def update(self):
"""Move the laser up the screen."""
# Update the decimal position of the laser.
self.y -= self.settings.laser_speed
# Update the rect position.
self.rect.y = self.y
def draw_laser(self):
"""Draw the laser to the screen."""
pygame.draw.rect(self.screen, self.color, self.rect)
|
10e9d887ece56205449d1c3412d614e91bc723ee | sicou2-Archive/pcc | /python_work/part1/ch05/c5_8.py | 1,590 | 3.859375 | 4 | usernames = ['admin', 'todd', 'betty', 'adam', 'scott', 'sally']
def looping(names):
if names:
for name in usernames:
if name == 'admin':
print("Welcome, keeper of the keys. The motor is still "
"running!")
else:
print(f"Welcome user {name.title()}!")
else:
print("We need to find some users.")
looping(usernames)
print("\n5_9")
empty_names = []
looping(empty_names)
print("\n5_10")
current_names = ['admin', 'toDd', 'betty', 'adam', 'scott', 'sally']
new_names = ['ToDd', 'Jake', 'sammy', 'sally']
current_names_lower = []
new_names_lower = []
def taken_check(current, current_lower, new, new_lower):
for name in current:
current_lower.append(name.lower())
for name in new:
new_lower.append(name.lower())
for name in new_lower:
if name in current_lower:
print(f"Username: {name} is already taken, please select"
" another.")
else:
current.append(name)
# I feel that the original name, not the lower name should be put in
#to current_names, however TLDC
taken_check(current_names, current_names_lower,
new_names, new_names_lower)
print(current_names, current_names_lower, new_names, new_names_lower)
print("\n5_11")
for num in range(1, 10):
if num == 1:
print(f"{str(num)}st")
elif num == 2:
print(f"{str(num)}nd")
elif num == 3:
print(f"{str(num)}rd")
else:
print(f"{str(num)}th") |
bb81d71014e5d45c46c1c34f10ee857f5763c75a | sicou2-Archive/pcc | /python_work/part1/ch03/c3_4.py | 1,813 | 4.125 | 4 | #Guest list
dinner_list = ['Sam Scott', 'Tyler Jame', 'Abadn Skrettn', 'Sbadut Reks']
def invites():
print(f'You want food {dinner_list[0]}? Come get food!')
print(f'Please honor me {dinner_list[1]}. Dine and talk!')
print(f'Hunger gnaws at you {dinner_list[2]}. Allow me to correct that.')
print(f'Poison is not for {dinner_list[3]}. You are safe eating here.')
invites()
list_len = len(dinner_list)
print(list_len)
print(f'\n{dinner_list[1]} will do me no honor. His name struck from the fun list\n\n')
del dinner_list[1]
dinner_list.append('Nahony Simpho')
invites()
print('\n\nThe council of Elders has seen fit to commission a more grand dining table. We have thus allowed for an expanded guest list.\n\n')
dinner_list.insert(0, 'Havlone of Maxuo')
dinner_list.insert(2, 'Barben Blorts')
dinner_list.append('Bill')
def expanded_invites():
print(f'We must talk {dinner_list[4]}. The food will be good.')
print(f'Be there of be dead {dinner_list[5]}. You will not starve.')
print(f'You have been asking forever. This one time {dinner_list[6]}, you may sit with us.')
invites()
expanded_invites()
list_len = len(dinner_list)
print(list_len)
print('\nWar! Trechery! The table has been destroyed by the vile Choob! Dinner for many has been lost to the sands of time. Our two closest advisors will be allowed council.\n')
list_len = len(dinner_list) - 2
for i in range(0, list_len):
dis_invited = dinner_list.pop()
print(f'Your dishonor shall be avenged {dis_invited}! Further preperations for correction are forthcoming!\n')
list_len = len(dinner_list)
print(list_len)
for i in range(0, list_len):
print(f'We urgently must consult, {dinner_list[0]}! We must correct our table tragedy!\n')
del dinner_list[0]
print(dinner_list)
# note(BCL): Working on 3-7
|
f5e0dd2d5fa00bff0eeac7772b2fc041a1c6d2b1 | sicou2-Archive/pcc | /python_work/part1/ch06/c6_1.py | 4,170 | 4.3125 | 4 | alice = {'first_name': 'alice', 'last_name': 'maple',
'city': 'springfield', 'age': 25, 'hair': 'brown',}
for num in alice:
print(alice[num])
#6_2
print("\nNEXT 6_2 and 6-10")
numbers = {'todd': [3, 4, 6, 8,],
'sammy': [5, 7, 3, 8,],
'joe': [6,],
'kyle': [7, 3,],
'janice': [3, 9, 1],
}
for num in numbers:
print(num.title(), numbers[num])
#6_3 and 6_4
print("\nNEXT")
glossary = {
'get()': 'Return the value for key if key is in the '
'dictionary.\n',
'def':'The keyword def introduces a function definition.\n',
'pop()':'If key is in the dictionary, remove it and return '
'its value.\n',
'len()':'Return the number of elements in set.\n',
'iterator':'An object that implements next, which is '
'expected to return the "next" element of the iterable '
'object that returned it\n',
'keys()': 'Return a new view of the dictionary\'s keys\n',
'values()': 'Return a new view of the dictionary\'s values'
'\n',
'items()': 'Return a new view of the dictionary\'s items '
'((key, value) pairs)\n',
'sorted()': 'Return a new sorted list from the items in '
'iterable\n',
'list()': 'Return a list of all the keys used in the '
'dictionary\n',
}
for word in glossary.keys():
print(word, ': ', glossary[word])
#6_5
print("\nNEXT")
river = {'amazon': 'brazil', 'congo': 'congo', 'orinoco': 'venezuela'}
for water in river:
print(f'The {water.title()} runs through {river[water].title()}')
print('\nOR DO THIS')
for water, country in river.items():
print(f"The {water.title()} runs through {country.title()}.")
print("\nNEXT 6-7")
alice = {'first_name': 'alice', 'last_name': 'maple',
'city': 'springfield', 'age': 25, 'hair': 'brown',
'eye': 'brown'}
bob = {'first_name': 'bob', 'last_name': 'aspen',
'city': 'shelbyville', 'age': 24, 'hair': 'blonde',
'eye': 'green'}
people = [alice, bob]
for person in people:
first_last = (f"Full name: {person['first_name'].title()}"
f"{person['last_name'].title()}.")
print(first_last)
print(f"Location: {person['city'].title()}.")
description = (f"Age: {person['age']}, "
f"Hair: {person['hair'].title()}, "
f"Eyes: {person['eye'].title()}.\n")
print(description)
print("\nNEXT 6-7")
trevor = {
'name': 'trevor',
'owner': 'adam',
'toy': 'stick',
}
dally = {
'name': 'dally',
'owner': 'bob',
'toy': 'catnip',
}
hero = {
'name': 'hero',
'owner': 'charlie',
'toy': 'ball',
}
pets = [trevor, dally, hero]
for pet in pets:
print(f"PET NAME: {pet['name'].title()}\n\tPET OWNER: "
f"{pet['owner'].title()}\n\t FAVORITE TOY: "
f"{pet['toy'].title()})")
print("\nNEXT 6-8")
favorite_places = {
'alice': ['austin', 'houston', 'greece'],
'bob': ['seattle', 'author'],
'charlie': ['channington'],
}
for person, places in favorite_places.items():
print(f"{person.title()}'s favorite places are: ", end=' ')
for place in places:
print(f"{place.title()}", end=', ')
print('\n')
print('\nNEXT 6-11')
cities = {
'paris':
{'country': 'france',
'language': 'french',
'word': 'food',
},
'perth':
{'country': 'australia',
'language': 'english',
'word': 'sun',
},
'moscow':
{'country': 'russia',
'language': 'russian',
'word': 'cold',
},
}
for city, facts in cities.items():
print(city.title())
for item, fact in facts.items():
print(f'\t{item.title()}: {fact.title()}') |
bc7185beb2e51477149df4606d5976d7bd8607bc | sicou2-Archive/pcc | /python_work/part2/alien_invasion/alien_invasion/diy/target_14_2.py | 991 | 3.59375 | 4 | import pygame
class Target:
"""A class for the target in Target Practice."""
def __init__(self, ai_game):
"""Initialize target settings and position."""
self.screen = ai_game.screen
self.settings = ai_game.settings
self.color = self.settings.target_color
self.screen_rect = self.screen.get_rect()
self.rect = pygame.Rect(0, 0, self.settings.target_width,
self.settings.target_height)
self.rect.x = self.screen_rect.right - (self.settings.target_width * 2)
self.y = float(self.rect.y + 1)
def update(self):
self.y += (self.settings.target_speed * self.settings.target_direction)
self.rect.y = self.y
def draw_target(self):
pygame.draw.rect(self.screen, self.color, self.rect)
def check_edges(self):
if (self.rect.bottom >= self.screen_rect.bottom or
self.rect.top <= 0):
self.settings.target_direction *= -1
|
f644021c93bb0affb75399edf463fcb554c56ddf | sicou2-Archive/pcc | /python_work/part1/ch11/city_functions.py | 336 | 3.890625 | 4 | """A module for returning a 'City, Country' string."""
def a_city(city, country, population=None):
"""Generate a neatly formatted 'City, Country'"""
if population:
city_country = f"{city}, {country}, population: {population}"
else:
city_country = f"{city}, {country}"
return city_country.title() |
a4d7377ac20dd283f71b0101c05f6ed682a4e849 | sicou2-Archive/pcc | /python_work/part1/ch05/amusement_park.py | 622 | 3.890625 | 4 | age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $25.")
else:
print("Your admission cost is $40.")
#Better way to do this.
print("Better\n")
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
else:
price = 20
print(f"Your admission price is ${price}.\n")
#Omit Else
print("Omit Else")
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
elif age >= 65:
price = 20
print(f"Your admission price is ${price}.\n") |
a2ddf6304441dfd004e6d90802554d4dca90467a | ayymk/code-algo-dicho | /find_the_number.py | 403 | 3.671875 | 4 | from random import *
x =randint(0,100)
y=int(input("Trouve le nombre entre 0 et 100: "))
z=0
while y!=x and z<7:
z=z+1
if y<=x:
y=int(input("Le nombre recherché est plus grand, réessaye: "))
else:
y=int(input("Le nombre recherché est plus petit, réessaye: "))
if x==y:
print ("bravo c'est bien "+str(x))
else:
print("Tu est vraiment nul , la bon chiffre est "+str(x)) |
91d8233f7d92a9b1a60d8a8d4226b250cc4833df | dilynfullerton/vpython | /projectile.py | 4,065 | 3.75 | 4 | __author__ = 'Alpha'
from visual import *
# Simple program where projectile follows path determined by forces applied to it
# Velocity is vector(number, number, number)
# Force is vector(number, number, number)
# Momentum is vector(number, number, number)
# Mass is number
# Position is vector(number, number, number)
# Acceleration is vector(number, number, number)
# Time is number
T_MAX = 1000
GRAV_ACCEL = vector(0, - 9.81, 0)
STEP = .01
# Mass Acceleration -> Force
def get_force(m, a):
f = m * a
return f
class Projectile:
def __init__(self, m, s, p, t, f):
self.m = m
self.s = s
self.p = p
self.t = t
self.f = f
self.grav_force()
# Projectile Force -> Projectile
def update_p(self):
p_f = self.p + self.f * STEP
self.p = p_f
# Projectile -> Projectile
def update_s(self):
s_f = self.s + STEP * self.p / self.m
self.s = s_f
# Projectile -> Projectile
def update_t(self):
t_f = self.t + STEP
self.t = t_f
# Projectile -> Force
def grav_force(self):
return get_force(self.m, GRAV_ACCEL)
# Force (listof Force) -> Projectile
def get_net_force(self, forces_on):
f_net = self.grav_force() + net_force(forces_on)
self.f = f_net
m0 = 1
s0 = vector(0, 0, 0)
p0 = vector(10, 20, 10)
t0 = 0
f0 = s0
BALL0 = Projectile(m0, s0, p0, t0, f0)
NO_OTHER_FORCES = [f0]
f_wind = vector(-1, -11, 4)
WIND = [f_wind]
MARKER_SCALE = .05
AXIS_SCALE = 70
SHOW_PATH = True
SHOW_POSITION_ARROW = True
SHOW_FORCE_ARROW = True
SHOW_MOMENTUM_ARROW = True
# (listof Force) -> Force
def net_force(forces):
f_net = vector(0, 0, 0)
for f in forces:
f_net += f
return f_net
# Projectile ->
def animate(projectile, forces):
s_i = projectile.s
projectile.get_net_force(forces)
xscale = AXIS_SCALE
yscale = AXIS_SCALE
zscale = AXIS_SCALE
width = .01 * AXIS_SCALE
xaxis = arrow(axis=(xscale, 0, 0),
shaftwidth=width)
yaxis = arrow(axis=(0, yscale, 0),
shaftwidth=width)
zaxis = arrow(axis=(0, 0, zscale),
shaftwidth=width)
unitx = (1, 0, 0)
unity = (0, 1, 0)
unitz = (0, 0, 1)
image = sphere(pos=projectile.s,
radius=projectile.m,
color=color.red)
if SHOW_PATH:
points(pos=[image.pos],
size=MARKER_SCALE*image.radius,
color=image.color)
if SHOW_POSITION_ARROW:
position_arrow = arrow(pos=vector(0, 0, 0),
axis=image.pos,
color=color.blue,
shaftwidth=width)
if SHOW_MOMENTUM_ARROW:
momentum_arrow = arrow(pos=image.pos,
axis=projectile.p,
color=color.green,
shaftwidth=width)
if SHOW_FORCE_ARROW:
net_force_arrow = arrow(pos=image.pos,
axis=projectile.f,
color=color.yellow,
shaftwidth=width)
while True:
rate(1/STEP)
if projectile.t > T_MAX:
break
elif projectile.s.y < s_i.y:
break
else:
projectile.update_s()
projectile.update_p()
projectile.update_t()
image.pos = projectile.s
if SHOW_PATH:
points(pos=[image.pos],
size=MARKER_SCALE*image.radius,
color=image.color)
if SHOW_POSITION_ARROW:
position_arrow.axis = image.pos
if SHOW_MOMENTUM_ARROW:
momentum_arrow.pos = image.pos
momentum_arrow.axis = projectile.p
if SHOW_FORCE_ARROW:
net_force_arrow.pos = image.pos
net_force_arrow.axis = projectile.f
#animate(BALL0, NO_OTHER_FORCES)
animate(BALL0, WIND) |
35d5bf06474999e2fdb2d06b16b2081abd52ca9d | Ashikur-ai/Starry-sky-with-python | /Game development 6.py | 544 | 3.9375 | 4 | import turtle as t
import random as r
# defining screen
win = t.getscreen()
win.bgcolor("black")
# defining turtle
rock = t.Turtle()
rock.color("yellow")
rock.speed(0)
# get random cordinate
for i in range(50):
x = r.randint(-300, 300)
y = r.randint(-300, 300)
# Turtle up down and filling the color
rock.begin_fill()
rock.up()
rock.goto(x, y)
rock.down()
for i in range(5):
rock.fd(20)
rock.lt(144)
rock.end_fill()
# looping the screen
win.mainloop() |
7d8db8c7e276d208bb4e6fa3b92539e76cb9ff71 | anantkaushik/stein | /python/problems/array/reverse.py | 262 | 3.96875 | 4 | def reversed_arr(arr,count):
if count==len(arr):
return arr
temp = arr[count]
count += 1
reversed_arr(arr,count)
arr[len(arr) - 1 - (count - 1)] = temp
return arr
arr = [22, 11, 20, 76, 123, 70]
count=0
print ("Reversed array: ",reversed_arr(arr,count)) |
e38fec0a8e17078c5e29d5c2bbd6e1db604a1af7 | alexandermfisher/cs50_artificial_intelligence | /01 - Knowledge/minesweeper/minesweeper.py | 11,932 | 4.3125 | 4 | import itertools
import random
class Minesweeper():
"""
Minesweeper game representation
"""
def __init__(self, height=8, width=8, mines=8):
# Set initial width, height, and number of mines
self.height = height
self.width = width
self.mines = set()
# Initialize an empty field with no mines
self.board = []
for i in range(self.height):
row = []
for j in range(self.width):
row.append(False)
self.board.append(row)
# Add mines randomly
while len(self.mines) != mines:
i = random.randrange(height)
j = random.randrange(width)
if not self.board[i][j]:
self.mines.add((i, j))
self.board[i][j] = True
# At first, player has found no mines
self.mines_found = set()
def print(self):
"""
Prints a text-based representation
of where mines are located.
"""
for i in range(self.height):
print("--" * self.width + "-")
for j in range(self.width):
if self.board[i][j]:
print("|X", end="")
else:
print("| ", end="")
print("|")
print("--" * self.width + "-")
def is_mine(self, cell):
i, j = cell
return self.board[i][j]
def nearby_mines(self, cell):
"""
Returns the number of mines that are
within one row and column of a given cell,
not including the cell itself.
"""
# Keep count of nearby mines
count = 0
# Loop over all cells within one row and column
for i in range(cell[0] - 1, cell[0] + 2):
for j in range(cell[1] - 1, cell[1] + 2):
# Ignore the cell itself
if (i, j) == cell:
continue
# Update count if cell in bounds and is mine
if 0 <= i < self.height and 0 <= j < self.width:
if self.board[i][j]:
count += 1
return count
def won(self):
"""
Checks if all mines have been flagged.
"""
return self.mines_found == self.mines
class Sentence():
"""
Logical statement about a Minesweeper game
A sentence consists of a set of board cells,
and a count of the number of those cells which are mines.
"""
def __init__(self, cells, count):
self.cells = set(cells)
self.count = count
def __eq__(self, other):
return self.cells == other.cells and self.count == other.count
def __str__(self):
return f"{self.cells} = {self.count}"
def known_mines(self):
"""
Returns the set of all cells in self.cells known to be mines.
"""
### Any time the number of cells is equal to the count, we know that all of that sentence’s cells must be mines.
if len(self.cells) == self.count:
return self.cells
else:
return set()
def known_safes(self):
"""
Returns the set of all cells in self.cells known to be safe.
"""
### Any time the count is equal to 0, we know that all of that sentence’s cells must be safe.
if self.count == 0:
return self.cells
else:
return set()
def mark_mine(self, cell):
"""
Updates internal knowledge representation given the fact that
a cell is known to be a mine.
"""
if cell in self.cells:
self.cells.remove(cell)
self.count -= 1
def mark_safe(self, cell):
"""
Updates internal knowledge representation given the fact that
a cell is known to be safe.
"""
if cell in self.cells:
self.cells.remove(cell)
def is_subset(self, other_sentence):
## tests to see if it is a subset of other sentence.
## returns true if yes it is or false if no it is not.
if self.cells != other_sentence.cells and self.cells.issubset(other_sentence.cells):
return True
else:
return False
def infer_new_sentance(self, other_sentence):
### where self.cells is a subset of other_sentence.cells a new sentence is made
different_cells = other_sentence.cells.difference(self.cells)
different_count = other_sentence.count - self.count
new_sentence = Sentence(different_cells, different_count)
return new_sentence
class MinesweeperAI():
"""
Minesweeper game player
"""
def __init__(self, height=8, width=8):
# Set initial height and width
self.height = height
self.width = width
# Keep track of which cells have been clicked on
self.moves_made = set()
# Keep track of cells known to be safe or mines
self.mines = set()
self.safes = set()
# List of sentences about the game known to be true
self.knowledge = []
def mark_mine(self, cell):
"""
Marks a cell as a mine, and updates all knowledge
to mark that cell as a mine as well.
"""
self.mines.add(cell)
for sentence in self.knowledge:
sentence.mark_mine(cell)
def mark_safe(self, cell):
"""
Marks a cell as safe, and updates all knowledge
to mark that cell as safe as well.
"""
self.safes.add(cell)
for sentence in self.knowledge:
sentence.mark_safe(cell)
def add_knowledge(self, cell, count):
"""
Called when the Minesweeper board tells us, for a given
safe cell, how many neighboring cells have mines in them.
This function should:
1) mark the cell as a move that has been made
2) mark the cell as safe
3) add a new sentence to the AI's knowledge base
based on the value of `cell` and `count`
4) mark any additional cells as safe or as mines
if it can be concluded based on the AI's knowledge base
5) add any new sentences to the AI's knowledge base
if they can be inferred from existing knowledge
"""
## form new sentance and add to knowledge base
neibouring_cells = set()
for i in range(max(0, cell[0]-1), min(cell[0] + 2, self.height)):
for j in range(max(0, cell[1]-1), min(cell[1] + 2, self.width)):
# Add the cell clicked on to moves made and safe set sets
if (i, j) == cell:
self.moves_made.add(cell)
self.mark_safe(cell)
else:
neibouring_cells.add((i,j))
new_sentence = Sentence(neibouring_cells, count)
## marks mines and safes for new sentance.
for mine in self.mines:
new_sentence.mark_mine(mine)
for safe in self.safes:
new_sentence.mark_safe(safe)
## add new sentence to knowledge base.
self.knowledge.append(new_sentence)
"""
update knowledge base in any inferneces can be made.
while any one of the three inference moves can generate new knowledge or ascribe a
cell as a mine or safe this loop will continue (i.e. until no more inferences can be
made and all new knowledge genereated by the new sentence/cell has been accounted for.)
"""
while self.inference_1() or self.inference_2() or self.inference_3():
# find any subsetting possibilities and update knowledge base.
for sentence_1 in self.knowledge.copy():
for sentence_2 in self.knowledge.copy():
if sentence_1.is_subset(sentence_2):
new_sentence = sentence_1.infer_new_sentance(sentence_2)
self.knowledge.append(new_sentence)
self.knowledge.remove(sentence_2)
# find any known mines or safes sentences and update mines and safes set
for sentence in self.knowledge:
for cell in sentence.known_safes().copy():
self.mark_safe(cell)
for cell in sentence.known_mines().copy():
self.mark_mine(cell)
# remove all empty sets in knowledge
for sentence in self.knowledge:
if sentence.cells == set():
self.knowledge.remove(sentence)
"""
These three infernce functions loop over all sentences in knowledge and retrun
a list of sentences that result from the relevant inferneces rules. If any of the
three lists is not empty a infernece can be made and the subsequent knowledge can be added to knowledge bank.
They are used in for the while loops condition to check if any inferneces can be made.
I.e. While inferneces can be made they will be made and knowledge will be updated.
"""
def inference_1(self):
"""
Returns a list of new sentences, that can be formed by sub set infernece rule.
That is to say if a sentence.cells is a subset of another sentance.cells, then the
differnce will be found and the count will be calculated and a new sentance will
be added to a list that will be returned.
knowledge must be a list of Sentences()
"""
new_sentences = []
for sentence_1 in self.knowledge:
for sentence_2 in self.knowledge:
if sentence_1.is_subset(sentence_2):
new_sentence = sentence_1.infer_new_sentance(sentence_2)
new_sentences.append(new_sentence)
return new_sentences
def inference_2(self):
"""
Returns a list of sentances where there are known safes. I.e where sentance.count = 0 and all cells are therefore safe.
"""
safe_sentences = []
for sentence in self.knowledge:
if sentence.known_safes() != set():
safe_sentences.append(sentence)
return safe_sentences
def inference_3(self):
"""
Returns a list of sentences where there are known mines. I.e. where length of set is equal to count, and all cells are therefore a mine.
"""
mine_sentences = []
for sentence in self.knowledge:
if sentence.known_mines() != set():
mine_sentences.append(sentence)
return mine_sentences
def make_safe_move(self):
"""
Returns a safe cell to choose on the Minesweeper board.
The move must be known to be safe, and not already a move
that has been made.
This function may use the knowledge in self.mines, self.safes
and self.moves_made, but should not modify any of those values.
"""
for move in self.safes:
if move not in self.moves_made and move not in self.mines:
return move
return None
def make_random_move(self):
"""
Returns a move to make on the Minesweeper board.
Should choose randomly among cells that:
1) have not already been chosen, and
2) are not known to be mines
"""
possible_moves = []
for i in range(0, self.height):
for j in range(0, self.width):
move = (i, j)
if move not in self.moves_made and move not in self.mines:
possible_moves.append(move)
### if available move, randomly pick one and return move, else return None as no move available.
if possible_moves:
random_index = random.randint(0,len(possible_moves)-1)
random_move = possible_moves[random_index]
return random_move
else:
return None
|
d56a0b6bc5da1d2a3e7000ac10738c93caf7875a | diacarcor/day-3-5-exercise | /main.py | 890 | 4.09375 | 4 | # 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#Combine both lower names
names = name1.lower() + name2.lower()
#Calculate digit one
digit_one = 0
digit_one += names.count("t") + names.count("r") + names.count("u") + names.count("e")
#Calculate digit two
digit_two = 0
digit_two += names.count("l") + names.count("o") + names.count("v") + names.count("e")
#Get score
score = digit_one * 10 + digit_two
#Check compatibility
message = f"Your score is {score}"
if (score < 10) or (score > 90):
message = message + ", you go together like coke and mentos."
elif (score >= 40) and (score <= 50):
message = message + ", you are alright together."
else:
message = message + "."
print(message) |
a30f252bdb52d336ef70f5d1e7f7deaf388568a3 | bmasse/Dev | /Python/L_Intro_A_Python/code/chap5/pipoem.py | 1,424 | 3.703125 | 4 | #!/usr/local/bin/python
# Contribution to the forever lasting discussion on indentation!
# After Petrarca, Shakespeare, Milton, Drs. P and many, many others,
# a sonnet has 14 lines and a certain rhyme scheme.
# Jacques Bens presented in 1965 in Paris the pi-sonnet with
# 3,1,4,1 and 5 lines, but the ultimate pi-poem I found in
# Brown's Python Annotated Archives p. 12:
# Based on a algorithm of Lambert Meertens (remember those days of the
# B -> ABC-programming language!!!)
import sys
def main():
k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
while 1:
p, q, k = k*k, 2L*k+1L, k+1L
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = 10L*(a%b), 10L*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
sys.stdout.write(`int(d)`)
sys.stdout.flush()
main()
# Reading/writing Python source often gives me the impression of
# reading/writing a poem!
# Layout, indentation, rythm, I like the look and feel!
# What does this tiny program do? It is not a sonnet, even not a
# pi-sonnet, but it surely produces Pi!
# The poem ( sorry, the program) needs some explanation.
# As a mathematician I recognize the continued fraction, odd/even,
# squares and all that matters.
# But it is a miracle! A few lines of Python code producing
# a infinity of pi-digits!
# Jaap Spies
# Hogeschool Drenthe
# Keep Peace in Mind |
25dbf9ad6efbef56ef718b4c0c8095b38cc4e933 | TroyCode/Super-Blinder | /app/stastics.py | 1,158 | 3.609375 | 4 | import time
class Words:
def __init__(self):
self.count_list = []
def add_list(self, word_array, time):
for word in word_array:
is_inside = False
for item in self.count_list:
if word in item["Name"]:
is_inside = True
item["Count"] = item["Count"] + 1
item["Times"].append(int(time))
if not is_inside:
new_item = {"Name": word, "Count": 1, "Times": [int(time)]}
self.count_list.append(new_item)
def dic_sort(self):
from operator import itemgetter
self.count_list = sorted(self.count_list, key=itemgetter('Count'))
self.count_list.reverse()
class Times:
def __init__(self):
self.time_stamp = time.time()
self.time_dic = {}
def add_stamp(self, description):
now = time.time()
gap = now - self.time_stamp
self.time_stamp = now
self.time_dic[description] = gap
def print_result(self):
accu = 0.0
for des in self.time_dic:
accu = accu + self.time_dic[des]
print "{des}: {gap}secs".format(
des=des,
gap=round(self.time_dic[des], 1))
print "total time: {}secs".format(round(accu, 1))
|
b7df9f711fba030043cb701c961918d9ff2d51f2 | diegoasanch/Project-Euler | /16 - Power Digit sum.py | 115 | 3.765625 | 4 | def digit_sum(number):
digits = [int(x) for x in str(number)]
return sum(digits)
print(digit_sum(2**1000)) |
e6873cf3124c7d86f97c7a744f6e6da908a908c4 | sun1218/MyTest | /fab_test.py | 676 | 3.515625 | 4 | class Fab(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __next__(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n += 1
return r
raise StopIteration()
def __iter__(self):
return self
for n in Fab(10):
print(n)
print("——————————————————————————————")
def Fab_2(max):
n, a, b = 0, 0, 1
while n < max:
yield b
temp = a + b
a = b
b = temp
n += 1
for n in Fab_2(10):
print(n)
|
8ab27a2740fb89fe98d49ea63d334f7e5caec3c0 | kenu/g-coin | /gcoin/proof.py | 756 | 3.84375 | 4 | import hashlib
DIFFICULTY = 1 # number of digits is difficulty
VALID_DIGITS = '0' * DIFFICULTY
def valid_proof(last_proof, proof):
""" Validates proof
last digits of hash(last_proof, proof)
== VALID_DIGITS
Args:
last_proof (int): previous proof
proof (int): proof to validate
Returns:
bool:
"""
proof_seed = '{0}{1}'.format(last_proof, proof).encode()
proof_hash = hashlib.sha256(proof_seed).hexdigest()
return proof_hash[:DIFFICULTY] == VALID_DIGITS
def find_proof(last_proof):
"""proof of work
Args:
last_proof (int):
Returns:
int: proof
"""
proof = 0
while valid_proof(last_proof, proof) is False:
proof += 1
return proof
|
86850fbb6c751efce65db5088fb83dee06b6ae84 | chrisullyott/wordsearch-solver | /app/file.py | 205 | 3.9375 | 4 | """
Helpers for files.
"""
def read_file_upper(filename):
"""Read a file as an uppercase string."""
with open(filename) as file:
contents = file.read().strip().upper()
return contents
|
d11c1c967cc19dff7e538080266d08eb9f148366 | GSacchetti/Segmentation-of-multispectral-and-thermal-images-with-U-NET | /Construction_data/excel_to_tif_array.py | 5,669 | 3.578125 | 4 | #######. This algorithm is to convert the excel files into tiff images and arrays. #######
#Our dataset were in the form of excel tables, to convert these tables into a tiff image, I created this Convert function.
#To perform this conversion, we have calculated a displacement step called "step",
#because this table represents a multispectral and thermal georeferential part (you can see the different
#columns in the data / Excel folder) extracted from ERDAS software, so the step represents its resolution.
#We can display them all 7 at once, for that we saved them in pictures but each length differently
#(You can see it in the data / TIFandNPY folder
#Loading packages
from PIL import Image
import xlrd
import numpy as np
import os,sys
from skimage.io import imsave,imread
import math
from os.path import join
#import pathproject as pp #TODO creation of a file containing every paths
def mymkdir(path):
if not os.path.exists(path):
os.mkdir(path)
def Convert(PathImportExcel,PathExportTif, channels=[3,4,5,6,7,8,9], step=12,factor=1000):
print('The channels used are : ',channels)
#Initialization of indices of images for each channel
print(os.listdir(PathImportExcel))
for element in list(os.listdir(PathImportExcel)):
if element.find('~$')==-1 and element.find('.D')==-1:
name=element.replace('.xlsx','')
print(element)
file= xlrd.open_workbook(PathImportExcel+element)
#Initilization of indice of subsets
for k in file.sheet_names():
tableau = file.sheet_by_name(str(k))
# Writting the number of lines of each subset
print('le nombre de lignes de '+str(k)+' %s ' % tableau.nrows)
# Writting the number of lines of each subset
print('le nombre de colonnes '+str(k)+' '+'%s ' % tableau.ncols)
minX=sys.maxsize
maxX=-sys.maxsize
minY=sys.maxsize
maxY=-sys.maxsize
for l in range(1,tableau.nrows):
x=tableau.cell_value(l,1)*factor
minX=min(minX,x)
maxX=max(maxX,x)
y=tableau.cell_value(l,2)*factor
minY=min(minY,y)
maxY=max(maxY,y)
#Determination's resolution
tab=[]
for i in range(1,4000):
tab.append(tableau.cell_value(i,1)*factor)
table=[]
for i in tab:
if not i in table:
table.append(i)
step=int(table[2]-table[1])
xSize=1+(maxX-minX)/step
ySize=1+(maxY-minY)/step
size =(round(xSize),round(ySize))
print('the image"s size:',size)
namesubset=name+'_'+str(k)
image_tif_path = join(PathExportTif,namesubset,'ImageTif')
image_array_path = join(PathExportTif,namesubset,'ImageArray')
mask_tif_path = join(PathExportTif,namesubset,'MaskTif')
mask_array_path = join(PathExportTif,namesubset,'MaskArray')
mymkdir(join(PathExportTif,namesubset))
mymkdir(image_tif_path)
mymkdir(image_array_path)
mymkdir(mask_tif_path)
mymkdir(mask_array_path)
matrix=np.zeros([size[0],size[1],len(channels)], dtype=np.float32)
for cid, h in enumerate(channels):
image= np.zeros((size[0],size[1]), dtype=np.float32)
for l in range(1,tableau.nrows):
i=math.floor((tableau.cell_value(l,1)*factor-minX+step/2.)/step)
j=math.floor((tableau.cell_value(l,2)*factor-minY+step/2.)/step)
image[i,j]=(tableau.cell_value(l,h))
matrix[i,j,cid]=tableau.cell_value(l,h)
imageint=(255*(image-image.min())/(image.max()-image.min())).astype(np.uint8)
imsave(join(image_tif_path,name+'_'+str(k)+'_B'+str(cid)+'.tif'),imageint)
#np.save(join(image_array_path,namesubset,'_image.npy'),matrix)
np.save(PathExportTif+'/'+namesubset+'/'+'ImageArray'+'/'+namesubset+'_image.npy',matrix)
#SAVE MASK
image= np.zeros((size[0],size[1],1), dtype=np.uint8)
for l in range(1,tableau.nrows):
i=int((tableau.cell_value(l,1)*factor-minX)/step)
j=int((tableau.cell_value(l,2)*factor-minY)/step)
v=tableau.cell_value(l,11)
if v=="other":
image[i,j]=0
else:
image[i,j]=255
#else:
#print('UNNKOWN '+v)
#quit()
imsave(PathExportTif+'/'+namesubset+'/'+'MaskTif'+'/'+name+'_'+str(k)+'_mask.tif',image)
np.save(PathExportTif+'/'+namesubset+'/'+'MaskArray'+'/'+namesubset+'_mask.npy',np.float32(image/255.0))
print(np.shape(image))
del image
#mainPath=os.getcwd()
#mainPath = '/content/gdrive/My Drive/U-NET'
#PathImportExcel=mainPath+'/data/Excel/'
#mymkdir(mainPath+'/data/TIFandNPY')
#PathExportTif=mainPath+'/data/TIFandNPY/'
PathImportExcel='/content/gdrive/My Drive/U-NET/data/Excel/'
mymkdir('/content/gdrive/My Drive/U-NET/data/TIFandNPY')
PathExportTif='/content/gdrive/My Drive/U-NET/data/TIFandNPY/'
#Application of method convert
Convert(PathImportExcel,PathExportTif)
|
73097e79c8ed996ebe58bc1638b3dfc938750d0e | abishamathi/python-program- | /even numbers.py | 120 | 3.546875 | 4 | even = []
for n in l :
if(n % 2 == 0):
even.appened(n)
return even
print(even num([1,2,3,4,5,6,7,8,9]))
|
8b3f291d7d9b0ecd8bc8584833a650e913c94773 | abishamathi/python-program- | /number of spaces.py | 124 | 3.703125 | 4 | fname=input('Enter file name:')
words=line.splits()
if(letter.isspace):
k=k+1
print('Occurrance of blank spaces:')
print(k)
|
0a4cc84bd54d8e538b82324172d78b145d7df88e | abishamathi/python-program- | /largest.py | 226 | 4.21875 | 4 | num1=10
num2=14
num3=12
if (num1 >= num2) and (num1 >= num3):
largest=num1
elif (num2 >= num1) and (num2 >=num3):
largest=num2
else:
largest=num3
print("the largest num between",num1,"num2,"num3,"is",largest)
|
54ed98a7d0f6c1fdde317afe0b8ff53b0cefe343 | LucaRuggeri17/pdsnd_github | /script.py | 7,337 | 4.125 | 4 | # Explore Bikeshare data
# Data creation May 2020
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
error_inputs = "ERROR. Please try again"
while True :
city_input = input("\nEnter the city to analyze: \nchicago,\nnew york,\nwashington. \n").lower()
if city_input in ['chicago', 'new york', 'washington']:
break
else:
print(error_inputs)
# TO DO: get user input for month (all, january, february, ... , june)
while True :
month_input = input("\nenter the month that you are interesting: \njanuary,\nfebruary,\nmarch,"
"\napril,\nmay,\njune\nto filter by, or \"all\" to apply no month filter\n").lower()
if month_input in ["january", "february", "march", "april", "may", "june", "all"]:
break
else:
print(error_inputs)
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
while True :
day_input = input("\nenter day of the week that you are interesting: \nmonday,\ntuesday,\nwednesday,\nthursday,"
"\nfriday,\nsaturday,\nsunday\nof week to filter by, or \"all\" to apply no day filter\n").lower()
if day_input in ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "all"]:
break
else:
print(error_inputs)
return city_input, month_input, day_input
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
input_file = CITY_DATA[city] #define input file for city and select from the dictionary the corresponding csv file
df = pd.read_csv(input_file) #dataframe variable to read the file csv
df["start_time_dt"] = pd.to_datetime(arg = df['Start Time'], format = '%Y-%m-%d %H:%M:%S') # convert the string start time in a data format
df["month"] = df['start_time_dt'].dt.month # extract the month from the date column
df["day_of_week"] = df['start_time_dt'].dt.day_name() # extract the day of the week from the date column
if month != 'all': #if you select different from all you have to filter according the different months
months_map = { "january":1,"february":2,"march":3,"april":4,"may":5,"june":6} #create a map where each month has an associated number
month_id = months_map[month]
df = df.loc[df['month'] == month_id] # dataframe becomes filter by month = to month_id
if day != 'all':
df = df.loc[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
df['Start Time'] = pd.to_datetime(arg = df['Start Time'], format = '%Y-%m-%d %H:%M:%S')
month = df['Start Time'].dt.month
weekday_name = df['Start Time'].dt.day_name()
hour = df['Start Time'].dt.hour
# TO DO: display the most common month
most_common_month = month.mode()[0]
print('The month most frequent is:', most_common_month)
# TO DO: display the most common day of week
most_common_day_week = weekday_name.mode()[0]
print('The day of the week most frequent is:', most_common_day_week)
# TO DO: display the most common start hour
most_common_start_hour = hour.mode()[0]
print('The hour most frequent is:', most_common_start_hour)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
print('The start station most frequent is:', df['Start Station'].value_counts().idxmax())
# TO DO: display most commonly used end station
print('The end station most frequent is:', df['End Station'].value_counts().idxmax())
# TO DO: display most frequent combination of start station and end station trip
start_end_stations = df["Start Station"] + "_" + df["End Station"] #concatenate the start station and end station strings
common_station = start_end_stations.value_counts().idxmax() # count the start and end station combination
print('Most frequent start+end stations are:\n{} \nto\n{}'.format(common_station.split("_")[0], common_station.split("_")[1])) # print the most frequent combination
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
start_time = time.time()
# TO DO: display total travel time
total_travel_time = df["Trip Duration"].sum()
print("Total travel time:\n", total_travel_time)
# TO DO: display mean travel time
mean_travel_time = df["Trip Duration"].mean()
print("Mean travel time:\n", mean_travel_time)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
typology_of_user = df["User Type"].value_counts()
# TO DO: Display counts of gender
if "Gender" in df.columns:
gender_counter = df["Gender"].value_counts()
print(gender_counter)
else:
print("This dataset has no information about gender")
# TO DO: Display earliest, most recent, and most common year of birth
if "Birth Year" in df.columns:
earliest_year_of_birth = df["Birth Year"].min()
most_recent_year_of_birth = df["Birth Year"].max()
common_year_of_birth = df['Birth Year'].mode()[0]
print("\nthis is the earliest year of birth: " + str(earliest_year_of_birth))
print("\nthis is the most recent year of birth: " + str(most_recent_year_of_birth))
print("\nthis is the most common year of birh: " + str(common_year_of_birth))
else:
print("This dataset has no information about birth year")
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
935f658529bd76c0f58a1dc795567d10ead00b20 | mhtarek/Uri-Solved-Problems | /1049.py | 648 | 3.78125 | 4 | x= input()
y= input()
z= input()
if x == "vertebrado":
if y=="ave":
if z=="carnivoro":
print("aguia")
elif z == "onivoro":
print("pomba")
elif y=="mamifero":
if z=="onivoro":
print("homem")
elif z == "herbivoro":
print("vaca")
elif x == "invertebrado":
if y=="inseto":
if z=="hematofago":
print("pulga")
elif z == "herbivoro":
print("lagarta")
elif y=="anelideo":
if z=="hematofago":
print("sanguessuga")
elif z == "onivoro":
print("minhoca")
|
cf3ef53dc91ea47ef1cdd9cc7c5fc36c05732d61 | mhtarek/Uri-Solved-Problems | /1216.py | 205 | 3.734375 | 4 | sum = 0
count = 0
while True:
try:
input()
sum+=int(input())
count+=1
except EOFError:
avg = float(sum/count)
print("%.1f" % avg)
break
|
033a7a9082b24b1ba9781d4ae26c98eac30cf805 | mhtarek/Uri-Solved-Problems | /1161.py | 249 | 3.5625 | 4 | def fact(m):
if m==1 or m==0:
return 1
else:
return m*fact(m-1)
while True:
try:
ar = [int(i) for i in input("").split()]
print(fact(ar[0])+fact(ar[1]))
except EOFError:
break
|
c289e68604c1ec7c15f08f2ab33b64e44a63983e | FuelDoks48/Project | /command_if.py | 1,410 | 3.515625 | 4 |
# Обработка специальных значений
# requsted_topping = ['mushrooms', 'green peppers', 'extra chesse']
# for requsted_topping in requsted_topping:
# print (f'Adding {requsted_topping}.')
# print(f'Finished make your pizza!')
# __________________________________________________________
#
# Проверка вхождений
# banned_user = ['marie', 'clare', 'holly', 'Robby']
# user = 'Jannet'
# if user not in banned_user:
# print(f'{user.title()}, you cant post a response if you wish')
# __________________________________________________________
# Простые команды if else
# age = 18
# if age >= 18:
# print('You are ready old')
# else:
# print('Sorry, you are too young to vote.')
# __________________________________________________________
# Цепочки if-elif-else
# age = 12
# if age < 5:
# print('Your admission cost is 0$')
# elif age < 18:
# print('Your admission cost is 18$')
# else:
# print('Your admission cost is 25$')
# __________________________________________________________
#
# number = int(input('enter your number:'))
# isPrime = True
# for divider in range(2, nubmer):
# if number % divider == 0:
# isPrime = False
# break
# if isPrime:
# print('Prime Number')
# else:
# print('Composite Prime')
# __________________________________________________________
|
c76282a14c6a1c54f0566890377035a533786f6c | Engineering-Course/LIP_JPPNet | /get_maximum_square_from_segmented_image.py | 3,716 | 3.609375 | 4 | # This function is used to get the largest square from the cropped and segmented image. It can be further used to find patterns
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import time
from collections import namedtuple
import glob
def printMaxSubSquare(M):
"""" find the largest square """
R = len(M) # no. of rows in M[][]
C = len(M[0]) # no. of columns in M[][]
S = [[0 for k in range(C)] for l in range(R)]
# here we have set the first row and column of S[][]
# Construct other entries
for i in range(1, R):
for j in range(1, C):
if (M[i][j] == 1):
S[i][j] = min(S[i][j-1], S[i-1][j],
S[i-1][j-1]) + 1
else:
S[i][j] = 0
# Find the maximum entry and
# indices of maximum entry in S[][]
max_of_s = S[0][0]
max_i = 0
max_j = 0
for i in range(R):
for j in range(C):
if (max_of_s < S[i][j]):
max_of_s = S[i][j]
max_i = i
max_j = j
print("Maximum size sub-matrix is: ")
count_i = 0
count_j = 0
position_matrix = []
for i in range(max_i, max_i - max_of_s, -1):
for j in range(max_j, max_j - max_of_s, -1):
position_matrix.append((i,j))
count_i+=1
print('count_i :' + str(count_i))
print('count_j :' + str(count_j))
return position_matrix
def crop_square_portion(image_file_name):
"""" crop and save image """
image_file_name_list = image_file_name.split('_')
vis_file_name = '_'.join(image_file_name_list[:2])+'_vis.png'
save_file_name = '_'.join(image_file_name_list[:3])+'_square.png'
cloth_type = image_file_name_list[-2]
list_index = cloth_type_list.index(cloth_type)
light_shade = light_shade_list[list_index]
dark_shade = dark_shade_list[list_index]
print(light_shade,dark_shade)
#read input image
img = cv2.imread(INPUT_DIR+vis_file_name,cv2.COLOR_BGR2RGB)
#detect shades from vis:
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
mask = cv2.inRange(hsv, light_shade, dark_shade)
#coverting to binary array:
np_img = np.array(mask)
np_img[np_img == 255] = 1
#coverting to binary array:
np_img = np.array(mask)
np_img[np_img == 255] = 1
#find and plot the largest square
var = printMaxSubSquare(np_img)
for point in var:
a,b = point
pt = (b,a)
cv2.circle(np_img,pt,5,(200,0,0),2)
##convert mask to bunary mask
np_img[np_img != 200] = 0
print('final mask shape:')
print(np_img.shape)
##crop and save the square image
img = cv2.imread(INPUT_DIR+image_file_name,cv2.COLOR_BGR2RGB)
print('input image shape:')
print(img.shape)
x,y,w,h = cv2.boundingRect(np_img)
crop_img = img[y:y+h,x:x+w]
print('cropped image shape:')
print(crop_img.shape)
cv2.imwrite(OUTPUT_DIR+save_file_name, crop_img)
if __name__ == "__main__":
INPUT_DIR = r' set your input folder where segmented images are there'
OUTPUT_DIR = r' set your output images'
cloth_type_list = ['UpperClothes','Dress','Pants','Scarf','Skirt','Coat']
light_shade_list = [(100, 240, 255),(0,255,70),(0,255,70),(10,150,125),(50,0,70),(10,100,200)]
dark_shade_list = [(190, 255, 255),(0,255,200),(100,255,200),(100,160,130),(60,255,200),(20,255,255)]
#for each bgcropped file read, pass to crop_image function
for file in glob.glob(INPUT_DIR+'*_cropped.png'):
print(file)
image_file_name = file.split('\\')[-1]
crop_square_portion(image_file_name)
|
da16b14210a67f0b8bff8212d023eff2040e5424 | AlifeLine/toolkit | /tools/quick_sort2.py | 617 | 4 | 4 | def quick_sort(arr, left=0, right=None):
if right is None:
right = len(arr) - 1
if left >= right:
return
l = left
r = right
key = arr[left]
while left < right:
while left < right and arr[right] >= key:
right -= 1
arr[left] = arr[right]
while left < right and arr[left] <= key:
left += 1
arr[right] = arr[left]
arr[right] = key
quick_sort(arr, l, right-1)
quick_sort(arr, right+1, r)
if __name__ == "__main__":
arr = [6,3,8,1,4,6,9,2]
#quick(arr, 0, len(arr)-1)
quick_sort(arr)
print(arr) |
72a89c29b77bca2fcada96ce5a4b46cc965128c4 | AlifeLine/toolkit | /tools/lru.py | 815 | 3.8125 | 4 | class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class Lru(object):
def __init__(self, vals):
self._head = None
for val in vals:
node = Node(val)
if self._head:
self._head.next = node
else:
self._head = node
def hit(self, val):
cur = self._head
while cur:
if cur.val == val and cur is not self._head:
next = cur.next
if next:
cur.next = next.next
cur.next.next = cur
next.next = self._head
self._head = next
return True
elif cur is not self._head:
return True
return False
|
bd001f39c500f13c409b9e4f22f41156cabc636d | leolion0/490-Lesson-3 | /question 1.py | 1,451 | 3.890625 | 4 | class Employee:
numEmployees = 0
def __init__(self, name="", family="", salary="", department=""):
self.name = name
self.family = family
self.salary = salary
self.department = department
Employee.numEmployees += 1
def fillFromUser(self):
self.name = str(input("Name of the employee: "))
self.family = str(input("Family of the employee: "))
self.salary = str(input("Salary of the employee: "))
self.department = str(input("Department of the employee: "))
def __str__(self):
outStr: str = "Name: " + self.name + "\n"
outStr += "Family: " + self.family + "\n"
outStr += "Salary: " + str(self.salary) + "\n"
outStr += "Department: " + self.department + "\n"
return outStr
def avgSal(employees):
average = 0
numEmps = employees[0].__class__.numEmployees
for i in employees:
average += int(i.salary)
return average / numEmps
class FulltimeEmployee(Employee):
def __init__(self, name="", family="", salary="", department="", hours=40):
Employee.__init__(self, name, family, salary, department)
self.hours = hours
theEmps = list()
theEmps.append( Employee("John", "White", 3600, "Sales"))
theEmps.append(FulltimeEmployee("Alice", "Wonderland", 74000, "IT", 43))
theEmps.append(FulltimeEmployee())
theEmps[2].fillFromUser()
for i in theEmps:
print(i)
print(avgSal(theEmps))
|
6ee056c951856f4bc7e8e6bd7d95b10865c3085b | rohitbapat/NQueensNRooks-Problem | /a0.py | 8,287 | 4.1875 | 4 | #!/usr/bin/env python3
# nrooks.py : Solve the N-Rooks problem!
#
# The N-Queens problem is: Given an empty NxN chessboard, place N queens on the board so that no queens
# can take any other, i.e. such that no two queens share the same row,column or are on the same diagonal
#
# Citations mentioned at the end of the code
import sys
# Count number of pieces in given row
def count_on_row(board, row):
count=0
# Iterate each node in every row
#[2]
for i in board[row]:
if(i==1):
count+=1
return count
# Count number of pieces in given column
def count_on_col(board, col):
count=0
# Iterate over every column node of every row
for x in ([a[col] for a in board]):
if(x==1):
count+=1
return count
# Count total number of pieces on board
def count_pieces(board):
count=0
# Double for loop to check each node and update count
for row in range(N):
for col in range(N):
if(board[row][col]==1):
count+=1
return count
# Return a string with the board rendered in a human-friendly format
def printable_board(board):
# Modifications done in display function to incorporate unusable nodes and tag them as X with -1 as value
#[4]
if(problem_type=="nqueen"):
return "\n".join([ " ".join([ "Q" if col==1 else "X" if col==-1 else "_" for col in row ]) for row in board])
elif(problem_type=="nrook"):
return "\n".join([ " ".join([ "R" if col==1 else "X" if col==-1 else "_" for col in row ]) for row in board])
else:
return "\n".join([ " ".join([ "K" if col==1 else "X" if col==-1 else "_" for col in row ]) for row in board])
# Add a piece to the board at the given position, and return a new board (doesn't change original)
def add_piece(board, row, col):
return board[0:row] + [board[row][0:col] + [1,] + board[row][col+1:]] + board[row+1:]
# Successor function to place N rooks if given as the input argument.
# Sucessor function same as nrooks.py successors3()
def nrooks_successors(board):
rook_number=count_pieces(board)
if(rook_number<N and board!=[]):
return [ add_piece(board, r, c) for c in range(0, rook_number+1) for r in range(0,N) if count_on_row(board,r)!=1 and count_on_col(board,c)!=1 and board[r][c]!=-1]
else:
return []
# Function to check if the queen is under attack with checking of diagonals
def check_position(board,r,c):
if((count_on_row(board,r))==1 or (count_on_col(board,c)==1)):
return True
#Iterate from start of Board to check the presence of a queen with respect to current queen position
for board_row in range(0,N):
for board_col in range(0,N):
# The first condition checks if the diagonals perpendicular to current queen diagonal have any Queens already
# The second condition checks for presence of queen above or below the current queen diagonal
# [5]
if((board_row+board_col==r+c) or (board_row-board_col==r-c)):
if(board[board_row][board_col]==1):
return True
return False
# Function to find and return successors of current board of N queens
def nqueen_successors(board):
# Accumaulate result state
result=[]
rook_number=count_pieces(board)
# Find all successors for current board in next column
for c in range(0,rook_number+1):
for r in range(0,N):
# If any inner conditions is true the piece is not appended as a valid successor
if(not(check_position(board,r,c)) and board[r][c]!=1 and board[r][c]!=-1):
result.append(add_piece(board,r,c))
return result
# Function to check if the knight is under attack
def check_position_nknight(board,r,c):
#Iterate from start of Board to check the presence of a queen with respect to current queen position
for board_row in range(0,N):
for board_col in range(0,N):
# The first condition checks if the diagonals perpendicular to current queen diagonal have any Queens already
# The second condition checks for presence of queen above or below the current queen diagonal
# [5]
#print(board_row)
#print(board_col)
if(board[board_row][board_col]==1):
if((int(r-board_row)**2)+(int(c-board_col)**2)==5):
return True
return False
# Function to find and return successors of current board of N Knights
def nknight_successors(board):
# Accumaulate result state
result=[]
#rook_number=count_pieces(board)
# Find all successors for current board in next column
for c in range(0,N):
for r in range(0,N):
# If any inner conditions is true the piece is not appended as a valid successor
#print(check_position_nknight(board,r,c))
if(not(check_position_nknight(board,r,c)) and board[r][c]!=1 and board[r][c]!=-1):
#print(r)
#print(c)
#print("Rohit")
result.append(add_piece(board,r,c))
return result
# Check if board is a goal state without count_on_row or count_on_col function already checked in the successor
def is_goal(board):
return count_pieces(board) == N
# Solve for n-queen
def solve_dfs_nqueen(initial_board):
fringe = [initial_board]
while len(fringe) > 0:
for s in nqueen_successors( fringe.pop() ):
if(count_pieces(s)==N):
if is_goal(s):
return(s)
fringe.append(s)
return False
# Solve for n-rooks
def solve_dfs_nrooks(initial_board):
fringe = [initial_board]
while len(fringe) > 0:
for s in nrooks_successors( fringe.pop() ):
# Check only if N rooks are placed
if(count_pieces(s)==N):
if is_goal(s):
return(s)
fringe.append(s)
return False
# Solution for n-knights
def solve_dfs_nknights(initial_board):
fringe = [initial_board]
while len(fringe) > 0:
for s in nknight_successors( fringe.pop() ):
# Check only if N knights are placed
if(count_pieces(s)==N):
if is_goal(s):
return(s)
fringe.append(s)
return False
# This is N, the size of the board. It is passed through command line arguments.
problem_type=str(sys.argv[1])
N = int(sys.argv[2])
# Set initial board nodes to Zero
initial_board=[0]*N
for i in range(N):
initial_board[i]=[0]*N
initial_board = [[0]*N for _ in range(N)]
#[3]
#Check if further arguments are provided for blocked positions
if(len(sys.argv)>3):
blocked_places=int(sys.argv[3])
for place in range(0,blocked_places):
blocked_row=int(sys.argv[(place*2)+4])
blocked_column=int(sys.argv[(place*2)+5])
# Decide a blocked position with node filled as -1
#[1]
initial_board[blocked_row-1][blocked_column-1]=-1
print ("Starting from initial board:\n" + printable_board(initial_board) + "\n\nLooking for solution...\n")
# Call to different solve functions based on user input
if(problem_type=="nqueen"):
solution = solve_dfs_nqueen(initial_board)
elif(problem_type=="nrook"):
solution = solve_dfs_nrooks(initial_board)
else:
solution = solve_dfs_nknights(initial_board)
print (printable_board(solution) if solution else "Sorry, no solution found. :(")
'''
[1] https://www.geeksforgeeks.org/printing-solutions-n-queen-problem/
Check solution states for N=4 for verification
[2] https://stackoverflow.com/questions/16548668/iterating-over-a-2-dimensional-python-list
Iterating over a 2D array in python
[3] https://www.programiz.com/python-programming/matrix
https://stackoverflow.com/questions/2739552/2d-list-has-weird-behavor-when-trying-to-modify-a-single-value
Way of creating a 2D matrix with different references
[4] https://stackoverflow.com/questions/20888693/python-one-line-if-elif-else-statement/20888751
if elif else statements on one line
[5] https://www.codesdope.com/blog/article/backtracking-explanation-and-n-queens-problem/
Perpendicular Diagonal Check for current Queen Diagonal
'''
|
bad58f360c606e5a92312ffd2115872b42fffd57 | tenasimi/Python_thero | /Class_polymorphism.py | 1,731 | 4.46875 | 4 | # different object classes can share the same name
class Dog():
def __init__(self, name):
self.name = name
def speak(self): # !! both Nico and Felix share the same method name called speak.
return self.name + " says woof!"
class Cat():
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says meow!"
#creating 2 instances one for each class
niko = Dog("niko")
felix = Cat("felix")
print(niko.speak())
print(felix.speak())
# metod 1 iterasiya ile gormek olur polimprfizmi
for pet in [niko,felix]: # pet!! iterating via list of items
print(type(pet))
print(type(pet.speak())) # both class instances share the same method name called speak
print()
print(pet.speak()) # however they are different types here main__.Cat' , main__.Dog'
print()
# metod 2 funksiya ile:
def pet_speak(pet):
print(pet.speak())
pet_speak(niko)
pet_speak(felix)
# Method3, abstract base class use
class Animal():
def __init__(self,name):
self.name = name
def speak(self): # we a raising an error, It's expecting you to inherit the animal class and then overwrite the speak method.
raise NotImplementedError("Subclass must implement this abstarct method")
# bunlari acsan erroru gorersen
#myanimal = Animal('fred')
#print(myanimal.speak())
class Dog(Animal):
def speak(self):
return self.name+ " says woof!"
class Cat(Animal):
def speak(self):
return self.name + " says meow!"
fido = Dog("Fido")
isis = Cat("isis")
# different object classes can share the same method name
print(fido.speak())
print(isis.speak()) |
5cd6aae2bacc1b6626dafbc541c626c811e67aac | tenasimi/Python_thero | /Class_Inheritance.py | 717 | 4.15625 | 4 | class Animal():
def __init__(self):
print("ANIMAL CREATED")
def who_am_i(self):
print("I am animal")
def eat(self):
print("I am eating")
myanimal = Animal() #__init__ method gets automatically executed when you
# create Anumal()
myanimal.who_am_i()
myanimal.eat()
print()
#Dog is a Derived class from the base class Animal
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog Created")
def who_am_i(self):
print("I am a dog!")
def bark(self):
print("WOOF!")
def eat(self):
print("I am a dog and eating")
mydog = Dog()
mydog.eat()
mydog.who_am_i()
mydog.bark()
mydog.eat() |
ef64e2b1091b79e6c1df275002c49bb501b70759 | tenasimi/Python_thero | /test_test_test.py | 1,345 | 3.828125 | 4 | print(1 % 2)
print(2 % 2)
print(3 % 2)
print(4 % 2)
print(5 % 2)
print(6 % 2)
print(7 % 2)
print(8 % 2)
print(9 % 2)
def almost_there(n):
return (abs(100-n) <= 10) or (abs(200-n) <= 10)
print(almost_there(190))
print(abs(20-11))
#help(map)
print()
def square(num):
return num**2
print(square(6))
def up_low(s):
d={"upper":0, "lower":0}
for c in s:
if c.isupper():
d["upper"]+=1
elif c.islower():
d["lower"]+=1
else:
pass
print ("Original String: ", s)
print("No. of Upper case characters: ", d["upper"])
print("No. of Lower case characters: ", d["lower"])
#vizivaem
s='Hello mr. Rogers, how are you, this fine Tuesday?'
up_low(s)
print()
def unique_list(l):
x=[]
for a in l:
if a not in x:
x.append(a)
return x
l = [1,1,1,1,3,3,4,6,5,6,9,46]
print(unique_list(l))
print()
def multiply(numbers):
total = numbers[0]
for x in numbers:
total *= x
return total
numbers = [1,2,3,-4]
print(multiply(numbers))
print()
def palindrome(s):
return s == s[::-1]
print(palindrome('alla'))
print()
import string
def ispangram(str1, alphabet = string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(str1.lower())
print(ispangram("The quick brown fox jumps over the lazy dog"))
|
6abeba2d5f744e34aa97a48fe06a5dac4cf27207 | tenasimi/Python_thero | /sec4_comparison_operators.py | 7,715 | 4.46875 | 4 | print(1 < 2 and 2 > 3)
print(1 < 2 and 2 < 3)
print('h' == 'h' and 2 == 2) # AND!! both of them must be true
print(1 == 2 or 2 < 3) # OR!! one of them must be true
print(not 1 == 1) # NOT !! for opposite boolean result
#
if True:
print('ITS TRUE!')
#
if False:
print('ITS False!')
else:
print('Its always True')
#
if 3>2:
print('3 greater 2, TRUE')
else:
print('3 is not greater 2, False')
#
if 3<2:
print('3 greater 2, TRUE')
else:
print('3 is not greater 2, False')
#
hungry = True
if hungry:
print('FEED ME!')
#
hungry = True
if hungry:
print('FEED ME!') #empty output
else:
print('Im not hungry')
#
loc = 'Bank'
if loc == 'Auto Shop':
print('Cars are cool!')
else:
print('I do not know much, maybe its bank')
#for checking other conditions use ELIF
# we can add and more lives for more conditions.
loc = 'Bank'
#loc = 'Auto Shop'
loc = 'Store'
if loc == 'Auto Shop':
print('Cars are cool!')
elif loc == 'Bank':
print('Money is cool!')
elif loc == 'Store':
print('Welcome to the store!')
else:
print('I do not know much')
#
#name = 'Jose' # esli nicto ne podoydet
#name = 'Frankie'
name = 'Sammy'
if name == 'Frankie':
print('Hello Frankie!')
elif name == 'Sammy':
print('Hello Sammy')
else:
print('What is your name?')
# for loop
my_iterable = [1,2,3]
for item_name in my_iterable:
print(item_name)
print()
#
mylist = [1,2,3,4,5,6,7,8,9,10]
for num in mylist:
print(num)
#
mylist = [1,2,3,4,5,6,7,8,9,10]
for jelly in mylist:
print(jelly)
#
mylist = [1,2,3,4,5,6,7,8,9,10]
for jelly in mylist:
print('hello')
#
mylist = [1,2,3,4,5,6,7,8,9,10]
for num in mylist:
# check for even
if num % 2 ==0:
print(num)
print()
# snacala iz spiska otbiraem cetnie cisla (if), a potom (else) vivodin to cto ostalos (necetnie)
mylist = [1,2,3,4,5,6,7,8,9,10]
for num in mylist:
if num % 2 == 0: # to cto delitsa na 2 bez ostatka
print(num)
else:
print(f'Odd Number: {num}')
print()
# to je samoe, naoborot, cnacala necetnie, potom to cto ostalos - cetnie
mylist = [1,2,3,4,5,6,7,8,9,10]
for num in mylist:
if num % 2 == 1: # to cto delitsa na 2 s ostatkom 1
print(num)
else:
print(f'Even Number: {num}')
print()
#
mylist = [1,2,3,4,5,6,7,8,9,10]
list_sum = 0
for num in mylist:
list_sum = list_sum + num #0+1=1, 1+2=3, 3+3=6, 6+4=10, 10+5=15,15+6=21,21+7=28,28+8=36,36+9=45,45+10=55
print(list_sum)
print()
#
mylist = [1,2,3,4,5,6,7,8,9,10]
list_sum = 0
for num in mylist:
list_sum = list_sum + num # to je samoe no podrobno v stolbike uvidim process slojeniya
print(list_sum) # placing print inside of for loop
print()
#
# iterating letters i string:
mystring = 'Hello World'
for letter in mystring:
print(letter)
print()
# ex. Print cool for as many times as your characters in string
for ggg in 'Hello World':
print('Cool!')
# You can also use the same iteration for each tuple.
# pecataem cto xotim v cislo raz soderjimoqo tu;ipa
tup = (1,2,3)
for item in tup:
print('cislo raz')
#
print()
# pecataem soderjanie tulip-a
tup = (1,2,3)
for item in tup:
print('item')
print()
#
mylist = [(1,2),(3,4),(5,6),(7,8)]
print(len(mylist))
for item in mylist:
print(item)
#unpack tuple ex.
print()
mylist = [(1,2),(3,4),(5,6),(7,8)]
for (a,b) in mylist:
print(a)
print(b)
#unpack tuple ex.
print()
mylist = [(1,2),(3,4),(5,6),(7,8)]
for a,b in mylist:
print(b)
#unpack tuple ex .
print()
mylist = [(1,2,3),(5,6,7),(8,9,10)]
for item in mylist:
print(item)
print()
# But I can do tuple unpacking here, only print 2 6 9 ex.:
mylist = [(1,2,3),(5,6,7),(8,9,10)]
for a,b,c in mylist:
print(b)
print()
# Dictionary iteration
#by default when you iterate through a dictionary you only iterate through the Keys.
d = {'k1':1, 'k2':2, 'k3':3}
for item in d:
print(item)
print()
# if you want iterate through items themselves call .items(:
d = {'k1':1, 'k2':2, 'k3':3}
for item in d.items():
print(item)
print()
# primenyaya priem visheprivedenniy v tuple, mojno delat UNPACKING
d = {'k1':1, 'k2':2, 'k3':3}
for key,value in d.items():
print(value)
print()
# only value ex.
d = {'k1':1, 'k2':2, 'k3':3}
for value in d.values():
print(value)
print()
# WHILE loop ex.
x = 0
while x < 5:
print(f'The current value of x is {x}')
x = x + 1 #or x +=1 is more compact
print()
# WHILE + else
x = 0
while x < 5:
print(f'The current value of x is {x}')
x += 1
else:
print('X is NOT less than 5')
print()
# pass keyword ex.
x = [1,2,3]
for item in x:
# many times programmers keep it as a placeholder to kind of avoid a syntax error b
pass
print('end of my script')
#
print()
mystring = 'Sammy'
for letter in mystring:
print(letter)
# I'm not actually printing out the letter.
print()
mystring = 'Sammy'
for letter in mystring:
if letter == 'a':
continue
print(letter)
# break ex. - stopping loop.
print()
mystring = 'Samrikitmo'
for letter in mystring:
if letter == 'k':
break
print(letter)
# break ex. - stopping loop at 2.
print()
x = 0
while x < 5:
if x == 2: # dobavlyaem
break # break uslovie
print(x)
x += 1
#
print()
#mylist = [a,b,c]
for bam in range(3): #all range from 0 to 3
print(bam)
print()
#mylist = [a,b,c]
for num in range(2,5): #start from 2 not include 5
print(num)
print()
#mylist = [a,b,c]
for num in range(3,10,2): #start from 3 not include 5 + step size 2
print(num)
k = list(range(3,28,2))
print(k)
print()
# enumerate with format + for
index_count = 0
for letter in 'abcde':
print('At index {} the letter is {}'.format(index_count,letter))
index_count += 1
print()
# to je samoe no s funksiey enumerate
word = 'abcde'
for item in enumerate(word): # v enumerate stavim iterable var - word
print(item)
print()
# delaem enumerate + tuple unpacking
word = 'abcde'
for ind,let in enumerate(word): # znaya cto vivedet tuple, delaem unpack naxodu
print(ind)
print(let)
print('\n')
# zip - funksiya sozdayuwaya tuple iz listov
mylist1 = [1,2,3]
mylist2 = ['a','b','c']
for item in zip(mylist1,mylist2):
print(item)
print()
# zip - funksiya sozdayuwaya tuple iz listov
mylist1 = [1,2,3]
mylist2 = ['a','b','c']
mylist3 = [100,200,300]
for item in zip(mylist1,mylist2,mylist3):
print(item)
print()
# zip - Zipp is only going to be able to go and zip together as far as the list which is the shortest.
mylist1 = [1,2,3,4,5,6]
mylist2 = ['a','b','c']
mylist3 = [100,200,300]
for item in zip(mylist1,mylist2,mylist3):
print(item)
print()
#list + zip - zipping together 2 lists
l = list(zip(mylist1,mylist2))
print(l)
# in
# in keyword PROVERKA USLOVIYA, est li x v spiske?
# is X in the list 1 to 3 and 0 return back a boolean true or false.
print('x' in ['x','y','z'])
print()
print('a' in 'a world') # string ex
print()
print('mykey' in {'mykey':345}) # dict ex.
print()
d={'mykey':345}
print(345 in d.keys())
print(345 in d.values())
print()
# min max functions
mylist = [10,20,30,40,100]
print(min(mylist))
print(max(mylist))
# random library use
from random import shuffle
mylist = [1,2,3,4,5,6,7,8,9,10]
shuffle(mylist) # peremewivaet (shuffle)
print(mylist)
print()
# ramdom integer function , grabs random int from interval
from random import randint
print(randint(0,100))
# also i can save its random output and use later
mynum = randint(0,10)
print(mynum)
#
# input
print(input('Enter a number here: '))
result = input('What is your name? ')
print(result)
print(type(result))
result = input('What is your favorite number? ')
print(float(result))
print(int(result))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.