text
stringlengths 37
1.41M
|
---|
import datetime
name = input('ENTER YOUR NAME HERE:- ')
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour<12:
print(f'GOOD MORNING {name}')
elif hour>=12 and hour<17:
print(f'GOOD AFTERNOON {name}')
else:
print(f'GOOD EVENING {name}')
passward = int(input('ENTER THE PASSWARD TO ACCESS THE SYSTEM:-' ))
if passward==7115:
print('SYSTEM ACCESS')
pass
if passward<7115:
print('SYSTEM DENIED')
print('DELETING ALL THE FILES OF THE SYSTEM...')
print('SENDING ALL THE FILES TO THE IP ADDRESS...')
print(10 * 'IOIOIIIOOOOOIIIIOOIIOIOOOOOOIIIIIIIOIOIOIOIOIOIOIOIOIOIIOIOIOOOOOIIIIIIIOIOIOOIIOIOIOIOIIOIOIOOOOOIOIOIIOOOIOIIOIO')
exit()
if passward>7115:
print('SYSTEM DENIED')
print('DELETING ALL THE FILES OF THE SYSTEM...')
print('SENDING ALL THE FILES TO THE IP ADDRESS...')
print(10 * 'IOIOIIIOOOOOIIIIOOIIOIOOOOOOIIIIIIIOIOIOIOIOIOIOIOIOIOIIOIOIOOOOOIIIIIIIOIOIOOIIOIOIOIOIIOIOIOOOOOIOIOIIOOOIOIIOIO')
exit()
print('''WELCOME TO THE SYSTEM CAPTAIN''')
|
# Take Inputs:
a = int(input('Enter the value of a: '))
b = int(input('Enter the value of b: '))
c = int(input('Enter the value of c: '))
#get the roots
d = (b*b - 4*a*c)**0.5
x1 = (-b + d)/(2*a)
x2 = (-b - d)/(2*a)
print('\r\nthe root of a quadratic equation ARE:')
print('x1: {0}'.format(x1))
print('x2: {0}'.format(x2))
|
from random import *
class PlayerController:
def __init__(self):
self._currentPlayer = 1
self._currentPlayerType = "human"
self._playerIdentity = 0
self.mode = "human"
# generate random player number
def chooseFirst(self):
self._currentPlayer = round(random.random()) + 1
def setPlayerIdentity(self, player):
self._playerIdentity = player
def getPlayerIdentity(self):
return self._playerIdentity
def setCurrentPlayer(self, player):
self._currentPlayer = player
# is the getter for the private variable
def currentPlayer(self):
return self._currentPlayer
def currentEnemy(self):
if self._currentPlayer == 1:
return 2
else:
return 1
# is the current Player human?
def isPlayerHuman(self):
return self._currentPlayerType == "human"
# alter the players
def changePlayer(self):
if self._currentPlayer == 1:
self._currentPlayer = 2
else:
self._currentPlayer = 1
if self.mode == "ki":
if self._currentPlayerType == "human":
self._currentPlayerType = "ki"
else:
self._currentPlayerType = "human"
if self.mode in ["inter", "machine"]:
self._currentPlayerType = "ki"
|
print("주문 가능한 메뉴:")
menu_list=['햄버거','샌드위치','콜라','사이다']
print(menu_list)
a=int(input("메뉴번호(0-3):"))
b=int(input("개수:"))
print("선택된 메뉴:",menu_list[a])
if a==0:
price=3000
elif a==1:
price=2000
elif a==2:
price=1000
elif a==3:
price=1000
print("총가격:%d"%(price*b))
|
"""
문제: 정수의 각 자리수의 합을 출력하라
입력 예)
정수:546
출력 예)
자리수의 합: 15
"""
a=int(input("정수:"))
b=0
while a>0:
c=a%10
b=b+c
a=a//10
print("자리수의 합:%d" %b)
a=int(input("정수:"))
sum=0
while a>0:
b=a%10
a=a//10
sum=sum+b
sum=sum+a
print(sum)
|
import operator
from time import sleep
from typing import Any, List
def wait_for_assert(expected_data: Any,
function: (),
message: str='',
retries: int=5,
delay_sec: int=1,
oper=operator.eq,
exceptions: List[Exception]=None,
print_data: bool = True):
""" Function that permits to assert a condition with a timeout
:param expected_data: Data that are expected in the assert
:param function: Function that returns data to be compared with expected data
:param message: Error message for failed assert
:param retries: Number of retries
:param delay_sec: Delay between retries in seconds
:param oper: operator to be used when comparing data
:param exceptions: exceptions to ignore
:param print_data: whether to print data to stdout
"""
for i in range(retries, -1, -1):
if not exceptions:
data = function()
else:
try:
data = function()
except tuple(exceptions):
sleep(delay_sec)
continue
try:
assert oper(expected_data, data), message
break
except AssertionError:
if i == 0:
# all retries are used
if print_data:
print('Expected data:', expected_data)
print('Operator: ', str(oper))
print('Actual data: ', data)
raise
sleep(delay_sec)
else:
raise AssertionError('All attempts exhausted (exceptions(s) raised)')
|
from helpers import get_data
from typing import List
def unique_letters_in_strings(strings: List[str]) -> int:
return len(set("".join(strings)))
def all_shared_letters_in_strings(strings: List[str]) -> int:
if not strings:
return 0
start_set = set(strings[0])
return len(start_set.intersection(*(set(string) for string in strings[1:])))
def split_input_to_blocks(data: str) -> List[str]:
return data.split("\n\n")
def split_block_to_lines(block: str) -> List[str]:
return block.split("\n")
def data_to_block_as_lines(data: str) -> List[List[str]]:
return [split_block_to_lines(block) for block in split_input_to_blocks(data)]
def sum_all_unique(data):
return sum(
unique_letters_in_strings(lines) for lines in data_to_block_as_lines(data)
)
def sum_all_present(data):
return sum(
all_shared_letters_in_strings(lines) for lines in data_to_block_as_lines(data)
)
def main():
data = get_data(day=6)
ans = sum_all_unique(data)
print(f"The answer is {ans}.")
ans = sum_all_present(data)
print(f"Achtually, it is {ans}.")
if __name__ == "__main__":
main()
|
from collections import namedtuple
from typing import Iterable
from itertools import tee
InputLine = namedtuple("InputLine", ("low", "high", "letter", "password"))
def is_password_valid(low: int, high: int, letter: str, password: str) -> bool:
return low <= password.count(letter) <= high
def is_password_valid_v2(low: int, high: int, letter: str, password: str) -> bool:
return (password[low - 1] == letter) ^ (password[high - 1] == letter)
def parse_input_line(line: str) -> InputLine:
tokens = line.split(" ")
low_high = tokens[0].split("-")
letter = tokens[1][:-1]
password = tokens[2]
low, high = int(low_high[0]), int(low_high[1])
return InputLine(low, high, letter, password)
def count_valid(inputs: Iterable[InputLine], checker=is_password_valid) -> int:
return sum(1 for input in inputs if checker(*input))
def main():
from helpers.data_access import get_data
data = get_data(day=2).split("\n")
inputs = (parse_input_line(line) for line in data)
inputs_1, inputs_2 = tee(inputs)
count = count_valid(inputs_1)
print(f"There are {count} valid passwords.")
count_v2 = count_valid(inputs_2, checker=is_password_valid_v2)
print(f"Actually there's {count_v2} valid passwords.")
if __name__ == "__main__":
main()
|
def chooseoption():
hotelsize = input("""
please select your hotel size by choosing a number
1 small
2 medium
3 big
or if you would like to continue your last hotel type 'start'
""")
print(hotelsize)
if hotelsize == 'start':
hotelsize = input("""
please select your hotel size by choosing a number
1 small
2 medium
3 big
""")
pause = 'start'
else:
pause = 'x'
with open('lastchoice.txt', 'w') as f:
f.write(hotelsize)
f.close()
return hotelsize, pause
|
def lastfirst(lst):
fname = list()
lname = list()
for name in lst:
nameV = name.split(',')
fname.append(nameV[1])
lname.append(nameV[0])
print('First name: ' , fname)
print('Last name: ', lname)
allnames = list()
allnames.append(fname)
allnames.append(lname)
return allnames
names = ['Gaaa,aaa','Haaa,kkk','JKKKK,llll']
mynames = lastfirst(names)
for alist in mynames:
print(alist)
|
# -*- coding: utf-8 -*-
"""
Herman Sanghera
October 26, 2019
CodingBat Solutions (Python)
This is a python file containing my own solutions to the
different Python Warmup-2 exercises on codingbat.com
"""
"""
Warmup-2 > string_times:
Given a string and a non-negative int n, return a larger string
that is n copies of the original string.
"""
def string_times(str, n):
answ = ""
for x in range(n):
answ += str
return answ;
"""
Warmup-2 > front_times:
Given a string and a non-negative int n, we'll say that the front
of the string is the first 3 chars, or whatever is there if the
string is less than length 3. Return n copies of the front.
"""
def front_times(str, n):
answ = ""
for x in range(n):
answ += str[:3]
return answ;
"""
Warmup-2 > string_bits:
Given a string, return a new string made of every other char
starting with the first, so "Hello" yields "Hlo".
"""
def string_bits(str):
return(str[::2])
"""
Warmup-2 > string_explosion:
Given a non-empty string like "Code" return a string like "CCoCodCode".
"""
def string_splosion(str):
answ = ""
for i in range(len(str)+1):
answ += str[0:i]
return answ
"""
Warmup-2 > last2:
Given a string, return the count of the number of times that a substring
length 2 appears in the string and also as the last 2 chars of the
string, so "hixxxhi" yields 1 (we won't count the end substring).
"""
def last2(str):
num = 0
if(len(str) <= 2):
return num
else:
last2 = str[-2:]
for i in range(len(str)-2):
if(last2 == str[i:i+2]):
num+=1
return num
"""
Warmup-2 > array_count9
Given an array of ints, return the number of 9's in the array.
"""
def array_count9(nums):
count = 0
for element in nums:
if element == 9:
count+=1
return count
"""
Warmup-2 > array_front9
Given an array of ints, return True if one of the first 4 elements
in the array is a 9. The array length may be less than 4.
"""
def array_front9(nums):
stop = len(nums)
if(len(nums) > 4):
stop = 4
for i in range(stop):
if nums[i] == 9:
return True;
return False;
"""
Warmup-2 > array123
Given an array of ints, return True if the sequence of numbers 1, 2,
3 appears in the array somewhere.
"""
def array123(nums):
for i in range(len(nums)-2):
if nums[i] == 1:
if nums[i+1] == 2:
if nums[i+2] == 3:
return True;
return False;
"""
Warmup-2 > string_match
Given 2 strings, a and b, return the number of the positions where
they contain the same length 2 substring. So "xxcaazz" and "xxbaaz"
yields 3, since the "xx", "aa", and "az" substrings appear in the same
place in both strings.
"""
def string_match(a, b):
count = 0
if len(a) >= len(b):
min = len(b)
else:
min = len(a)
for i in range(min-1):
target1 = a[i:i+2]
target2 = b[i:i+2]
if(target1 == target2):
count+=1;
return count
|
lista=["Luis","Maria","Cecy","Beto"]
print(lista[:])
#añadir elementos a la lista
lista.append("Isma")
print(lista[:])
lista.extend(["Gordo","Eve"])
print(lista[:])
print(lista.index("Luis"))
print("Luis" in lista)
lista.extend(["Luis","Pedro"])
print(lista[:])
|
import itertools
my_list = ['a','b','c']
combinations = itertools.combinations(my_list, 3)
for c in combinations:
print(c)
# permutations = itertools.permutations(my_list, 3)
# for p in permutations:
# print(p)
|
def permutations(word):
if len(word) == 1:
return [word]
else:
# get all permutations
perms = permutations(word[1:])
char=word[0]
result=[]
for perm in perms:
for i in range(len(perm) + 1):
p = perm[:i]+char+perm[i:]
if p not in result:
result.append(p)
return result
print(permutations('abc'))
|
age =int(input('请输入你的年龄:'))
subject =input('请输入你的专业:')
college =input('是否是重点大学:')
if age > 25 and subject == '电子工程专业':
print('面试成功')
elif college == '是' and subject == '电子信息工程专业':
print('面试成功')
elif age < 28 and subject == '计算机':
print('面试成功')
else:
print('不符合面试要求')
|
print('请输入(中心,音乐模块,微信支付模块)')
while True:
a = input('输入:')
if a == '中心':
print('您的分数为:35')
elif a == '音乐模块':
print('您的分数为:30')
elif a == '微信支付模块':
print('您的分数为: 40')
else:
print('输入有误')
break
|
a = int(input('请您输入一个年份'))
if (a%4==0 and a%100!=0) or a%400==0:
print('这个年份是闰年')
else:
print('这个年份是平年')
|
a = int(input('输出花的朵数'))
if a == 1:
print('你是我的唯一')
elif a == 3:
print('I Love You')
elif a == 10:
print('十全十美')
elif a == 99:
print('天长地久')
elif a == 108:
print('求婚')
elif a == 999:
print('土豪')
else:
print('掏钱吧')
|
import random
class Die:
# constructor
def __init__(self, sides=2, value=0):
# can't have a 1 sided die...
if not sides >= 2:
raise ValueError("Must have at least 2 sides")
# can't have letters either...
if not isinstance(sides, int):
raise ValueError("Sides must be a whole number")
# if all is well, give back a random value within the
# number of sides on the die
self.value = value or random.randint(1, sides)
# turn an instance of the Die into an integer
def __int__(self):
return self.value
# equality, allow comparing die value to other values.
# Ie. Die() instance is less than 4, etc.
# equal to
def __eq__(self, other):
return int(self) == other
# not equal to
def __ne__(self, other):
return int(self) != other
# greater than
def __gt__(self, other):
return int(self) > other
# less than
def __lt__(self, other):
return int(self) < other
# greater than or equal to
def __ge__(self, other):
return int(self) > other or int(self) == other
# less than or equal to
def __le__(self, other):
return int(self) < other or int(self) == other
# allow adding 2 dice to one another
def __add__(self, other):
return int(self) + other
# radd = right hand operation
def __radd__(self, other):
return int(self) + other
# return a printable representation of the object
# (info: https://stackoverflow.com/questions/1984162/purpose-of-pythons-repr)
def __repr__(self):
return str(self.value)
class D6(Die):
def __init__(self, value=0):
super().__init__(sides=6, value=value)
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#===============================================================
l = list(range(2000,3200+1))
#print(l)
for number in l :
#print(number)
isDivided = (number%7)
fiveDivided = number%5
if isDivided == 0 and fiveDivided != 0:
print(number)
# In[ ]:
#===============================================================
# Write a program which will find all such numbers which are divisible by 7
# but not multiple of 5 between 2000 to 3200 both included
l = list(range(2000,3200+1))
new_list = [number * 1 for number in l if ((number%7 == 0) and (number%5 != 0))]
print(new_list)
# In[ ]:
#===============================================================
#Reverse first name and last name provided by user space between first name and lastname
first_Name = input("Please provide first name ")
lats_Name = input("Please provide last name ")
first_last_name = [first_Name,' ',lats_Name]
#first_last_name = first_last_name.reverse()
first_last_name.reverse()
username = ''
for name in first_last_name:
# print(name)
l = []
l.extend(name)
l.reverse()
#print("=====",l)
for n in l:
username = username + n
print(username)
# In[ ]:
#===============================================================
# Python Program to find Volume of Sphere using Functions
import math
def Area_of_Triangle(radius):
sa = 4 * math.pi * radius * radius
Volume = (4 / 3) * math.pi * radius * radius * radius
print("\n The Surface area of a Sphere = %.2f" %sa)
print("\n The Volume of a Sphere = %.2f" %Volume)
Area_of_Triangle(12)
# In[ ]:
#===============================================================
# Accepts comma seperated sequence and generate list
comma_separated = input("Please provide comma separated list - ")
comma_separated_list = []
for word in comma_separated:
#print(word)
comma_separated_list.extend(word)
if word == ',':
comma_separated_list.remove(word)
print(comma_separated_list)
#==============Second option using string function==========
comma_separated.split(',')
# In[3]:
#===============================================================
#Nested for loop
for i in range(0,5):
j=i+1
s=""
for k in range(0,j):
s=s+"*"
print(s)
h=4
for i in s:
s=s[0:h]
h=h-1
print(s)
# In[ ]:
#===============================================================
#Reverse word after accepting from user
word = input("Please provide first name ")
word=word[::-1]
print(word)
#Reverse word after accepting from user
word = input("Please provide first name ")
word_list = [word]
#first_last_name = first_last_name.reverse()
word_list.reverse()
#print(word_list)
reversWord = ""
for rword in word_list:
l = []
l.extend(rword)
l.reverse()
for n in l:
reversWord = reversWord + n
print(reversWord)
|
months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
num_of_month = int(input('Enter number of month (1-12): '))
print('Name of month: ' + str(months[num_of_month - 1]))
|
firstName = input('Enter first name: ')
lastName = input('Enter last name: ')
print('------------------------------------------------')
print('Greetings! Hello Mr. ' + firstName + ' ' + lastName)
print('------------------------------------------------')
|
# program to replace {} with user provided input.
# Ex:
# Today is {} and it is a happy day! <- Monday, Tuesday, wednesday etc.
inp_str = input('Enter a string with {}: ')
inp_repl = input('Enter a replacement variable: ' )
index = inp_str.find('{}')
if index >= 0:
ret_str = inp_str[:index] + inp_repl + inp_str[index+2:]
print(ret_str)
else:
print('{} is not found!')
|
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
elif n == 1:
return 1
else:
return self.Fibonacci(n - 1) + self.Fibonacci(n - 2)
if __name__ == '__main__':
n = 10
s = Solution()
print(s.Fibonacci(n))
|
# Tuple is similar to list, but it is immutible.
fruits = ('Apple', 'Banana', 'Grapes', 'orange')
# fruits[1] = 'Mango' // Not Possible will get TypeError: 'tuple' object does not support item assignment
print(fruits[1])
print(fruits[2:10])
print(fruits[:2])
print(fruits[3:])
# Tuple/list slicing
numbers = [1, 4, 6, 7, 9, 10, 37, 38, 87] # defining list
print(numbers[2:7])
print(numbers[2:9:3]) # here third parameter is used to define interval of number to be print.
|
w = float(input('Enter your Weight in Kg: '))
h = float(input('Enter your height in meter: '))
def getBMIVal(weight, height):
return weight/height**2
print('Your BMI value is : ', getBMIVal(w, h))
|
# CMPM146 - Game AI
# P1 - Dijkstra's in a Dungeon
# By: Sean Song and Hana Cho
from p1_support import load_level, show_level, save_level_costs
from math import inf, sqrt
from heapq import heappop, heappush
def dijkstras_shortest_path(initial_position, destination, graph, adj):
""" Searches for a minimal cost path through a graph using Dijkstra's algorithm.
Args:
initial_position: The initial cell from which the path extends.
destination: The end location for the path.
graph: A loaded level, containing walls, spaces, and waypoints.
adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.
Returns:
If a path exits, return a list containing all cells from initial_position to destination.
Otherwise, return None.
"""
q = [(0, initial_position)] # node queue
visited = {initial_position: (0, None)} # dist, prev
# while queue not empty
while q:
cur_dist, cur = heappop(q) # get current
if cur == destination: # check success
path = [cur]
back = visited[cur][1]
while back and back is not initial_position: # backpathing
path = [back] + path
back = visited[back][1]
return [initial_position] + path
for pos, cost in adj(graph, cur): # for each neighbour
if cost is not inf:
pathcost = cost + cur_dist
if not visited.get(pos) or pathcost < visited[pos][0]:
visited[pos] = (pathcost, cur)
heappush(q, (pathcost, pos))
return None
def dijkstras_shortest_path_to_all(initial_position, graph, adj):
""" Calculates the minimum cost to every reachable cell in a graph from the initial_position.
Args:
initial_position: The initial cell from which the path extends.
graph: A loaded level, containing walls, spaces, and waypoints.
adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.
Returns:
A dictionary, mapping destination cells to the cost of a path from the initial_position.
"""
level = {**graph["spaces"],**{pos:1.0 for pos in graph["waypoints"].values()}} # recomprehend graph
level_cost = {}
for pos in level: # for every reachable space
p = dijkstras_shortest_path(initial_position, pos, graph, adj) # find path
cost = 0 if p else inf
if p:
for i in range(len(p)-1):
a = p[i]
b = p[i+1]
cost = cost + (level[a] + level[b]) / 2 * (1 if abs(a[0]-b[0]) + abs(a[1]-b[1]) > 1 else sqrt(2)) #calc path cost
level_cost[pos] = cost
return level_cost
def navigation_edges(level, cell):
""" Provides a list of adjacent cells and their respective costs from the given cell.
Args:
level: A loaded level, containing walls, spaces, and waypoints.
cell: A target location.
Returns:
A list of tuples containing an adjacent cell's coordinates and the cost of the edge joining it and the
originating cell.
E.g. from (0,0):
[((0,1), 1),
((1,0), 1),
((1,1), 1.4142135623730951),
... ]
"""
neighbors = []
# iterate over adjacent cells
for i in range(cell[0]-1, cell[0]+2):
for j in range(cell[1]-1, cell[1]+2):
# if cell is not original cell
if (i, j) != cell:
# if cell is a wall
if (i, j) in level['walls']:
cost = inf
# if new cell is diagonal from original cell
elif abs(i - cell[0]) > 0 and abs(j - cell[1]) > 0:
cost = sqrt(2) * 0.5 * \
(level['spaces'][(i, j)] + level['spaces'][cell])
else:
cost = 0.5 * (level['spaces'][(i, j)] +
level['spaces'][cell])
neighbors.append(((i, j), cost))
return neighbors
def test_route(filename, src_waypoint, dst_waypoint):
""" Loads a level, searches for a path between the given waypoints, and displays the result.
Args:
filename: The name of the text file containing the level.
src_waypoint: The character associated with the initial waypoint.
dst_waypoint: The character associated with the destination waypoint.
"""
# Load and display the level.
level = load_level(filename)
show_level(level)
# Retrieve the source and destination coordinates from the level.
src = level['waypoints'][src_waypoint]
dst = level['waypoints'][dst_waypoint]
# Search for and display the path from src to dst.
path = dijkstras_shortest_path(src, dst, level, navigation_edges)
if path:
show_level(level, path)
else:
print("No path possible!")
def cost_to_all_cells(filename, src_waypoint, output_filename):
""" Loads a level, calculates the cost to all reachable cells from
src_waypoint, then saves the result in a csv file with name output_filename.
Args:
filename: The name of the text file containing the level.
src_waypoint: The character associated with the initial waypoint.
output_filename: The filename for the output csv file.
"""
# Load and display the level.
level = load_level(filename)
show_level(level)
# Retrieve the source coordinates from the level.
src = level['waypoints'][src_waypoint]
# Calculate the cost to all reachable cells from src and save to a csv file.
costs_to_all_cells = dijkstras_shortest_path_to_all(
src, level, navigation_edges)
save_level_costs(level, costs_to_all_cells, output_filename)
if __name__ == '__main__':
filename, src_waypoint, dst_waypoint = 'example.txt', 'a', 'e'
# Use this function call to find the route between two waypoints.
test_route(filename, src_waypoint, dst_waypoint)
# Use this function to calculate the cost to all reachable cells from an origin point.
cost_to_all_cells(filename, src_waypoint, 'my_costs.csv')
|
import random
choices = ['rock', 'scissors', 'paper','0']
exitGame = False
while(exitGame == False):
computer_choice = random.choice(choices)
user_choice = None
while user_choice == None:
print("\n############# ROCK PAPER SCISSORS ###########")
print("## TYPE 'rock', 'paper', 'scissors' OR '0' TO EXIT ###########")
user_choice = input("Make your choice:")
if user_choice not in choices:
user_choice = None
if(user_choice == computer_choice):
print("Draw")
elif user_choice == 'paper':
if computer_choice == 'scissors':
print("Computer chose scissors")
print("Computer Wins!")
elif computer_choice == 'rock':
print("Computer chose rock")
print("+++ You Win +++")
elif user_choice == 'rock':
if computer_choice == 'paper':
print("Computer chose paper")
print("Computer Wins!")
elif computer_choice == 'scissors':
print("Computer chose scissors")
print("+++ You Win +++")
elif user_choice == 'scissors':
if computer_choice == 'rock':
print("Computer chose rock")
print("Computer Wins!")
elif computer_choice == 'paper':
print("Computer chose paper")
print("+++ You Win +++")
elif user_choice == '0':
exitGame = True
user_choice = None
print("Bye!")
|
def get_surface_radius() -> float:
""" Function for input from user radius of surface """
print(" Введите радиус поверхности( дробная часть отделяется точкой")
print(" Пример: 1.001")
radius = input(" ")
try:
res = float(radius)
except:
print(" Введите правильные данные")
return get_surface_radius()
return res
def get_surface_height() -> float:
""" Function for input from user height of surface """
print(" Введите высоту поверхности:")
print(" (разность между показаниями сферометра на детали и эталонной\
плоскости)")
print(" (дробная часть отделяется точкой)")
print(" Пример: 1.001")
height = input(" ")
try:
height = float(height)
except:
print(" Введите правильные данные")
return get_surface_height()
return height
|
from PIL import Image #@UnresolvedImport
import pdb
import numpy as np
from roslib.msgs import EXT
'''
im.transform(size, AFFINE, data, filter) ⇒ image
Applies an affine transform to the image, and places the result in a new image with the given size.
Data is a 6-tuple (a, b, c, d, e, f) which contain the first two rows from an affine transform matrix. For each pixel (x, y) in the output image, the new value is taken from a position (a x + b y + c, d x + e y + f) in the input image, rounded to nearest pixel.
This function can be used to scale, translate, rotate, and shear the original image.
'''
# Load an image for testing
image = Image.open('rockys.png')
# Set the output size
ext_size = (200, 200)
h, w = ext_size
# Fit the affine parameters to a quadrilateral with the coorners c using matrix A
c1 = (1500, 500)
c2 = (1300, 700)
c3 = (1500, 900)
c4 = (1700, 700)
A = np.mat([[0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1],
[h, 0, 1, 0, 0, 0], [0, 0, 0, h, 0, 1],
[h, w, 1, 0, 0, 0], [0, 0, 0, h, w, 1],
[0, w, 1, 0, 0, 0], [0, 0, 0, 0, w, 1]])
b = np.mat(c1 + c2 + c3 + c4).T
# Solve for the parameters
data_mat = (A.T * A).I * A.T * b
data = np.array(data_mat.T)[0]
print(data)
# Transform the image
ext_image = image.transform(ext_size, Image.AFFINE, data)
# Show the transformed image
ext_image.show()
|
import sys
def replace_quotes(text):
flag = False
new_text = ''
for char in text:
if char == '\"':
if flag:
char = "''"
flag = False
else:
char = '``'
flag = True
new_text += char
return new_text
def main():
print replace_quotes(sys.stdin.readlines())
return 0
if __name__ == '__main__':
main()
|
introduction=input("Enter something about yourself: ")
charCount=0
wordCount = 1
for x in introduction:
charCount+=1
if x ==" ":
wordCount+=1
print("Number of characters in the entered string: ",charCount)
print("Number of words in the entered string: ",wordCount)
|
"""
Straws [dicebox 1.0]
Draw straws.
Author(s): Jason C. McDonald
"""
import random
class StrawBundle:
"""
A bundle of straws, one of which is short.
"""
def __init__(self, count=1, short=1, draws=0):
"""
Initialize a bundle of straws.
"""
# The number of straws in the bundle.
self.__count = count
# The number of short straws in the bundle.
self.__short = short
# The number of straws to draw.
self.__draws = draws
# If unspecified, we will draw all the straws.
if self.__draws == 0:
self.__draws = self.__count
# The straws drawn.
self.__drawn = []
# Generate the bundle of straws.
self.__straws = [True] * self.__short
self.__straws += [False] * (self.__count - self.__short)
def draw(self):
"""
Draw straws.
"""
self.__drawn = random.sample(self.__straws, self.__draws)
def display(self):
"""
Show the results of the straw draw.
"""
for i in range(0, len(self.__drawn)):
if self.__drawn[i]:
print(str(i+1) + ". You drew a short straw!")
else:
print(str(i+1) + ". You're okay.")
|
"""
class Person:
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
def male(self):
print(f"{self.name} you are male!")
def female(self):
print(f"{self.name}you are female!")
ramesh = Person("Ramesh", "5.6", "75")
shruti = Person("Shruti", "5.3", "65")
# Another Example :
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
happy_bday = Song(["Happy birthday to you","I don't want to get sued","So I'll stop right there"])
bulls_on_parade = Song(["They rally around tha family","With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
"""
class Song:
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_song(self):
for lines in self.lyrics:
print(lines)
sad_songs = Song(["Tum hi ho , kyuki tum hi ho ", "Me tenu samjavan ki me tere bin lgta ji", "Tu hi hai aasihqui"])
love_songs = Song(["Tere liye duniya chod di hai", "love me thoda"])
sad_songs.sing_song()
|
types_of_people = 10
binaries = 1
print("There is {} types of peoples out there , one who understand the binaries and another who can't".format(types_of_people))
print(f"binaries have two digits one is {binaries} and another is 0")
|
import math
co = float(input('cateto oposto:'))
ca = float(input('cateto adjacente:'))
h = math.hypot(co, ca)
print('o comprimento da hipotenusa é {:.2f}'.format(h))
|
peso = float(input('Qual o seu peso? (KG)'))
alt = float(input('Qual a sua altura? (M)'))
imc = peso / (alt ** 2)
print(imc)
if imc < 18.5:
print('Voce está abaixo do peso')
elif 18.5 <= imc < 25:
print('voce eta no peso ideal')
elif 25 <= imc < 30:
print('voce esta com sobrepeso')
elif 30 <= imc < 40:
print('voce esta obeso')
elif imc >= 40:
print('voce esta com obesidade MORBIDA, VA AO MEDICO URGENTEMENTE')
|
velo = int(input('qual a velocidade do veículo em km/h:'))
if velo > 80:
print('VOCE FOI MULTADO !!!')
print('Multa no valor de R${}'.format((velo-80)*7))
else:
print('Situaçao normal')
|
import csv
def numbers(s):
return any(i.isdigit() for i in s)
with open('ways_tags.csv') as f:
reader = csv.DictReader(f)
new_set = set()
for row in reader:
if row['key'] == 'street' and numbers(row['value']):
new_set.add(row['value'])
# The set cannot simply be printed, as the Unicode characters would not be displayed properly.
# The following loop is created specifically to display the names nicely, with Unicode characters and all.
for value in new_set:
print unicode(value, 'utf-8').encode('utf-8')
|
sandwich = [["rye", "sourdough", "baguette"],
[["ham", "salami", "turkey"],
["swiss", "munster", "cheddar"]],
["mayo", "mustard", "tabasco"]]
print sandwich[0][1]
print sandwich[1]
print sandwich[1][0][0]
print sandwich[2]
print sandwich[1][1][2]
print sandwich[0][1]
city_info = {'new_york' : { 'mayor' : "Bill DeBlasio",
'population' : 8406000,
'website' : "http://www.nyc.gov"
},
'los_angeles' : { 'mayor' : "Eric Garcetti",
'population' : 3884307,
'website' : "http://www.lacity.org"
},
'miami' : { 'mayor' : "Tomas Regalado",
'population' : 417650,
'website' : "http://www.miamigov.com"
},
'chicago' : { 'mayor' : "Rahm Emanuel",
'population' : 2719000,
'website' : "http://www.cityofchicago.org/"
}
}
print city_info["los_angeles"]
print city_info["chicago"]["mayor"]
print city_info["new_york"]["population"]
print city_info["miami"]["website"]
print city_info["los_angeles"]["mayor"]
print city_info["chicago"]
for city in city_info:
for info in city_info[city]:
print "The " + info + " of " + city + " is " + str(city_info[city][info])
|
import string
import random
s1 = string.ascii_lowercase
s2 = string.ascii_uppercase
s3 = string.digits
s4 = string.punctuation
length = input("Enter the length of the password: ")
if(not length.isnumeric()):
print("Please enter the valid length of the password")
else:
password = []
password.extend(s1)
password.extend(s2)
password.extend(s3)
password.extend(s4)
password=random.sample(password,int(length))
newPassword = "".join(password)
print(newPassword)
|
"""
This script looks in specified folder for files with either .prt.x or .asm.x extension, where x is an integer.
These file will be renamed by removing the .x parts.
- If multiple files map to the same name - the highest integer is used.
- If a file without the .x part already exists - it will be overwritten.
"""
import os
import sys
COMPONENT_DIR = 'components'
def find_prt_files(input_dir):
print 'input_dir : {0}'.format(input_dir)
prt_files = {}
for root, dirs, files in os.walk(input_dir):
for ff in files:
if '.prt.' in ff or '.asm.' in ff:
new_name = ff
while is_integer(new_name[-1]):
new_name = new_name[:-1]
new_name = new_name[:-1]
new_name_full = os.path.join(root, new_name)
if new_name_full in prt_files:
prt_files[new_name_full]['file_names'].append(ff)
else:
prt_files[new_name_full] = {}
prt_files[new_name_full]['file_names'] = [ff]
prt_files[new_name_full]['root'] = root
prt_files[new_name_full]['new_name'] = new_name
return prt_files
def is_integer(char):
try:
int(char)
except ValueError:
return False
return True
if __name__ == '__main__':
files = find_prt_files(COMPONENT_DIR)
for key, value in files.iteritems():
print 'In dir: {0:35} {1:20} --> {2}'.format(value['root'], value['new_name'], value['file_names'])
ipt = raw_input('found {0} prt files with integer extension, would you like to rename these y/n [n]?'.format(len(files.keys())))
print '"{0}"'.format(ipt)
if not ipt in ['y', 'Y']:
print 'Will not rename files...'
sys.exit(0)
for key, value in files.iteritems():
if os.path.isfile(key):
print 'Found file name without integer extension "{0}" in {1}, removing...'.format(value['new_name'], value['root'])
os.remove(key)
max_value = -1
the_winner = ''
for prt_file in value['file_names']:
ext_value = int(prt_file.split('.')[-1])
if ext_value > max_value:
the_winner = prt_file
max_value = ext_value
print 'We have a winner "{0}" from {1}'.format(the_winner, value['file_names'])
os.rename(os.path.join(value['root'], the_winner), key)
print 'Changed (full) name to {0}'.format(key)
for to_remove in value['file_names']:
full_name = os.path.join(value['root'], to_remove)
if os.path.isfile(full_name):
os.remove(full_name)
print 'Removed {0}'.format(full_name)
else:
print 'Does not exist any more {0}'.format(full_name)
print 'Done, files have been renamed!'
|
def reverseList(l):
l.reverse()
for i in l:
if type(i) == list:
reverseList(i)
return l
m = eval(input("Enter a list"))
print(reverseList(m))
|
h=int(input("Cuantos hombres estan inscritos"))
m=int(input("Cuantas mujeres hay inscritas"))
total=m+h
ph=(h*100)/total
pm=(m*100)/total
print("El total de alumnos inscritos son ",total)
print("EL porcenaje de hombre es de %.1f"%ph,"%")
print("EL porcenaje de mujeres es de %.1f"%pm,"%")
|
from chromosome import Chromosome
from queue import PriorityQueue
import random
import math
class Population:
# Initializer for a population of different backpack
# configurations (Chromosomes)
def __init__(self, n):
# Desired population size is inputted by the user
self.size = n
self.population = []
# The desired number of Chromosomes are then generated randomly and
# added to the list used to store the population of Chromosomes
for i in range(n):
newChromosome = Chromosome([random.randint(0,1) for i in range(7)])
self.population.append(newChromosome)
# A getter function for the size of the population
def getSize(self):
return self.size
# Prints out the specifications of the current population, including
# the weight, priority and fitness values for each Chromosome in the
# population as well as their gene configuration
def printPop(self):
for i in self.population:
i.printChromosome()
# A getter function for the fittest Chromosome configuration
# in the current population.
def getFittestChromosome(self):
# Sort the population to make sure the Chromosome at
# the front is the fittest
self.population.sort()
# Return the fittest Chromosome
return self.population[0]
# Culls the population
def cull(self):
# Sorts the population in order from highest
# fitness to lowest fitness
self.population.sort()
# Cull the population by 50%, making the remaining the
# population of parents of the new generation
parents = self.population[:len(self.population)//2]
# Initialize an empty list that will hold the children
# from each parent pair
children = []
# If there is only one parent left, make the population this
# parent as no more culling or crossover can be done. Return
# true as the population can't be culled anymore
if (len(parents) == 1):
self.population = parents
self.size = len(self.population)
return True
# While there are enough pairs to perform crossover,
# find too parents, use the reproduction function to
# get the list of their two children following crossover
# and then call the mutation function on each, appending
# the resulting child to the list of children
while (len(parents) > 1):
p1 = parents.pop(0)
p2 = parents.pop(0)
offspring = Chromosome.reproduce(p1, p2)
for i in offspring:
i.mutation()
children.append(i)
# If there is a parent left, call the mutation function on
# it and then append it to the list of children
if (len(parents) == 1):
child = parents.pop(0)
child.mutation()
children.append(child)
# Make the population equal to the new generation
# and update the length respectively
self.population = children
self.length = len(self.population)
# Return false as there is still more culling to be done
return False
|
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101) #to get same random number
df = pd.DataFrame(randn(5,4),['A','B', 'C','D','E'],['W','X','Y','Z'])
print(df)
print(df['W']) #Indexing DataFrame
print(type(df['W']))# type of Series
print(df.W) #avoid this but it work
print(df[['W', 'Z']])# get Sub DataFrame
df['NEW'] = df['W'] + df['Z'] #creating new col in DataFrame using arithmetic operation
print(df)
#removing col from DataFrame
df_drop_copy = df.drop('NEW',axis=1)#it remove from and made copy but wont change on original DataFrame axis=1 is important
print(df)
print(df_drop_copy)
df.drop('NEW',axis=1, inplace=True)#permanently remove from DataFrame
print(df)
#to remove row use axis=0 which is default and for col axis=1
print(df.drop('E'))
print(df)
print(df.shape)#return tuple which is row,col value
#SELECTING ROWS
print(df.loc['A'])#retrun row series
print(df.iloc[2])
print(df.loc['B','Y'])
print(df.loc[['A','B'],['W','X']])
|
#!/usr/bin/python2.7
'''
------# ! / usr /bin/env python
'''
#Validate valid order or non-order(reject) & Identify message type
import time
from six.moves import input
import os
clear = lambda: os.system('clear')
from threading import Timer
#Figure out how to make this do various things after time, not just print.
timeout = 3
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
prompt = "You have %d seconds to choose the correct answer...\n" % timeout
#answer = input(prompt)
answer = input(prompt)
#input_InFIXMsg = raw_input("Enter FIX Message: ")
t.cancel()
'''
input_TryAgain = 'n'
StopRun = 'no'
while StopRun != 'yes':
#Prompt User for FIX message
input_InFIXMsg = raw_input("Enter FIX Message: ")
#Validate message
while input_InFIXMsg not in ['35=D', '35=8']:
clear()
print("ERROR: **Invalid message type**")
print('')
input_TryAgain = raw_input ("Enter Again?\n[y/n] ")
if input_TryAgain == ('y'):
StopRun = ('no')
print('Looping...')
time.sleep(1)
clear()
break
if input_TryAgain == ('n'): #This logic works when valid FIX message; because default TryAgainset above to no?
StopRun = ('yes')
break
print("\n"*100)
print('FIX Engine validator now OFFLINE!')
'''
#End Program
|
#Sorteo para 5 personas, hay 3 premios
#OJO: una persona no puede ganar dos veces
from random import randint
pipol = ["Pepito", "Shitz", "Luis", "RoDi", "Filomeno"]
for sorteo in range(3):
ganador = pipol[randint(0,len(pipol)-1)]
print("Ganador", sorteo + 1,":", ganador)
pipol.remove(ganador)
|
""" 02 - Utilizando estruturas de repetição com variável de controle,
faça um programa que receba uma string com uma frase informada pelo usuário e
onte quantas vezes aparece as vogais a,e,i,o,u e mostre na tela,
depois mostre na tela essa mesma frase sem nenhuma vogal.
"""
from unidecode import unidecode #FUNÇÃO RESPONSÁVEL POR REMOVER OS ACENTOS DAS VOGAIS
def d(): #FUNÇÃO CRIADA PARA CHAMAR UMA DECORAÇÃO DE TEXTO SIMPLES.
print('-=-'*20)
#INPUT PARA RECEBER A FRASE DO USUÁRIO.
frase = str(input('''Digite uma frase qualquer
--> : ''')).upper()#TRANSFORMA A FRASE EM MAIUSCULO
frase = unidecode(frase)#AQUI REMOVE OS ACENTOS
vogais = 'AEIOU' #VARIÁVEL PARA ARMAZENAR AS VOGAIS
lista_de_vogais = list() #LISTA PARA ARMAZENAR AS VOGAIS RETIRADAS DO INPUT
#VARIÁVEIS ABAIXO SERVEM PARA CONTAGEM DAS LETRAS.
a = 0
e = 0
i = 0
o = 0
u = 0
#NESSE for A ESTRUTURA IRÁ VERIFICAR CADA LETRA DA FRASE A PROCURA DE VOGAIS...
for v in frase:
#SE A LETRA EM QUE O for ESTIVER FOR UM "A" ELEL IRÁ CONTAR MAIS UM NA VARIÁVEL a. E ASSIM POR DIANTE...
if v == 'A':
a+=1
if v == 'E':
e+=1
if v == 'I':
i+=1
if v == 'O':
o+=1
if v == 'U':
u+=1
# NESTE for A ESTRUTURA IRÁ PERCORRER A FRASE RECEBIDA PELO INPUT.
for r in frase:
#SE A LETRA QUE ESTIVER SENDO PECORRIDA ESTIVER NA VARIÁVEL DAS VOGAIS...
if r in vogais:
#E SE ESSA LETRA NÃO ESTIVER NA LISTA DE VOGAIS... A FUNÇÃO .append IRÁ ADICIONAR À MESMA.
if r not in lista_de_vogais: #ESTA CONDIÇÃO SERVE PARA NÃO SE REPETIR VOGAIS NA LISTA DE VOGAIS ENCONTRADAS NA FRASE.
lista_de_vogais.append(r)
#NESTE for A ESTRUTURA IRÁ PERCORRER A VARIÁVEL VOGAIS...
for p in vogais:
frase = frase.replace(p, '') #A CADA VOGAL PECORRIDA A FUNÇÃO .replace IRÁ SUBSTITUIR A LETRA NA FRASA DO USUÁRIO POR UMA STR VAZIA.
d()
print('''As vogais nessa frase foram:
--> {}'''.format(sorted(lista_de_vogais))) #NESTE print, A FUNÇÃO sorted ORDENA AS VOGAIS ENCONTRADAS NA FRASE EM ORDEM ALFABÉTICA.
d()
#AQUI NESSE PRINT ABAIXO, SERVE PARA INFORMAR QUANTAS LETRAS DE CADA VOGAL FORAM ENCONTRADAS NA FRASE
print('''Foram {} letras "A",
{} letras "E",
{} letras "I",
{} letras "O",
e {} letras "U"'''.format(a,e,i,o,u))
d()
print('''A frsae sem as vogais fica assim:
--> {}'''.format(frase))
d()
|
import random
def determine(num, guess):
cowbull = [0, 0]
#num = str(num)
#guess = str(guess)
for i in range(4):
if num[i] == guess[i]:
cowbull[0] += 1 #cow++
else:
for k in range(4):
if guess[i] == num[k] and k != i:
cowbull[1] += 1 #bull++
#break
return cowbull
if __name__ == '__main__':
num = random.randrange(1000, 9999)
print("Cows and Bulls")
print("--------------")
print("Instructions: \n\nEnter a 4 digit number. "
"If the number guessed has x amount of correct \n"
"digits in the correct place, then you will have "
"x cows. If the number guessed has y amount of \n"
"correct digits in the wrong place, then you will "
"y bulls. A cow cannot count as a bull, so if the \n"
"number is 1211, and you guess 1333, you will "
"recieve 1 cow, 0 bulls.\n")
print("Random 4 digit number has been generated.")
print(num)
numGuess = 0
guess = raw_input("Guess the number: ")
if str(guess) == "exit":
print("You didn't even try. I am thankful I am a computer and not a disgraceful chimp...")
exit()
cowbull = [0, 0]
numGuess = 1
while str(guess) != str(num):
if str(guess) == "exit":
print("You are a failure and it took you " + str(numGuess) + " guesses to figure it out.")
print("The number was " + str(num))
exit()
while len(str(guess)) != 4:
guess = raw_input("Invalid number. PLease enter a valid number: ")
cowbull = determine(str(num), str(guess))
print(str(cowbull[0]) + " cows, " + str(cowbull[1]) + " bulls.")
guess = raw_input("Guess the number: ")
numGuess += 1
print("4 cows. It only took " + str(numGuess) + " guesses.")
|
for i in range(10):
if i % 2 == 0:
print("Aren't people who use tabs instead of spaces utterly loathsome?")
if i % 2 == 1:
print("I'd hate to be the sucker who has to fix this file's whitespace.")
#In some spots I've used 8 spaces, and in other spots I've used a tab
#If we want to change from tabs to spaces. . .
#Type :%s/\t/ /gc
#If we want to change from spaces to tabs. . .
#Type :%s/ \{8}/\t/gc
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 11:36:26 2020
@author: Administrator
"""
length=float(input("Enter the length of Rectangle"))
breadth=float(input("Enter the breadth of Rectangle"))
area_of_rectangle=length*breadth
if length>breadth:
print("the area of rectangle is: ",area_of_rectangle)
else :
print("U ENTERED WRONHG IN PUT BREDTH IS GREATER THNAN LENGTH SO IT IS NOT POSSIBLE")
|
from random import randint
class Gladiator:
def __init__(self, health, rage, damage_low, damage_high, name):
""" (int, int, int, int, str, int) -> Gladiator
Represents a Gladiator with the health, rage, the lowest
damage possible, and the highest damage possible"""
self.health = health
self.rage = rage
self.damage_low = damage_low
self.damage_high = damage_high
self.name = name
def __str__(self):
""" (Gladiator) -> (Gladiator)
Returns a string with the format
health, rage, damage_low, damage_high
>>> goku = Gladiator(100, 0, 5, 20)
>>> print(goku)
>>> Health: 100, Rage: 0, Damage_low: 5, Damage_high 20
"""
return "{} || Health: {}, Rage: {}, Damage_low: {}, Damage_high: {}".format(
self.name, self.health, self.rage, self.damage_low,
self.damage_high)
def attack(self, other_g):
""" Gladiator, Gladiator -> Gladiator, Gladiator
"""
hit = randint(self.damage_low, self.damage_high)
if randint(1, 100) <= self.rage:
other_g.health = other_g.health - (hit * 2)
self.rage = 0
else:
self.rage += 15
other_g.health = other_g.health - hit
def heal(self):
''' Gladiator -> Gladiator
Function will heal the the gladiator by taking 10 rage
to heal for 5 and the gladiator cannont heal over 100
'''
if self.rage >= 10:
self.health = min(100, self.health + 5)
self.rage = max(0, self.rage - 10)
def is_dead(self):
''' Gladiator _> bool
Function will return True iff has no health
left
'''
if self.health <= 0:
return True
else:
return False
def rage_ing_up(self):
''' Gladiator -> Gladiator
Function will add 20 to the rage if the gladiator
chooses to pass
'''
if self.rage <= 100:
self.rage = min(100, self.rage + 20)
return Gladiator
def __repr__(self):
return 'Gladiator({}, {}, {}, {})'.format(
repr(self.health),
repr(self.rage), repr(self.damage_low), repr(self.damage_high))
def haboken(self, opponent):
''' Gladiator, Gladiator ->
Function will take away hp from the defender from a range of 50 to 100
'''
fire = randint(40, 60)
hit = randint(self.damage_low, self.damage_high)
if self.rage >= 45:
opponent.health = opponent.health - fire
self.rage = 0
else:
self.rage += 15
opponent.health = opponent.health - hit
def dragon_kick(self, other_glad):
''' Gladiator, Gladiator ->
New move an attacker can do against a defender
The move can make any type of damage from the range of
25 - 40 and requires atleast 40 rage
'''
hit = randint(self.damage_low, self.damage_high)
kick = randint(25, 40)
if self.rage >= 30:
other_glad.health = other_glad.health - kick
self.rage = 0
else:
other_glad.health = other_glad.health - hit
self.rage += 15
class Gameplay:
''' class used to generate multiple characters for a game '''
def __init__(self, gladiators):
''' [Gladiator] '''
self.gladiators = gladiators
def is_fighter(self, fighter_name):
''' returns true iff the fighter_name matches one of the fighters '''
return fighter_name.lower() in [
fighter.name.lower() for fighter in self.gladiators
]
def get_fighter(self, fighter_name):
for fighter in self.gladiators:
if fighter.name.lower() == fighter_name.lower():
return fighter
|
#Using ordered list of items, by starting the search at halfway, can discard greater/smaller set of values if item not found using pivot.
#Keep track of first and last points of the list to find mid point of list
#Divide and conqueror implementation
def binary_search(ordered_list, item):
first = 0
last = len(ordered_list) - 1
found = False
while first <= last and not found:
mid = (first+last)//2
if ordered_list[mid] == item:
return True
else:
if ordered_list[mid] < item:
first = mid + 1
else:
last = mid - 1
return found
#Recursive implementation
def recursive_binary_search(ordered_list, item):
if len(ordered_list) == 0:
return False
else:
mid = len(ordered_list) // 2
if ordered_list[mid] == item:
return True
else:
if ordered_list[mid] < item:
return recursive_binary_search(ordered_list[mid+1:], item)
else:
return recursive_binary_search(ordered_list[:mid], item)
test_list = [1,2,3,4,5,6,7,8,9,10,15,16,17,18]
print(binary_search(test_list, 12))
print(recursive_binary_search(test_list, 5))
|
class HashTable:
def __init__(self):
self.size = 11 #arbitrary but use prime number to have easier time resolving collisions
self.keys = [None] * self.size #initialise list of keys of length size and using None values
self.values = [None] * self.size #initialise list of values corresponding to keys of length size and using None values
#simple remainder hash function
def hash_function(self, key, size):
return key & size
#open addressing using linear probing technique with offset +1
def rehash(self, oldhash, size):
return (oldhash + 1) % size
def put(self, key, value):
hashvalue = self.hash_function(key, len(self.keys))
if self.keys[hashvalue] == None:
self.keys[hashvalue] = key
self.values[hashvalue] = value
else:
if self.keys[hashvalue] == key:
self.values[hashvalue] = value #if key already exists in table, replace old data with new data
else:
next_slot = self.rehash(hashvalue, len(self.keys))
while self.keys[next_slot] is not None and self.keys[next_slot] != key:
next_slot = self.rehash(next_slot, len(self.keys))
if self.keys[next_slot] == None:
self.keys[next_slot] = key
self.values[next_slot] = value
else:
self.values[next_slot] = value #replace old data with new data
def get(self, key):
start_slot = self.hash_function(key, len(self.keys))
value = None
stop = False
found = False
pos = start_slot
while self.values[pos] is not None and not found and not stop:
if self.keys[pos] == key:
found = True
value = self.values[pos]
else:
pos = self.rehash(pos, len(self.keys))
if pos == start_slot:
stop = True
return value
#overloading methods to allow access using []
def __getitem__(self, key):
return self.get(key)
def __putitem__(self, key, value):
self.put(key, value)
#Time complexity:
#Average case: search = O(1)
# insert = O(1)
# delete = O(1)
#Worst case: search = O(n)
# insert = O(n)
# delete = O(n)
#
#Space complexity:
#Worst case: O(n)
|
from random import randint
name = raw_input('enter your name:')
try:
f = open('game.txt','r')
except:
f = file('game.txt','w')
f = open('game.txt','w')
f.write('0 0 0')
f = open('game.txt','r')
#score = f.read().split()
#game_times = int(score[0])
#min_times = int(score[1])
#total_times = int(score[2])
lines = f.readlines()
f.close()
scores = {}
for l in lines:
s = l.split()
scores[s[0]] = s[1:]
score = scores.get(name)
print(score)
if score is None:
score = [0,0,0]
game_times = int(score[0])
min_times = int(score[1])
total_times = int(score[2])
if game_times > 0:
avg_times = float(total_times) / game_times
else:
avg_times = 0
print 'You have Played %d times,guessed the answer use %d time for the least times,%d times is average'% (game_times, min_times, avg_times)
num = randint(1,100)
times = 0
print 'Guess what I think?'
bingo = False
while bingo == False:
times +=1
answer = input()
if answer < num:
print 'too small!'
if answer > num:
print 'too big!'
if answer == num:
print 'Bingo!'
bingo = True
if game_times == 0 or times < min_times:
min_times = times
total_times += times
game_times += 1
scores[name] = [str(game_times),str(min_times),str(total_times)]
result = ''
for n in scores:
print(n)
line = n + ' ' + ' '.join(scores[n])+'\n'
result += line
f = open('game.txt', 'w')
f.write(result)
f.close()
|
import json
with open('config.json') as json_data_file:
data = json.load(json_data_file)
#Gets compass bearing
def getCompassBearing():
destination = raw_input('destination = ')
return destination
#Returns the offset in between two cardinal points
def getDifference (cardinal1, cardinal2):
difference = raw_input('difference = ')
return int(difference)
#Receives an angle and returns the cardinal point
def compassBearing(angle):
for key, value in data['compass_rose'].iteritems():
if angle >= value['min'] and angle <= value['max']:
return key
|
prenotazioni=[]
lettera_sì=[]
lettera_no=[]
while True:
dati_pren=input("Scrivi nome e cognome del partecipante: (Scrivi STOP per interrompere la lista) ")
if dati_pren=="STOP":
break
else:
prenotazioni.append(dati_pren)
richesta_lettera=input("Il partecipante deve ricevere una lettera di conferma? ")
if richesta_lettera=="Sì":
lettera_sì.append(dati_pren)
elif richesta_lettera=="No":
lettera_no.append(dati_pren)
print("I partecipanti che devono ricevere una lettera di conferma sono:", lettera_sì)
|
#! /usr/bin/env python3
"""--- Advent of Code Day 22: Crab Combat ---"""
from typing import List, Deque, Tuple
from collections import deque
from itertools import islice
FILENAME = "day_22.txt"
def calculate_score(cards: Deque[int]) -> int:
score = 0
for i, n in enumerate(reversed(cards), 1):
score += i * n
return score
def part1(inp: List[str]) -> int:
player_1, player_2 = inp
player_1 = deque([int(x) for x in player_1.split('\n')[1:]])
player_2 = deque([int(x) for x in player_2.split('\n')[1:]])
while player_1 and player_2:
card_1 = player_1.popleft()
card_2 = player_2.popleft()
if card_1 > card_2:
player_1.append(card_1)
player_1.append(card_2)
else:
player_2.append(card_2)
player_2.append(card_1)
if player_1:
return calculate_score(player_1)
else:
return calculate_score(player_2)
def get_round_hash(player_1: Deque[int], player_2: Deque[int]) -> str:
hash = "p1"
for card in player_1:
hash += ','
hash += str(card)
hash += "p2"
for card in player_2:
hash += ','
hash += str(card)
return hash
def recursive_combat(player_1: Deque[int], player_2: Deque[int]) -> Tuple[Deque[int], ...]:
history = set()
player_1, player_2 = deque(player_1), deque(player_2)
while player_1 and player_2:
# Hashes the current round's cards and checks if the exact same round
# has been played before
curr_hash = get_round_hash(player_1, player_2)
if curr_hash in history:
return player_1, deque()
history.add(curr_hash)
card_1 = player_1.popleft()
card_2 = player_2.popleft()
# if both player hands have at least as many cards as most recent card drawn
# enter recursive combat
if len(player_1) >= card_1 and len(player_2) >= card_2:
tmp_1, tmp_2 = recursive_combat(islice(player_1, card_1), islice(player_2, card_2))
if tmp_1:
player_1.append(card_1)
player_1.append(card_2)
elif tmp_2:
player_2.append(card_2)
player_2.append(card_1)
# else regular rules apply
else:
if card_1 > card_2:
player_1.append(card_1)
player_1.append(card_2)
else:
player_2.append(card_2)
player_2.append(card_1)
return player_1, player_2
def part2(inp: List[str]) -> int:
player_1, player_2 = inp
player_1 = [int(x) for x in player_1.split('\n')[1:]]
player_2 = [int(x) for x in player_2.split('\n')[1:]]
player_1, player_2 = recursive_combat(player_1, player_2)
if player_1:
return calculate_score(player_1)
else:
return calculate_score(player_2)
def main():
with open(FILENAME) as f:
inp = f.read().strip().split('\n\n')
print(f'Part 1: {part1(inp)}')
print(f'Part 2: {part2(inp)}')
if __name__ == "__main__":
main()
|
#lambda fn that multiply argument x with argument y
a=lambda x,y:x*y
print(a(4,2))
#fibonacci series to n
def fib(n):
b=[0,1]
any(map(lambda _:b.append(b[-1]+b[-2]),range(2,n)))
print(b)
n=int(input("Number"))
fib(n)
#multiply each number of list with a no
l=list(range(20))
l=list(map(lambda n:n*5,l))
print(l)
#nos divisible by 9
l=list(range(100))
l1=list(filter(lambda n:(n%9==0),l))
print(l1)
#count the even nos in the list
l=list(range(1,20))
count=len(list(filter(lambda n:(n%2==0) ,l)))
print(count)
|
import copy, itertools
def get_all_pairs(lst):
""" Get pairs of elements in the
list in all possible ways.
INPUT: list of N elements
OUTPUT: list of list of lists containing the pairs
Example: lst [0,1,2,3]
res = [ [[0,1], [2,3]],
[[0,2], [1,3]],
[[0,3], [1,2]]
"""
result =[]
L = len(lst)
if (L%2) :
raise NameError("Number of elements is odd. Aborting.")
if L < 2:
return [lst]
a = lst[0]
for i in range(1,L):
pair = [a,lst[i]]
rest = get_all_pairs(lst[1:i]+lst[i+1:])
for res in rest:
result.append(copy.deepcopy([pair] + res))
return result
# Join n lists of strings in all possible ways.
# Input: list of lists of strings with the same number of elements.
# Ouput: list of lists with all possible concatenations.
def permutator_minor(lst):
N = len(lst)
first=lst[0]
L = len(first)
P = L
for l in range(1,L):
P = l * P
Nt = P**(N-1)
result = [ first ]*Nt
i = 1
for element in lst[1:]:
perm = itertools.permutations(element)
pe = 0
for p in perm:
for j in range(int(Nt/P)):
index = i*pe + j%i + int(j/i) *P*i
result[index] =\
[a + b for a, b in zip(result[index], p)]
pe = pe + 1
i = i * P
return(result)
################################################################
####################### MARKUS FUNCTIONS ######################
################################################################
# Permutation function for deductive search, outer part
def permutator_minimus(trees,ploidy):
back_list=[]
for i_tree in range(0,int(ploidy/2)):
back_list.append([i_tree])
for i_trees in range(1, trees):
internal_list=[]
work_list=copy.deepcopy(back_list)
for i_allele in range(0,int(ploidy/2)):
for i_work in range(0,len(work_list)):
internal_list.append(work_list[i_work]+[i_allele])
back_list=internal_list
return (back_list)
# Permutation function for deductive search, inner part
def permutator_maximus(inlist):
ploidy_count=len(inlist[0])*2
tree_count=len(inlist)
pop_map=permutator_minimus(tree_count, ploidy_count)
## print(pop_map)
final_list=[]
for diploid_map in range (0,len(pop_map)):
work_copy=copy.deepcopy(inlist)
temp_list=[]
for diploid in range (0,len(pop_map[diploid_map])):
temp_list.append(work_copy[diploid].pop(pop_map[diploid_map][diploid]))
## print(temp_list)
final_list.append([work_copy, temp_list])
if len(final_list[0][0][0])is 1:
print(" Deduction to diploid successfull.")
final_list=final_list[0:int((len(final_list)/2))]
## print ("List length:", len(final_list),"\nFinal List:\n",final_list)
return (final_list)
|
print("The area of CIRCLE is :",3.14*float(input())**2)
|
class F:
def __init__(self):
self.item = 0
G = F()
l = [1, 2, 3, G, 'h']
l.remove(G)
print(l)
|
import random
class RandomizedSet(object):
def __init__(self):
self.dic={}
self.nums=[]
def insert(self, val):
if val not in self.dic:
self.dic[val]=len(self.nums)
self.nums.append(val)
return True
return False
def remove(self, val):
if val in self.dic:
idx=self.dic[val]
self.dic[self.nums[-1]]=idx
self.nums[idx]=self.nums[-1]
del self.dic[val]
self.nums.pop()
return True
return False
def getRandom(self):
return random.choice(self.nums)
|
def DisplayName(_name):
print(f"Votre nom est {_name}")
def DisplayFirstName(_firstname):
print(f"Votre nom est {_firstname}")
def DisplayFullName(_name,_firstname):
print(f"Vous vous appelez {_firstname} {_name}") if _name != "Bakashika" and _firstname !="Jessie" else print(f"Bonjour votre majesté {_firstname} {_name} ")
name = input("Quel est ton nom de famille? \t")
firstname = input("Quel est ton prénom? \t")
DisplayName(name)
DisplayFirstName(firstname)
DisplayFullName(name, firstname)
|
person_count = int(input("Please enter the number of people: "))
cake_count = int(input("Please enter the number of cake: "))
matrix = []
for i in range(0, person_count):
sub_matrix = []
str_row = input('Please enter row %d: ' % i)
str_row_item = str_row.split(' ')
for item in str_row_item:
sub_matrix.append(float(item))
matrix.append(sub_matrix)
print('Your input: ')
print(matrix)
col_sum = []
for i in range(0, cake_count):
col_sum.append(0)
for row in matrix:
for i, element in enumerate(row):
col_sum[i] += element
for i, row in enumerate(matrix):
for j, element in enumerate(row):
if col_sum[j] == 0:
matrix[i][j] = -1
else:
matrix[i][j] = matrix[i][j] / col_sum[j]
print('plan:')
print(matrix)
|
import threading
class CoreNodeList:
def __init__(self):
self.lock = threading.Lock()
self.list = set()
def add(self,peer):
"""
Coreノードをリストに追加
"""
with self.lock:
self.list.add((peer))
print('Current Core List: ', self.list)
def remove(self, peer):
"""
離脱したと判断されるCoreノードをリストから削除
"""
with self.lock:
if peer in self.list:
print('Removing peer: ',peer)
self.list.remove(peer)
print('Current Core list: ', self.list)
def overwrite(self, new_list):
"""
複数のpeerの接続状況確認を行ったあとで一括の上書き処理をしたいような場合
"""
with self.lock:
print('core node list will be going to overwrite')
self.list = new_list
print('Current Core list: ',self.list)
def get_c_node_info(self):
"""
リストのトップにあるpeerを返却
"""
return list(self.list)[0]
def get_list(self):
"""
現在接続状況にあるpeerの一覧を返す
"""
return self.list
|
values = [[10000, 500], [9000, 600], [5000, 1000], [3000, 1200], [0, 1500]]
i = float(input("Enter an interest rate "))
def prv(ar, r, n):
return ar * ((1-(1+r)**-n)/r)
def pv(fv, r, n):
return fv / ((1+r) ** n)
def start(values, r):
output = []
num = 0
while num < len(values):
output.append(prv(values[num][1], r, 10) + pv(values[num][0], r, 10))
print("The total present value for future value of", values[num][0], "and annual revenue of ",
values[num][1], "for 10 years at", str(i*100) + "%", "interest is $", output[num])
num += 1
while i <= 0:
i = float(input("Please enter a valid interest rate: "))
else:
start(values, i)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Auteur(s) : Dylan DE MIRANDA ([email protected]) & Alexy DA CRUZ ([email protected])
# Version : 0.1
# Date : 07/01/2021
# Thème du script : Losange vide : création d'un losange vide affiché à l'écran.
def auRevoir():
"""
affiche 3 sauts de ligne et Fin du programme
Entrées : aucune
Sortie : aucune
"""
print("\n\n\nAu revoir\n\nFin du programme")
def losangeVide(N, motif):
"""
dessine un losange vide avec un certain motif pour les contours
Entrées :
N : la hauteur du losange (le nombre de lignes)
motif : le caractère de dessin pour les contours
Sortie :
Affichage du losange vide
Exemple :
losangeVide(5, "*")
dessine le losange ci-dessous
*
* *
* *
* *
* *
* *
* *
* *
*
""" # on divise la hauteur par 2 pour avoir la hauteur d'un cote seulement (partie haute ou partie basse) soit deux triangles
losange = [] # init tableau dans lequel se trouvera le losange
for i in reversed(range(1, N)): # boucle partant de N à 1
losange.append(' '*i + motif) # on ajoute le string généré au tableau losange
losange.append(motif) # ligne du millieu
for i in range(0, len(losange)): # boucle allant de 0 à la taille de la triangle haut du losange
if (i > 0): # pour n'afficher que un motif pour la première et dernière ligne du losange
spaces = (' '*(i))*2 # générer les espaces necessaires entre les motifs pour qu'il soit vide
losange[i] = losange[i] + spaces[:-1] + motif # on modifie la ligne pour faire la partie droite du losange et ajouter entre les deux motifs le vide
print(losange[i]) # on affiche la ligne
# on genere le triangle bas pour compléter le losange
for i in reversed(range(0, len(losange)-1)): # boucle partant de 0 à N
print(losange[i]) # on affiche la ligne
################################################
########## PROGRAMME PRINCIPAL ################
################################################
# L'utilisateur donne la hauteur
N = int(input("Quelle hauteur pour le losange ? "))
# L'utilisateur donne le motif pour les contours du losange
M = str(input("Quel motif pour le losange ? "))
if (N) >= 2:
losangeVide(N, M) # On appelle la fonction avec les différents paramètres
auRevoir() # On appelle la fonction pour quitter le programme
|
from remaining_integer import RemainingInteger
def test_simple():
rem = RemainingInteger()
arr = [6, 1, 3, 3, 3, 6, 6]
assert rem.find_remaining_integer(arr) == 1
def test_middle_number():
rem = RemainingInteger()
arr = [1, 2, 3, 1, 3, 1, 3]
assert rem.find_remaining_integer(arr) == 2
def test_last_number():
rem = RemainingInteger()
arr = [50, 60, 4, 2, 4, 4, 2, 13, 50, 2, 13, 50, 13]
assert rem.find_remaining_integer(arr) == 60
|
import collections
def number_to_snapshot(number):
return ''.join(sorted(str(number)))
snapshot_to_count = collections.defaultdict(int)
n = 1
while True:
cube = n * n * n
snapshot = number_to_snapshot(cube)
snapshot_to_count[snapshot] += 1
if snapshot_to_count[snapshot] == 5:
target_snapshot = snapshot
break
n += 1
n = 1
while True:
cube = n * n * n
if number_to_snapshot(cube) == target_snapshot:
print cube
break
n += 1
|
# name = "bilal"
# age = '23'
# is_new = True
# print(name,age,is_new)
# name = input('What is your name? ')
# color = input('What is your favourite color? ')
# print(name + 'Likes' + color)
# birth_year = input('birth year: ')
# print(type(birth_year))
# age = 2019 - int(birth_year)
# print(age)
# print(type(age))
# pounds = input('what is your weight(lbs) ')
# kilo = int(pounds) * 0.45
# #print(type(kg))
# print(kilo)
# kilo = input('what is your weight(kilo): ' )
# pounds = int(kilo) * 2.20
# print(pounds)
# name = "my name is bilal"
# print(len(name))
# print(name.upper())
# print('Name' in name)
# print (name.find('bilal'))
# print (10 ** 2)
# print(20 % 3)
# x = 20
# x += 4
# print(x)
# x = 2.8
# print(round(x))
# print(abs(-2.9))
# is_hot = False
# is_cold = True
#
# if is_hot:
# print("It's a hot day")
# print("drink plenty of water")
# elif is_cold:
# print("it's a cold day")
# print("wear warm cloths")
#
# else:
# print("It's a lovely day")
# print("Enjoy your day")
# house_price = 1000000
# is_buyer_good = False
# if is_buyer_good:
# down_payment = 0.1 * house_price
# else:
# down_payment = 0.2 * house_price
# print(f"down_payment: ${down_payment}")
#name = input("what is your name? ")
# if len(name) < 4:
# print("character should more then three")
# elif len(name) > 15:
# print("your name is too long")
# else:
# print("you have a good name")
u_weight = input("what is your weight: ")
unit = input("(k)ilo or (P)ounds: ")
if unit.upper() == "pounds":
convert = int(u_weight) * 0.45
print(f"you are {convert} kilos")
else:
convert = int(u_weight) / 0.45
print(f"you are {convert} pounds")
|
line = raw_input().split(" ")
n1 = float(line[0])
n2 = float(line[1])
n3 = float(line[2])
n4 = float(line[3])
average = (n1*2 + n2*3 + n3*4 + n4)/10;
print "Media: %.1f" % average
if (average >= 7.0):
print "Aluno aprovado."
elif(average < 5.0):
print "Aluno reprovado."
elif (average >= 5 and average < 7):
print "Aluno em exame."
n5 = float(raw_input())
print "Nota do exame: %.1f" % n5
average = (average + n5)/2
if (average >= 5):
print "Aluno aprovado."
elif(average < 5):
print "Aluno reprovado."
print "Media final: %.1f" % average
|
even_numbers = 0
odd_numbers = 0
positive_numbers = 0
negative_numbers = 0
for i in range(0, 5):
number = float(raw_input())
if number % 2 == 0:
even_numbers += 1
else:
odd_numbers += 1
if number < 0:
negative_numbers += 1
if number > 0:
positive_numbers += 1
print "%d valor(es) par(es)" % even_numbers
print "%d valor(es) impar(es)" % odd_numbers
print "%d valor(es) positivo(s)" % positive_numbers
print "%d valor(es) negativo(s)" % negative_numbers
|
a = int(raw_input())
b = int(raw_input())
if (b < a):
b, a = a, b
odd_sum = 0
for i in range(a+1, b):
if i % 2 == 1:
odd_sum += i
print odd_sum
|
values = raw_input().split(" ")
v1 = float(values[0])
v2 = float(values[1])
v3 = float(values[2])
print "TRIANGULO: %.3f" % ((v1 * v3)/2)
print "CIRCULO: %.3f" % (3.14159 * v3**2)
print "TRAPEZIO: %.3f" % ((v1+v2)*v3/2)
print "QUADRADO: %.3f" % (v2**2)
print "RETANGULO: %.3f" % (v1*v2)
|
salary = float(raw_input())
if salary >= 0 and salary <= 400:
money_earned = (salary * .15)
new_salary = salary + money_earned
percentual_increase = 15
elif salary > 400 and salary <= 800:
money_earned = (salary * .12)
new_salary = salary + money_earned
percentual_increase = 12
elif salary > 800 and salary <= 1200:
money_earned = (salary * .1)
new_salary = salary + money_earned
percentual_increase = 10
elif salary > 1200 and salary <= 2000:
money_earned = (salary * .07)
new_salary = salary + money_earned
percentual_increase = 7
else:
money_earned = (salary * .04)
new_salary = salary + money_earned
percentual_increase = 4
print "Novo salario: %.2f" % new_salary
print "Reajuste ganho: %.2f" % money_earned
print "Em percentual: %d %%" % percentual_increase
|
# Random password generator
# atleast 8 characters,
# atleast 1 uppercase letters
# atleast 1 lowercase
# atleast 1 numeric number
# atleast 1 special characters
import random
upper_char_A = ["A","B","C","D","E","F","G","H"]
lower_char_a = ["a", "b", "c", "d", "e", "f", "g", "h"]
special_char = ["!", "@", "#", "$", "%", "&", "*", "^", "~"]
upper_char_I = ["I","J","K","L","M","N","O","P"]
lower_char_i = ["i", "j", "k", "l", "m", "n", "o", "p"]
random_upper_char = random.choice(upper_char_A)
random_lower_char = random.choice(lower_char_a)
random_special_char = random.choice(special_char)
random_numeric_char = random.randint(0,10)
random_upper_char1 = random.choice(upper_char_I)
random_lower_char1 = random.choice(lower_char_i)
# random_special_char1 = random.choice(special_char)
random_numeric_char1 = random.randint(0,10)
weak_password = random_upper_char + random_lower_char + random_special_char + str(random_numeric_char)
intermediate_password = weak_password + random_upper_char1 + random_lower_char1 + random_special_char + str(random_numeric_char1)
strong_password = str(random_numeric_char) + weak_password + intermediate_password + weak_password + random_upper_char + str(random_numeric_char)
print("1. Weak password")
print("2. Intermediate password")
print("3. Strong password")
while True:
choice = int(input("Choose the password type(1-3) :"))
if choice == 1:
name_choice = input("Want to Add your name in the password?yes/no : ")
if name_choice == "yes" or name_choice == "y":
ask_first_name = input("Enter your first name :")
ask_last_name = input("Enter the last name :")
print("Password Generated :", ask_first_name + weak_password + ask_last_name)
elif name_choice == "no" or name_choice == "n":
print("password Generated : ", weak_password)
else:
print("Please give answer in 'yes' or 'no'!!")
elif choice == 2:
name_choice = input("Want to Add your name in the password?yes/no : ")
if name_choice == "yes" or name_choice == "y":
ask_first_name = input("Enter your first name :")
ask_last_name = input("Enter the last name :")
print("Password Generated : ", ask_first_name + intermediate_password + ask_last_name)
elif name_choice == "no" or name_choice == "n":
print("Password Generated : ",intermediate_password)
else:
print("Please give answer in 'yes' or 'no'!!")
elif choice == 3:
name_choice = input("Want to Add your name in the password?yes/no : ")
if name_choice == "yes" or name_choice == "y":
ask_first_name = input("Enter your first name :")
ask_last_name = input("Enter the last name :")
print("Password Generated : ", ask_first_name + strong_password + ask_last_name)
elif name_choice == "no" or name_choice == "n":
print("Password Generated : ", strong_password)
else:
print("Please give answer in 'yes' or 'no'!!")
else:
print("Please Enter the Correct Choice!! ")
|
"""
Note generators
Copyright (C) 2012 Alfred Farrugia
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
class StaticIterator:
"""
A static value generator, returns the same value
"""
def __init__(self, value=1, id=''):
self.value = value
self.id = id
def __iter__(self):
return self
def next(self):
return self.value
class LoopingArray:
"""
A generator returning values from an array.
[value1, value2, value3, value4, ..... valuex]
^
loopindex
on next(), the loopindex is moved. By default the value is incremented
by 1, however this can be modified by adding values to the list
functioniterator (see below).
Example:
x = LoopingArray([1,2,3])
print x.next()
> 1
print x.next()
> 2
print x.next()
> 3
The parameter functioniterator can be used as a stepper function.
functioniterator
is a list of tuples (function,generator)
Example:
x = LoopingArray(
[1,2,3,4,5,6],
functioniterator=[('add', StaticIterator(value=2))]
)
This will loop through the array with a step of 2
x = LoopingArray(
[1,2,3,4,5,6],
functioniterator=[('add', LoopingArray([1,2]))]
)
This will loop through the array with a step of 1 and then a step of 2
The items in functioniterator list are evaluated in sequence
For example:
x = LoopingArray(
[1,2,3,4,5,6],
functioniterator=[
('add', StaticIterator(value=2)), ('dec', StaticIterator(value=1))
]
)
First the array index is incremented by 2 ('add', StaticIterator(value=2))
and then the index is decremented by 1 ('dec', StaticIterator(value=1))]).
Having a list of StaticIterator in functioniterator is useless however you
can create complex patterns when adding other generators such as
LoopingArray or LoopingIndexedArray.
"""
def __init__(self, arr,
functioniterator=[('add', StaticIterator(value=1))], id='',
debug=False):
self.arr = arr
self.index = 0
self.functioniterator = functioniterator
self.id = id
self.debug = debug
def __iter__(self):
return self
def next(self):
r = self.arr[int(self.index)]
if self.debug:
print('%s:%s' % (self.id, r))
for op, fn in self.functioniterator:
if op == 'add':
val = fn.next()
self.index = (self.index + val) % len(self.arr)
elif op == 'mult':
val = fn.next()
self.index = (self.index * val) % len(self.arr)
elif op == 'dec':
val = fn.next()
self.index = (self.index - val) % len(self.arr)
elif op == 'div':
val = fn.next()
self.index = (self.index / val) % len(self.arr)
return r
class LoopingIndexedArray:
"""
A LoopingIndexedArray returns items from an array.
values = [value1, value2, value3, value4, value5]
indexes = [index1, index2, index3, index4, index5]
^
loopindex
returns values[indexes[loopindex]]
on next(), the loopindex is moved. By default the value is incremented
by 1, however this can be modified by adding values to the list
functioniterator (see below).
Example:
x = LoopingIndexedArray([1,2,3,4,5],[0,1,0,2,0,3])
x.next()
> 1
x.next()
> 2
x.next()
> 1
x.next()
3
x.next()
> 1
if any of the values in indexes is an array, multiple notes are played
from the arr index
x = LoopingIndexedArray([[1],[2],[3],[4],[5]],[[0,1],1,0,2,0,3])
print x.next()
print x.next()
print x.next()
print x.next()
print x.next()
x.next()
> [1, 2]
x.next()
> [2]
x.next()
> [1]
x.next()
> [3]
x.next()
> [1]
Refer to functioniterator documentation at class LoopingArray
"""
def __init__(self, arr, indexes,
functioniterator=[('add', StaticIterator(value=1))], id='',
debug=False):
self.arr = arr
self.indexes = indexes
self.functioniterator = functioniterator
self.id = id
self.index = 0
self.debug = debug
def __iter__(self):
return self
def next(self):
if isinstance(self.indexes[int(self.index) % len(self.indexes)], int):
r = self.arr[
self.indexes[
int(self.index) % len(self.indexes)
] % len(self.arr)
]
else:
r = []
for x in self.indexes[int(self.index) % len(self.indexes)]:
r = r + self.arr[x % len(self.arr)]
if self.debug:
print('%s:%s' % (self.id, r))
for op, fn in self.functioniterator:
if op == 'add':
val = fn.next()
self.index = (self.index + val) % len(self.indexes)
elif op == 'mult':
val = fn.next()
self.index = (self.index * val) % len(self.indexes)
elif op == 'dec':
val = fn.next()
self.index = (self.index - val) % len(self.indexes)
elif op == 'div':
val = fn.next()
self.index = (self.index / val) % len(self.indexes)
return r
class LoopingIncrementalIndexedArray:
"""
A LoopingIncrementalIndexedArray returns items from an array.
values = [value1, value2, value3, value4, value5]
indexes = [index1, index2, index3, index4, index5]
^
loopindex
noteindex=noteindex+indexes[loopindex]
returns values[noteindex]
on next(), the loopindex is moved. By default the value is incremented
by 1, however this can be modified by adding values to the list
functioniterator (see below).
Example:
x = LoopingIncrementalIndexedArray([1,2,3,4,5],[0,1,-1,2,0,3])
x.next()
> 1
x.next()
> 1
x.next()
> 2
x.next()
> 1
x.next()
> 3
x.next()
> 3
x.next()
> 1
Note: negative values will move the loopindex to the right
Refer to functioniterator documentation at class LoopingArray
"""
def __init__(self, arr, indexes,
functioniterator=[('add', StaticIterator(value=1))], id='',
debug=False):
self.arr = arr
self.indexes = indexes
self.index = 0
self.incindex = 0
self.functioniterator = functioniterator
self.id = id
self.debug = debug
def __iter__(self):
return self
def next(self):
r = self.arr[int(self.incindex) % len(self.arr)]
if self.debug:
print('%s:%s' % (self.id, r))
self.incindex += self.indexes[self.index % len(self.indexes)]
self.index += 1
return r
def add_track(midi, tempo, track, channel, time, startbeat,
beat=[], notes=[], velocities=[], length=0):
"""
Adds a midi track. Please use MidiGenerator instead
"""
midi.addTrackName(track, time, "Track %s" % track)
midi.addTempo(track, time, tempo)
beat_index = startbeat
while beat_index - startbeat < length:
beat_value, duration_value = beat.next()
for note in notes.next():
midi.addNote(
track,
channel,
note,
beat_index,
duration_value,
velocities.next()
)
beat_index += beat_value
|
a = [1,2]
# b = {a:1}
# # TypeError: unhashable type: 'list'
# print(b)
print(a.__hash__) # None
# print(hash(a))
'''
Traceback (most recent call last):
File "hashable_objects.py", line 7, in <module>
print(hash(a))
TypeError: unhashable type: 'list
'''
a = (1,2)
b = {a:1}
print(b)
print(a.__hash__) # None
print(hash(a))
from collections import Hashable
from abc import ABCMeta, ABC, abstractmethod
class HashableObject(Hashable, metaclass=ABCMeta):
def __init__(self):
pass
def __eq__(self, other):
return True if isinstance(other, self.__class__) and self.get_key() == other.get_key() else False
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash(self.get_key())
@abstractmethod
def get_key(self):
pass
class MyHashableClass(HashableObject):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def get_key(self):
return self.a, self.b
a1 = MyHashableClass(1,2,3)
a2 = MyHashableClass(4,5,6)
a3 = MyHashableClass(4,5,8)
print(a1 == a2)
print(a2 == a3)
a = {}
a[a1] = 1
print(a)
|
x = 0
while x < 10:
print('x is currently :', x)
x += 1
else:
print('All done!')
# Break continue and pass
x = 0
while x < 10:
print('x is currently :', x)
print('x is still less than 10 , adding 1 to x')
x += 1
if (x == 3):
print(' Hey x is equals 3!')
pass ## pass does nothing
break
else:
print(' continuing.....')
continue
|
#1
def fun(name,age):
print(f'{name}在{2018+100-age}年为100岁')
fun('xuzhiqian',17)
#2
def fun():
n = int(input("请输入整数"))
if n%2 == 0:
print('偶数')
elif n%2 ==1:
print('奇数')
else:
print('请输入整数')
fun()
#3
def fun(ls):
flag = 0
for i in ls:
if i=='':
flag = 0
else:
flag = 1
if flag:
print('没空')
else:
print('有空')
fun([1,2,''])
#3.2
def fun(ls):
while '' in ls:
print('有空')
break
fun([1,2])
#3.3
def fun(ls):
return all(ls)
print(fun([1,2,'']))
#4.1
def fun(ls):
return [x*x for x in ls]
x = fun([1,2,3])
print(x)
#4.2
def fun(ls):
return map(lambda x: x*x,ls)
x = list(fun([1,2,3]))
print(x)
#5
from functools import reduce
def fun(ls):
return reduce(lambda x,y: x+y,ls)
x = fun([1,2,3])
print(x)
#6
def fun(ls):
return [x**0.5 for x in ls]
x = fun([4,16,64])
print(x)
#7
def fun(lst,lst2):
st = set(lst)
st2 = set(lst2)
ls = []
for i in st:
for j in st2:
if i == j:
ls.append(j)
return ls
x = fun([4,16,64,1,64],[1,64,4])
print(x)
#8.1
def fun(a,b,c):
if a>b:
b = a
if b>c:
c = b
return c
x = fun(100,50,101)
print(x)
#8.2
def fun(a,b,c):
max = 0
if a>b:
max = a
else:
max = b
if c>max:
max = c
return max
x = fun(100,50,101)
print(x)
|
# -*- coding:utf-8 -*-
# &Author AnFany
# 计算自定义精度的任意正实数的算数平方根:直接法,二分法,牛顿迭代法,数对比值法(未实现),
import big_number_product as b_p # 大数乘法
import big_number_division as b_d # 大数除法
import big_number_sub_add as b_s_a # 大数加减法
class SQRT():
def __init__(self, number, decimal, sign='s', method='s_direct'):
"""
计算自定义精度的任意正实数的算数平方根:直接法,二分法,牛顿迭代法
:param number: 进行开平方的数, 整数或者小数均可,字符串或者非字符串均可
:param decimal: 需要控制的精度
:param sign: 默认为's','s':控制平方根的精度,获取小数点后第一个非0的数字开始计算,decimal位的准确的数字。
'p':使得输出的平方根的平方与number的误差绝对值不大于1e(-decimal)
:param method: 默认为's_direct','s_direct':直接法;'s_dichotomy':二分法;
's_newton':牛顿迭代法;
"""
self.n = str(number)
self.d = decimal
self.s = sign
self.m = method
self.add = 8 # 当利用二分法,牛顿迭代法,数对比值法,如果sign=‘s’,就是获取准确的平方根,需要将精度扩大
self.l = 0 # 对于0.0002,0.05这样的整数部分为0的,计算其小数点后面连续为0的个数,判断精度时需要用到
self.change = self.trans_number() # 数字变为标准格式缩小的倍数。在计算平方根位数的时候需要多算这几位
def trans_number(self):
"""
需要将数字变为小数点前面只有一位数字的数,并使得缩小的倍数是10的偶数次方
例如:11.22变为0.1122,缩小了100倍,11662.33变为1.166233缩小了10000倍,0.89,0.0028这样的值不进行转变
需要记录倍数的一半,最后需要对得到的结果进行放大处理
:return: 缩小的倍数的一半以及变化后的数字
"""
# 首选判断是不是小数
if '.' not in self.n:
length = len(self.n)
if length == 1:
self.n += '.0' # 为了后面比较大小更方便,添加上小数点
return 0
elif length % 2 == 0:
self.n = '0.%s' % self.n
return length // 2
else:
self.n = '%s.%s' % (self.n[0], self.n[1:])
return length // 2
else:
# 首先判断小数点的位置
d_index = self.n.index('.')
if d_index == 1:
# 对于0.0002,0.05这样的整数部分为0的,计算其小数点后面连续为0的个数
if self.n[0] == '0':
for s in self.n[2:]:
if s == '0':
self.l += 1
else:
break
return 0
self.n = self.n.replace('.', '')
if d_index % 2 == 0:
self.n = '0.%s' % self.n
else:
self.n = '%s.%s' % (self.n[0], self.n[1:])
return d_index // 2
def compare_number(self, p):
"""
比较用字符串表示的数字和转换后的开方的数的大小
:param p: 字符串,代表当前平方根的平方
:return: 前者小返回-1, 等于返回0,大于返回1
"""
# 首先判断字符串p中是否有小数点,没有的话添加上,因为比较大小不会影响结果
if '.' not in p:
p += '.0'
# 首先判断p中整数的部分
d_index = p.index('.') # 为1
# 因为self.n的整数部分只有一位
if d_index > 1:
return 1
else:
# 比较整数部分的大小
int_p = int(p[0])
int_n = int(self.n[0])
if int_p > int_n:
return 1
elif int_p < int_n:
return -1
else:
# 挨个数字比较小数部分
f_p, f_n = p[2:], self.n[2:]
length_p, length_n = len(f_p), len(f_n)
min_length = min(length_p, length_n)
for h in range(min_length):
int_f_p = int(f_p[h])
int_f_n = int(f_n[h])
if int_f_p > int_f_n:
return 1
elif int_f_p < int_f_n:
return -1
# 判断长度较大的剩余的数字是不是均为0
if length_p == length_n:
return 0
elif length_p > length_n:
if list(set(f_p[min_length:])) == ['0']:
return 0
else:
return 1
else:
if list(set(f_n[min_length:])) == ['0']:
return 0
else:
return -1
def control_s(self, s_d, decimal):
"""
平方根小数点后面第一个非0的数字开始计数
:param s_d: 需要判断的对象,代表平方根
:param decimal: 数字个数的要求
:return: 不满足返回False,满足返回True
"""
# 首先判断字符串s_d中是否有小数点,没有的话添加上,不会影响结果
if '.' not in s_d:
s_d += '.0'
# 判断小数点的位置
d_index = s_d.index('.')
first_no_zero = 0 # 第一个非0的数是否出现的标识
count = 0 # 开始计数
for h in s_d[(1 + d_index):]: # 排除掉小数点
if h != '0':
first_no_zero = 1 # 第一个非0的数出现
count += 1
else:
if first_no_zero:
count += 1
if count >= decimal:
return True
else:
return False
def control_p(self, s_d, decimal):
"""
s_d的平方与转换后的开方的数之间的差值绝对值不大于1e(-decimal)
:param s_d: 需要判断的对象,代表平方根
:param decimal: 差的精度要求
:return: 不满足返回False,满足返回True
"""
# 首先计算平方
squre = b_p.big_product(s_d, s_d)
# 然后计算差值
sub = b_s_a.big_subtraction(squre, self.n)
# 如果是负数,去掉负号
if sub[0] == '-':
sub = sub[1:]
# 因为是比较大小
if '.' not in sub:
sub += '.0'
# 开始比较大小
d_index = sub.index('.')
if d_index > 1: # 因为1e(-decimal)整数部分只有一位1.0,0.1,0.01,0.001……等等
return False
elif d_index == 1:
if int(sub[0]) > 1:
return False
elif int(sub[0]) == 1:
if decimal != 0:
return False
else: # 和1.0比较大小
if list(set(sub[2:])) == ['0']:
return True
else:
return False
else:
if decimal == 0:
return True
# 考虑到需要开方的数,可能比较小,此时精度要在这个的基础上更小。
# 也就是对于0.0002,0.05这样的整数部分为0的,计算其小数点后面连续为0的个数
# 判断小数点后连续为0的个数
count_zero = 0 # 判断差值中小数点之后,连续为0的个数
for h in sub[2:]:
if h != '0': # 只要出现其他的数字,就判断连续为0的个数是否满足需求的精度
if count_zero >= self.l + decimal + self.change: # 需要加上开方的数原来自身的精度或者
return True
else:
return False
else: # 小数点出现后,只要为0就开始加1
count_zero += 1
def get_result(self, s_result, str_s):
"""
将算法得到的算数平方根,转换为最终的结果,一是扩大倍数,二是截取需要的长度
:param s_result: 待处理的算数平方根
:param str_s: 如果为‘p’:控制的是平方的精度,不对得到的平方根进行截取,如果为‘s’:需要对平方根进行截取
:return: 最终的结果
"""
# 编程便利性
if '.' not in s_result:
s_result += '.0'
d_index = s_result.index('.') # 获取小数点位置
s_result += '0' * (self.change + self.d) # 防止小数点往后移动时出现没有数字的情况
# 如果需要扩大倍数
if self.change:
s_result = s_result.replace('.', '')
if str_s == 's': # 需要对结果进行截取
if s_result[0] == '0':
last_result = s_result[d_index:(d_index + self.change)] \
+ '.' + s_result[(d_index + self.change):][:self.d] # 截取
else:
last_result = s_result[:(d_index + self.change)] \
+ '.' + s_result[(d_index + self.change):][:self.d] # 截取
else:
if s_result[0] == '0':
last_result = s_result[d_index:(d_index + self.change)] \
+ '.' + s_result[(d_index + self.change):]
else:
last_result = s_result[:(d_index + self.change)] \
+ '.' + s_result[(d_index + self.change):]
else:
# 需要判断整数部分是不是为0
if s_result[0] == '0':
# 需要从小数点后第一个不为0的数字,开始提取self.d个数字
last_result = s_result[:2]
count = 0
start = 0
d = s_result[2:]
while count < self.d and start < len(d) - 1:
last_result += d[start]
if d[start] != '0':
count += 1
else:
if count:
count += 1
start += 1
else:
# 直接提取小数点后self.d个数字
if str_s == 's':
last_result = s_result[:(self.d + 2)] # 算上前面的整数部分和小数点
else:
last_result = s_result
# 对于开方的数为完全平方数的情况,得到的结果后面肯定会有连续的0,为了结果的美观,去要去掉
for k in range(len(last_result) - 1, -1, -1):
if last_result[k] == '.':
return last_result[: k]
elif last_result[k] != '0':
return last_result[: (1 + k)]
def s_direct(self):
"""
利用直接法获得平方根,
:return: 字符串形式的算数平方根
"""
# 首先确定整数位上的数字
first_n = int(self.n[0])
if first_n == 9:
start_n = '3.'
elif 4 <= first_n < 9:
start_n = '2.'
elif 1 <= first_n < 4:
start_n = '1.'
else:
start_n = '0.'
# 判断当前解是否满足条件,保证正确性,此时多保留几位
while not eval('self.control_%s' % self.s)(start_n, self.l + self.d + self.change):
# 试错法获取下一个数字
for i in range(0, 11):
# 添加数字后
new_sqrt = start_n + str(i)
# 计算平方
product = b_p.big_product(new_sqrt, new_sqrt)
# 比较结果
compare_result = self.compare_number(product)
# 如果大于,说明上一个值是对的
if compare_result == 1:
start_n += str(i - 1)
break
elif compare_result == 0:
return self.get_result(new_sqrt, self.s)
# 添加1-9都小于,说明需要添加的就是数字9
if i == 10:
start_n += str(9)
return self.get_result(start_n, self.s)
# 利用二分法计算算数平方根
def s_dichotomy(self):
"""
利用二分法计算算数平方根
:return: 最终的结果
"""
min_num = '0' # 二分法开始的最小值
max_num = '4' # 二分法开始的最大值
middle_num = '2.' # 二分法开始的中间值
# 判断当前解是否满足条件,保证正确性,此时多保留几位
if self.s == 'p':
leave_count = self.d + self.l + self.change
elif self.s == 's':
leave_count = self.d + self.l + self.change + self.add
# 依然是根据精度判断
while not self.control_p(middle_num, leave_count):
# 注意因为中间值的精确度小的话,会导致每次的middle_num 不变,因此下面的精度要稍微大点
middle_num = str(b_d.big_division(b_s_a.big_addition(min_num, max_num), '2', leave_count * 3))
# 计算乘积
product = b_p.big_product(middle_num, middle_num)
# 判断大小
compare_result = self.compare_number(product)
if compare_result == 1:
# 大值变小
max_num = middle_num
elif compare_result == -1:
# 小值变大
min_num = middle_num
else:
return self.get_result(middle_num, self.s)
return self.get_result(middle_num, self.s)
# 利用牛顿迭代法计算算数平方根
def s_newton(self):
"""
利用牛顿迭代计算算数平方根
:return: 最终的结果
"""
start_num = '1'
# 判断当前解是否满足条件,保证正确性,此时多保留几位
if self.s == 'p':
leave_count = self.d + self.l + self.change
elif self.s == 's':
leave_count = self.d + self.l + self.change + self.add
# 依然是根据精度判断
while not self.control_p(start_num, leave_count):
# a = (a + (self.n/a)) /2
# 保留位数也要稍微大点
start_num = b_d.big_division(
str(b_s_a.big_addition(start_num,
str(b_d.big_division('%s' % self.n,
start_num, leave_count * 3)))), '2', leave_count * 3)
return self.get_result(start_num, self.s)
|
# code to build, compile and fit a convolutional neural network (CNN) model to the MNIST dataset of images of
# handwritten digits.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Run this cell first to import all required packages. Do not make any imports elsewhere in the notebook
import tensorflow as tf
from keras.layers import BatchNormalization
from keras.utils import to_categorical
from matplotlib.ticker import MaxNLocator
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.models import Sequential
'''The MNIST dataset consists of a training set of 60,000 handwritten digits with corresponding labels, and a test set
of 10,000 images. The images have been normalised and centred. The dataset is frequently used in machine learning
research, and has become a standard benchmark for image classification models.
Your goal is to construct a neural network that classifies images of handwritten digits into one of 10 classes.'''
# Run this cell to load the MNIST data
mnist_data = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist_data.load_data()
print('Train: X=%s, y=%s' % (train_images.shape, train_labels.shape))
print('Test: X=%s, y=%s' % (test_images.shape, test_labels.shape))
# plot the digits
y = train_labels
X = train_images
fig, ax = plt.subplots(2, 5)
for i, ax in enumerate(ax.flatten()):
im_idx = np.argwhere(y == i)[0]
plottable_image = np.reshape(X[im_idx], (28, 28))
ax.imshow(plottable_image, cmap='gray_r')
# pick a sample to plot
sample = 1
image = train_images[sample]
# plot the sample
fig = plt.figure
plt.imshow(image, cmap='gray')
plt.show()
# Complete the following function.
print(train_images.shape) # (60000,28, 28)--number of samples, height of image, width of image
# frequency chart
unique, counts = np.unique(y, return_counts=True)
plt.bar(unique, counts)
plt.xticks(unique)
plt.xlabel("Digits")
plt.ylabel("Quantity")
plt.title("Digits in MNIST 784 dataset")
plt.show()
def scale_mnist_data(xtrain, xtest, ytrain, ytest):
"""
Scales training and test set so that they have minimum and maximum values equal to 0 and 1 respectively (normalize).
and reshapes so that there is a single channel """
scaled_train_images = xtrain.reshape((xtrain.shape[0], 28, 28, 1))
scaled_test_images = xtest.reshape((xtest.shape[0], 28, 28, 1))
scaled_train_images, scaled_test_images = xtrain[..., np.newaxis] / 255.0, xtest[..., np.newaxis] / 255.0
# one hot encode target values
train_labels = to_categorical(ytrain)
test_labels = to_categorical(ytest)
return scaled_train_images, scaled_test_images, train_labels, test_labels
scaled_train_images, scaled_test_images, train_labels, test_labels = scale_mnist_data(train_images, test_images,
train_labels, test_labels)
# Input Layer expects data in the format of NHWC
# N = Number of samples
# H = Height of the Image
# W = Width of the Image
# C = Number of Channels
print(scaled_train_images.shape) # (60000, 28, 28, 1)
'''
Build the convolutional neural network model
Using the Sequential API, build your CNN model according to the following spec:
The model should use the input_shape in the function argument to set the input size in the first layer.
A 2D convolutional layer with a 3x3 kernel and 8 filters.
Use 'SAME' zero padding and ReLU activation functions.
Make sure to provide the input_shape keyword argument in this first layer.
A max pooling layer, with a 2x2 window, and default strides.
A flatten layer, which unrolls the input into a one-dimensional tensor.
Two dense hidden layers, each with 64 units and ReLU activation functions.
A dense output layer with 10 units and the softmax activation function.
In particular, your neural network should have six layers.'''
# need this code to avoid "failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED" error
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
# Currently, memory growth needs to be the same across GPUs
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
except RuntimeError as e:
# Memory growth must be set before GPUs have been initialized
print(e)
'''
#This model from the assignment is not as accurate as the model from machinelearningmaster.com
def get_model(input_shape):
model = Sequential(
[Conv2D(8, (3, 3), activation='relu', input_shape=input_shape, padding='SAME', name='Conv2D_layer_1'),
# default data_format='channels_last'
MaxPooling2D((2, 2), name='MaxPool_layer_2'),
Flatten(name='Flatten_layer_3'),
Dense(64, activation='relu', name='Dense_layer_4'),
Dense(64, activation='relu', name='Dense_layer_5'),
Dense(10, activation='softmax', name='Dense_layer_6')
])
return model
'''
# the assignment asks for the model above, but I want to compare my answers with machinelearningmastery.com
def get_model():
model = Sequential(
[Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1),
name='Conv2D_layer_1'),
# default data_format='channels_last'
MaxPooling2D((2, 2), name='MaxPool_layer_2'),
Flatten(name='Flatten_layer_3'),
Dense(100, activation='relu', kernel_initializer='he_uniform', name='Dense_layer_4'),
Dense(10, activation='softmax', name='Dense_layer_5')
])
return model
model = get_model()
print(model.summary()) # this is easier to read
# compile the model
# Optimizers in machine learning are used to tune the parameters of a neural network
# in order to minimize the cost function.Contrary to what many believe, the loss function is not the same thing as
# the cost function. While the loss function computes the distance of a single prediction from its actual value,
# the cost function is usually more general. Indeed, the cost function can be, for example, the sum of loss
# functions over the training set plus some regularization.
# Compile the model using the Adam optimiser (with default settings),
# the cross-entropy loss function and accuracy as the only metric."""
# SGD stochastic gradient descent Instead of computing the gradients over the entire dataset, it performs a
# parameter update for each example in the dataset. The problem of SGD is that the updates are frequent and with a
# high variance, so the objective function heavily fluctuates during training. Although this alows
# the function to jump to better local minima, it disadvantages the convergence in a specific local minima.
# a better solution would be Mini Batch Gradient Descent these gradient descent algorithms are not good for sparse data,
# subject to the choice of learning rate, and have a high possibility of getting stuck into a suboptimal local minima
# opt = SGD(lr=0.01, momentum=0.9)
# Adaptive optimizers on the other hand don't require a tuning of the learning rate
# value. They solve issues of gradient descents algorithms, by performing small updates for
# freq occuring features and large updates for the rarest ones
# ADAM is the best among adaptive optimizers in most cases, it is good with sparse data, and no
# need to focus on the learning rate.
opt = tf.keras.optimizers.Adam()
acc = tf.keras.metrics.Accuracy()
def compile_model(model):
model.compile(optimizer=opt,
loss='categorical_crossentropy',
metrics=['accuracy'])
compile_model(model)
# FIT THE MODEL TO THE TRAINING DATA############################
print(scaled_train_images.shape)
def train_model(scaled_train_images, train_labels, scaled_test_images, test_labels):
history = model.fit(scaled_train_images, train_labels, epochs=5, batch_size=256,
validation_data=(scaled_test_images, test_labels))
return history
history = train_model(scaled_train_images, train_labels, scaled_test_images, test_labels)
# Plot the learning curves
# We will now plot two graphs:
# Epoch vs accuracy
# Epoch vs loss
# We will load the model history into a pandas DataFrame and use the plot method to output
# the required graphs.
frame = pd.DataFrame(history.history)
print(frame.columns)
plt = frame.plot(y=["accuracy", "val_accuracy"], color=['b', 'g'], xlabel="Epochs",
ylabel=["Train Accuracy", "Validation Accuracy"], title='Accuracy vs Epochs', legend=True)
plt.xaxis.set_major_locator(MaxNLocator(integer=True))
# Run this cell to make the Loss vs Epochs plot
frame2 = pd.DataFrame(history.history)
plt2 = frame2.plot(y=["loss", "val_loss"], color=['b', 'g'], xlabel="Epochs",
ylabel=["Train Loss", "Validation Loss"], title='Loss vs Epochs', legend=True)
plt2.xaxis.set_major_locator(MaxNLocator(integer=True))
# The returned history object holds a dictionay record of the loss values and
# metric value(s) during training for each Epoch (in this case length 2)
print(history.history)
print(len(history.history))
# Run your function to evaluate the model
def evaluate_model(scaled_test_images, test_labels):
test_loss, test_accuracy = model.evaluate(scaled_test_images, test_labels, verbose=2)
return test_loss, test_accuracy
test_loss, test_accuracy = evaluate_model(scaled_test_images, test_labels)
# loss: 4.88% - accuracy: 98.55%
print('> Test accuracy: %.3f %%' % (test_accuracy * 100.0))
print('> Test loss: %.3f %%' % (test_loss * 100.0))
'''Model predictions Let's see some model predictions! We will randomly select four images from the test data,
and display the image and label for each.
For each test image, model's prediction (the label with maximum probability) is shown, together with a plot showing
the model's categorical distribution. '''
# Run this cell to get model predictions on randomly selected test images
num_test_images = scaled_test_images.shape[0]
random_inx = np.random.choice(num_test_images, 4)
random_test_images = scaled_test_images[random_inx, ...]
random_test_labels = test_labels[random_inx, ...]
predictions = model.predict(random_test_images)
fig, axes = plt.subplots(4, 2, figsize=(16, 12))
fig.subplots_adjust(hspace=0.4, wspace=-0.2)
for i, (prediction, image, label) in enumerate(zip(predictions, random_test_images, random_test_labels)):
axes[i, 0].imshow(np.squeeze(image))
axes[i, 0].get_xaxis().set_visible(False)
axes[i, 0].get_yaxis().set_visible(False)
axes[i, 0].text(10., -1.5, f'Digit {label}')
axes[i, 1].bar(np.arange(len(prediction)), prediction)
axes[i, 1].set_xticks(np.arange(len(prediction)))
axes[i, 1].set_title(f"Categorical distribution. Model prediction: {np.argmax(prediction)}")
plt.show()
# Improvement to Learning############################################
#####################################################################
####################################################################
# Batch Normalization
# Batch normalization can be used after convolutional and fully connected layers.
# It has the effect of changing the distribution of the output of the layer,
# specifically by standardizing the outputs.
# This has the effect of stabilizing and accelerating the learning process.
# We can update the model definition to use batch normalization after the
# activation function for the convolutional and dense layers of our baseline model. The updated version of
# define_model() function with batch normalization is listed below.
# this function builds the model and compiles in one step (vs what we did early, building 2 functions)
def define_model():
model = Sequential(
[Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', input_shape=(28, 28, 1)),
# default data_format='channels_last'
MaxPooling2D((2, 2)),
Flatten(),
Dense(100, activation='relu', kernel_initializer='he_uniform'),
BatchNormalization(),
Dense(10, activation='softmax')
])
# compile Model
opt = tf.keras.optimizers.Adam()
model.compile(optimizer=opt,
loss='categorical_crossentropy',
metrics=['accuracy'])
return model
model_BatchNorm = define_model()
print(model_BatchNorm.summary())
def train_model(scaled_train_images, train_labels):
history_BatchNorm = model_BatchNorm.fit(scaled_train_images, train_labels, epochs=5, batch_size=256)
# save model
model_BatchNorm.save('final_model.h5')
return history_BatchNorm
history_BatchNorm = train_model(scaled_train_images, train_labels)
def evaluate_model_bn(scaled_test_images, test_labels):
test_loss_BN, test_accuracy_BN = model_BatchNorm.evaluate(scaled_test_images, test_labels, verbose=2)
return test_loss_BN, test_accuracy_BN
test_loss_BN, test_accuracy_BN = evaluate_model_bn(scaled_test_images, test_labels)
# Batch Norm Accuracy 98.58%, Loss 4.29%
print('> Batch Norm Test accuracy: %.3f %%' % (test_accuracy_BN * 100.0))
print('> Batch Norm Test loss: %.3f %%' % (test_loss_BN * 100.0))
|
#!/bin/python3
# IT101 - RPG dungeon game project
# Jordan Golden
def showInstructions():
#print a main menu and the commands
print('''
RPG Game
========
Navigate your way through the Deadmines and
thwart the Defias Brotherhood. Defeat the
bosses and get to the exit with their loot.
Commands:
go [direction]
get [item]
attack monster
''')
def showStatus():
#print the player's current status
print('---------------------------')
print('You are in the ' + currentRoom)
#print the current inventory
print('Inventory : ' + str(inventory))
#print a monster if there is one
if "monster" in rooms[currentRoom]:
print('There is a monster in the room: ' + rooms[currentRoom]['monster'])
#print an item if there is one
if "item" in rooms[currentRoom]:
print('You see a ' + rooms[currentRoom]['item'])
print("---------------------------")
#an inventory, which is initially empty
inventory = []
#a dictionary linking a room to other rooms
rooms = {
'Mine Entrance' : {
'south' : 'Ironclad Cove'
},
'Ironclad Cove' : {
'north' : 'Mine Entrance',
'east' : 'Mineshaft 1',
'monster' : 'Rhahk\'zor',
'item' : 'rhahk\'zor\'s_hammer'
},
'Mineshaft 1' : {
'west' : 'Ironclad Cove',
'south' : 'Mast Room'
},
'Mast Room' : {
'north' : 'Mineshaft 1',
'east' : 'Mineshaft 2',
'monster' : 'Sneed',
'item' : 'buzzsaw'
},
'Mineshaft 2' : {
'west' : 'Mast Room',
'north' : 'Goblin Foundry'
},
'Goblin Foundry' : {
'south' : 'Mineshaft 2',
'north' : 'Powder Room',
'monster' : 'Gilnid',
'item' : 'lavishly_jeweled_ring'
},
'Powder Room' : {
'south' : 'Goblin Foundry',
'east' : 'Dank Cove',
'item' : 'powder_barrel'
},
'Dank Cove' : {
'west' : 'Powder Room',
'east' : 'Dreadnought'
},
'Dreadnought' : {
'west' : 'Dank Cove',
'up' : 'Dreadnought Cabin',
'monster' : 'Mr. Smite',
'item' : 'smite\'s_hammer'
},
'Dreadnought Cabin' : {
'down' : 'Dreadnought',
'east' : 'Mine Exit',
'monster' : 'Edwin van Cleef',
'item' : 'unsent_letter'
},
'Mine Exit' : { 'west' : 'Dreadnought Cabin' }
}
#start the player in the dungeon entrance
currentRoom = 'Mine Entrance'
showInstructions()
#loop forever
while True:
showStatus()
#get the player's next 'move'
#.split() breaks it up into an list array
#eg typing 'go east' would give the list:
#['go','east']
move = ''
while move == '':
move = input('>')
move = move.lower().split()
#if they type 'go' first
if move[0] == 'go':
#check that they are allowed wherever they want to go
if move[1] in rooms[currentRoom]:
#set the current room to the new room
currentRoom = rooms[currentRoom][move[1]]
#there is no door (link) to the new room
else:
print('You can\'t go that way!')
#if they type 'get' first
if move[0] == 'get' :
#if the room contains an item, and the item is the one they want to get
if "item" in rooms[currentRoom] and move[1] in rooms[currentRoom]['item']:
#add the item to their inventory
inventory += [move[1]]
#display a helpful message
print('You got ' + move[1] + '.')
#delete the item from the room
del rooms[currentRoom]['item']
#otherwise, if the item isn't there to get
else:
#tell them they can't get it
print('Can\'t get ' + move[1] + '!')
if move[0] == 'attack' and move[1] == 'monster':
if "monster" in rooms[currentRoom]:
print('Monster is defeated!')
del rooms[currentRoom]['monster']
else:
print('Nothing to attack here.')
# player wins if they get to the exit with the unsent letter
if currentRoom == 'Mine Exit' and 'unsent_letter' in inventory:
print('You beat the dungeon... YOU WIN!')
break
|
from datetime import datetime
import pandas
import random
import smtplib
today = datetime.now()
today_tuple = (datetime.now().month, datetime.now().day) # We create the tuple with today's month and day, like (12,30)
# Use pandas to read the birthdays.csv
data = pandas.read_csv("birthdays.csv")
# Use dictionary comprehension to create a dictionary from birthday.csv that is formated like this:
# birthdays_dict = {
# (birthday_month, birthday_day): data_row
# }
# Dictionary comprehension for pandas DataFrame looks like this: So iterate all the values in all rows (data.interrows) one by one.
# you get the index and the values of each row (data_row), the values in each row is (John [email protected] 1961 7 26)
# Then you get the column month value and the column day value and you store it in a tuple (month, day) --> this is gona be the new_key (keyword terminology)
# the value will be the whole row (John [email protected] 1961 7 26), and you will be storing this in the new dictionary.
birthdays_dict = {(data_row["month"], data_row["day"]): data_row for (index, data_row) in data.iterrows()}
# e.g. if the birthdays.csv looked like this:
# name,email,year,month,day
# Angela,[email protected],1995,12,24
#Then the birthdays_dict should look like this:
# birthdays_dict = {
# (12, 24): Angela,[email protected],1995,12,24
# }
# Then you could compare and see if today's month/day tuple matches one of the keys in birthday_dict like this:
if today_tuple in birthdays_dict: # If the today mondy and day in inside birday_dict then
file_path = f"letter_templates/letter_{random.randint(1,3)}.txt" # Choose one of the letters
birth_person = birthdays_dict[today_tuple] # We get hold of the values that contains the key today_tuple, which is a day and month, like (21, 7)
with open(file_path) as letter_file: # We open the letter.txt randomly selected before
contents = letter_file.read() # We read it
contents = contents.replace("[NAME]", birth_person["name"]) # Replace the literal [NAME] for the value of the key 'name'
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(user="[email protected]", password="IN_PASS_PLACE")
connection.sendmail(
from_addr="[email protected]",
to_addrs=birth_person["email"],
msg=f"Subject:Happy Birthday\n\n{contents}"
)
|
from turtle import Turtle, Screen
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time
# Create the screen and give it size, color and title.
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("My Pong Game")
screen.tracer(0) # --> Turn off the animation. Then the right_paddle gets created and we update the image after it.
# Initialize Right and Left paddles from Paddle class and pass in starting positions in a Tuple
r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
# We initialize ball from Ball class. Ball inherits methods and attributes from Turtle class.
ball = Ball()
# Initialize this one. Inherits Turtle class too. It provides color, hides the turtle, penup, position for the two scores, etc.
scoreboard = Scoreboard()
# Enable screen listening to detect the keys you press and run the methods go_up or go_down if you press the arrows up and down or w or s.
screen.listen()
screen.onkey(r_paddle.go_up, "Up")
screen.onkey(r_paddle.go_down, "Down")
screen.onkey(l_paddle.go_up, "w")
screen.onkey(l_paddle.go_down, "s")
# To update the image, "tracer" disable the animation and "update" method shows a picture of the current image.
game_is_on = True
while game_is_on:
time.sleep(0.1) # We slow the screen because the ball goes too fast
screen.update() # Update the screen, is like to show a picture of the screen in every iteration of the while loop.
ball.move() # We got the ball to move with every refresh of the screen.
# Detect collision with top wall
if ball.ycor() > 280 or ball.ycor() < -280:
ball.bounce_y() # it detects when the ball hits the top or bottom of the screen.
# Detect collision with paddle
if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320:
ball.bounce_x()
# Detect when R paddle misses:
if ball.xcor() > 380:
ball.reset_position()
scoreboard.l_point() # We call the method l_point which adds +1 scoreboard(self).l_point attribute
# Detect when L paddle misses:
if ball.xcor() < - 380:
ball.reset_position()
scoreboard.r_point()
screen.exitonclick()
|
from tkinter import *
THEME_COLOR = "#375362"
class QuizInterface:
# In the class init we will create the user interface.
def __init__(self): # Everytime we create a new object from the class QuizInterface, a window will be created
self.window = Tk() # We create the window as the property of the class.
self.window.title("Quizzler")
self.window.config(padx=20, pady=20, background=THEME_COLOR)
self.score_label = Label(text="Score: 0", fg="white", bg=THEME_COLOR)
self.score_label.grid(column=1, row=0)
self.canvas = Canvas(width=300, height=250, bg="white")
self.question_text = self.canvas.create_text(
150,
125,
text="Some question text",
fill=THEME_COLOR,
font=("Arial", 20, "italic")
)
self.canvas.grid(row=1, column=0, columnspan=2, pady=50)
true_image = PhotoImage(file="images/true.png")
self.true_button = Button(image=true_image, highlightthickness=0)
self.true_button.grid(row=2, column=0)
false_image = PhotoImage(file="images/false.png")
self.false_button = Button(image=false_image, highlightthickness=0)
self.false_button.grid(row=2, column=1)
self.window.mainloop() # This is a kind of while loop that is constantly looking for any change in the app
# self.window() in this example. So if there is another while loop in the program it will cause problems, so the other
# while loop have to be removed. In this case we have the while loop in the main.py
|
from tkinter import *
def button_clicked():
print("I got clicked")
new_text = input.get() # Get hold of what you are typing
my_label.config(text=new_text) # When we click the button the text of the label will change
window = Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
window.config(padx=20, pady=20) # Padding. You add more space on the sides
# Label
my_label = Label(text="New Text", font=("Arial", 24, "bold" ))
my_label.grid(column=0, row=0)
# Button
button = Button(text="Click Me", command=button_clicked)
button.grid(column=1, row=1)
# New Button
new_button = Button(text="Click Me New Button", command=button_clicked)
new_button.grid(column=2, row=0)
# Entry
input = Entry(width=10)
input.grid(column=3, row=2)
window.mainloop()
|
MY_LAT = 55.953251 # Your latitude
MY_LONG = -3.188267 # Your longitude
iss_latitude = 51.54
iss_longitude = 1
if int(iss_latitude) in range(50, 60) and int(iss_longitude) in range(2, -9, -1):
sunrise = 4
sunset = 19
hour = 21
if hour >= sunset or hour <= sunrise:
print("Ullet")
else:
print("No ISS")
|
# This is a simple hangman game and there are 10 questions.
"""
After each question, in brackets, there is a hint that let's player the expected output
The game records the number of questions you have answered wrong.
If you fail a question, the program responds with "You are hanging the man\n"
After six mistakes game is lost and stops
You get the message "You have hanged the man\n"
If you finish the game
you get "you're done (insert name), you reached the end and only made x mistake/s"
"""
# Create dictionary that contains each question and the correct answer to which I can refer.
answers_dict = {'When was ALU founded?': 2015,
'Who is the CEO of ALU?': 'Fred Swaniker',
'Where are ALU campuses?': 'Rwanda and Mauritius',
'How many campuses does ALU have?': 2,
'What is the name of ALU Rwanda’s Dean?': 'Gaidi Faraj',
'Who is in charge of Student Life?': 'Sila Ogidi',
'What is the name of our Lab?': 'Nigeria',
'How many students do we have in Year 2 CS?': 57,
'How many degrees does ALU offer?': 8,
'Where are the headquarters of ALU?': 'Mauritius'}
# First we get the player's name
player_name = input('Hello and welcome to hangman by Aimar, what is you name? ')
# Then we give the user a set of instructions that explains the game and the expected input.
print(f'''
Hi {player_name}, lets see how well you know ALU
The game is very simple, you will first see a question and in brackets is the expected answer.
As an example:
For (Year) give the year in numbers i.e 2010
For (Full Name) give the full name and capitalize the first letters i.e Aimar Cyusa
Nothing difficult right, have fun!!
''')
# Ask if the user wants to play
start_game = input('Do you want to start playing? yes or no: ')
# Start game. Game will run if start game starts with y
while start_game.lower().startswith('y'):
WRONG_ANSWERS = 0 # Variable that holds number of wrong answers
user_input = int(input('When was ALU founded? ')) # Ask question and save answer
if user_input in answers_dict.values(): # Check if users answer in all correct answers
print('well done\n')
else: # If there is no answer
WRONG_ANSWERS += 1 # First we add one to the wrong answers count
if WRONG_ANSWERS == 6: # Check if we have not reached the total
print('You have hanged the man\n')
break
print('You are hanging the man\n') # If not print hanging the man
user_input = input('Who is the CEO of ALU? ')
# There are two possible answers; Fred Swaniker or Swaniker Fred
# Lower and split correct answer at the space and save each name as first and last name
first_name, last_name = (answers_dict['Who is the CEO of ALU?']).lower().split()
# Convert the player's response and split at the space to create a list of user answers
user_answers = user_input.lower().split()
# Check whether real first and last names are in our user_answers list
if first_name and last_name in user_answers:
print('well done\n')
else: # If they are not
WRONG_ANSWERS += 1 # Add 1 to our wrong answers count
if WRONG_ANSWERS == 6: # Check if we have not reached the total
print('You have hanged the man\n')
break
print('You are hanging the man\n') # If not then print hanging the man
user_input = input('Where are ALU campuses? ')
first_campus, second_campus = (answers_dict['Where are ALU campuses?']).lower().split(' and ')
user_answers = user_input.lower().split()
if first_campus and second_campus in user_answers:
print('well done\n')
else:
WRONG_ANSWERS += 1
if WRONG_ANSWERS == 6:
print('You have hanged the man\n')
break
print('You are hanging the man\n')
user_input = int(input('How many campuses does ALU have? '))
if user_input in answers_dict.values():
print('well done\n')
else:
WRONG_ANSWERS += 1
if WRONG_ANSWERS == 6:
print('You have hanged the man\n')
break
print('You are hanging the man\n')
user_input = input('What is the name of ALU Rwanda’s Dean? ')
first_name, last_name = (answers_dict['What is the name of ALU Rwanda’s Dean?']).lower().split()
user_answers = user_input.lower().split()
if first_name and last_name in user_answers:
print('well done\n')
else:
WRONG_ANSWERS += 1
if WRONG_ANSWERS == 6:
print('You have hanged the man\n')
break
print('You are hanging the man\n')
user_input = input('Who is in charge of Student Life? ')
first_name, last_name = (answers_dict['Who is in charge of Student Life?']).lower().split()
user_answers = user_input.lower().split()
if first_name and last_name in user_answers:
print('well done\n')
else:
WRONG_ANSWERS += 1
if WRONG_ANSWERS == 6:
print('You have hanged the man\n')
break
print('You are hanging the man\n')
user_input = input('What is the name of our Lab? ')
if user_input in answers_dict.values():
print('well done\n')
else:
WRONG_ANSWERS += 1
if WRONG_ANSWERS == 6:
print('You have hanged the man\n')
break
print('You are hanging the man\n')
user_input = int(input('How many students do we have in Year 2 CS? '))
if user_input in answers_dict.values():
print('well done\n')
else:
WRONG_ANSWERS += 1
if WRONG_ANSWERS == 6:
print('You have hanged the man\n')
break
print('You are hanging the man\n')
user_input = int(input('How many degrees does ALU offer? '))
if user_input in answers_dict.values():
print('well done\n')
else:
WRONG_ANSWERS += 1
if WRONG_ANSWERS == 6:
print('You have hanged the man\n')
break
print('You are hanging the man\n')
user_input = input('Where are the headquarters of ALU? ')
if user_input in answers_dict.values():
print('well done\n')
else:
print('You are hanging the man\n')
WRONG_ANSWERS += 1
# If player reaches the end of the
# Print congratulatory statement
# Include the number of wrong answer's they may have had
# For the sake of english correctness, If we have one mistake prints ...only made 1 mistake
# Otherwise print ...only make x mistakes. x!=0
if WRONG_ANSWERS == 1:
print(f"\nwell done\n {player_name}, you're done and only made {WRONG_ANSWERS} mistake")
else:
print(f"\nwell done\n{player_name}, you're done and only made {WRONG_ANSWERS} mistakes")
break
|
import tensorflow as tf
x_data = [1,2,3]
y_data = [1,2,3]
W = tf.Variable(tf.random_normal([1]), name='weight')
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
hypothesis = X * W
cost = tf.reduce_sum(tf.square(hypothesis - Y))
learning_rate = 0.1
gradient = tf.reduce_mean((W*X-Y) * X)
descent = W - learning_rate * gradient
# optimize의 gradient 를 사용하여 대체할 수 있음. 그 쪽이 좀 더 깔끔함
# 단지, 본인이 radient를 잘라서 써야할 때는 구현하여 사용한다.
# assign은 변수값의 초기화를 뜻함. variable을 통한 초기화
update = W.assign(descent)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(21):
sess.run(update, feed_dict = {X:x_data, Y:y_data})
print(step, sess.run(cost,feed_dict={X:x_data, Y:y_data}), sess.run(W))
|
def inSquare(x, y):
return abs(x) + abs(y) <= 1
x = float(input())
y = float(input())
if inSquare(x, y):
print("YES")
else:
print("NO")
|
# Decorators are used to modify functionality of function
# Here we change normal add frunction to add 2 tuples
import functools
def point_add_decorator(func):
@functools.wraps(func)
def point_add(*args, **kwargs):
# print(type(args[0]))
if type(args[0]) == type((1, 2)):
x = func(args[0][0], args[1][0])
y = func(args[0][1], args[1][1])
return (x, y)
elif type(args[0]) == type(1) or type(args[0]) == type(1.1):
r = func(*args, **kwargs)
return r
else:
raise TypeError("Type of aurgument not correct")
return point_add
@point_add_decorator
def add(x, y):
return x + y
a = 2.2
b = 4.1
print(type(a))
result = add(a, b)
print(result)
p1 = tuple([a, b])
p2 = (1, 2)
result = add(p1, p2)
print(result)
# add functools.wrap to preserver identity if not it will take identity of wrapper functions
print(add.__name__)
print(help(add))
|
import webbrowser
class Video:
"""This class contains basic properties of a video.
Attributes:
title (str): Title of video
duration (number): Number of minutes
"""
def __init__(self, title, duration=0):
self.title = title
self.duration = duration
class Movie(Video):
"""This class defines some info of a movie and opens youtube
trailer in a new browser's tab.
Attributes:
storyline (str): Storyline of video
poster_image_url (str): Link of box art image
trailer_youtube_url (str): Link of youtube's video trailer
"""
valid_ratings = ["G", "PG", "PG-13", "R"]
def __init__(self, movie_title, movie_storyline, poster_image,
trailer_youtube):
Video.__init__(self, movie_title)
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
""" Open new tab in web browser with youtube trailer url """
webbrowser.open(self.trailer_youtube_url)
class TvShow(Video):
"""This class defines properties of a TvShow
Attributes:
season (number): Season of this TvShow
number_of_episodes (number) : Number of episodes in this TvShow
tv_station (number): Producer of this TvShow
"""
def __init__(self, tv_show_title, season, number_of_episodes, tv_station):
Video.__init__(tv_show_title)
self.season = season
self.number_of_episodes = number_of_episodes
self.tv_station = tv_station
def get_local_listings(self):
pass
|
import hashlib
import random
import string
import hmac
SECRETE_KEY = "129jcn299jcji"
# SECURE COOKIES
# For speed up, we don't need to use SHA-256 to encrypt cookies.
# md5 and a SECRETE KEY is good enough
def make_hmac(value):
"""
Generate a hash-based message authentication code
:param value: cookie's value
:return: A hmac
"""
return hmac.new(SECRETE_KEY, value).hexdigest()
def check_secure_cookie(s):
"""
Check if cookie sent from browser is valid or not
:param s: cookie string
:return: If cookie is valid, return its right value, unless return None
"""
try:
value, hashing_value = s.split('|')
if make_hmac(value) == hashing_value:
return value
except Exception as e:
pass
return None
def make_secure_cookie(value):
"""
Create secure cookie for a value
:param s: cookie's value
:return: a string contains 2 part: cookie's value, hmac's value splited
by `|` sign
"""
return "{}|{}".format(value, make_hmac(str(value)))
# SECURE PASSWORD
# To make password cannot be reverted, even in case loosing all, we use
# sha256 to encrypt password with a random salt.
def make_salt():
"""Generate a random 5 character length salt"""
return ''.join([random.choice(string.letters) for i in xrange(5)])
def make_pw_hash(name, pw, salt=None):
"""
Generate hashing password from username, password and salt
:param name: username
:param pw: raw password
:param salt: random salt
:return: a string includes hashed password and its salt separated by `|`
sign
"""
if not salt:
salt = make_salt()
hash = hashlib.sha256(name + pw + salt).hexdigest()
return "{}|{}".format(hash, salt)
def valid_pwd(name, pwd, h):
"""
Check if username and password is valid
:param name: username string from browser
:param pwd: password string from browser
:param h: password get from database in form `<hashing>|<salt>`
:return:
"""
if h:
_, salt = h.split("|")
actual_hash = make_pw_hash(name, pwd, salt)
if actual_hash != h:
return False
return True
|
print("Hola Mundo")
variable1 = "Gato"
variable2 = 100
variable3 = 45.23
print(variable1)
print(variable2)
print(variable3)
variable1 = "Perro"
print("El valor de la variable variable1 es: ", variable1)
print("El valor de la variable variable1 es {} y el valor de la variable variable2 es {}".format(variable1, variable2))
|
'''
A estas alturas hemos visto lo basico de un curso de python1, en este ejemplo, trabajaremos
con lectura y escritura de archivos de texto. Para ello, tomaremos un archivo, leeremos los
nombres existentes en el y obtendremos las iniciales de ellos, armando un diccionario el cual
se exportara a un archivo de salida
'''
file_open = open('archivo_input.txt', 'r')#la r significa lectura, la w escritura, entre las principales
#la informacion del archivo la guardaremos en una lista
diccionario_iniciales = {}
line = file_open.readline()#leemos la primera linea para formar el ciclo
while line:#no sabemos cuantas lineas son, leemos hasta que se acabe el archivo
line = line.replace("\n", "")#le quitamos el enter a la linea
names = line.split(" ")#con spline seperamos por espacio
iniciales = "{}{}".format(names[0][0], names[1][0])
#agregamos la key generada al diccionario
diccionario_iniciales.update({iniciales:line})
line = file_open.readline()#continuamos leyendo
file_open.close()#siempre debemos cerrar el archivo abierto
#exportamos a un archivo
file_export = open("archivo_iniciales.txt", 'w')#declaramos el archivo de salida
for inicial in diccionario_iniciales:
line_print = "{}:{}\n".format(inicial, diccionario_iniciales[inicial])#el \n representa un enter o salto de lineas
file_export.write(line_print)
file_export.close()
|
'''
previamente trabajamos con listas y ya sabemos como funcionan, a continuacion trabajaremos con un
nuevo tipo de listas que se llama Diccionario.
Practicamente los diccionarios son estructuras que permiten asociar una palabra clave a un valor,
este valor puede ser de cualquier tipo.
'''
#un diccionario se define entre llaves, las claves entre comillas seguido de : y el valor que representaran
dictionary = {"clave": 1, "clave2": "Valor 02", "clave3" : [1, 2, 3]}
#para acceder a un valor de un diccionario se hace con ['clave']
print(dictionary['clave2'])
#podemos obtener todas las claves existentes
print(dictionary.keys())
#podemos recorrer todas las claves usando estructuras for
for key in dictionary:
print("Key {} tiene valor de {} ".format(key, dictionary[key]))
#podemos agregar elementos al diccionario
dictionary.update({"nueva_clave":["value1", "value2"]})
print(dictionary)
#NOTA: todas los ejemplos y demases vistos previamente pueden ser usados en diccionarios
#una clave, puede almacenar un diccionario tambien
dictionary_02 = {"clave_m" : 124}
dictionary.update({"dict_value":dictionary_02})
print(dictionary)
#Nota: el procesamiento de esto se llama Hash
|
'''
Las condiciones o decisiones son segmentos de codigo que se ejecutan dependiendo de un
valor o una condicion que nosotros declaremos. Al igual que en la vida, las condiciones permiten ejecutar
codigo, si queremos darnos un lujo, comprar un regalo a su novia, salir a vacacionar, etc.
Para trabajar con condiciones en python existen las palabras reservadas: if, else y elif, un segmento clasico de
codigo de condiciones es como sigue
if condiciones:
acciones -> importante siempre se debe tabular para definir el bloque de codigo que se quiere ejecutar
else:#significa en caso contrario
acciones alternativas
'''
#ejemplo de evaluacion de notas
nota_1 = int(input("Ingresa tu nota"))
if nota_1 > 4:
print("Alumno aprobado")
else:
print("Alumno reprobado")
#tambien podemos comparar palabras
nombre = input("Ingrese un nombre")
if nombre == "Juan":
print("El nombre ingresado coincide")
else:
print("No es Juan")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.