text
stringlengths 37
1.41M
|
---|
def get_str(str1):
character = str1[0]
str1 = str1.replace(character, '$')
str1 = character + str1[1:]
return str1
if __name__ == "__main__":
string_made = input('Enter the string: ')
print(get_str(string_made)) |
name_list = ['Sudarshan', 'Niku', 'Suraj', 'Swapnil']
def find_john(name_list):
for i in name_list:
if i == 'John':
return i
return "Not found"
print(find_john(name_list))
|
d1 = {'Apple': 1, 'Banana': 2, 'Orange': 3}
d2 = {'Queen': 4, 'King': 5, 'Prince': 6, 'Princess': 7}
dict3 = d1.copy()
dict3.update(d2)
print(dict3) |
paragraph = "tar rat arc car elbow below state taste cider cried dusty got hurt my chin"
paraSplit = paragraph.split()
def findAnagram(paraSplit):
dict = {}
for word in paraSplit:
key = ''.join(sorted(word))
if key in dict.keys():
dict[key].append(word)
else:
dict[key] = []
dict[key].append(word)
output = ""
for key, value in dict.items():
if len(value) > 1:
output = output + ' '.join(value) + ' '
return output
print(findAnagram(paraSplit))
|
d1 = {0: 1, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 15, 7: 20}
def check_key_presence(d1, k):
if k in d1:
print('Key is present.')
else:
print('key is not present.')
check_key_presence(d1, 2)
check_key_presence(d1, 3)
check_key_presence(d1, 5)
check_key_presence(d1, 11)
check_key_presence(d1, 6)
check_key_presence(d1, 10) |
#!/usr/bin/python3.6
def plus(a, b):
return a + b
def minus(a, b):
return a - b
def durchschnitt(a, b):
return (a + b) / 2
def gleiches_vorzeichen(a, b):
return (a >= 0 and b >= 0) or (a < 0 and b < 0)
while True:
a = float(input('Erste Zahl: '))
b = float(input('Zweite Zahl: '))
op = input('Operation: ')
if op == '+':
resultat = plus(a, b)
print(f'{a} + {b} = {resultat}')
elif op == '-':
resultat = minus(a, b)
print(f'{a} - {b} = {resultat}')
elif op == 'd':
resultat = durchschnitt(a, b)
print(f'Durchschnitt von {a} und {b}: {resultat}')
elif op == 'v':
resultat = gleiches_vorzeichen(a, b)
if resultat == True:
print(f'{a} und {b} haben das gleiche Vorzeichen')
else:
print(f'{a} und {b} haben unterschiedliche Vorzeichen')
|
for i in range(10):
print(i)
for c in "Hallo":
print(c)
for line in open("lyrics.txt"):
print(line.strip())
for zahl in [1, 2, 3, 4, 5]:
print(zahl)
for index, wort in enumerate(['Habe', 'nun', 'ach'], 1):
print(f"Das {index}. Wort ist { wort }.")
|
def print_2(eins, zwei):
print(eins, zwei)
def print_1(eins):
print(eins)
def print_nichts():
print('Nichts')
print_2('Zwiebelnsauce', 'Bratwurst')
print_1('Eule')
print_nichts()
vorname = 'Marco'
nachname = 'Schmalz'
print_2(vorname, nachname)
# Speziell in Python
print_2(zwei=nachname, eins=vorname)
print(1, 2, 3, sep='-')
# Default-Werte für Argumente oder auch optionale Argumente
def print_etwas_oder_nichts(etwas=''):
if etwas == '':
print('Nichts')
else:
print(etwas)
print_etwas_oder_nichts('etwas')
print_etwas_oder_nichts()
def multiplizieren(a, b):
print('MULTIPLIZIEREN', a, b)
return a * b
def quadrieren(a):
print('QUADRIEREN', a)
return a * a
def addieren(a, b):
print('ADDIEREN', a, b)
return a + b
a = 3
b = 4
a_quadrat = quadrieren(a)
b_quadrat = quadrieren(b)
c_quadrat = addieren(a_quadrat, b_quadrat)
print(f"{a}² + {b}² = {c_quadrat}")
|
liste = [1, 2, 3, 4, 5, 6]
print("Zweites Element:", liste[1])
print(liste[1:3])
print(liste[1:])
print(liste[-1])
print(liste[:3])
print('anna'[2])
print('anna'[1:3])
|
#!/usr/bin/python3
import csv
filename = 'mitglieder.csv'
for mitglied in csv.DictReader(open(filename)):
# Frage: Wie lauten die Emailadressen der Mitglieder die noch nicht
# bezahlt haben?
print(mitglied['Vorname'], mitglied['Nachname'])
# Idealer Output: "Vorname1 Nachame1" <[email protected]>, "Vorname2 ...
|
def isPalindrome(word):
for index in range(len(word) // 2):
if word[index] != word[-index-1]:
return False
return True
def isPalindromRekursiv(word):
if len(word) <= 1: # simple Fälle
return True
else:
if word[0] != word[-1]:
return False
else:
return word[1:-1] istDasInnereEinPalindrome???
woerter = [] #'asna Anna kurt wasitacatisaw level'.split()
for word in woerter:
if isPalindrome(word):
print('"{}" ist ein Palindrom'.format(word))
else:
print('"{}" ist KEIN Palindrom'.format(word))
word = input("Gib ein Satz ein: ")
word = word.lower().replace(' ', '') # Sanitize input
print(isPalindrome(word))
|
for i in range(10): # for (int i=0; i<10; i++) {}
print(i)
print("-" * 20)
for i in range(1, 11, 2):
print(i)
|
#!/usr/bin/python3
import csv
import datetime
heute = datetime.date.today()
file = open('../team.csv')
reader = csv.DictReader(file)
entries = list(reader)
lehrlinge = []
for entry in entries:
if 'Lehre' in entry['Gruppen'].split(', '):
lehrlinge.append(entry)
for lehrling in lehrlinge:
datumsliste = lehrling['Geburtstag'].split('.')
lehrling['Geburtstag'] = '-'.join(reversed(datumsliste))
for lehrling in lehrlinge:
print(lehrling['Geburtstag'])
juengste = lehrlinge[0]
for lehrling in lehrlinge[1:]:
if lehrling['Geburtstag'] > juengste['Geburtstag']:
juengste = lehrling
print(juengste)
|
cantidadNumeros = 0
numerosSumatoria = 0
resultado = 1
print("en este programa haremos la division de la cantidad de numeros que tu quieras")
cantidadNumeros = int(input("Cuantos numeros deseas dividir?"))
for i in range(1,cantidadNumeros + 1):
numerosSumatoria = int(input("ingresa el valor"))
if(i == 1):
resultado = numerosSumatoria
else:
resultado = resultado / numerosSumatoria
print("tu division es: ",resultado)
|
def is_equilateral(a, b, c):
return a == b == c
def is_isosceles(a, b, c):
return a == b or b == c or c == a
def is_scalene(a, b, c):
return a != b and b != c and c != a
a = input('Enter the length of the first side: ')
b = input('Enter the length of the second side: ')
c = input('Enter the length of the third side: ')
if is_equilateral(a, b, c):
print('Triangle is equilateral!')
if is_isosceles(a, b, c):
print('Triangle is isosceles!')
if is_scalene(a, b, c):
print('Triangle is scalene!')
# Another correct implementation, but with slightly different behavior:
# It won't tell you that equilateral triangles are also isosceles triangles
if is_equilateral(a, b, c):
print('Triangle is equilateral!')
elif is_isosceles(a, b, c):
print('Triangle is isosceles!')
else:
print('Triangle is scalene!')
|
# Car Assignment
class Car:
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if price > 10000:
self.tax = "15%"
else:
self.tax = "12%"
def displayAll(self):
print("Price: " + str(self.price))
print("Speed: " + self.speed)
print("Fuel: " + self.fuel)
print("Mileage: " + self.mileage)
print("Tax: " + self.tax)
return self
car1 = Car(15000, '120mph', 'Full', '45mpg')
car1.displayAll()
car1 = Car(7500, '100mph', 'Empty', '25mpg')
car1.displayAll()
|
# For Loop Basic 1
# 1. Basic - Print all the numbers/integers from 0 to 150
for num in range(0, 151):
print(num)
# 2. Multiples of five - Print all the multiples of 5 from 5 to 1,000,000
for five in range(0, 100001):
if(five % 5 == 0):
print(five)
# 3. Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print 'Coding', if divisible by 10 "Coding Dojo"
for num in range(1, 101):
if(num % 10 == 0):
print("Coding Dojo")
elif(num % 5 == 0):
print("Coding")
else:
print(num)
# 4. Whoa! That suckers's huge - Add odd integers from 0 to 500,000, and print the final sum
sum = 0
for num in range(0, 50):
if(num % 2 != 0):
sum = sum + num
print(sum)
print("FINAL SUM: ", sum)
# 5. Countdown by Fours - Print positive numbers starting at 2018, couting down by fours(exclude 0)
for num in range(2018, 0, -1):
if(num % 4 == 0):
print(num)
# 6. Flexible Countdown - Given 'lolwNum', 'highNum', 'mult', print multiples of mult from lowNum to highNum, using a FOR loop. For (2,9,3), print 3 6 9 (on succesive lines)
def multiples(lowNum, highNum, mult):
for num in range(lowNum, highNum):
if(num % mult == 0):
print(num)
# Test Case
multiples(0, 100, 2)
multiples(0, 100, 3)
multiples(0, 100, 4)
|
# Insertion Sort
arr = [4,3,2,10,12,1,5,6]
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
print(arr)
return arr
insertionSort(arr)
|
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list
if __name__ == '__main__':
n = int (input ().strip ())
arr = list (map (int, input ().strip ().split ()))
print (sorted (set (arr))[-2])
|
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/the-minion-game
def minion_game(s):
# your code goes here
vowels = 'AEIOU'
kevsc = 0
stusc = 0
slen = len (s)
for i in range (slen):
if s[i] in vowels:
kevsc += (slen - i)
else:
stusc += (slen - i)
if kevsc > stusc:
print ("Kevin", kevsc)
elif kevsc < stusc:
print ("Stuart", stusc)
else:
print ("Draw")
if __name__ == '__main__':
minion_game(input().strip())
|
#!/usr/bin/env python3
# https://www.hackerrank.com/challenges/designer-door-mat
N, M = map(int,input().split())
for i in range(1,N,2):
print (('.|.' * i).center (M, '-'))
print ('WELCOME'.center (M, '-'))
for i in range(N-2,-1,-2):
print (('.|.' * i).center (M, '-'))
|
#!/usr/bin/env python3
def jump_clouds (c):
x = len (c)
j = 0
i = 0
while i < (x - 1):
if i + 2 < x and c[i + 2] == 0:
i += 2
j += 1
elif i + 1 < x and c[i + 1] == 0:
i += 1
j += 1
return j
_ = input ()
c = list (map (int, input ().strip ().split ()))
print (jump_clouds (c))
|
#!/usr/bin/env python3
from collections import Counter
_ = input ()
stock = Counter (input ().strip ().split ())
pairs = 0
for n in stock.values ():
pairs += int (n / 2)
print (pairs)
|
#https://www.acmicpc.net/problem/2580
import sys
def search(board,i,j):
count=[0]*10
#row
for k in range(9):
count[board[i][k]]+=1
#column
for k in range(9):
count[board[k][j]]+=1
#square
x=i//3
y=j//3
for n in range(3):
for m in range(3):
count[board[3*x+n][3*y+m]]+=1
#get candidate
candidate=[]
for k in range(9,0,-1):
if count[k]==0:
candidate.append(k)
return candidate
def sudoku(board,blank,k):
if k==len(blank):
return board
i,j=blank[k]
candidate=search(board,i,j)
if candidate:
for x in candidate:
board[i][j]=x
flag=sudoku(board,blank,k+1)
if flag:
return flag
else:
board[i][j]=0
return []
else:
return []
board=[]
blank=[]
for i in range(9):
line=list(map(int,sys.stdin.readline().split()))
board.append(line)
for j in range(9):
if line[j]==0:
blank.append([i,j])
board=sudoku(board,blank,0)
for i in range(9):
print(*board[i])
|
#https://www.acmicpc.net/problem/2581
def isPrime(x):
if x==1:
return False
for d in range(1,int(x**0.5)):
if x==d+1:
continue
if x%(d+1)==0:
return False
else:
return True
N=int(input())
M=int(input())
sum=0
min=10001
for x in range(N,M+1):
if isPrime(x):
sum+=x
if min>x:
min=x
if sum==0:
print(-1)
else:
print(sum)
print(min)
|
#https://www.acmicpc.net/problem/1193
import math
def get_order(X,group):
max_order=(group*(group+1))/2
return group+X-max_order
X=int(input())
sol=(-1+(1+8*X)**0.5)/2
group=math.ceil(sol)
order=get_order(X,group)
if group%2==0:
print('%d/%d'%(order,group+1-order))
else:
print('%d/%d'%(group+1-order,order))
|
import urllib.request
from bs4 import BeautifulSoup as BS
def fetch_poem():
'''Fetch Shakespeare poems from MIT site (http://shakespeare.mit.edu/)
and writes them into a file poem_name.txt for example The Sonnets.txt
Also return a dictionary with poem name as key and the poem as value'''
poems = { "A Lover's Complaint" : 'LoversComplaint',
'The Rape of Lucrece' : 'RapeOfLucrece',
'Venus and Adonis' : 'VenusAndAdonis'}
poem_dicts = {}
url = "http://shakespeare.mit.edu/Poetry/"
for poem in poems:
poem_url = url + poems[poem] + '.html'
response = urllib.request.urlopen(poem_url)
html_doc = response.read().decode('utf-8')
html_string = BS(html_doc, 'html.parser')
poem_lines = ''
for block in html_string.find_all('blockquote'):
for line in block.strings:
poem_lines += line
# with open(poem+'.txt', 'w') as f:
# f.write(poem_lines)
poem_dicts[poem] = poem_lines
return poem_dicts |
# Ref link: https://www.youtube.com/watch?v=0DnG0Kc9M2E
def diagonal_matrix_traversal(mat, rows, cols):
if not mat or not mat[0]:
return []
diagonals = [[] for i in range(rows + cols - 1)]
for i in range(rows):
for j in range(cols):
diagonals[i + j].append(mat[i][j])
res = diagonals[0]
for i in range(1, len(diagonals)):
if i % 2 != 0:
res.extend(diagonals[i])
else:
res.extend(diagonals[i][ : : -1])
return res
rows = int(input())
cols = int(input())
arr = [[int(i) for i in input().split()] [ : rows] for j in range(cols)]
print(*(diagonal_matrix_traversal(arr, rows, cols)))
|
def check_array_rotation(arr, size):
if size == 0:
return 0
min = 0
for i in range(1, size):
if arr[i] < arr[min]:
min = i
return min
size = int(input())
arr = [int(element) for element in input().split()] [ : size]
print(check_array_rotation(arr, size))
|
# Second Largest in array
# You have been given a random integer array/list(ARR) of size N.
# You are required to find and return the second largest element present in the array/list.
# If N <= 1 or all the elements are same in the array/list then return -2147483648 or -2 ^ 31.
# (It is the smallest value for the range of Integer)
# Input format :
# The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
# The first line of each test case or query contains an integer 'N' representing the size of the array/list.
# The second line contains 'N' single space separated integers representing the elements in the array/list.
# Output Format :
# For each test case, print the second largest in the array/list if exists, -2147483648 otherwise.
# Output for every test case will be printed in a separate line.
# Constraints :
# 1 <= t <= 10^2
# 0 <= N <= 10^5
# Time Limit: 1 sec
# Sample Input 1:
# 1
# 7
# 2 13 4 1 3 6 28
# Sample Output 1:
# 13
# Sample Input 2:
# 1
# 5
# 9 3 6 2 9
# Sample Output 2:
# 6
# Sample Input 3:
# 2
# 2
# 6 6
# 4
# 90 8 90 5
# Sample Output 3:
# -2147483648
# 8
def second_largest_element(arr, size):
largest = arr[0]
second_largest = -1
for i in range(1, size):
if arr[i] > largest and arr[i] != largest:
second_largest = largest
largest = arr[i]
elif arr[i] > second_largest and arr[i] != largest:
second_largest = arr[i]
return second_largest
size = int(input())
arr = [int(element) for element in input().split()] [ : size]
print(second_largest_element(arr, size)) |
# Swap Alternate
# You have been given an array/list(ARR) of size N. You need to swap every pair of alternate elements in the array/list.
# You don't need to print or return anything, just change in the input array itself.
# Input Format :
# The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
# First line of each test case or query contains an integer 'N' representing the size of the array/list.
# Second line contains 'N' single space separated integers representing the elements in the array/list.
# Output Format :
# For each test case, print the elements of the resulting array in a single row separated by a single space.
# Output for every test case will be printed in a separate line.
# Constraints :
# 1 <= t <= 10^2
# 0 <= N <= 10^5
# Time Limit: 1sec
# Sample Input 1:
# 1
# 6
# 9 3 6 12 4 32
# Sample Output 1 :
# 3 9 12 6 32 4
# Sample Input 2:
# 2
# 9
# 9 3 6 12 4 32 5 11 19
# 4
# 1 2 3 4
# Sample Output 2 :
# 3 9 12 6 32 4 11 5 19
# 2 1 4 3
def swap_alternate(l,size):
# checking if list has even number of elements or not
if size % 2 == 0:
# swapping the elements in the list in an interval of 2
for ele in range(0, size, 2):
l[ele], l[ele + 1] = l[ele + 1], l[ele]
return l
# works if list has odd number of elements in the list
else:
# swapping the elements in the list in an interval of 2
for ele in range(0, size - 1, 2):
l[ele], l[ele + 1] = l[ele + 1], l[ele]
return l
#size of the list
size = int(input())
# taking input for the list
l = list(map(int, input().split())) [ : size]
#printing the final output by calling the function
print(swap_alternate(l,size)) |
# 1 2 3 4 5
# 2 2 3 4 5
# 3 3 3 4 5
# 4 4 4 4 5
# 5 5 5 5 5
#for taking input from user
n=int(input())
#loop for rows
for i in range(1,n+1):
#loop for colunmns
for j in range(1,n+1):
if j<=i:
print(i,end="")
else:
print(j,end="")
print() |
import sys
import re
def main(path_to_file):
regex = r"\w+|\S"
output = []
with open(path_to_file, 'r') as in_file:
for line in in_file:
sentence = []
for match in re.finditer(regex, line, re.MULTILINE | re.UNICODE):
sentence.append(match.group())
if(len(sentence) > 0):
output.append(sentence)
print(output)
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Error: Pass a file to read.', file=sys.stderr)
sys.exit(1)
else:
main(sys.argv[1]) |
# Jake Carpenter
# CS 21, Fall 2018
# Program: tennis
from random import random
# plays a single game
def play_game(prob_a):
a=0
b=0
points = ['0','15','30','40']
# plays the game until someone wins or it goes into deuce
while a<=3 and b<=3 and (a!=3 or b!=3):
# see who won the point
if random() < prob_a:
a+=1
else:
b+=1
# tell the score
if a<4 and b<4:
print('Current score:',points[a]+'-'+ points[b])
# checks if the game is at deuce
if a==b:
print('Deuce')
# continues the game in deuce
while a!=b+2 and b!=a+2:
# see who won the point
if random() < prob_a:
a+=1
else:
b+=1
# checks if back at deuce or who has advantage or if someone won
if a==b:
print('Deuce')
elif a==(b+1):
print('Advantage Player A')
elif a==(b+2):
None
elif b==(a+2):
None
else:
print('Advantage Player B')
# checks who won the deuce
if a>b:
# tells that player A won this game
print('Winner: Player A \n')
return('A')
else:
# tells that player B won this game
print('Winner: Player B \n')
return('B')
# checks who won the game
elif a>b:
# tells that player A won this game
print('Winner: Player A \n')
return('A')
else:
# tells that player B won this game
print('Winner: Player B \n')
return('B')
# shows the overall wins and what percentage player A won
def print_summary(num_a_wins, num_b_wins):
# prints the results
print('Here are the results:')
print('Player A won', num_a_wins,'games.')
print('Player B won', num_b_wins,'games.')
percent = num_a_wins/(num_a_wins+num_b_wins)*100
print('Player A won {0:0.1f}'.format(percent) +'% of the games.')
# plays the specified number of games with the specified probability
def play_games(num_games,prob_a):
num_a_wins = 0
num_b_wins = 0
# plays all the games
for i in range(num_games):
if play_game(prob_a) == 'A':
num_a_wins += 1
else:
num_b_wins += 1
# returns how many wins each player had
return(num_a_wins, num_b_wins)
# prints an intro telling how the game works
def print_intro():
print('This program takes the diference in skill level of the players')
print('to determine the outcome of a tennis match in any number of')
print('games in tennis')
# gets the inputs from the user
def get_inputs():
# checks to see if the inputs are valid
num_games = 0
while num_games < 1:
try:
num_games = int(input('Enter a positive number of games: '))
except ValueError:
print('The input should have been an integer.')
#checks if the inputs are valid
prob_a = -1
while 0 > prob_a or prob_a > 1:
try:
prob_a = float(input('Probability that A wins each point' +
' between 0 and 1: '))
except ValueError:
print('The input should have been a float.')
# returns the inputs to use in other function(s)
return(num_games,prob_a)
def main():
# puts all the functions together to run as one funciton
print_intro()
num_games, prob_a = get_inputs()
num_a_wins, num_b_wins = play_games(num_games,prob_a)
print_summary(num_a_wins,num_b_wins)
main()
|
TICKET_PRICE = 10
SERVICE_CHARGE = 2
tickets_remaining = 100
def calculate_price(num):
return (num * TICKET_PRICE) + SERVICE_CHARGE
while tickets_remaining >= 1:
print("There are {} tickets remaining.".format(tickets_remaining))
name = input("Please type your name: ")
print("Hello, {}!!".format(name))
num_tickets = input("How many tickets would you like? ")
try:
num_tickets = int(num_tickets)
if num_tickets > tickets_remaining:
raise ValueError("There are only {} tickets remaining.".format(tickets_remaining))
except ValueError as err:
print("Uh oh... we ran into an issue :( \n{}\nPlease try again!".format(err))
else:
final_price = calculate_price(num_tickets)
print("Your price of {} tickets will be: {}".format(num_tickets, final_price))
answer = input("Would you like to proceed, {}? \nY/N ".format(name))
if answer.lower() == "y":
print("S O L D !")
tickets_remaining -= num_tickets
else:
print("Thank you anyways, {}!".format(name))
print("Sorry, the tickets are all sold out!") |
# coding=utf-8
dineromensual=int(input("Dinero mensual a guardar\n"))
years = int(input("Años a guardar\n"))
#Inicializacion de los 12 meses
meses = []
for mes in range(12):
meses.append(mes)
interes = 1.035
dineromes = []
dinerosininterez = (dineromensual*12) * years
dineroconinterez = 0
for _ in range(len(meses)):
dineromes.append(dineromensual)
for year in range(years-1):
for mes in range(len(meses)):
dinerototal = dineromes[mes]
dineroconinterez = dinerototal * interes
dineromes[mes] = dineroconinterez + dineromensual
dineroconinterez = 0
for _ in range(len(meses)):
dineroconinterez = dineroconinterez + dineromes[_]
print('Dinero con interez ' + str(dineroconinterez))
print('Dinero sin interez '+ str(dinerosininterez))
print('Dinero de diferencia debido al interez ' + str(dineroconinterez - dinerosininterez))
|
Entrada = []
Contador_paginacao = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
while True:
valor_entrada = int(input("Digite a páginação: "))
if valor_entrada in Entrada:
Contador_paginacao[valor_entrada - 1] = Contador_paginacao[valor_entrada - 1] + 1
print(Entrada)
print(Contador_paginacao)
else:
if (len(Entrada) < 5):
Entrada.append(valor_entrada)
Contador_paginacao[valor_entrada - 1] = Contador_paginacao[valor_entrada - 1] + 1
print(Entrada)
print(Contador_paginacao)
else:
i = 0
while i < len(Entrada):
print(i)
if (Contador_paginacao[(Entrada[i - 1]) - 1]) == 1:
Contador_paginacao[Entrada[i - 1] - 1] = 0
Contador_paginacao[valor_entrada - 1] = Contador_paginacao[valor_entrada - 1] + 1
Entrada[i - 1] = valor_entrada
i = i + 1
break
|
#!/usr/bin/env python
class isy(object):
def __init__(self,y,m,d):
print 'now is',y,m,d
if y%100==0:
if y%400==0:
print 'yes'
else:
print 'no'
elif y%4==0:
print 'yes'
else:
print 'no'
a=isy(2004,1,1)
|
def function1(x, y):
big, small = (x, y) if x > y else (y, x)
leaves = big % small
if not leaves == 0:
return function1(small, leaves)
else:
return small
print(function1(-165, -3))
|
def max_array(array):
max = 0
for e in array:
if e > max:
max = e
return max
def min_array(array):
min = 2000000
for e in array:
if e < min:
min = e
return min
if __name__ == "__main__":
array = [2,3,4,5,6,7,78,321,2,12,1,2]
print(max_array(array))
print(min_array(array))
|
# lambda expressions
from functools import reduce
# lambda syntax:
# lambda param: action(param)
# my_list = [1, 2, 3]
# def multiply_by2(item):
# return item*2
# def only_odd(item):
# return item % 2 != 0
# def accumulator(acc, item):
# print(acc, item)
# return acc + item
# print(list(map(lambda item: item*2, my_list)))
# print(list(filter(lambda item: item % 2 != 0, my_list)))
# print(reduce(lambda acc, item: acc + item, my_list))
# print(my_list)
# Square a List
# my_list = [5,4,3]
# # Andrei's code
# new_list = list((map(lambda num: num**2, my_list)))
# print(new_list)
# # my code
# print(list(map(lambda item: item*item, my_list)))
# List Sorting
a = [(0,2), (4,3), (9,9), (10, -1)]
# a.sort() sorts by first item
# a.sort(key=lambda x: x[1]) sorts by the second item
# print(a) |
# Frequency Counter - sameFrequency
# Write a function called sameFrequency. Given two positive integers, find out if the two numbers have the same frequency of digits.
# Time Complexity Should be O(N)
############### METHOD 01 ###############
from collections import Counter
def sameFrequency(num1, num2):
return Counter(str(num1)) == Counter(str(num2))
############### METHOD 02 ###############
def sameFrequency(num1, num2):
if len(str(num1)) != len(str(num2)):
return False
numDict_01 = {i:str(num1).count(i) for i in str(num1)}
numDict_02 = {i:str(num2).count(i) for i in str(num2)}
for key, val in numDict_01.items():
if key not in numDict_02.keys():
return False
elif numDict_01[key] != numDict_02[key]:
return False
return True |
# Sliding Window
# This pattern involves creating a window which can either be array or number from one position to another.
# Depending on a certain condition, the windows either increases or closes (and a new window is created)
# Very useful for keeping track of a subset of data in an array/string etc
# Example
# Write a function called maxSubarraySum which accepts an array of integers and a number called n. The function should calculate the maximum sum of n consecutive elements in the array.
def maxSubarraySum(arr, num):
if len(arr) < num: return None
maxSum = 0
tempSum = 0
for i in range(num):
maxSum += arr[i]
tempSum = maxSum
for j in range(num, len(arr)):
tempSum = tempSum - arr[j-num] + arr[j]
maxSum = max(tempSum, maxSum)
return maxSum
print(maxSubarraySum([2,6,9,2,1,8,5,6,3],3)) # 19
print(maxSubarraySum([1,2,5,2,8,1,5],4)) # 17
print(maxSubarraySum([4,2,1,6],1)) # 6
print(maxSubarraySum([4,2,1,6,2],4)) # 13
print(maxSubarraySum([],4)) # None |
# Sliding Window - maxSubarraySum
# Given an array of integers and a number, write a function called maxSubarraySum which finds the maximum sum of a subarray with the length of the number passed to the function.
# Note that a subarray must consist of consecutive elements from the original array. In the first example below, [100,200,300] is a subarray of the original array, but [100,300] is not.
def maxSubarraySum(arr,num):
maxSum = 0
tempSum = 0
if len(arr) < num: return None
for i in range(num):
maxSum += arr[i]
tempSum = maxSum
for j in range(num, len(arr)):
tempSum = tempSum - arr[j-num] + arr[j]
if tempSum > maxSum:
maxSum = tempSum
return maxSum
print(maxSubarraySum([100,200,300,400], 2)) # 700
print(maxSubarraySum([1,4,2,10,23,3,1,0,20], 4)) # 39
print(maxSubarraySum([-3,40,-2,6,-1], 2)) # 5
print(maxSubarraySum([3,-2,7,-4,1,-1,4,-2,1], 2)) # 5
print(maxSubarraySum([2,3], 3)) # None |
# ---------------------- PROBLEM 08 (RANDOM) ----------------------------------#
# Write a function called maxSubarraySum which accepts an array of integers and
# a number called n. The function should calculate the maximum sum of n consecutive
# elements in the array.
# Sample input: [1, 2, 5, 2, 8, 1, 5], 2
# Sample output: 10
# ----------------METHOD 01---------------------#
# COMPLEXITY = TIME: O(n^2), SPACE: O(1)
def MaxSubArraySum(arr, num):
# Check Length of Array, if its less than num than return None
if len(arr) < num: return None
# Define maxSum = -inf, to compare with the maxSum
maxSum = float('-inf')
# Initiate For Loop to iterate over arr starting from i to i+num
for i in range((len(arr)-num)+1):
# Sum Four Elements of an array
numSum = sum(arr[i:i+num])
# Compare it with maxSum
if maxSum < numSum:
# if Sum is greater than maxSum, replace the value of sum with maxSum
maxSum = numSum
# Return maxSum
return maxSum
# ----------------METHOD 01---------------------#
# ----------------METHOD 02---------------------#
# COMPLEXITY = TIME: O(n), SPACE: O(1)
def MaxSubArraySum(arr, num):
if len(arr) < num: return None
SubArraySum = sum(arr[0:num])
MaxSum = SubArraySum
for end in range(num, len(arr)):
SubArraySum = SubArraySum + arr[end] - arr[end-num]
MaxSum = max(MaxSum, SubArraySum)
return MaxSum |
class Graphs:
def __init__(self):
self.adjacencyList = {}
def addVertex(self, vert):
if vert not in self.adjacencyList:
self.adjacencyList[vert] = []
return self.adjacencyList
def addEdge(self, vert_01, vert_02):
self.adjacencyList[vert_01].append(vert_02)
self.adjacencyList[vert_02].append(vert_01)
return self.adjacencyList
def removeEdge(self, vert_01, vert_02):
self.adjacencyList[vert_01].remove(vert_02)
self.adjacencyList[vert_02].remove(vert_01)
return self.adjacencyList
def removeVertex(self, vert):
lst = self.adjacencyList[vert].copy()
for i in lst:
self.removeEdge(vert, i)
del self.adjacencyList[vert]
return self.adjacencyList
graph = Graphs()
graph.addVertex('Tokyo')
graph.addVertex('Dallas')
graph.addVertex('Aspen')
graph.addVertex('Hong Kong')
graph.addVertex('Los Angeles')
graph.addEdge('Hong Kong','Tokyo')
graph.addEdge('Aspen','Dallas')
graph.addEdge('Los Angeles','Dallas')
graph.addEdge('Hong Kong','Dallas')
graph.addEdge('Dallas','Tokyo')
print(graph.addEdge('Los Angeles','Hong Kong'))
# {'Tokyo': ['Hong Kong', 'Dallas'],
# 'Dallas': ['Aspen', 'Los Angeles', 'Hong Kong', 'Tokyo'],
# 'Aspen': ['Dallas'],
# 'Hong Kong': ['Tokyo', 'Dallas', 'Los Angeles'],
# 'Los Angeles': ['Dallas', 'Hong Kong']}
# print(graph.removeEdge('Hong Kong','Dallas'))
print(graph.removeVertex("Hong Kong"))
# {'Tokyo': ['Dallas'],
# 'Dallas': ['Aspen', 'Los Angeles', 'Tokyo'],
# 'Aspen': ['Dallas'], 'Los Angeles': ['Dallas']}
|
# Write a function called someRecursive which accepts an array and a callback. The function returns true if a single value in the array returns true when passed to the call back. Otherwise it returns False.
def isOdd(num):
if num % 2 != 0: return True
def isEven(num):
if num % 2 == 0: return True
def someRecursive(arr, fun):
if len(arr) == 0: return False
if fun(arr[0]): return True
return someRecursive(arr[1:], fun) |
# Strings - Non Repeating Character
def non_repeating(stri):
count = {}
for i in range(len(stri)):
char = stri[i]
if char in count:
count[char] += 1
else:
count[char] = 1
for char in stri:
if count[char] == 1:
return char
return None
print(non_repeating('aabcb')) # c
print(non_repeating('xxyz')) # y , return first one
print(non_repeating('aabb')) # None |
# Write a recursive function called flatten which accepts an array of arrays and returns a new array with all values flattened.
def flatten(arrs):
if arrs == []:
return arrs
if isinstance(arrs[0], list):
return flatten(arrs[0]) + flatten(arrs[1:])
return arrs[:1] + flatten(arrs[1:])
print(flatten([1,2,3,[4,5]])) # [1,2,3,4,5]
print(flatten([1,[2,3,[4,[5]]]])) # [1,2,3,4,5] |
# Applications (Its a FIFO Data Structure):
# Queue of any kind | Background Tasks | Uploading Resources | Printing / Task Processing
# Big O of Queues - Insertion - O(1) | Removal - O(1) | Searching - O(N) | Access - O(N)
class Node:
def __init__(self, val):
self.val = val
self.next = None
class Queue:
def __init__(self):
self.first = None
self.last = None
self.size = 0
def enqueue(self, val):
newNode = Node(val)
if self.first == None:
self.first = newNode
self.last = newNode
else:
self.last.next = newNode
self.last = newNode
self.size += 1
return self
def dequeue(self):
if self.size == 0:
return None
else:
currentNode = self.first
nextNode = currentNode.next
currentNode.next = None
self.first = nextNode
self.size -= 1
return currentNode.val
def traverse(self):
currentNode = self.first
while currentNode is not None:
print(currentNode.val)
currentNode = currentNode.next
queue = Queue()
queue.enqueue(1).enqueue(2).enqueue(3).enqueue(4)
queue.traverse()
print(queue.dequeue()) |
# Write a recursive function called capitalizeWords. Given array of words, return a new array containing each word capitalized.
################# METHOD 01 #################
def capitalizeWords(arr, result=[]):
if len(arr) == 0: return result
result.append(arr[0].upper())
return capitalizeWords(arr[1:], result) |
# Write a function called ProductofArray which takes in an array of numbers and returns the product of them all.
def ProductofArray(arr):
if len(arr) == 0: return 1
return arr[0] * ProductofArray(arr[1:])
print(ProductofArray([1,2,3])) # 6
print(ProductofArray([1,2,3,10])) # 60 |
# Factorial
# Write a function which accepts a number and returns the factorial of that number. A factorial is the product of an integer and all the integers below itl e.g. factorial four is equal to 24. factorial zero is always 1.
def factorial(num):
if num == 0: return 1
return num * factorial(num-1)
print(factorial(1)) # 1
print(factorial(2)) # 2
print(factorial(4)) # 24
print(factorial(7)) # 5040 |
# Anagrams
# he goal of this exercise is to write some code to determine if two strings are anagrams of each other.
# An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase).
# For example:
# "rat" is an anagram of "art"
# "alert" is an anagram of "alter"
# "Slot machines" is an anagram of "Cash lost in me"
# Your function should take two strings as input and return True if the two words are anagrams and False if they are not.
# You can assume the following about the input strings:
# No punctuation
# No numbers
# No special characters
from collections import Counter
def anagram_checker(str1, str2):
################# Way01 #################
if len(str1) != len(str2):
str1 = str1.replace(" ","").lower()
str2 = str2.replace(" ","").lower()
return Counter(str1) == Counter(str2)
"""
Check if the input strings are anagrams of each other
Args:
str1(string),str2(string): Strings to be checked
Returns:
bool: Indicates whether strings are anagrams
"""
################# Way02 #################
if len(str1) != len(str2):
str1 = str1.replace(" ","").lower()
str2 = str2.replace(" ","").lower()
if sorted(str1) == sorted(str2):
return True
return False
################# Way03 #################
str1 = str1.lower().replace(" ","")
str2 = str2.lower().replace(" ","")
obj = {}
for letter in str1:
if letter not in obj:
obj[letter] = 1
else:
obj[letter] += 1
for letter in str2:
if letter in obj.keys():
if obj[letter] != str2.count(letter):
return False
else:
return False
return True
# Test Cases
print ("Pass" if not (anagram_checker('water','waiter')) else "Fail")
print ("Pass" if anagram_checker('Dormitory','Dirty room') else "Fail")
print ("Pass" if anagram_checker('Slot machines', 'Cash lost in me') else "Fail")
print ("Pass" if not (anagram_checker('A gentleman','Elegant men')) else "Fail")
print ("Pass" if anagram_checker('Time and tide wait for no man','Notified madman into water') else "Fail") |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self, val):
newNode = Node(val)
if self.root is None:
self.root = newNode
return self
currentNode = self.root
while True:
if newNode.val > currentNode.val:
if currentNode.right:
currentNode = currentNode.right
else:
currentNode.right = newNode
return self
else:
if currentNode.left:
currentNode = currentNode.left
else:
currentNode.left = newNode
return self
def find(self, target):
if self.root is None: return False
currentNode = self.root
while currentNode is not None:
if target == currentNode.val:
return True
elif target > currentNode.val:
currentNode = currentNode.right
else:
currentNode = currentNode.left
return False
def BFS(self):
node = self.root
queue = []
outdata = []
queue.append(node)
while len(queue) != 0:
node = queue.pop(0)
outdata.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return outdata
def DFS_PRE(self):
outdata = []
current = self.root
def DFS_helper(outdata, current):
outdata.append(current.val)
if current.left:
DFS_helper(outdata, current.left)
if current.right:
DFS_helper(outdata, current.right)
DFS_helper(outdata, current)
return outdata
def DFS_POST(self):
outdata = []
current = self.root
def DFS_helper(outdata, current):
if current.left:
DFS_helper(outdata, current.left)
if current.right:
DFS_helper(outdata, current.right)
outdata.append(current.val)
DFS_helper(outdata, current)
return outdata
def DFS_IN(self):
outdata = []
current = self.root
def DFS_helper(outdata, current):
if current.left:
DFS_helper(outdata, current.left)
outdata.append(current.val)
if current.right:
DFS_helper(outdata, current.right)
DFS_helper(outdata, current)
return outdata
bst = BST()
bst.insert(10).insert(5).insert(2).insert(7).insert(13).insert(11).insert(16)
print(bst.BFS()) # [10, 5, 13, 2, 7, 11, 16]
print(bst.DFS_PRE()) # [10, 5, 2, 7, 13, 11, 16]
print(bst.DFS_POST()) # [2, 7, 5, 11, 16, 13, 10]
print(bst.DFS_IN()) # [2, 5, 7, 10, 11, 13, 16] |
# Write a recursive function called fib which accepts a number and returns the nth number in the Fibonacci sequence. Recall that the Fibonacci sequence is the sequence of whole numbers 1,1,2,3,5,8....which starts with 1 and 1, and where every number thereafter is equal to the sum of the previous two numbers.
def fib(num):
if num == 1 : return 0
if num == 2 : return 1
return fib(num-1) + fib(num-2)
def fib(num):
if num <=2 : return 1
return fib(num-1) + fib(num-2) |
"""
Определить, какие из слов «attribute», «класс», «функция», «type» невозможно записать в байтовом типе.
"""
try:
b_attribute = b'attribute'
except Exception as exc:
print("Не удалось записать в байтовом виде", b_attribute)
try:
b_class = b'класс'
except Exception as exc:
print("Не удалось записать в байтовом виде", b_attribute)
try:
b_func = b'функция'
except Exception as exc:
print("Не удалось записать в байтовом виде", b_attribute)
try:
b_type = b'type'
except Exception as exc:
print("Не удалось записать в байтовом виде", b_attribute)
# Невозможно представить в байтовом виде слова написанные на кириллице: "класс" и "функция" |
'''
Created on 2013-2-26
@author: yannpxia
'''
def Sum_Square_Difference(num):
list=[]
for i in range(1,num + 1):
difference = Sum_and_square(i) - Squar_and_sum(i)
list.append(difference)
return list
def Squar_and_sum(num):
sum = 0
for i in range(1,num+1):
sum = sum + i*i
return sum
def Sum_and_square(num):
sum = 0
for i in range(1,num+1):
sum = sum +i
sum = sum * sum
return sum
if __name__ == '__main__':
num = 100
difference = Sum_and_square(num) - Squar_and_sum(num)
print difference |
# return the length of list
a = [1, 2, 3, 5, 8]
print(len(a))
print(max(a))
print(min(a))
print(sorted(a))
print(list(reversed(a)))
print(a)
|
# Code to implement a B-tree
# Programmed by Hugo Chavez
# Last modified February 12, 2019
import math
class BTree(object):
# Constructor
def __init__(self,item=[],child=[],isLeaf=True,max_items=5):
self.item = item
self.child = child
self.isLeaf = isLeaf
if max_items <3: #max_items must be odd and greater or equal to 3
max_items = 3
if max_items%2 == 0: #max_items must be odd and greater or equal to 3
max_items +=1
self.max_items = max_items
def FindChild(T,k):
# Determines value of c, such that k must be in subtree T.child[c], if k is in the BTree
for i in range(len(T.item)):
if k < T.item[i]:
return i
return len(T.item)
def InsertInternal(T,i):
# T cannot be Full
if T.isLeaf:
InsertLeaf(T,i)
else:
k = FindChild(T,i)
if IsFull(T.child[k]):
m, l, r = Split(T.child[k])
T.item.insert(k,m)
T.child[k] = l
T.child.insert(k+1,r)
k = FindChild(T,i)
InsertInternal(T.child[k],i)
def Split(T):
#print('Splitting')
#PrintNode(T)
mid = T.max_items//2
if T.isLeaf:
leftChild = BTree(T.item[:mid])
rightChild = BTree(T.item[mid+1:])
else:
leftChild = BTree(T.item[:mid],T.child[:mid+1],T.isLeaf)
rightChild = BTree(T.item[mid+1:],T.child[mid+1:],T.isLeaf)
return T.item[mid], leftChild, rightChild
def InsertLeaf(T,i):
T.item.append(i)
T.item.sort()
def IsFull(T):
return len(T.item) >= T.max_items
def Insert(T,i):
if not IsFull(T):
InsertInternal(T,i)
else:
m, l, r = Split(T)
T.item =[m]
T.child = [l,r]
T.isLeaf = False
k = FindChild(T,i)
InsertInternal(T.child[k],i)
def height(T):
if T.isLeaf:
return 1
return 1 + height(T.child[0])
def Search(T,k):
# Returns node where k is, or None if k is not in the tree
if k in T.item:
return T
if T.isLeaf:
return None
return Search(T.child[FindChild(T,k)],k)
def Print(T):
# Prints items in tree in ascending order
if T.isLeaf:
for t in T.item:
print(t,end=' ')
else:
for i in range(len(T.item)):
Print(T.child[i])
print(T.item[i],end=' ')
Print(T.child[len(T.item)])
def PrintD(T,space):
# Prints items and structure of B-tree
if T.isLeaf:
for i in range(len(T.item)-1,-1,-1):
print(space,T.item[i])
else:
PrintD(T.child[len(T.item)],space+' ')
for i in range(len(T.item)-1,-1,-1):
print(space,T.item[i])
PrintD(T.child[i],space+' ')
def SearchAndPrint(T,k):
node = Search(T,k)
if node is None:
print(k,'not found')
else:
print(k,'found',end=' ')
print('node contents:',node.item)
#------------------------------------------------------------------------------
def Extract(T, A):
if T.isLeaf:
for i in range(len(T.item)):
A.append(T.item[i])
for i in range(len(T.child)):
Extract(T.child[i],A)
def MinItemAtDepth(T,depth):
if depth == 0:
return T.item[0]
if T.isLeaf:
return math.inf
else:
return MinItemAtDepth(T.child[0],(depth-1))
def MaxItemAtDepth(T,depth):
if depth == 0:
return T.item[-1]
if T.isLeaf:
return math.inf
else:
return MaxItemAtDepth(T.child[-1],depth-1)
def NumNodesAtDepth(T, depth):
if depth == 0:
return 1
else:
temp = 0
for i in range(len(T.child)):
temp += NumNodesAtDepth(T.child[i],depth -1)
#print(temp)
return temp
def PrintAtDepth(T, depth):
if depth == 0:
for i in range(len(T.item)):
print(T.item[i], end =' ')
else:
for i in range(len(T.child)):
PrintAtDepth(T.child[i],depth-1 )
def FullNodes(T):
if IsFull(T):
return 1
x = 0
for i in range(len(T.child)):
x += FullNodes(T.child[i])
return x
def FullLeaf(T):
if T.isLeaf:
if IsFull(T):
return 1
else:
return 0
fullLeaf = 0
for i in range(len(T.child)):
fullLeaf += FullLeaf(T.child[i])
return fullLeaf
def KeyAtDepth(T, k):
if k in T.item:
return 0
if T.isLeaf:
return -1
if k > T.item[-1]:
d = KeyAtDepth(T.child[-1], k)
else:
for i in range(len(T.item)):
if k < T.item[i]:
d = KeyAtDepth(T.child[i],k)
if d == -1:
return -1
return d+1
L = [30, 50, 10, 20, 60, 70, 100, 40, 90, 80, 110, 120, 1, 11 , 3, 4, 5,105, 115, 200, 2, 45, 6]
T = BTree()
depth = 1
for i in L:
#print('Inserting',i)
Insert(T,i)
#PrintD(T,'')
#print('\n####################################')
PrintD(T, '')
print('\n---------------Depth/Height-----------------')
H = height(T)
print('\nHeight of Tree', height(T))
print('\n-------------Extract------------------------')
B = []
A = Extract(T,B)
print('\n', A)
print('\n---------------Min Item at Depth-------------------')
x = MinItemAtDepth(T,depth)
print('\nMin Item at depth', depth,':', x)
print('\n---------------Max Item at Depth-------------------')
ma = MaxItemAtDepth(T,depth)
print('\nMax Item at depth',depth, ':', ma)
print('\n---------------Number of Nodes at Depth------------')
y = NumNodesAtDepth(T,1)
print('\n',y)
print('\n----------------Print At Depth-----------------------')
print()
PrintAtDepth(T,depth)
print()
print('\n----------------Full Nodes--------------------------')
x = FullNodes(T)
print('\n',x)
print('\n----------------Full Leaves--------------------------')
x = FullLeaf(T)
print('\n',x)
print('\n----------------Key At Depth-------------------------')
dep = KeyAtDepth(T, 5)
print('\nKey at depth:',dep) |
class Undirected_Graph_Adjlist_Hashtable:
def __init__(self):
self.graph = {}
self.nodeNum = 0
def add_vertex(self,node):
if node not in self.graph:
self.graph[node] = []
self.nodeNum += 1
else:
raise "Conflict Node"
def add_edge(self,node1,node2):
if node1 not in self.graph:
raise f"No Node {node1} to connect"
elif node2 not in self.graph:
raise f"No Node {node2} to connect"
else:
if node2 in self.graph[node1]:
raise "Conflict Edge"
else:
self.graph[node1].append(node2)
self.graph[node2].append(node1)
def display(self):
for v in self.graph:
print(f"{v} --> ",end="")
for v2 in self.graph[v]:
print(f"{v2} ",end="")
print("")
if __name__ == "__main__":
graph = Undirected_Graph_Adjlist_Hashtable()
graph.add_vertex(1)
graph.add_vertex(2)
graph.add_vertex(3)
graph.add_vertex(4)
graph.add_edge(1,2)
graph.add_edge(2,3)
graph.add_edge(3,1)
graph.add_edge(1,4)
graph.add_edge
graph.display()
|
from tkinter import messagebox
from views.GUI.withdraw_interface import WithdrawInterface
class WithdrawController():
'''
Controller class for the WithdrawInterface view.
Attributes:
main_controller: a reference to the main controller object
withdraw_interface: the view this class controls
Methods:
withdraw: Take money out of user account using the customer model
'''
def __init__(self, main_controller):
self.main_controller = main_controller
self.main_controller.main_interface.master.title('Withdrawal')
self.withdraw_interface = WithdrawInterface(main_controller.main_interface.main_interface_frame)
self.withdraw_interface.right_amount_20_button.config(command=lambda: self.withdraw(20))
self.withdraw_interface.right_amount_40_button.config(command=lambda: self.withdraw(40))
self.withdraw_interface.right_amount_80_button.config(command=lambda: self.withdraw(80))
self.withdraw_interface.left_amount_100_button.config(command=lambda: self.withdraw(100))
self.withdraw_interface.left_amount_200_button.config(command=lambda: self.withdraw(200))
self.withdraw_interface.left_amount_400_button.config(command=lambda: self.withdraw(400))
self.withdraw_interface.right_amount_other_button.config(command=self.withdraw_other_amount)
self.withdraw_interface.left_cancel_button.config(command=self.cancel)
def withdraw(self, amount = 0):
if self.main_controller.customer_model.current_account.withdraw(amount) == True:
messagebox.showwarning('Success', 'You have withdrawn {} from your account'.format(amount))
self.main_controller.customer_model._save_to_file()
self.main_controller.change_controller('confirm', message='Withdrawal successful')
else:
messagebox.showwarning('Failed', 'You do not have enough money for this transaction')
self.main_controller.change_controller('confirm', message='Withdrawal unsuccessful')
def withdraw_other_amount(self):
self.main_controller.change_controller('withdraw_other')
def cancel(self):
self.main_controller.change_controller('confirm', message='You have canceled withdrawal') |
# JAGGED ARRAYS
# Playing arround with Python to create a jagged array class
class JaggedArray():
def __init__(self, rows=1):
if isinstance(rows, int) and rows > 0:
self.rows = rows
self.jArray = []
for i in range(self.rows):
self.jArray.append([])
def append(self, value, row:int):
if not isinstance(row, int):
print('IndexError: row index {} is invalid'.format(row))
return self.jArray
if row not in range(self.rows):
print('IndexError: row index {} is out of bounds'.format(row))
return self.jArray
size = len(self.jArray[row])
new_row = [ None for i in range(size+1)]
for i in range(size+1):
if i == size:
new_row[i] = value
else:
new_row[i] = self.jArray[row][i]
self.jArray[row] = new_row
return self.jArray
def deleteAt(self, row, col):
if not isinstance(row, int):
print('IndexError: row index {} is invalid'.format(row))
return self.jArray
if row not in range(self.rows):
print('IndexError: row index {} is out of bounds'.format(row))
return self.jArray
if not isinstance(col, int):
print('IndexError: column index {} is invalid'.format(col))
return self.jArray
if col not in range(len(self.jArray[row])):
print('IndexError: column index {} is out of bounds'.format(col))
return self.jArray
size = len(self.jArray[row])
new_row = [self.jArray[row][i] for i in range(size) if i != col]
self.jArray[row] = new_row
return self.jArray
def deleteLastOf(self, row):
if not isinstance(row, int):
print('IndexError: row index {} is invalid'.format(row))
return self.jArray
if row not in range(self.rows):
print('IndexError: row index {} is out of bounds'.format(row))
return self.jArray
size = len(self.jArray[row])
new_row = [self.jArray[row][i] for i in range(size-1)]
self.jArray[row] = new_row
return self.jArray
def elementAt(self, row, col):
if not isinstance(row, int):
print('IndexError: row index {} is invalid'.format(row))
return self.jArray
if row not in range(self.rows):
print('IndexError: row index {} is out of bounds'.format(row))
return self.jArray
if not isinstance(col, int):
print('IndexError: column index {} is invalid'.format(col))
return self.jArray
if col not in range(len(self.jArray[row])):
print('IndexError: column index {} is out of bounds'.format(col))
return self.jArray
return self.jArray[row][col]
def lengths(self):
lengths = []
for i in range(self.rows):
lengths.append(len(self.jArray[i]))
print('Row {} has {} element(s)'.format(i, len(self.jArray[i])))
return (lengths)
def print(self):
print('Rows: {}'.format(self.rows))
for i in range(self.rows):
print(self.jArray[i])
j_array = JaggedArray(3)
print()
print('Initializing Jagged Array with 3 rows...')
j_array.lengths()
print()
j_array.print()
print()
print('Appending 5 in row 1...')
j_array.append(5, 1)
print()
j_array.lengths()
print()
j_array.print()
print()
print('Appending 10 in row 3...')
j_array.append(10, 3)
print()
j_array.lengths()
print()
j_array.print()
print()
print('Appending 10 in row 2...')
j_array.append(11, 2)
print()
j_array.lengths()
print()
j_array.print()
print()
print('Appending 10 in row 2:')
j_array.append(10, 1)
print()
j_array.lengths()
print()
j_array.print()
print()
print('Appending 1 in row 0...')
j_array.append(1, 0)
print()
j_array.lengths()
print()
j_array.print()
print()
print('Deleting the last element in row 0...')
j_array.deleteLastOf(0)
print()
j_array.lengths()
print()
j_array.print()
print()
print('Deleting the element at index 0 in row 1...')
j_array.deleteAt(1, 0)
print()
j_array.lengths()
print()
j_array.print()
print()
print('Accessing the first element of row 2...')
print('The first element is: {}'.format(j_array.elementAt(2, 0)))
print()
j_array.lengths()
print()
j_array.print() |
"""
Напишите функцию, которая возвращает все варианты комбинаций членов списков, переданных на вход.
Пример:
pairwise([1, 2, 3], ['a'], [True, False]) = [
[1, 'a', True],
[1, 'a', False],
[2, 'a', True],
[2, 'a', False],
[3, 'a', True],
[3, 'a', False]
]
"""
import json
from typing import List
def pairwise(*lists: List) -> List:
if not lists:
return []
if len(lists) == 1:
return lists[0]
first, second, *others = lists
result = [[val0, val1] for val0 in first for val1 in second]
while others:
next_list, *others = others
result = [
[*row, val]
for row in result
for val in next_list
]
return result
def solve():
lists = json.loads(input())
answer = pairwise(*lists)
print(json.dumps(answer))
if __name__ == '__main__':
solve()
|
"""
В магазине продается неограниченное количество плинтусных реек с длинами 1,2,…,n. Вы хотите купить некоторый набор реек,
чтобы получить суммарную длину L.
Разрешается чтобы в вашем наборе были рейки имеющие одну и ту же длину. Какое минимальное количество реек нужно, чтобы
получить длину L?
Формат входных данных
Единственная строка входных данных содержит два целых числа n и L
(1 ≤ n ≤ 10^4, 1 ≤ L < 10^10)
Формат выходных данных
Выведите ровно одно целое число — минимальное количество реек, которое нужно чтобы получить длину L.
"""
def solve():
max_rail_len, target_len = map(int, input().split())
rails_cnt = target_len // max_rail_len
if target_len % max_rail_len:
rails_cnt += 1
print(rails_cnt)
if __name__ == '__main__':
solve()
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
def fibby():
a,b = 0,1
yield a
yield b
while True:
a,b = b,a+b
yield b
N = input()
kk = fibby()
print(map(lambda x:x**3,[kk.next() for x in range(N)]))
|
my_tuple = tuple()
print(my_tuple)
my_tuple = ()
print(my_tuple)
rndm = ("M. Jackson", 1958, True)
print(rndm)
("self_taught",)
dys = ("1984", "Brave new World", "Fahrenheit 451")
print(dys[1])
#dys[1] = "Handmaid's Tale"
print("1984" in dys)
print("Handmaid's Tale" not in dys)
my_dict = dict()
my_dict
print(my_dict)
my_dict = {}
print(my_dict)
fruits = {"Apple": "Red", "Banana": "Yellow"}
print(fruits)
facts = dict()
# add a value
facts["code"] = "fun"
# look up a key
print(facts["code"])
facts["Bill"] = "Gates"
print(facts["Bill"])
facts["founded"] = 1776
print(facts["founded"])
bill = dict({"Bill Gates": "charitable"})
#print(bill["hey"])
print("Bill Gates" in bill)
print("Bill Doors" not in bill)
books = {"Dracula": "Stoker", "1984": "Orwell", "The Trial": "Kafka"}
del books["The Trial"]
print(books)
rhymes = {"1": "fun",
"2": "blue",
"3": "me",
"4": "floor",
"5": "live"
}
n = 2
#n = input("Type a number:")
if n in rhymes:
rhyme = rhymes[n]
print(rhyme)
else:
print("Not found.")
lists = []
rap = ["Kanye West", "Jay Z", "Eminem", "Nas"]
rock = ["Bob Dylan", "The Beatles", "Led Zeppelin"]
djs = ["Zeds Dead", "Tiesto"]
lists.append(rap)
lists.append(rock)
lists.append(djs)
print(lists)
rap = lists[0]
print(rap)
rap.append("Kendrick Lamar")
print(lists)
locations = []
la = (34.0522, 188.2437)
chicago = (41.8781, 87.6298)
locations.append(la)
locations.append(chicago)
print(locations)
eights = ["Edgar Allen Poe", "Charles Dickens"]
nines = ["Hemingway", "Fitzgerald", "Orwell"]
authors = (eights, nines)
print(authors)
bday = {"Hemingway": "7.21.1899", "Fitzgerald": "9.24.1896"}
my_list = [bday]
print(my_list)
my_tuple = (bday, )
print(my_tuple)
me = {"height": "72", "color": "green", "author": "say"}
print(me[input("height, color or author?")])
frank_black = ["Violet", "Don't Clip Your Wings", ] |
import torch
import torch.nn.functional as F
class Net(torch.nn.Module):
def __init__(self,n_feature,n_hidden,n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature,n_hidden)
self.predict = torch.nn.Linear(n_hidden,n_output)
def forward(self,x):
x = F.relu(self.hidden(x))
x = self.predict(x)
return x
net1 = Net(1,10,1)
print(net1)
"""
Net (
(hidden): Linear (1 -> 10)
(predict): Linear (10 -> 1)
)
"""
net2 = torch.nn.Sequential(
torch.nn.Linear(1,10),
torch.nn.ReLU(),
torch.nn.Linear(10,1)
)
print(net2)
"""
Sequential(
(0): Linear(in_features=1, out_features=10, bias=True)
(1): ReLU()
(2): Linear(in_features=10, out_features=1, bias=True)
)
"""
"""
为什么两个结果打印出来的网络不一样
因为F.relu 是类似一个自己构造的函数
而torch.nn.Relu()是一个类,会独立显示
两个的功能是一样的
""" |
#A+BのAの部分を入力してもらう
input_numberA = input('数値を入力してください: ')
while not input_numberA.isdigit():
input_numberA = input('数値を入力してください: ')
numberA = int(input_numberA)
input_while = ' '
answer = numberA
while input_while != 'end':
print(answer)
print("1, +\n2, -\n3, ×\n4, ÷ ")
#演算記号の選択をしてもらう
input_symbol = input('使いたい演算記号と対応する数字を入力してください:')
while not input_symbol.isdigit():
input_symbol = input('使いたい演算記号と対応する数字を入力してください:')
symbol = int(input_symbol)
while symbol < 1 or symbol > 4 :
input_symbol = input('使いたい演算記号と対応する数字を入力してください:')
while not input_symbol.isdigit():
input_symbol = input('使いたい演算記号と対応する数字を入力してください:')
symbol = int(input_symbol)
#A+BのBの部分を入力してもらう
input_numberB = input('数値を入力してください:')
while not input_numberB.isdigit():
input_numberB = input('数値を入力してください:')
numberB = int(input_numberB)
#計算する
if symbol == 1:
answer += numberB
print(answer)
elif symbol == 2:
answer -= numberB
print(answer)
elif symbol == 3:
answer *= numberB
print(answer)
elif symbol == 4:
while numberB == 0:
print("Error")
input_numberB = input('正しい数値を入力してください:')
while not input_numberB.isdigit():
input_numberB = input('数値を入力してください:')
numberB = int(input_numberB)
answer /= numberB
print(answer)
else:
print('正しい数値を入力してください')
print('計算を終了する場合は end と入力してください')
print('計算を続ける場合はエンターキーを押してください')
input_while = input(':')
print('計算結果は'+ str(answer) + 'です')
|
hvelho = ''
ivelho = 0
mulheres = 0
sidade = 0
for c in range(1, 4):
print('---- {}° PESSOA ----'.format(c))
n = input('NOME: ')
i = int(input('IDADE: '))
s = input('SEXO [M/F]: ').strip().lower()
sidade = sidade + i
if c == 1 and s == 'm':
hvelho = n
ivelho = i
if s == 'm' and i > ivelho:
hvelho = n
ivelho = i
if i < 20 and s == 'f':
mulheres = mulheres + 1
m = (sidade)/3
print('A média das idades é {}'.format(m))
print('O homem mais velho chama {} e tem {} anos'.format(hvelho, ivelho))
print('Temos {} mulheres com menos de 20 anos'.format(mulheres)) |
n = 1
while n != 0:
n = int(input('Digite um valor: '))
print('FIM')
c = 2
while c <= 20:
print(c)
c = c + 1 |
ano = int(input('Digite o ano aqui: '))
r = ano % 4
t = ano % 100
y = ano % 400
import datetime
print(datetime.date.today().year)
if r == 0 and t != 0 and y == 0:
print('O ano é bissexto')
else:
print('O ano não é bissexto') |
j = ('n', 'b', 'w', 'c', 'i', 't', 'a', 'n', 'f', 'j')
print(j[0:6])
print(j[-1:-5: -1])
print(sorted(j))
print(j.index('c')) |
lista = []
apareceu = False
while True:
v = int(input('Digite um valor: '))
if v in lista:
print('Valor duplicado. Não adicionado')
else:
lista.append(v)
print('Valor adicionado com sucesso.')
if v == 5:
apareceu = 'sim'
resp = input('Deseja continuar?')
if resp in 'nN':
break
lista.sort(reverse=True)
print(f'Você digitou {len(lista)} elementos')
print(f'Os valores em ordem decrescente são {lista}')
if apareceu == 'sim':
print(f'O valor 5 foi encontrado na lista!')
else:
print(f'O valor 5 não foi encontrado na lista')
|
print('Gerador de PA:')
print('=-' * 20)
p = int(input('Primeiro termo:'))
r = int(input('Razão da PA:'))
cont = 0
while cont <= 10:
print('{} >> '.format(p), end = '')
p = p + r
cont += 1
print('PAUSA')
t = 1
while t > 0:
t = int(input('Quantos termos a mais você quer mostrar? '))
ncont = 0
while ncont < t:
print('{} >> '.format(p), end='')
p = p + r
ncont += 1
cont += 1
print('PAUSA')
print('Progressão finalizada com {} termos mostrados.'.format(cont)) |
print('-'*40)
print(' JOGO NA MEGA SENA ')
print('-'*40)
jogos = int(input('Quantos jogos você quer que eu sorteie? '))
print('-+'*3, f'SORTEANDO {(jogos)} JOGOS', '-+'*3,)
import random
from time import sleep
lista = []
aux = []
for b in range(0, jogos):
while len(aux) < 6:
n = random.randint(0, 60)
if n not in aux and n not in lista:
aux.append(n)
aux.sort()
lista.append(aux[:])
aux.clear()
for c in range(0, jogos):
print(f'Jogo {c+1}: {lista[c]}')
sleep(1)
|
def reverseLinkedListInRange(head, start, end):
'''
Given the head node of a Linked List and a start and end index, reverse the order of the nodes between the start and end
indicies.
Example:
head -> 1 -> 2 -> 3 -> 4 -> 5, start = 2, end = 4. Result => head -> 1 -> 4 -> 3 -> 2 -> 5
'''
currNode = head
i = 1
beforeNodes = []
inNodes = []
afterNodes = []
while i <= end + 1
if i < start: beforeNodes.append(currNode)
elif i in range(start,end + 1): inNodes.append(currNode)
else: afterNodes.append(currNode)
i += 1
for i in range(len(inNodes) - 1, -1, -1):
if i == 0: inNodes[i].next = afterNodes[0]
else: inNodes[i].next = inNodes[i -1]
beforeNodes[-1].next = inNodes[-1]
return head |
class WordDictionary(object):
'''
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or ".".
A "." means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
https://leetcode.com/problems/add-and-search-word-data-structure-design/
'''
def __init__(self):
self.children = {}
def addWord(self, word):
letters = list(word)
if len(letters) == 0: return
c = letters.pop(0)
if c not in self.children:
self.children[c] = WordDictionary()
self.children[c].addWord(letters)
def findWord(self, word):
letters = list(word)
print(letters)
if len(letters) == 0: return True
c = letters.pop(0)
if c == ".":
for letter in self.children:
return self.children[letter].findWord(letters)
elif c not in self.children: return False
else: return self.children[c].findWord(letters)
|
#!/usr/bin/python
#coding:utf-8
from string import Template
#3-1
print '#3-1'
#3-2
print '#3-2'
format = "Hello, %s, %s enough for ya?"
values = ('world','Hot')
print format % values
format = "Pi with three decimals: %.3f"
from math import pi
print format % pi
s = Template('$x, glorious $x!')
print s.substitute(x='slurm')
s = Template("It's ${x}tastic!")#当替换的是一个单词的一部分,使用{}
print s.substitute(x='slurm')
s = Template("Make $$ selling $x!")
print s.substitute(x='slurm')
s = Template('A $thing must never $action')
d = {}
d['thing'] = 'gentleman'
d['action'] = 'show his socks'
print s.substitute(d)
#3-3
print '#3-3'
print '%s plus %s equals %s' % (1,1,2)#使用元组进行格式化,必须要使用圆括号括起来
print '%.*s' % (5,'Guido van Rossum')#可以使用.×的方式来从元组中取得参数
print '%010.2f' % pi#最前面的0表示将剩余的字段宽度使用0填充
print ('%+5d' % 10) + '\n' + ('%+5d' % -10)#使用+时,无论是正数还是负数都会标出符号
#width = input('Please enter width: ')
#price_width = 10
#item_width =width - price_width
#header_format = '%-*s%*s'
#formats = '%-*s%*.2f'
#print '=' * width
#print header_format % (item_width,'Item',price_width,'Price')
#print '-' * width
#print formats % (item_width,'Apples',price_width,0.4)
#print formats % (item_width,'Pears',price_width,0.5)
#print formats % (item_width,'Cantaloupes',price_width,1.92)
#print formats % (item_width,'Dried Apricots(16 oz.)',price_width,8)
#print formats % (item_width,'Prunes(4 lbs)',price_width,12)
#print '-' *width
#3-4
print '#3-4'
subject = 'With a moo-moo here, and a moo-moo there'
print subject.find('moo')#find返回的是第一次出现的位置,没有找到就返回-1
print subject.find('moo',15)#设置起始查询点
seq = ['1','2','3','4','5']
sep = '+'
print sep.join(seq)
dir = ' ','usr','bin','env'
print '/'.join(dir)
str = 'AAAAAAAAAbbbbbbbbb'
print str.lower()
print str.title()#将所有单词的首字母大写
print 'This is a test.'.replace('is','eez')
print '1+2+3+4+5'.split('+')
print ' inter '.strip()
print '!!!!!!*****inter*******!!!!!'.strip('*!')
from string import maketrans
table = maketrans('cs','kz')
print len(table)
print table[97:123]#maketrans是一个ascii表
print 'This is an incredible test'.translate(table) |
import re
#getting the text the file "two cities"
text = open("two_cities.txt",encoding='utf-8').read().replace('\n','')
#getting the total length of the text for the loop
text_length = len(text)
#deleting anything but letters and spaces(" ")
i = 0
while i < (text_length):
if (not((text[i] == " ") or (re.match("^[A-Za-zΑ-Ωα-ωίϊΐόάέύϋΰήώ]*$",text[i])))):
text = text.replace(text[i], "")
text_length = len(text) #redeclaring the total length of the text
i += 1
text_list = text.split(" ") #forming a list in which every item is a word from the text
total_length = 0 #the sum of every items length in the list
list_length = len(text_list) #amount of items in the list
#deleting the empty items
i = 0
while (i < list_length):
if (text_list[i] == ""):
del text_list[i]
list_length = len(text_list)
i += 1
#finding item couples with total length 20 and removing them from the list
i = 0
while (list_length != 0): #until there are no words
hasCouples = 0
while i < (list_length - 1):
j = 1
while j < (list_length - 1):
if (len(text_list[i] + text_list[j]) == 20):
hasCouples = 1
del text_list[i]
del text_list[j]
list_length = len(text_list)
#break
j += 1
i += 1
list_length = len(text_list)
if (hasCouples == 0): #there are no couples left so the loop has to end
list_length = 0
print(text_list)
|
def add(x, y):
return x+y
def subtract(x, y):
return x-y
def multiply(x, y):
return x*y
def divide(x, y):
return x/y
print(" Welcom to Tandemloop Simple Calculator.")
while True:
operation = input("Enter operation(add subtract divide multiply): ")
if operation in ('add', 'subtract', 'divide', ''multiply'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if operation == 'add':
print(num1 + num2)
elif operation == 'subtract':
print(num1 - num2)
elif operation == 'multiply':
print(num1 * num2)
elif operation == 'divide':
print(num1 / num2)
break
else:
print("Invalid Input")
|
'''Given a 32-bit signed integer, reverse digits of an integer.'''
class Solution:
def reverse(self, x: int) -> int:
import math
if -math.pow(2,31) < x < math.pow(2,31)-1:
if x > 0:
result = int(str(x).rstrip('0')[::-1])
if result < math.pow(2,31)-1:
return result
else:
return 0
if x < 0:
result = 0-int(str(-x).rstrip('0')[::-1])
if result > -math.pow(2,31):
return result
else:
return 0
if x ==0:
return 0
else:
return 0
|
#!/bin/python
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return "Student object (name: %s)" % self.name
__repr__=__str__
def print_score(self):
print("%s: %s" % (self.name, self.score))
bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
bart
lisa
bart.print_score()
lisa.print_score()
|
def expect(xDistribution, function):
xvals = list(xDistribution.keys())
prob = list(xDistribution.values())
outputlist = [function(xvals[j]) * prob[j] for j in range(len(prob))]
expectation = sum(outputlist)
return expectation
##################################################
# Your code below each comment
##################################################
def getVariance(xDistribution):
#Step 1 - Calculate the expected value E(X)
function = lambda x: x
mu = expect(xDistribution, function)
def getSquaredDistanceToMu(x):
#Step 2 - Calculate (X-E(X))^2
sd = (x - mu) ** 2
return sd
#Step 3 - Calculate Variance: Var(X)=E((X-E(X))^2)
variance = expect(xDistribution, getSquaredDistanceToMu)
return variance
def main():
xDistributionExample1={1: 1/5, 2: 2/5, 3: 2/5}
functionExample1=lambda x: x ** 2 # squares an input
print(expect(xDistributionExample1, functionExample1))
print(getVariance(xDistributionExample1))
xDistributionExample2={1: 1/6, -1/2: 1/3, 1/3: 1/4, -1/4: 1/12, 1/5: 1/6}
functionExample2=lambda x: 1/x
print(expect(xDistributionExample2, functionExample2))
print(getVariance(xDistributionExample2))
if __name__ == '__main__':
main() |
#!/usr/local/bin/python3
"""
Let's play Blackjack!
Blackjack game using deckofcardsapi.com
"""
import random
import requests
from pprint import pprint
"""
TODO (Done) Start new game
Create new deck and set number of players
TODO (Done) Reshuffle function
Reshuffle existing deck
TODO (Done) Draw card function
Draw a card and append it to player's hand
TODO The Deal
Deal initial hand to all players and dealer
TODO Betting
Place bets
TODO Dealer turn
TODO NPC turn
TODO Player turn
"""
def new_game():
"""
Function to create a new deck and return the deck_id,
determine the number of players and the number of decks,
allocate the starting bank for each player,
and set the deck lower limit before reshuffle.
"""
print("\nLet's play some Blackjack!")
# Prompt user and set variable for number of players
num_of_players = 3 # Lazy mode
# numplayers = input("\nHow many players will there be: ")
# Prompt user and set variable for number of decks to shuffle
numdecks = 6 # Lazy mode
# numdecks = input("\nHow many decks would you like to shuffle: ")
# URL to generate a new deck
url = "https://deckofcardsapi.com/api/deck/new/shuffle/"
# parameter for number of decks
querystring = {"deck_count": numdecks}
print(f"\nShuffling cards.")
# send GET request
response = requests.request("GET", url, params=querystring)
# parse json response
deck = response.json()
# extract deck ID
deck_id = deck["deck_id"]
# Print deck id
print(f"\nNew game starting with deck id: {deck_id}\n")
# init bank dictionary
bank = {}
# set starting bank for each player
for player in range(num_of_players):
player += 1
bank[f"P{player}"] = 100
# set and print player number
player_num = f"P{random.randint(1, num_of_players)}"
print(f"You are player #{player_num[1]}\n")
# set deck lower limit before reshuffle
deck_cut = random.randint(40, 75)
return deck_id, deck_cut, num_of_players, player_num, bank
def draw_card(deck_id):
"""
function to draw cards
"""
# URL to draw cards from deck
url = "https://deckofcardsapi.com/api/deck/" + deck_id + "/draw/"
# send GET request
draw = requests.request("GET", url).json()
# extract card value
card = draw['cards'][0]['code'][0]
# extract remaining cards in the deck
remaining = draw['remaining']
return card, remaining
def shuffle_deck(deck_id):
"""
Function to reshuffle an existing deck
"""
print(f"Reshuffling deck id: {deck_id}\n")
# URL to shuffle existing deck
url = f"https://deckofcardsapi.com/api/deck/{deck_id}/shuffle/"
# send GET request
requests.request("GET", url)
# set deck lower limit before reshuffle
deck_cut = random.randint(40, 75)
return deck_cut
def the_deal(deck_id, num_of_players, player_num, bank):
"""
Round deal 2 cards to each player
"""
def play_game():
"""
main function to play Blackjack
"""
# shuffle a new deck of cards
deck_id, deck_cut, num_of_players, player_num, bank = new_game()
print(deck_cut)
print(num_of_players)
print(bank)
cont = "y"
while cont.lower() == "y":
card, remaining = draw_card(deck_id)
print(card)
print(remaining)
cont = input("Draw another card? y/n\n")
if __name__ == "__main__":
play_game()
|
#!/bin/python3
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def print_singly_linked_list(node, sep):
while node:
print(str(node.data))
node = node.next
if node:
print(sep)
# Complete the compare_lists function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def compare_lists(llist1, llist2):
curr1 = llist1
curr2 = llist2
is_equal = 1
while True:
if (curr1 is None) & (curr2 is not None):
is_equal = 0
break
elif (curr2 is None) & (curr1 is not None):
is_equal = 0
break
elif (curr1 is None) & (curr2 is None):
break
elif curr1.data == curr2.data:
curr1 = curr1.next
curr2 = curr2.next
else:
is_equal = 0
break
return is_equal
if __name__ == '__main__':
tests = int(input())
for tests_itr in range(tests):
llist1_count = int(input())
llist1 = SinglyLinkedList()
for _ in range(llist1_count):
llist1_item = int(input())
llist1.insert_node(llist1_item)
llist2_count = int(input())
llist2 = SinglyLinkedList()
for _ in range(llist2_count):
llist2_item = int(input())
llist2.insert_node(llist2_item)
print_singly_linked_list(llist1.head, sep=' ')
print_singly_linked_list(llist2.head, sep=' ')
result = compare_lists(llist1.head, llist2.head)
print(str(int(result)) + '\n')
|
# Complete the solve function below.
def solve(s):
words = s.split(" ")
temp = []
for word in words:
if word != '':
word = list(word)
word[0] = word[0].upper()
word = "".join(word)
temp.append(word)
s = " ".join(temp)
print(s)
return s
if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
# s = input()
# s = 'hello world'
s = 'j k l z x c v b n m Q W E R T Y U I O P A S D F G H J K L Z X C V B N M'
result = solve(s)
fptr.write(result + '\n')
fptr.close()
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the camelcase function below.
def camelcase(s):
from collections import Counter
dc = Counter(s)
new_dict = dict()
for key, value in dc.items():
if str(key).isupper():
new_dict[key] = value
s = sum(new_dict.values()) + 1
return s
if __name__ == '__main__':
# s = input()
s = 'saveChangesInTheEditor'
result = camelcase(s)
print(result)
|
"""
This script builds and runs a graph with miniflow.
There is no need to change anything to solve this quiz!
However, feel free to play with the network! Can you also
build a network that solves the equation below?
(x + y) + y
"""
from miniflow import *
t, u, v, w, x, y, z = Input(), Input(), Input(), Input(), Input(), Input(), Input()
f = Add(y, z)
g = Add(f, u, v)
i = Mul(g, w, x)
h = Mul(i, t)
feed_dict = {t: 3, u: 13, v: 7, w: 12, x: 10, y: 5, z: 8}
sorted_nodes = topological_sort(feed_dict)
output = forward_pass(h, sorted_nodes)
# NOTE: because topological_sort set the values for the `Input` nodes we could also access
# the value for x with x.value (same goes for y).
print("({} + {} + {} + {}) * {} * {} * {} = {} (according to miniflow)".format(
feed_dict[y],
feed_dict[z],
feed_dict[u],
feed_dict[v],
feed_dict[w],
feed_dict[x],
feed_dict[t],
output))
|
#Phonebook using Hash Table#
#"defaultdict" is first imported from the collections
from collections import defaultdict
count=0 #for checking table size
class HashTable:
def __init__ (self, size):
self.HashTab=defaultdict(list)
for i in range (size):
self.HashTab[i]=[]
self.display()
def hashing(self,name): #Hash function
sum=0
l=len(name)
for i in range (0,l):
sum=sum+ord(name[i])
return(sum%size)
def insert_record(self,pos,nm,ph): #direct insertion without replacement
global count
if len(self.HashTab[pos])==0:
self.HashTab[pos].append(nm)
self.HashTab[pos].append(ph)
count=count+1
elif self.HashTab[pos][0]==nm:
self.HashTab[pos].append(ph)
else:
self.find_next_vacant_pos(pos, nm, ph)
def find_next_vacant_pos(self,pos,nm,ph): #Finds next vacant position in the table
global count
for i in range (1,size):
z=(pos+i)%size
if len(self.HashTab[z])==0:
self.HashTab[z].append(nm)
self.HashTab[z].append(ph)
count=count+1
break
def wreplace(self,pos,nm,ph): #Insertion with replacement
global count
if len(self.HashTab[pos])==0:
self.HashTab[pos].append(nm)
self.HashTab[pos].append(ph)
count=count+1
elif self.HashTab[pos][0]==nm:
self.HashTab[pos].append(ph)
elif pos==self.hashing(self.HashTab[pos][0]):
self.find_next_vacant_pos(pos,nm,ph)
else:
temp=self.HashTab[pos]
self.HashTab[pos]=[]
self.HashTab[pos].append(nm)
self.HashTab[pos].append(ph)
self.find_next_pos(pos,temp)
def find_next_pos(self,pos,temp): #Find next position in the table
global count
for i in range (1,size):
z=(pos+i)%size
if len(self.HashTab[z])==0:
self.HashTab[z]=temp
count=count+1
break
def display(self): #Displays full hash table
print("******Hash Table******")
for i in sorted (self.HashTab.items()):
print(i)
def search(self,nm): #Search perticular name in the table
flag=0
pos=h.hashing(nm)
if len(self.HashTab[pos])!=0 and self.HashTab[pos][0]==nm:
print("\nRecord for "+ nm +" found !!")
print(self.HashTab[pos])
else:
for i in range (1,size):
z=(pos+i)%size
if len(self.HashTab[z])!=0 and self.HashTab[z][0]==nm:
print("\nRecord for "+ nm +" found at "+ str(z))
print(self.HashTab[z])
flag=1
break
if flag==0:
print("\nRecord for "+ nm +" not found")
#MANI CODING
size=int(input("Enter the Telephone book size: "))
while True:
print("\n\n***Telephone Dictionary***")
print("1)Add new record without replacement")
print("2)Add new record with replacement\n3)display all records\n4)Search any record\n5)Exit phonebook")
a=int(input("Answer: "))
if a==1: #Without relacement
h=HashTable(size)
count=0
while True:
name=str.strip(input("Enter the name: "))
name=name.upper()
phnumber=int(input("Enter the phonenumber: "))
pos=h.hashing(name)
h.insert_record(pos,name,phnumber)
h.display()
opt=int(input("Do you want to add more elements(1-YES/0-NO): "))
if opt==1:
if (count==size):
print("Phonebook is full !! can not add more elements")
break
else:
break
elif a==2: #with replacement
h=HashTable(size)
count=0
while True:
name=str.strip(input("Enter the name: "))
name=name.upper()
phnumber=int(input("Enter the phone number: "))
pos=h.hashing(name)
h.wreplace(pos,name,phnumber)
h.display()
opt=int(input("Do you want to add more elements(1-YES/0-NO): "))
if opt==1:
if (count==size):
print("Phonebook is full !! can not add more elements")
break
else:
break
elif a==3: #display hash table
h.display()
elif a==4: #search perticular name
name=str.strip(input("Enter the name: "))
h.search(name.upper())
else: #exit phonebook
break
|
"""
dlib test.
This was used for learning how to used dlib for face key-point detection.
Not final result of project.
Used tutorials:
http://www.paulvangent.com/2016/08/05/emotion-recognition-using-facial-landmarks/
http://www.paulvangent.com/2016/04/01/emotion-recognition-with-python-opencv-and-a-face-dataset/
by __author__ = "Paul van Gent, 2016"
and also referenced
opencv dlib documentation https://www.learnopencv.com/tag/dlib/
"""
import cv2
import dlib
import numpy as np
import math
import csv
import sklearn
class EmotionRecognizerNode(object):
""" Class for emotion recognizer node. """
def __init__(self):
self.image = None
self.clahe_image = None # histogram equalized
self.video_capture = cv2.VideoCapture(0) #Webcam object
self.detector = dlib.get_frontal_face_detector() #Face detector
self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") #Landmark identifier. Set the filename to whatever you named the downloaded file
self.detections = None
self.xmean = 0 # center of face x
self.ymean = 0 # center of face y
self.all_landmarks_vectorized = []
def get_landmarks_vectorized(self, image):
""" For an image node finds keypints and generates vectors. """
print "landmarks_vectorized 1"
landmarks_vectorized = []
detections = self.detector(image, 1)
for k,d in enumerate(detections): # for each face detected (if more than one)
predicted_landmarks = self.predictor(image, d) #Draw Facial Landmarks with the predictor class
xlist = []
ylist = []
for i in range(1,68): #Store X and Y coordinates in two lists
xlist.append(float(predicted_landmarks.part(i).x))
ylist.append(float(predicted_landmarks.part(i).y))
self.xmean = np.mean(xlist) #Find both coordinates of centre of gravity
self.ymean = np.mean(ylist)
xcentral = [(x-self.xmean) for x in xlist] # x distance from point to center
ycentral = [(y-self.ymean) for y in ylist] # y distance from point to center
if xlist[26] == xlist[29]: #If x-coordinates of the set are the same, the angle is 0, catch to prevent 'divide by 0' error in function
anglenose = 0
else:
anglenose = int(math.atan((ylist[26]-ylist[29])/(xlist[26]-xlist[29]))*180/math.pi) #point 29 is the tip of the nose, point 26 is the top of the nose brigde
if anglenose < 0: #Get offset by finding how the nose brigde should be rotated to become perpendicular to the horizontal plane
anglenose += 90
else:
anglenose -= 90
for x, y, w, z in zip(xcentral, ycentral, xlist, ylist):
landmarks_vectorized.append(x) # Add the coordinates relative to the centre of gravity
landmarks_vectorized.append(y)
#Get the euclidean distance between each point and the centre point (the vector length)
meannp = np.asarray((self.ymean,self.xmean))
coornp = np.asarray((z,w))
dist = np.linalg.norm(coornp-meannp)
landmarks_vectorized.append(dist)
#Get the angle of the vector relative to the image, corrected for the offset of face rotation corresponding to angle of nosebrigde
anglerelative = (math.atan((z-self.ymean)/(w-self.xmean))*180/math.pi) - anglenose
landmarks_vectorized.append(anglerelative)
if len(detections) < 1:
landmarks_vectorized = "error" #If no face is detected set the data to value "error" to catch detection errors
self.all_landmarks_vectorized.append(landmarks_vectorized)
return landmarks_vectorized
def draw(self, landmarks):
""" Draws keypoint and center of mass on webcam face image."""
# features
for i in range(1, 68):
cv2.circle(self.frame, (landmarks.part(i).x, landmarks.part(i).y), 1, (0,0,255), thickness=2)
# center of mass
cv2.circle(self.frame, (int(self.xmean), int(self.ymean)), 1, (255, 0, 0), thickness = 3)
def run(self):
""" The main run loop. """
while True:
#ret, self.frame = self.video_capture.read()
# read image using OpenCV
self.frame = cv2.imread("test.png")
# process image
gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
self.clahe_image = clahe.apply(gray)
landmark_vectors = self.get_landmarks_vectorized(self.clahe_image)
self.detections = self.detector(self.clahe_image, 1) # detect faces
for k,d in enumerate(self.detections):
predicted_landmarks = self.predictor(self.clahe_image, d)
self.draw(predicted_landmarks)
cv2.imshow("image", self.frame)
if cv2.waitKey(10) & 0xFF == ord('q'):
print "================================="
print "Quitting.. Saving data to .CSV"
print "================================="
with open('../all_landmarks_vectorized.csv', 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
for row in self.all_landmarks_vectorized:
wr.writerow(row)
break
node = EmotionRecognizerNode()
node.run()
|
def preference():
answer = input("hi, do you wanna play a game?: ")
if answer == "yes":
print("schweet!")
from time import sleep
sleep(1.4) # Time in seconds
print("i knew you would make the right choice")
from time import sleep
sleep(1.2) # Time in seconds
else:
print("welp you dont have a choice")
preference()
from time import sleep
sleep(1.5) # Time in seconds
print("hmmmm lets see if you can guess what number im thinking of!")
from time import sleep
sleep(3) # Time in seconds
print("theres an infinte amount of choices, eh?")
from time import sleep
sleep(3) # Time in seconds
print("ill be nice and let you pick a range")
from time import sleep
sleep(3) # Time in seconds
lowerbound = int(input("whats the smallest number?:"))
upperbound = int(input("now the largest number:"))
import random
randomNum = random.randint(lowerbound, upperbound)
print("hmmmm very intresting choices. now i will pick a number in between")
from time import sleep
sleep(1) # Time in seconds
#start guessing
guess = input("any guesses what number it could be: ")
|
import pickle
import random
class TweetGenerator:
def __init__(self):
self.transition_dict = {}
self.loaded = False
def load_generator(self, filename):
"""
Prep the generator by specifying the markov chain's transition probabilities.
:param filename: file location of the pickle object to be loaded
"""
self.transition_dict = pickle.load(open(filename, "rb"))
self.loaded = True
def generate_tweet(self):
"""
Generate a fake tweet based on the trigram model markov chain.
:return: string denoting the fake tweet
"""
w1 = "BEGIN"
w2 = "TWEET"
tweet = ""
w3 = random.choice(self.transition_dict[(w1, w2)])
while w3 != "END":
tweet = tweet + " " + w3
w1 = w2
w2 = w3
w3 = random.choice(self.transition_dict[(w1, w2)])
return tweet
|
from collections import deque
def main():
n = int(input())
words = {input(): set() for _ in range(n)}
m = int(input())
for _ in range(m):
a, b = input().split()
words[a].add(b)
words[b].add(a)
colors = {}
q = deque()
for start in words.keys():
if start in colors:
continue
q.append((start, True))
while q:
curr, color = q.pop()
if curr in colors and colors[curr] != color:
print('impossible')
return
colors[curr] = color
for o in words[curr]:
if o not in colors:
q.append((o, not color))
print(*(k for k in colors if colors[k]))
print(*(k for k in colors if not colors[k]))
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
"""
Small method just to help me with small tasks.
"""
import os
import argparse
from PIL import Image
def crop_image(file_path, padding, dest_path=None):
"""Crop Image"""
try:
image = Image.open(file_path)
image = image.crop((padding, padding, image.size[0] - padding,
image.size[1] - padding))
image.save(dest_path if dest_path else file_path)
except IOError as ex:
print("cannot crop image file:", file_path, ' error: ', ex)
def crop_images(files_paths, padding, dest_folder):
"""Add padding to images"""
for file_path in files_paths:
dest_file = file_path if dest_folder is None else os.path.join(
dest_folder, os.path.basename(file_path))
crop_image(file_path, -1 * padding, dest_file)
def auto_crop_image(file_path, dest_path=None):
"""Removes zero padding from image"""
try:
image = Image.open(file_path)
box = image.getbbox()
image = image.crop(box)
image.save(dest_path if dest_path else file_path)
except IOError as ex:
print("cannot auto_crop image file:", file_path, ' error: ', ex)
def auto_crop_images(files_paths, dest_folder):
"""Removes zero padding from images"""
for file_path in files_paths:
dest_file = file_path if dest_folder is None else os.path.join(
dest_folder, os.path.basename(file_path))
auto_crop_image(file_path, dest_file)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Image utils:')
parser.add_argument(
'--add-padding', dest='padding', type=int, help='Padding')
parser.add_argument(
'-o', '--output', type=str, help='Output folder (must exist)')
parser.add_argument(
'--auto-crop', action='store_true', default=False,
help='Auto crop images')
parser.add_argument('files', nargs='+', help='Files')
args = parser.parse_args()
# ToDo: method to iterate over files and run func?
if args.padding and args.padding != 0:
crop_images(args.files, args.padding, args.output)
elif args.auto_crop:
auto_crop_images(args.files, args.output)
else:
print('Nothing to do here. Exiting now....')
|
import curses
from random import randint
curses.initscr()
curses.noecho()
curses.curs_set(0)
win = curses.newwin(20,60,0,0) #y,x not x,y
win.keypad(1)
win.border(0)
win.nodelay(1)
snake = [(4,10),(4,9),(4,8)]
food = (10,20)
ESC = 27
key = curses.KEY_RIGHT
score = 0
win.addch(food[0],food[1],"O")
while key!=ESC:
win.addstr(0,2," Score: " + str(score) + " ")
win.timeout(100)
prev_key = key
event = win.getch()
key = event if event != -1 else prev_key
if key not in [curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_UP, curses.KEY_DOWN, ESC]:
key = prev_key
#position of snake
y = snake[0][0]
x = snake[0][1]
#keys to move the snake
if key == curses.KEY_DOWN:
y += 1
if key == curses.KEY_UP:
y -= 1
if key == curses.KEY_LEFT:
x -= 1
if key == curses.KEY_RIGHT:
x += 1
snake.insert(0,(y,x))
#snake dies when it touches border
if y==0 or y==19:
break
if x==0 or x==59:
break
#snake dies when it touches itself
if snake[0] in snake[1:]:
break
#if snake eats food
if snake[0]==food:
score += 1
food = ()
while food == ():
food = (randint(1,18),randint(1,58))
if food in snake:
food = ()
win.addch(food[0],food[1],"O")
else:
#moving the snake around
last = snake.pop()
win.addch(last[0],last[1]," ")
win.addch(snake[0][0],snake[0][1],"*")
curses.endwin()
print(f"Score = {score}") |
from tkinter import *
from functools import partial
import random
class Menu:
def __init__(self):
# Formatting variables
background_color = "deep sky blue"
# Menu frame
self.menu_frame = Frame(width=10, bg=background_color, pady=10)
self.menu_frame.grid()
# Quiz heading (row 0)
self.quiz_heading_label = Label(self.menu_frame,
text="MENU",
font="Arial 20 bold",
bg=background_color,
padx=10, pady=10)
self.quiz_heading_label.grid(row=0)
# Introduction of the quiz (row 1)
self.quiz_introduction_label = Label(self.menu_frame,
text="Welcome to World Countries Quiz"
" Please push the button to start ",
font="arial 14 italic", wrap=250,
justify=LEFT, bg=background_color,
padx=150, pady=15)
self.quiz_introduction_label.grid(row=1)
# Start button (row 2)
self.start_button = Button(self.menu_frame, text="Start",
font="Arial 14", padx=10, pady=10,
bg="light green", command=self.start)
self.start_button.grid(row=2)
# History button (row 3)
# Help button (row 4)
self.help_button = Button(self.menu_frame, text="Help",
font="Arial 14",
bg="light gray",
padx=2, pady=2, command=self.help)
self.help_button.grid(row=4, column=1)
def help(self):
get_help = Help(self)
get_help.help_text.configure(text="Push 'Start' to start the game,"
"entry your answer and press "
"'enter' to keep playing.")
def start(self):
get_start = Start(self)
# Help page
class Help:
def __init__(self, partner):
background = "orange"
partner.help_button.config(state=DISABLED)
self.help_box = Toplevel()
self.help_box.protocol('WM_DELETE_WINDOW', partial(self.close_help, partner))
self.help_frame = Frame(self.help_box, width=300, bg=background)
self.help_frame.grid()
self.how_heading = Label(self.help_frame, text="Help/Instructions",
font="arial 10 bold", bg=background)
self.how_heading.grid(row=0)
self.help_text = Label(self.help_frame, text="", justify=LEFT,
width=40, bg=background, wrap=250)
self.help_text.grid(row=1)
self.dismiss_btn = Button(self.help_frame, text=" I got it",
width=10, bg="green", font="arial 10 bold",
command=partial(self.close_help, partner))
self.dismiss_btn.grid(row=3, pady=10)
def close_help(self, partner):
partner.help_button.config(state=NORMAL)
self.help_box.destroy()
# Start page(game page)
class Start:
def __init__(self, partner):
# color of page
background = "light yellow"
# disable start button
partner.start_button.config(state=DISABLED)
# set up child window(start page)
self.start_box = Toplevel()
# after user closed start page, released start button
self.start_box.protocol('WM_DELETE_WINDOW', partial(self.close_start, partner))
# set up start frame
self.start_frame = Frame(self.start_box, width=500, pady=50,
bg=background,)
self.start_frame.grid()
# set up the heading (row 0)
self.start_heading = Label(self.start_frame, text="Please type the correct answer",
font="arial 18 bold", bg=background)
self.start_heading.grid(row=0)
# Entry box (row 2)
self.entry_box = Entry(self.start_frame, width=10,
font="arial 12")
self.entry_box.grid(row=3)
# Quit button (row 3)
self.quit_button = Button(self.start_frame, text="Exit",
font="Arial 14",
bg="brown",
command=partial(self.close_start, partner))
self.quit_button.grid(row=4, column=1)
# Questions text (row 1)
self.question_text = Label(self.start_frame,
font="Arial 13",
bg="light yellow")
self.question_text.grid(row=1)
# Result text (row 2)
self.result_text = Label(self.start_frame,
font="Arial 13",
bg="light yellow")
self.result_text.grid(row=2)
# Submit button (row 5)
self.submit_button = Button(self.start_frame,
text="Submit",
font="Arial 13",
command=self.submit_answer)
self.submit_button.grid(row=5)
# Question List
self.questionlist = [["What is the biggest country in the world", "Russia"], ["What is the most populated country",
"China"], ["What country is the capital of Paris", "France"], ["What is the smallest country in the world",
"Vatican"],
["What country is the capital of Wellington", "NewZealand"]]
self.num_questions = 0
self.score = 0 # for count the score
random.shuffle(self.questionlist)
self.question = self.questionlist[0][0]
self.correct_answer = self.questionlist[0][1]
self.question_text.config(text=self.question, fg="black")
# Submit answer and check the answer
def submit_answer(self):
user_answer = self.entry_box.get()
if user_answer == self.correct_answer:
print("Correct")
self.score += 1
else:
print("Incorrect")
self.num_questions += 1
if self.num_questions != 5:
self.question = self.questionlist[self.num_questions][0]
self.correct_answer = self.questionlist[self.num_questions][1]
self.question_text.config(text=self.question)
else:
print(f"You have got {self.score} out of 5 questions correct!")
quit() # print score
# destroy the program
def close_start(self, partner):
partner.start_button.config(state=NORMAL)
self.start_box.destroy()
if __name__ == "__main__":
root = Tk()
root.title("World Countries Quiz")
something = Menu()
root.mainloop()
|
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
ans = []
def backtrack(S = '', left = 0, right = 0):
if len(S) == 2 * n:
ans.append(S)
return
if left < n:
backtrack(S+'(', left+1, right)
if right < left:
backtrack(S+')', left, right+1)
backtrack()
return ans
def generateParenthesis2(self, n):
if not n:
return []
left,right,ans = n,n,[]
self.dfs(left,right,ans,'')
return ans
def dfs(self,left,right,ans,string):
if left > right:#递归出口1:左必须小于右,意味着必须先有足够的左括号才能加右括号
return
if not left and not right:#递归出口2:当左和右为0时,将string保存
ans.append(string)
return
if left:
self.dfs(left-1,right,ans,string+"(")
if right:
self.dfs(left,right-1,ans,string+")")
S = Solution()
print(S.generateParenthesis2(2))
|
def removeDuplicates(nums,val):
length = len(nums)
if length == 0:
return 0
point = 0
for i in range(0,len(nums)):
if nums[i] != val: #如果相等,point不动,先赋值再前进
nums[point] = nums[i]
point += 1
return point,nums
print(removeDuplicates([1,2,2,3,4,6,7,2],2))
|
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dic = {}
for value in nums:
if value in dic:
return True
else:
dic[value] = 1
return False
def containsDuplicate2(self, nums):
return len(set(nums)) != len(nums) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.