text
stringlengths 37
1.41M
|
---|
list=["a","b","c","d","e","f"]
#insert method
list.append(5)# insert at last if we have to insert into agiven position then we have to use insert method "a.insert(len(a),x)" is equal to a.append
print list
a = [66.25, 333, 333, 1, 1234.5]
a = [66.25, 333, 333, 1, 1234.5]
print a.count(66.25),a.count(333)
a.append(999)
a.insert(1,2)#first argument is position and second argument is insert element
print a
a[len(a):]=list # qual to a.extend(list)
print a
#delete an element
#delete an element through the element value
a.remove(333)# here 1st 333 is deleted if 333 is not present in the list then it show error
print a
#delete an element through the index position
a.pop(0)# if you delete an item in a given position then you use a.pop() method
print a
#know the position of an element
print a.index("a")# if you want to a element position then you have to use index method .this method return the position of an element if the number of element is more than one then it return the first position of an element :if element is not present in the list then it return error .
#sorting
a.sort()
print a
customlist = [
Custom('object', 99),
Custom('michael', 1),
Custom('theodore the great', 59),
Custom('life', 42)
]
def getkey(
class Custom(object):
def __init__(self, name, number):
self.name = name
self.number = number
def __repr__(self):
return '{}: {} {}'.format(self.__class__.__name__,
self.name,
self.number)
def __cmp__(self, other):
if hasattr(other, 'number'):
return self.number.__cmp__(other.number)
print sorted(customlist)
|
class parentclass:
var1="i am var1"
var2="i am var2"
class childclass(parentclass):
pass
parentobject=parentclass
childobject=childclass
print parentobject.var1
print childobject.var1
print "here we show that childobject access the parentobject property"
|
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
emp1=Employee("chandan","5000")
emp2=Employee("meghnad","8000")
print emp1.name
print emp2.name
print "Employee.__doc__:", Employee.__doc__#return class documentation string define classes namespace here print "Common base class for all employee
print "Employee.__name__:", Employee.__name__#here print class name and that is employee
print "Employee.__module__:", Employee.__module__#here it print module name where class is defined here print __main__
print "Employee.__bases__:", Employee.__bases__#it return empty tuple containing the base classes
print "Employee.__dict__:", Employee.__dict__#dictionary contain classes name space here it return "{'__module__': '__main__', 'displayCount': <function displayCount at 0x7f999f53f758>, 'empCount': 0, 'displayEmployee': <function displayEmployee at 0x7f999f53f7d0>, '__doc__': 'Common base class for all employees', '__init__': <function __init__ at 0x7f999f53f6e0>}
|
import json
from difflib import get_close_matches
#load dictionary data into variable called 'data'
data = json.load(open("data.json"))
#create function
def translation(w):
#whenever words get passed into this function, it will convert all characters to lower case
w = w.lower()
#conditional if word passed into function is present in 'data.json'
if w in data:
#return key 'word' from the 'data.json' file
return data[w]
#condition used if word is incorrect but similar to keyword in dictionary
elif len(get_close_matches(w, data.keys())) > 0:
yn = input("did you mean %s instead? Enter Y if yes, N if not: " % get_close_matches(w, data.keys())[0])
if yn == "Y":
return data[get_close_matches(w, data.keys())[0]]
elif yn == "N":
return "The word does not exist, Please double check word."
else:
return "We did not understand your input."
#else condition used if word is not fount in 'data.json'
else:
return "The word does not exist, Please double check word."
#ask user to enter a word and assign it to the variable 'word'
word = input("Enter word: ")
#print out function with word as paramenter which will output the dictionary definition
output = translation(word)
if type(output) == list:
#create for loop to create a more readable output
for item in output:
print(item)
else:
print(output)
|
import pygame
from config import PLAYLIST, BACK, JUMP, KEY, FORWARD, DIE
class AudioService:
"""A class to represent audio service which handles the audio of the game.
"""
def __init__(self):
"""Loads audio files for the audio service.
Audio filepaths are obtained from the config -file.
"""
self._playlist = PLAYLIST
self.music = pygame.mixer.music
self.music.set_volume(0.4)
self.menu_music_active = False
self.music_on = True
self.sound_effects_on = True
def play_music(self, index=0):
"""Handles the background music.
Does nothing if music is flagged off or
if menu music is active and index is 0.
Otherwise play the music according to the index.
Args:
index (int, optional): Is used to choose music from the playlist.
0 = menu music (default)
1 = level 1 music
2 = level 2 music...
"""
if self.music_on:
if not self.menu_music_active and index == 0:
self.music.fadeout(500)
self.music.load(self._playlist[index])
self.music.play(loops=-1)
self.menu_music_active = True
elif index >= 1:
self.music.fadeout(500)
self.music.load(self._playlist[index])
self.music.play(loops=-1)
self.menu_music_active = False
def set_music_off(self):
"""Flags the music off and stops the current music.
"""
self.menu_music_active = False
self.music_on = False
self.music.stop()
def set_sound_effects_off(self):
"""Flags the sound effects off.
"""
self.sound_effects_on = False
def set_music_on(self):
"""Flags the music on and start menu music.
"""
self.music_on = True
self.play_music()
def set_sound_effects_on(self):
"""Flags the sound effects on.
"""
self.sound_effects_on = True
def get_audio_information(self):
"""Get information if audio and sound fx are on or off.
Returns:
(tuple): Return tuple with two booleans.
"""
return (self.music_on, self.sound_effects_on)
def play_back_sound(self):
"""Play the sound effect "back" if sound effects are flagged on.
"""
if self.sound_effects_on:
back = pygame.mixer.Sound(BACK)
back.play()
def play_forward_sound(self):
"""Play the sound effect "forward" if sound effects are flagged on.
"""
if self.sound_effects_on:
forward = pygame.mixer.Sound(FORWARD)
forward.play()
def play_key_sound(self):
"""Play the sound effect "key" if sound effects are flagged on.
Adjust the volume.
"""
if self.sound_effects_on:
key = pygame.mixer.Sound(KEY)
key.set_volume(0.5)
key.play()
def play_jump_sound(self):
"""Play the sound effect "jump" if sound effects are flagged on.
Adjust the volume.
"""
if self.sound_effects_on:
jump = pygame.mixer.Sound(JUMP)
jump.set_volume(0.5)
jump.play()
def play_die_sound(self):
"""Play the sound effect "die" if sound effects are flagged on.
"""
if self.sound_effects_on:
die = pygame.mixer.Sound(DIE)
die.play()
|
class NewGameView:
"""A class to represent new game view of UI.
Attributes:
renderer: Renderer object.
"""
def __init__(self, renderer):
"""Constructs all the necessary attributes for finish view.
Args:
renderer (Renderer): Renderer object which renders the display.
"""
self._renderer = renderer
self._width = self._renderer.width
self._height = self._renderer.height
self._big = int(self._height / 10)
self.small = int(self._height / 20)
self._lines = []
def show(self, nickname, color=(255, 255, 255)):
"""Prepares all information to show for the renderer object.
New game view allows player to create new save object with personal nickname.
Continue text will be rendered as grey color until player has typed all 4 required
letters for nickname.
Information is forwarded inside list of lines.
Following information will be rendered:
1. Game and view name
2. Nickname status
3. Continue key
4. Back to main menu key
Args:
nickname (str): Nickname of the save
color (tuple, optional): Color of the continue text. Defaults to (255, 255, 255).
"""
self._lines.append(["ENTER YOUR NICKNAME", self.small,
self._width / 2, self._height / 2])
self._lines.append([nickname, self._big, self._width / 2,
self._height / 2 + (self.small * 2.4)])
self._lines.append(["CONTINUE ( press ENTER )", self.small,
self._width / 2, self._height / 2 + (self.small * 4.8), color])
self._lines.append(["BACK TO MAIN MENU ( press ESC )", self.small,
self._width / 2, self._height / 2 + (self.small * 6)])
self._renderer.render_menu("CREATE NEW GAME", self._lines)
|
class MenuView:
"""A class to represent menu view of UI.
Attributes:
renderer: Renderer object.
"""
def __init__(self, renderer):
"""Constructs all the necessary attributes for finish view.
Args:
renderer (Renderer): Renderer object which renders the display.
"""
self._renderer = renderer
self._width = self._renderer.width
self._height = self._renderer.height
self.small = int(self._height / 20)
self._extra_small = int(self._height / 30)
self._lines = []
def show(self, records):
"""Prepares all information to show for the renderer object.
Information is forwarded inside list of lines.
Following information will be rendered:
1. Game and view name
2. TOP3 records (text colors: gold, silver, bronze)
3. New game view key
4. Load game view key
5. Exit key
Args:
records (list): List of save objects.
"""
self._lines.append(["TOP3 RECORDS:", self._extra_small,
self._width / 2, self._height / 2 - (self._extra_small * 2.4)])
self._lines.append([records[0], self._extra_small, self._width / 2,
self._height / 2 - (self._extra_small * 1.2), (255, 215, 0)])
self._lines.append([records[1], self._extra_small,
self._width / 2, self._height / 2, (192, 192, 192)])
self._lines.append([records[2], self._extra_small, self._width / 2,
self._height / 2 + (self._extra_small * 1.2), (205, 127, 50)])
self._lines.append(["NEW GAME ( press N )", self.small,
self._width / 2, self._height / 2 + (self.small * 2.4)])
self._lines.append(["LOAD GAME ( press L )", self.small, self._width /
2, self._height / 2 + (self.small * 3.6)])
self._lines.append(["GAME SETUP ( press S )", self.small, self._width /
2, self._height / 2 + (self.small * 4.8)])
self._lines.append(["EXIT ( press ESC )", self.small,
self._width / 2, self._height / 2 + (self.small * 6)])
self._renderer.render_menu("MAIN MENU", self._lines)
|
import sys
def testWhileElse():
count = 0
while count < 5:
print(count)
count += 1
else:
print(count, 'false')
def testForElse():
#else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况
#下执行,while … else 也是一样
for num in range(10,20): # 迭代 10 到 20 之间的数字
for i in range(2,num): # 根据因子迭代
if num%i == 0: # 确定第一个因子
j=num/i # 计算第二个因子
print('%d 等于 %d * %d' % (num,i,j))
break # 跳出当前循环
else: # 循环的 else 部分
print(num, '是一个质数')
def forStep():
arr = ['a','b','c']
for i in range(0, 10, 3):
print(i)
for i, val in enumerate(arr):
print(i, val)
def testIn(x):
if x in ['1','2',3]:
print('in')
else:
print('out')
def funcParams(x, y=1,n='hello'):
print(x)
print(y)
print(n)
def funcMutable(a, L=[]):
L.append(a)
return L
#Python doesn't copy objects you pass during a function call ever.
#Function parameters are names. When you call a function Python binds
#these parameters to whatever objects you pass (via names in a caller scope).
#Objects can be mutable (like lists) or immutable (like integers, strings in
#Python). Mutable object you can change. You can't change a name,
#you just can bind it to another object.
def funcMutableNone(a, L=None):
if L is None:
L=[]
L.append(a)
return L
def passParamsTest(x):
x=3
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
def main():
#sys argvs, sys.argv[0] being the program itself
print('Hello there', sys.argv[1])
def concat(*args, sep="/"):
return sep.join(args)
def parrot(voltage, state='a stiff', action='voom'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.", end=' ')
print("E's", state, "!")
def make_incrementor(n):
return lambda x: x+n
if __name__ == '__main__':
testWhileElse()
testForElse()
#main()
forStep()
testIn(3)
testIn('c')
funcParams(3)
funcParams(3, 2)
funcParams(3, 3,'world')
print(funcMutable(3))
print(funcMutable(4))
print(funcMutableNone(4))
print(funcMutableNone(5))
x = 4
passParamsTest(x)
print(x)
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
test="Hello World!",
#'hello', SyntaxError: positional argument follows keyword argument
sketch="Cheese Shop Sketch")
print(concat("earth", "mars", "venus"))
d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)
f = make_incrementor(42)
print(f(33))
|
"""
All Rules relevant to contexts that work with strings.
It may be subject, object, etc.
"""
import re
import logging
from ..rules.base import Rule
log = logging.getLogger(__name__)
class StringEqualRule(Rule):
"""Rule that is satisfied if the string value equals the specified property of this rule"""
def __init__(self, val):
if not isinstance(val, str):
log.error('%s creation. Initial property should be a string', type(self).__name__)
raise TypeError('Initial property should be a string')
self.val = val
def satisfied(self, what, inquiry=None):
return isinstance(what, str) and what == self.val
class StringPairsEqualRule(Rule):
"""Rule that is satisfied when given data is an array of pairs and
those pairs are represented by equal to each other strings"""
def satisfied(self, what, inquiry=None):
if not isinstance(what, list):
return False
for pair in what:
if len(pair) != 2:
return False
if not isinstance(pair[0], str) and not isinstance(pair[1], str):
return False
if pair[0] != pair[1]:
return False
return True
class RegexMatchRule(Rule):
"""Rule that is satisfied when given data matches the provided regular expression.
Note, that you should provide syntactically valid regular-expression string."""
def __init__(self, pattern):
try:
self.regex = re.compile(pattern)
except Exception as e:
log.exception('%s creation. Failed to compile regexp %s', type(self).__name__, pattern)
raise TypeError('pattern should be a valid regexp string. Error %s' % e)
def satisfied(self, what, inquiry=None):
return bool(self.regex.match(str(what)))
|
# 이진트리 순회(깊이우선탐색)
# 아래 그림과 같은 이진트리를 전위순회와 후위순회를 연습해보세요.
# 1
# 2 3
# 4 5 6 7
# 전위순회 출력 : 1 2 4 5 3 6 7 중위순회 출력 : 4 2 5 1 6 3 7 후위순회 출력 : 4 5 2 6 7 3 1
import sys
import math
from collections import deque
# heapq를 사용할 수 있도록 추가
import heapq as hq
#sys.stdin = open("in1.txt", "rt")
# 전위순회
def f_DFS(v):
if v <= 7:
print(v, end=' ')
f_DFS(2*v)
f_DFS(2*v + 1)
# 중위순회
def f_DFS1(v1):
if v1 <= 7:
f_DFS1(2*v1)
print(v1, end=' ')
f_DFS1(2*v1 + 1)
# 후위순회
def f_DFS2(v2):
if v2 <= 7:
f_DFS2(2*v2)
f_DFS2(2 * v2 + 1)
print(v2, end=' ')
f_DFS(1)
print()
f_DFS1(1)
print()
f_DFS2(1)
|
# coding=utf-8
'''
Created on 30/01/2016
@author: jmonterrubio
Address parsing tests
'''
import unittest
from map_parser.map import address
ONE_GOOD_CITY = 'City'
UNKNOWN_ADDRESS_FIELD = 'address:'
BAD_ADDRESS_FIELD = 'addr:city:info'
class TestsParseAddress(unittest.TestCase):
# Parse correctly a well defined address
def test_parse_address(self):
an_address = {}
an_address['city'] = ONE_GOOD_CITY
parsed_address = {}
address.fill(parsed_address, 'addr:city', ONE_GOOD_CITY)
self.assertEqual(parsed_address, an_address)
# Parse correctly an address with bad fields
def test_parse_address_bad_field(self):
an_address = {}
parsed_address = {}
address.fill(parsed_address, BAD_ADDRESS_FIELD, '')
self.assertEqual(parsed_address, an_address)
# Parsing is not adding unknown fields
def test_parse_address_unknown_field(self):
an_address = {}
parsed_address = {}
address.fill(parsed_address, UNKNOWN_ADDRESS_FIELD, '')
self.assertEqual(parsed_address, an_address)
if __name__ == '__main__':
unittest.main()
|
import numpy as np
list1=[90,32,89,21]
print(list1[-2:])
print(np.argmin(list1)) # least element(21) present in 3rd index position
list2=[[12,31,23,67],[89,45,21,34],[56,25,78,96]]
print(*np.argmin(list2,axis=1)) # Row-wise
print(*np.argmin(list2,axis=0)) # Column-wise
|
#В матрице a(n, m) поменять местами столбцы с минимальным и максимальным
# количествами четных элементов. Матрица — список списков.
def change(a):
n = len(a)
m = len(a[0])
for j in range(m):
b = []
count = 0
for i in range(n):
if a[i][j] % 2 == 0:
count += 1
b.append(count)
a.append(b)
print(a)
a = [[1, 2, 3], [4, 6, 7], [8, 8, 2]]
c = change(a)
|
# Введенную с клавиатуры строку вывести на экран наоборот (использовать цикл)(0,5 балла)
def revers(s):
string = ''
# Вызываем функцию, ей в качестве аргумента точку
s = s.split('.')
for i in range(0, len(s)):
string += s[i][::-1].strip() + '. '
print(string)
strl = input()
revers(strl)
|
# नितीन पटले
# 𝓑𝓣𝟣𝟪𝓒𝓢𝓔𝟢𝟢𝟦
import sys
# prime number is in the form
# 6n ± 5
def product_of_primes(a):
if a <= 1: return []
l = []
i = 2
count = 0
while (a%i == 0):
a = a//i
count += 1
if(count > 0):
l.append([i, count])
i = 3
count = 0
while (a%i == 0):
a = a//i
count += 1
if(count > 0):
l.append([i, count])
i = 5
while i*i<=a:
count = 0
while(a%i == 0):
a = a//i
count+=1
if count > 0:
l.append([i, count])
count = 0
while(a%(i+2) == 0):
a = a//(i+2)
count+=1
if count > 0:
l.append([i+2, count])
i+=6
if a > 1:
l.append([a, 1])
return l
def __main__():
args = sys.argv
a = int(args[1])
l = product_of_primes(a)
m = len(l)
for i in range(m-1):
for j in range(l[i][1]): # print l[i][1] times
print(l[i][0], end=" ")
if(m > 0):
for j in range(l[m-1][1] - 1):
print(l[m-1][0], end=" ")
print(l[m-1][0], end="")
__main__()
|
# नितीन पटले
# 𝓑𝓣𝟣𝟪𝓒𝓢𝓔𝟢𝟢𝟦
import sys
def gcd(a, b):
if(b == 0):
return a
return gcd(b, a%b)
def extended_euclidean(a, b):
if(b == 0):
return [1, 0]
[x1, y1] = extended_euclidean(b, a%b)
x = y1
y = x1 - (a//b)*y1
return [x, y]
def multiplicative_inverse(a, n):
g = gcd(a, n)
if(g != 1):
return -1
return (extended_euclidean(a//g, n//g)[0] + n)%n
# method 1 improvement needed according to the issue raised
def system_of_congruences_1(a, b, m):
M = 1
n = len(a)
# you also have to write for case where
# gcd(mi, mj) != 1
# then you will have to disintegrate mi, mj then check if any inconsistencies exists
# lecture _09_08
# print("before loop")
for i in range(n):
if(b[i] % gcd(a[i], m[i]) != 0):
return []
# gcd(m[i], m[j]) > 1 currently is wrong
# need to be improvised
for j in range(n):
if i!=j and (gcd(m[i], m[j]) > 1):
return []
M = m[i]*M
x = []
for i in range(n):
#(M//mi) * inverse(M//mi) * inverse(ai) * bi
ai = (multiplicative_inverse(a[i], m[i]) * b[i])%m[i]
xi = (M//m[i]) * multiplicative_inverse(M//m[i], m[i]) * ai
x.append(xi)
return x
# method 2 needs improvement
# def system_of_congruences_2(a, b, m):
# M = 1
# n = len(a)
# if(n == 0):
# return []
# for i in range(n):
# if b[i]%gcd(a[i], m[i])!=0:
# return []
# x = solutions_of_congruence(a[0], b[0], m[0])
# l = []
# for i in x:
# flag = 1
# for j in range(n):
# if((a[j]*i)%m[j] != b):
# flag = 0
# break
# if flag == 1:
# l.append(i)
# return l
def __main__():
args = sys.argv
n = int(args[1])
a = []
b = []
m = []
for i in range(n):
a.append(int(args[3*i + 2]))
b.append(int(args[3*i + 3]))
m.append(int(args[3*i + 4]))
ans = system_of_congruences_1(a, b, m)
if(len(ans) == 0):
print("N")
else:
print("Y", end=" ")
n = len(ans)
for i in range(n-1):
print(ans[i], end=" ")
print(ans[n-1], end="")
__main__()
|
print('my name is')
for i in range(3):
print('Jimmy Five Time (' + str(i) + ')')
|
def is_multiple(n, m):
if n % m == 0:
return True
else:
return False
print(is_multiple(20, 5))
print(is_multiple(13, 5))
|
def remove(word):
punc = ['.', ',', '!', '?', ':', ';', '-']
new_word = ''
for i in word:
if i not in punc: new_word += i
return new_word
print(remove('apple?'))
print(remove('hd,a:sie,w-n,fe;dw!!!'))
|
import random
import string
from words import Words
class Hangman:
guesses = 8
lettersGuessed = []
__guessed = ''
def __init__(self, words):
self.__words = words
def start(self):
print 'Welcome to the game, Hangam!'
print 'I am thinking of a word that is', len(self.__words.secretWord), ' letters long.'
print '-------------'
def game(self):
print 'You have ', self.guesses, 'guesses left.'
self.__getAvailable()
letter = raw_input('Please guess a letter: ')
if letter in self.lettersGuessed:
self.__getGuessed()
print 'Oops! You have already guessed that letter: ', self.guesses
elif letter in self.__words.secretWord:
self.lettersGuessed.append(letter)
self.__getGuessed()
print 'Good Guess: ', self.__guessed
else:
self.guesses -=1
self.lettersGuessed.append(letter)
self.__getGuessed()
print 'Oops! That letter is not in my word: ', self.__guessed
print '------------'
def __getAvailable(self):
available = self.__words.getAvailableLetters()
for letter in available:
if letter in self.lettersGuessed:
available = available.replace(letter, '')
print 'Available letters', available
return available
def __getGuessed(self):
self.__guessed = self.__words.getGuessedWord()
for letter in self.__words.secretWord:
if letter in self.lettersGuessed:
self.__guessed += letter
else:
self.__guessed += '_ '
def end(self):
if self.__words.isWordGuessed(self.__words.secretWord, self.lettersGuessed) == True:
print 'Congratulations, you won!'
else:
print 'Sorry, you ran out of guesses. The word was ', self.__words.secretWord, '.'
|
import csv
def entry2csv(listdata):
# enters list data to csv file
with open("student_data.csv", 'a', newline = '') as datafile:
entry = csv.writer(datafile)
if datafile.tell() == 0:
entry.writerow(['Name', 'Age', 'Ph No.', 'Email ID'])
entry.writerow(listdata)
def lwrcase(txt):
# converting in lowercase
txt_l = ""
for i in txt:
if (ord(i) >= 65 and ord(i) <= 90):
txt_l = txt_l + chr(ord(i) + 32)
else:
txt_l = txt_l + i
return txt_l
def numsuffix(num):
# adding suffix to number
nS = ""
n_l = num % 10
if num % 100 >= 11 and num % 100 <= 19:
nS = str(num)+"th"
elif n_l == 1:
nS = str(num)+"st"
elif n_l == 2:
nS = str(num)+"nd"
elif n_l == 3:
nS = str(num)+"rd"
else:
nS = str(num)+"th"
return nS
def inptverif(txt):
# checking for blank inputs
verif = False
while(not verif):
inpt = input(f"\t{str(txt)}\t: ")
if inpt == "":
print("Entry cannot be blank, Please enter valid info.")
verif = False
else:
verif = True
return inpt
if __name__ == '__main__':
# Taking entries
entr = True
n = 1
while(entr):
# filling info
print(f"\nEnter {numsuffix(int(n))} student's following information:")
s_name = inptverif("Name\t")
typ_chk = False
while(not typ_chk):
try:
s_age = int(inptverif("Age (In years)"))
typ_chk = True
except ValueError:
print("Age should be a Whole Number, Please enter valid info.")
typ_chk = False
s_ph = inptverif("Phone number")
s_email = inptverif("Email ID")
info_list = [s_name, s_age, s_ph, s_email] # listing info
# condition to check entry
print("\nPlease verify the info:")
print(f"\tName:\t\t{info_list[0]}\n\tAge:\t\t{info_list[1]}\n\tPhone Number:\t{info_list[2]}\n\tEmail ID:\t{info_list[3]}")
try_chk = False
while(not try_chk):
chk = input("\nIs the entered info correct? (y/n): ")
chk = lwrcase(chk)
if chk == "y":
entry2csv(info_list)
print("\nEntry Uploaded!\n")
# condition to ask next entry
try_info = False
while(not try_info):
nN = int(n + 1)
rep = input(f"\nWish to enter {numsuffix(nN)} student's info? (y/n): ")
rep = lwrcase(rep)
if rep == "y":
n += 1
try_info = True
elif rep == "n":
entr = False
try_info = True
else:
print("Wrong Input!")
try_info = False
try_chk = True
elif chk == "n":
try_chk = True
else:
print("Wrong Input!")
try_chk = False
|
"""Doubly-linked list class definition.
Defines a general purpose doubly-linked list data structure with a nested class to define the nodes of the list.
.. _React Library:
https://github.com/hivebattery/gui/blob/master/driver/react/data_structures/doubly_linked_list.py
"""
class DoublyLinkedList(object):
"""General purpose doubly-linked list.
Behaves as a FIFO.
Attributes:
__sentinel (DoublyLinkedList.DoublyLinkedListNode): The list's sentinel with a dummy value.
__auto_pop (bool): Whether nodes should be removed after iterating through them.
__size (int): The number of elements currently in the list.
"""
class DoublyLinkedListNode(object):
"""General purpose doubly-linked list node.
"""
def __init__(self, val):
"""Doubly-linked List Node constructor.
Initializes the node to the default i.e. a node that's not in any list. The object to be stored
in the node is also specified here.
Args:
val: The object to be stored in the node.
"""
self.__next = self
self.__prev = self
self.__value = val
def __str__(self):
"""Stringify node.
Provides a more representative string representation of this node.
Returns:
str: The string representation of the object stored in this node.
"""
return str(self.value)
@property
def next(self):
"""DoublyLinkedList.DoublyLinkedListNode: The node inserted to the list right before this one.
"""
return self.__next
@next.setter
def next(self, value):
self.__next = value
@property
def prev(self):
"""DoublyLinkedList.DoublyLinkedListNode: The node inserted to the list right after this one.
"""
return self.__prev
@prev.setter
def prev(self, value):
self.__prev = value
@property
def value(self):
"""The object stored in the node.
"""
return self.__value
@value.setter
def value(self, value):
self.__value = value
def splice_right(self, node):
"""Adds a new node to the right of the sentinel.
Args:
node (DoublyLinkedList.DoublyLinkedListNode): The node to be spliced in.
"""
node.next = self.next
node.prev = self
self.next = node
node.next.prev = node
def splice_out(self):
"""Removes a node from the list.
"""
self.prev.next = self.next
self.next.prev = self.prev
def __init__(self, auto_pop=False):
"""Doubly-linked List constructor.
Initializes the list to the default i.e. an empty list with a sentinel.
Args:
auto_pop (bool): See `self.auto_pop`.
"""
self.__sentinel = self.DoublyLinkedListNode(None)
self.__auto_pop = auto_pop
self.__size = 0
def __len__(self):
"""`self.__size` getter.
Returns:
int: The number of elements in the list.
"""
return self.__size
def __str__(self):
"""Stringify the entire list.
Joins the string representation of each nodes with a comma.
Returns:
str: The string representation of the list.
"""
return ", ".join([str(node) for node in self])
def __iter__(self):
"""List iterator.
If auto pop is active, all elements are removed after being yielded.
Yields:
The object in the next node.
"""
node = self.__sentinel.prev
while not self.__is_sentinel(node):
val = node.value
prev_node = node.prev
if self.__auto_pop:
self.__size -= 1
node.splice_out()
node = prev_node
yield val
def __copy__(self):
"""Clone this list.
Returns:
DoublyLinkedList: A deep copy of the list.
"""
copy = DoublyLinkedList()
for node in self:
copy.insert(node)
return copy
def insert(self, val):
"""Insert a new object to the list.
A new node is created to hold this object.
Args:
val: The object to be inserted.
"""
node = self.DoublyLinkedListNode(val)
self.__sentinel.splice_right(node)
self.__size += 1
def remove(self, val):
"""Remove the node that contains this specific object.
Given that this method relies on the object's implementation of `__eq__` and that there is no indexing,
the time complexity to remove an object is O(n).
Args:
val: The object to be removed.
Returns:
bool: True if the object was matched and removed, False otherwise.
"""
node = self.__sentinel.prev
while not self.__is_sentinel(node):
if node.value == val:
node.splice_out()
return True
node = node.prev
return False
def is_empty(self):
"""Check if the list is empty.
Returns:
bool: True if the list is empty, False otherwise.
"""
return self.__size == 0
def pop(self):
"""Return and remove the element that was inserted first to the list.
Returns:
The object in the node removed.
"""
if not self.is_empty():
val = self.__sentinel.prev.value
self.__sentinel.prev.splice_out()
self.__size -= 1
else:
val = None
return val
def clear(self):
"""Reset the list to its default, empty state.
"""
self.__sentinel = self.DoublyLinkedListNode(None)
self.__size = 0
def toggle_auto_pop(self):
"""Activate or deactivate the auto pop feature.
Note:
See `self.__auto_pop`.
"""
self.__auto_pop = not self.__auto_pop
def get_last(self):
"""Return the element that was inserted first to the list, without removing it.
Returns:
The object in the node that was first inserted to the list.
"""
return self.__sentinel.prev
@staticmethod
def __is_sentinel(node):
"""Checks if the node is the sentinel.
Args:
node (DoublyLinkedList.DoublyLinkedListNode): The node that will be subjected to the test.
Returns:
bool: True if the node is the sentinel, False otherwise.
"""
return node.value is None
|
n=int(input('n='))
if (n==28) or (n==29):
print('februarie')
if n==30:
print('aprilie','iunie','septembrie','noiembrie')
if n==31:
print('ianuarie','martie','mai','iule','august','octombrie','decembrie')
if (n<28) or (n>31):
print('numar de zile invalid')
|
# -*-encoding=utf-8-*-
"""
全面复习各种奇怪的排序
"""
"""
直接插入排序
"""
def insert_sort(nums):
for i in range(1, len(nums)):
tmp = nums[i]
j = i - 1
while j >= 0 and tmp < nums[j]:
nums[j+1] = nums[j]
j -= 1
nums[j+1] = tmp
return nums
"""
归并排序
"""
def merge_sort(nums):
if len(nums) == 1:
return nums
else:
mid = len(nums) / 2
left = merge_sort(nums[:mid])
right = merge_sort(nums[mid:])
return merge(left, right)
def merge(nums1, nums2):
i = 0
j = 0
len1 = len(nums1)
len2 = len(nums2)
ans = []
while i < len1 and j < len2:
if nums1[i] < nums2[j]:
ans.append(nums1[i])
i += 1
else:
ans.append(nums2[j])
j += 1
if i == len1:
ans.extend(nums2[j:])
else:
ans.extend(nums1[i:])
return ans
"""
堆排序
"""
def heap_sort(nums):
build_heap(nums)
length = len(nums)
for i in range(1, length+1):
nums[0], nums[length - i] = nums[length - i], nums[0]
adjust(nums, 0, length - i)
return nums
def build_heap(nums):
length = len(nums)
for i in range(length/2, -1, -1):
adjust(nums, i, length)
def adjust(nums, i, l):
"""
最大堆
"""
max_idx = i
if 2 * i + 2 < l:
if nums[2 * i + 2] > nums[max_idx]:
max_idx = 2 * i + 2
if 2 * i + 1 < l:
if nums[2 * i + 1] > nums[max_idx]:
max_idx = 2 * i + 1
if max_idx != i:
nums[i], nums[max_idx] = nums[max_idx], nums[i]
adjust(nums, max_idx, l)
"""
快排
"""
def quick_sort(nums):
helper(nums, 0, len(nums) - 1)
return nums
def helper(nums, start, end):
if start < end:
p = divide(nums, start, end)
helper(nums, start, p-1)
helper(nums, p+1, end)
def divide(nums, start, end):
"""
nums[j] 是有序区的最后一个比pivot小的数
nums[j+1] 是有序区的第一个比pivot大的数
"""
pivot = nums[end]
j = start - 1
for i in range(start, end):
if nums[i] < pivot:
nums[j+1], nums[i] = nums[i], nums[j+1]
j += 1
nums[end] = nums[j+1]
nums[j+1] = pivot
return j+1
print insert_sort([4,9,3,2,5,6,8,7,1])
print merge_sort([4,9,3,2,5,6,8,7,1])
print heap_sort([4,9,3,2,5,6,8,7,1])
print quick_sort([4,9,3,2,5,6,8,7,1])
|
import numpy
def u(ary1, ub):
print(ary1)
print(ary1.__len__())
std = numpy.std(ary1)
average = numpy.average(ary1)
ua = std/numpy.sqrt(ary1.__len__())
U = numpy.sqrt(float(ua)**2+float(ub)**2)
return {
'平均数': f'{average}',
'标准差': f'{std}',
'Ua': f'{ua}',
'Ub': f'{ub}',
'U': f'{U}'
}
if __name__ == '__main__':
print('输入数据数目:')
n = int(input())
print('输入\n')
arys = input().split(' ')
arys = [float(i) for i in arys]
print('输入Ub!:')
ub = input()
print(u(arys, ub))
|
class minHeap:
def __init__(self):
self.heapList = [0]
self.size = 0
def percUp(self, i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heapList[i] = tmp
i = i // 2
def insert(self, k):
self.heapList.append(k)
self.size += 1
self.percUp(self.size)
def percDown(self, i):
while (i * 2) <= self.size:
min = self.minChild(i)
if self.heapList[i] > min:
temp = self.heapList[i]
self.heapList[i] = self.heapList[min]
self.heapList[min] = temp
i = min
def minChild(self, i):
if i * 2 + 1 > self.size:
return i * 2
else:
if self.heapList[i * 2] < self.heapList[i * 2 + 1]:
return i * 2
else:
return i * 2 + 1
def delMin(self):
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.size]
self.size -= 1
self.heapList.pop()
self.percDown(1)
return retval
# def heapSort(self):
# def buildHeap(self, alist):
# i = len(alist // 2)
# self.size = len(alist)
# self.heapList = [0] + alist[:]
# while i > 0:
# self.percDown(i)
# i -= 1
class heap:
def __init__(self):
self.heapList = [0]
self.size = 0
self.arr = []
def percUp(self, i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[i // 2]
self.heapList[i // 2] = tmp
i = i // 2
def insert(self, k):
self.heapList.append(k)
self.size += 1
self.percUp(self.size)
def minChild(self, i):
if i * 2 + 1 > self.size:
return i * 2
else:
if self.heapList[i * 2] < self.heapList[i * 2 + 1]:
return i * 2
else:
return i * 2 + 1
def percDown(self, i):
while (i * 2) <= self.size:
min = self.minChild(i)
if self.heapList[i] > self.heapList[min]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[min]
self.heapList[min] = tmp
i = min
def delMin(self):
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.size]
self.size -= 1
self.heapList.pop()
self.percDown(1)
return retval
def heapSort(self):
while self.size > 0:
tmp = self.heapList[1]
self.heapList[1] = self.heapList[self.size]
self.heapList[self.size] = tmp
val = self.heapList.pop()
self.size -= 1
self.arr.append(val)
self.percDown(1)
heap = heap()
heap.insert(4)
heap.insert(9)
heap.insert(10)
heap.insert(11)
heap.delMin()
heap.insert(5)
heap.insert(123)
heap.insert(32)
heap.insert(12)
heap.insert(17)
heap.insert(19)
print(heap.heapList)
heap.heapSort()
print(heap.heapList)
print(heap.arr)
# newheap = minHeap()
# newheap.buildHeap([1, 5, 34,2, 5, 7,3 ,57,6 ,7 ])
# print(newheap.heapList)
|
import turtle
import random
myTurtle = turtle.Turtle()
myWin = myTurtle.screen
def draw_spiral(myTurtle, linelen):
if linelen > 0:
myTurtle.forward(linelen)
myTurtle.right(90)
draw_spiral(myTurtle, linelen - 5)
# draw_spiral(myTurtle, 150)
# myWin.exitonclick()
def tree(branchLen, t):
if branchLen > 5:
t.forward(branchLen)
t.right(20)
tree(branchLen-15, t)
t.left(40)
tree(branchLen-15, t)
t.right(20)
t.backward(branchLen)
def tree_2(branchLen, t):
t.width(branchLen * 0.04)
if branchLen > 5:
t.width(branchLen * 0.04)
rand = random.randint(1, 100)
t.forward(branchLen)
t.right(rand)
tree(branchLen - 15, t)
t.left(rand)
tree(branchLen - 15, t)
t.right(rand)
t.backward(branchLen)
def main():
t = turtle.Turtle()
myWin = turtle.Screen()
t.left(90)
t.up()
t.backward(100)
t.down()
t.color("green")
tree_2(100, t)
myWin.exitonclick()
main()
|
def insertion_sort(arr):
for k in range(1, len(arr)):
value = arr[k]
position = k
while position > 0 and arr[position - 1] > value:
arr[position] = arr[position - 1]
position -= 1
arr[position] = value
return arr
test_arr = [11, 5, 2, 7, 48, 12, 443, 0, 3, 8, 4, 6]
print(insertion_sort(test_arr))
|
#descrip_stat.py功能: 以自訂函數寫法計算敍述統計並回傳
import math
def depsta(sample):
#depsta功能: 計算樣本的敍述統計
maxv=max(sample)
minv=min(sample)
meanv=sum(sample)/len(sample)
sumi=0
for i in range(0, len(sample)):
sumi=sumi+((sample[i]-meanv)**2)
varv=sumi/(len(sample)-1)
stdv=math.sqrt(varv)
return(maxv, minv, meanv, varv, stdv)
sample=[5,8,9,6,4,1,5,3,6,2]
print('max=%2.1f,min=%2.1f, mean=%2.1f,var=%2.1f,std=%2.1f'%(depsta(sample)))
|
#RC_6_4 功能: 終值
def fvfix(pv, i, n):
#fvfix: 計算終值公式
result=pv*(1+i)**n
return(result)
pv=100
i=0.03
n=int(input('計算終值的年數 = '))
print('%d年後的終值 = %6.2f' %(n, fvfix(pv, i, n)))
|
#E_7_13: 檔案更名與檔案刪除
import os
import os.path
PATH1='./file/WangWei_poetry_1.txt'
PATH2='./file/WangWei_poetry_2.txt'
if os.path.isfile(PATH1) and os.access(PATH1, os.R_OK):
os.rename('./file/WangWei_poetry_1.txt', '辛夷塢王維.txt')
print('%s檔案已更名%s' %('WangWei_poetry_1.txt','辛夷塢王維.txt'))
else:
print('WangWei_poetry_1.txt檔案不存在')
if os.path.isfile(PATH2) and os.access(PATH2, os.R_OK):
os.remove(PATH2)
print('%s檔案已刪除' %('WangWei_poetry_2.txt'))
else:
print('WangWei_poetry_2.txt檔案不存在')
|
#E_5_1 功能: 輸入一個數值,判斷若小於50則開根號乘以10
import math
num=int(input('請輸入任一數'))
Tt=num
if num<50:
Tt=math.sqrt(num)*10
print(num,Tt)
|
#E_6_8.py 功能: 預設參數的使用範例
import math
def defaultscore(score=40):
#defaultscore: 判斷若小於50則開根號乘以10
if score<50:
return math.sqrt(score)*10
else:
return score
name='Jack'
ss=[16,'',36,55,'']
for ii in ss:
if type(ii) is int:
result=defaultscore(ii)
else:
result=defaultscore()
print('%s 的成績 = %4.2f ' % (name, result))
|
import abc
class Leifeng:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def wash(self):
""""wash"""
@abc.abstractmethod
def sweep(self):
"""sweep"""
@abc.abstractmethod
def buy_rice(self):
"""buy rice"""
class Undergraduate(Leifeng):
def wash(self):
print "undergraduate wash"
def sweep(self):
print "undergraduate sweep"
def buy_rice(self):
print "undergraduate buy rice"
class Volunteer(Leifeng):
def wash(self):
print "volunteer wash"
def sweep(self):
print "volunteer sweep"
def buy_rice(self):
print "volunteer buy rice"
class IFactory:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def CreateLeifeng(self):
"""create class leifeng"""
class UndergraduateFactory(IFactory):
def CreateLeifeng(self):
return Undergraduate()
class VolunteerFactory(IFactory):
def CreateLeifeng(self):
return Volunteer()
if __name__ == "__main__":
# create undergraduate to sweep
i_factory = UndergraduateFactory()
leifeng = i_factory.CreateLeifeng()
leifeng.sweep()
# create volunteer to wash
i_factory = VolunteerFactory() # just replace UndergraduateFactory with VolunteerFactory
leifeng = i_factory.CreateLeifeng()
leifeng.wash()
|
#E_5_3 功能: 成績分等級
score=int(input('輸入成績0-100分: '))
grade='輸入'
if score<60: #條件1
grade='戊等'
elif score <70: #條件2
grade='丁等'
elif score<80: #條件3
grade='丙等'
elif score<90: #條件4
grade='乙等'
elif score<=100: #條件5
grade='甲等'
else: #條件6
grade='輸入錯誤'
print (score,grade)
|
#RC_6_8 功能: 年金給付金額
def annuity(pv, i, n):
#annuity: 計算年金公式
up=i*((1+i)**n)
down=((1+i)**n)-1
result=pv*(up/down)
return(result)
i=0.03
n=int(input('輸入貸款年數 = '))
pv=1000000
print('每年應付貸款金額 = %10.2f' %(annuity(pv, i,n)))
|
#E_5_8 功能: 計算1-(1/n)的函數。
n=int(input('Please input n : '))
result=0
for i in range(2,n+1,1):
result=result+(1-(1/i))
print('%s %.2f' %('The result is ', result))
|
#!/usr/bin/env python
"""
This is an example for python docstring, including modules,
functions, classes, methods, etc.
"""
import math
print math.__doc__ # standard modules' docstring.
print str.__doc__ # standard function docstring.
print '#' * 65
def foo():
"""It's just a foo() function."""
pass
class foobar(object):
"""It's just a foobar class."""
def bar(self):
"""It's just a foobar.bar() function."""
pass
def get_doc(self):
return self.__doc__
f = foobar()
print f.__doc__
print f.get_doc()
print __doc__
print foo.__doc__
print foobar.__doc__
print foobar.bar.__doc__
print '#' * 65
#from pydoc import help
#def foobar():
# """
# It's just a foobar function.
# """
# return
#help(foobar)
|
#sumn_def.py功能: 主程式呼叫1層自訂函數
def sumnfunc(n):
#A_func功能: 計算累加
sumn=0
for i in range(n+1):
sumn=sumn+i
return(sumn)
num=int(input('輸入一個正整數n = '))
result=sumnfunc(num)
print('1累加到n的結果 = ', result)
|
# Coding Challenge Level 2 - Find the max and min of a Python Set
#
# Print the max and min numbers of this set
# set([15, 11, 8, 15, 32, 20])
# For example 8 and 32
example_set = ([15, 11, 8, 15, 32, 20])
# Approach 1 - Using the built-in functions:
print("\nBuilt-in functions:")
print("The maximum number in the set is " + str(max(example_set)) + ".")
print("The minimum number in the set is " + str(min(example_set)) + ".")
# Approach 2 - Creating and using custom functions:
def get_max(data_set):
maximum = data_set[0]
for element in data_set:
if element > maximum:
maximum = element
return maximum
def get_min(data_set):
minimum = data_set[0]
for element in data_set:
if element < minimum:
minimum = element
return minimum
print("\nCustom functions:")
print("The maximum number in the set is " + str(get_max(example_set)) + ".")
print("The minimum number in the set is " + str(get_min(example_set)) + ".")
|
import numpy as np
class Net():
"""
Implements a neural network with a user-determined number and size of hidden layers.
Except for the final hidden layer, each hidden layer is followed
by a non-linear function f(x) = x when x >= 0, x/100 when x < 0.
Predicts by selecting the index of the maximum output.
Trains by minibatch gradient descent using a softmax loss function + regularization.
"""
def __init__(self, input_size, hidden_sizes, output_size, std=1e-4, bstd=1e-4):
"""
Initializes the network.
input_size = the length of each individual input vector
hidden_sizes = a list specifying how many nodes are in each hidden layer, e.g. [], [2], [3,3]
output_size = the number of class labels in the prediction task
std = the standard deviation to use for initializing weights
bstd = the standard deviation to use for initializing biases
"""
num_hidden_layers = len(hidden_sizes)
# initialize weight matrices
self.weights = []
if num_hidden_layers > 0:
for i in xrange(num_hidden_layers):
if i == 0:
self.weights.append(std * np.random.randn(input_size, hidden_sizes[0]))
else:
self.weights.append(std * np.random.randn(hidden_sizes[i-1], hidden_sizes[i]))
self.weights.append(std * np.random.randn(hidden_sizes[-1], output_size))
else:
self.weights.append(std * np.random.randn(input_size, output_size))
# initialize bias vectors
self.biases = []
for i in xrange(num_hidden_layers):
self.biases.append(bstd * np.random.randn(hidden_sizes[i]))
self.biases.append(bstd * np.random.randn(output_size))
def loss(self, X, y=None, reg=0.0):
"""
Computes the class scores for X.
X = numpy.array whose rows are the input vectors
If y is provided, this function also computes the loss function
as well as the gradients for use in training.
y = numpy.array whose rows y[i] are the correct class labels (indices in 0,...,output_size-1) for the corresponding X[i]
reg = the regularization parameter, which scales the regularization
term in the loss function.
"""
Ws = self.weights
bs = self.biases
N, D = X.shape # number of samples, number of features per sample
# Compute the forward pass
self.activations = []
for i in xrange(len(Ws)): # for each set of weights
W,b = Ws[i], bs[i]
if i == 0:
H = np.dot(X,W) + b
else:
H = np.dot(self.activations[-1],W) + b
if i < len(Ws) - 1: # if we're computing hidden activations, apply nonlinear function
H = (H > 0) * (H) + (H < 0) * (H/100.0)
self.activations.append(H)
scores = self.activations[-1]
# If there's no labels provided, stop here
if y is None:
return scores
# Compute the loss
exped_scores = np.exp(scores)
sums = np.sum(exped_scores,axis=1)
# softmax classifier loss
data_loss = (-1.0/N) * np.sum(np.log(exped_scores[range(N),y.astype(int)] / sums))
# loss due to regularization
reg_loss = 0
for i in xrange(len(Ws)):
reg_loss += np.sum(Ws[i]**2)
reg_loss *= reg*(0.5)
loss = data_loss + reg_loss
# Compute gradients
weights_grads = []
biases_grads = []
activation_grads = []
for i in xrange(len(Ws)):
weights_grads.append(np.copy(Ws[i]))
biases_grads.append(np.copy(bs[i]))
activation_grads.append(np.copy(self.activations[i]))
DlossDscores = np.array(exped_scores / (N * np.matrix(sums).T))
DlossDscores[range(N),y.astype(int)] -= (1.0/N)
for i in xrange(len(Ws)-1,-1,-1):
if i == 0:
weights_grads[0] = np.dot(X.T, activation_grads[0]) + reg*Ws[0]
biases_grads[0] = np.dot(np.ones((1,N)), activation_grads[0])[0]
elif i == len(Ws)-1:
H = self.activations[i-1]
weights_grads[i] = np.dot(H.T, DlossDscores) + reg*Ws[i]
biases_grads[i] = np.dot(np.ones((1,N)), DlossDscores)[0]
dH = np.dot(DlossDscores, Ws[i].T)
activation_grads[i-1] = dH
else:
H = self.activations[i-1]
dH_out = activation_grads[i]
weights_grads[i] = np.dot(H.T, dH_out) + reg*Ws[i]
biases_grads[i] = np.dot(np.ones((1,N)), dH_out)[0]
dH = np.dot(dH_out, Ws[i].T)
dH = dH * (H > 0) + dH/100.0 * (H < 0)
activation_grads[i-1] = dH
grads = {}
grads['weights'] = weights_grads
grads['biases'] = biases_grads
return loss, grads
def train(self, X, y, X_val, y_val,
learning_rate=1e-3, learning_rate_decay=0.95,
reg=1e-5, num_iters=100,
batch_size=200, verbose=False):
"""
Trains the network via minibatch gradient descent.
X = numpy.array whose rows are the input vectors
y = numpy.array whose rows y[i] are the correct class labels for X[i]
learning_rate = number that scales the gradient descent steps
learning_rate_decay = number that scales the learning_rate after each training epoch
reg = the regularization parameter, scales the regularization term in the loss function
num_iters = how many minibatch gradient descent steps to take
batch_size = the size of each minibatch, if 0, will train with full batches
verbose = bool, whether to print loss, learning rate during training
"""
num_train = X.shape[0]
if batch_size > 0:
iterations_per_epoch = max(num_train / batch_size, 1)
else:
iterations_per_epoch = max(num_train / len(X), 1)
for it in xrange(num_iters):
X_batch = None
y_batch = None
# create minibatch
if batch_size > 0:
indices = np.random.choice(X.shape[0],batch_size)
X_batch = X[indices]
y_batch = y[indices]
else:
X_batch = X
y_batch = y
# Compute loss and gradients using the current minibatch
loss, grads = self.loss(X_batch, y=y_batch, reg=reg)
for i in xrange(len(self.weights)):
self.weights[i] -= grads['weights'][i] * learning_rate
self.biases[i] -= grads['biases'][i] * learning_rate
if verbose and it % 100 == 0:
print 'iteration %d / %d: loss %f, learning rate %f' % (it, num_iters, loss, learning_rate)
# Every epoch, decay the learning rate
if it % iterations_per_epoch == 0:
learning_rate *= learning_rate_decay
def predict(self, X):
"""
Returns the predicted class labels (indices in 0,...,output_size) for input X.
"""
y_pred = np.argmax(self.loss(X),axis=1)
return y_pred
|
from collections import deque
from typing import Optional, Set, Text
LIMIT = 3
class Manager:
def __init__(self, limit: Optional[int] = LIMIT) -> None:
self.queue = deque() # 待抓取的网页
self.visited = dict() # 已抓取的网页
self.limit = limit # 进入待爬取队列重试上限
if self.limit is None:
self.limit = LIMIT
def new_url_size(self) -> int:
"""获取待爬取 URL 集合的大小"""
return len(self.queue)
def old_url_size(self) -> int:
"""获取已爬取 URL 集合的大小"""
return len(self.visited)
def has_new_url(self) -> bool:
"""判断是否有待爬取的 URL"""
return self.new_url_size() != 0
def get_new_url(self) -> Text:
"""获取一个待爬取的 URL
在已爬取中为该 URL 计数
"""
new_url = self.queue.popleft() # 从左侧取出一个链接
if new_url in self.visited: # 记录已经爬取
self.visited[new_url] += 1
else:
self.visited[new_url] = 1
return new_url
def add_new_url(self, url: Optional[Text] = None) -> bool:
"""将新的单个 URL 添加到待爬取的 URL 集合
若该 URL 已爬取,只要没超过限制范围,依然可以添加到待爬取集合
"""
if url is None or url in self.queue:
return False
if url not in self.visited:
self.queue.append(url)
return True
else:
if self.visited[url] < self.limit:
self.queue.append(url)
return True
else:
return False
def add_new_urls(self, urlset: Optional[Set[Text]] = None) -> None:
"""将新的多个 URL 添加到待爬取的 URL 集合"""
if urlset is None or len(urlset) == 0:
return
for url in urlset:
self.add_new_url(url)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The tests."""
from unittest import TestCase
from fzbz import FizzBuzz
class FzBzTest(TestCase):
"""Fizz Buzz Test."""
def setUp(self):
"""Setup."""
self.obj = FizzBuzz()
def test_num(self):
"""The return value should be based of FizzBuzz."""
for n in range(100):
with self.subTest(n=n):
ret = self.obj()
exp = "FizzBuzz" if n % 3 == 0 and n % 5 == 0 else \
"Fizz" if n % 3 == 0 and n % 5 != 0 else \
"Buzz" if n % 3 != 0 and n % 5 == 0 else \
str(n)
self.assertEqual(ret, exp)
|
rival = -999999
contador = 0
while True:
jugador = int(input("Dame tu mejor numero: "))
if jugador == -1:
break
contador = 1
if jugador > rival:
rival = jugador
if contador != 0:
print("el nuevo rival es: ",rival)
# Otro código
while True:
palabra = input('Rompe el hechizo: ')
if palabra == 'chupacabra':
break
print('Has salido del ciclo')
|
# Si el ingreso del ciudadano no era superior a 85,528 pesos, el impuesto era igual al 18% del ingreso menos 556 pesos y 2 centavos
# (esta fue la llamada exención fiscal ).
# Si el ingreso era superior a esta cantidad, el impuesto era igual a 14,839 pesos y 2 centavos, más el 32% del excedente sobre 85,528 pesos.
# Nota: Este país feliz nunca devuelve dinero a sus ciudadanos. Si el impuesto calculado es menor que cero,
# solo significa que no hay impuesto (el impuesto es igual a cero). Ten esto en cuenta durante tus cálculos.
ingreso = float(input("Cuál es tu ingreso anual?: "))
if ingreso >1 and ingreso <= 85526:
ipi = (ingreso*.18) - 556.2
print("Tu impuesto IPI asciende a la cantidad de: ",round(ipi,0))
elif ingreso <= 0:
print("No tiene que pagar impuestos!")
else:
excedente = ingreso - 85528
ipi = 14839.2 + (excedente*.32)
print("Tu impuesto IPI asciende a la cantidad de: ",round(ipi,0))
|
def validate(n):
n_list = [int(x) for x in str(n)]
doubled_list = list()
# Even
if len(n_list) % 2 == 0:
doubled_list = [x*2 if index % 2 != 0 else x for index, x in enumerate(n_list, 1)]
# Odd
else:
doubled_list = [x*2 if index % 2 == 0 else x for index, x in enumerate(n_list, 1)]
cleaned_list = [int(str(x)[0]) + int(str(x)[1]) if x > 9 else x for x in doubled_list]
return sum(cleaned_list) % 10 == 0
print(validate(input('Input Credit Card Number')))
# Passed
|
items = []
num_items = int(input("How many items have you got? : "))
for i in range(0, num_items):
item = [input("\nLabel: "), int(input("Size: "))]
items.append(item)
print("Your items are: "+str(items))
bin_size = int(input("What is the size of your bins/containers? : "))
bins = [["bin1", bin_size, []]] #bin array [bin_name, remaining capacity, [items]]
#bubble sort
def bubbleSort(arr):
for i in range(len(arr)-1):
for j in range(0, len(arr)-i-1):
if arr[j][1] < arr[j+1][1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
bubbleSort(items)
for i in range(0, len(items)): # for every item in the items array
added = False #initially they aren't added to any bin
for b in range(0, len(bins)): #for every bin in the bin array
if items[i][1] <= bins[b][1]: #check if the size of the current item is lower than the capacity of the bin
bins[b][2].append(items[i]) #if it is, add the item to that bin
bins[b][1] = bins[b][1] - items[i][1] #take the capacity of the bin added to, and subtract the size of the item
added = True #the item has been added
break #can stop checking the bins
if (added != True):
bins.append(["bin"+str(int(bins[len(bins)-1][0][3])+1), (bin_size-items[i][1]), [items[i]]])
for i in range(0, len(bins)):
print("\n"+bins[i][0]+"("+str(bin_size)+") : "+ str(bins[i][2]))
|
#!/usr/bin/env python
'''
search a fasta file for a specific sequence
Usage:
python find_sequence.py --target ATAAT < sequence.fa
'''
import argparse
import collections
import logging
import sys
def reverse_complement(sequence):
'''
return the reverse complement of the input sequence
TODO: YOU NEED TO IMPLEMENT THIS
'''
return sequence
def find_target(target):
'''
given a target sequence, read the fasta sequence from stdin and report
any exact matches
'''
# this section reads the entire fasta file from stdin
# and stores the sequence in the fasta variable
logging.info('reading fasta file...\n')
fasta = ''
for line in sys.stdin:
if line.startswith('>'):
continue
# append the line to fasta,
# ignoring any whitespace
# we also want our string to be upper case.
fasta += line.strip().upper()
logging.info('searching %i bases...', len(fasta))
# this is the part you need to implement
# one method of finding 'target' is to slide across
# the fasta sequence with a loop and check for an exact match at
# each position.
# some potentially useful things to use
count = 0
rctarget = reverse_complement(target)
k = len(target)
# TODO: YOUR CODE HERE
logging.info("done: found %i", count)
if __name__ == '__main__':
# accept and parse command line arguments
parser = argparse.ArgumentParser(description='Find sequence')
parser.add_argument('--target', required=True, help='sequence to find')
args = parser.parse_args()
# configure program logging
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.DEBUG)
# find target in fasta (read from stdin)
find_target(args.target)
|
import argparse
def synthesize_text(speech):
"""Synthesizes speech from the input string of text."""
from google.cloud import texttospeech
client = texttospeech.TextToSpeechClient()
input_text = texttospeech.types.SynthesisInput(text=speech)
# Note: the voice can also be specified by name.
# Names of voices can be retrieved with client.list_voices().
voice = texttospeech.types.VoiceSelectionParams(
language_code='ko-KR',
ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE)
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
response = client.synthesize_speech(input_text, voice, audio_config)
# The response's audio_content is binary.
with open('output2.mp3', 'wb') as out:
out.write(response.audio_content)
#print('Audio content written to file "output2.mp3"')
# [END tts_synthesize_text]
|
num=input()
num=num.split()
num1=int(num[0])
num2=int(num[1])
val=input()
val=val.split()
list1=[]
sum1=0
for i in range(num1):
list1.append(int(val[i]))
for j in range(num2):
sum1=sum1+list1[j]
print(sum1)
|
num=int(input())
val=1
for i in range(1,num+1):
val=val*i
print(val)
|
from pprint import pprint
class Animals():
type_animals = "Живое существо"
name = "Без имени"
weight = 0
fill = 0
state = "Отдыхает"
sound = "......."
def __init__(self, name, weight):
"""
Определяем имя и вес
"""
self.name = name
self.weight = weight
def feed(self, value=10):
"""
Кормим животное
"""
print(f"Вы даёте {self.type_animals} {self.name} еды в размере {value}%")
fully_charged = self.fill + value
if fully_charged > 100:
print(f"{self.type_animals} {self.name} не может столько съесть")
else:
self.fill += value
print(f"{self.type_animals} {self.name} сыто на {self.fill}%")
def voice(self):
"""
Животное издает звук
"""
print(self.sound)
def action_start(self):
"""
Действие по умолчанию
"""
state = "Контакт"
def action_stop(self):
"""
Действие по умолчанию
"""
state = "Отдыхает"
class Goose(Animals):
type_animals = "Гусь"
sound = "Га-га-га"
def action_start(self):
self.state = "В процессе сбора яиц"
print("Начинаем собирать яйца")
def action_stop(self):
self.state = "Отдыхает"
print("Собрали сколько смогли яиц")
class Cow(Animals):
type_animals = "Корова"
sound = "Му-у-у-у"
def action_start(self):
self.state = "В процессе дойки"
print("Начинаем доить")
def action_stop(self):
self.state = "Отдыхает"
print("Закончили доить")
class Sheep(Animals):
type_animals = "Овца"
sound = "Бе-е-е-е"
def action_start(self):
self.state = "В процессе стрижки"
print("Начинаем стричь")
def action_stop(self):
self.state = "Отдыхает"
print("Закончили стричь")
class Hen(Animals):
type_animals = "Курица"
sound = "Ко-ко-ко"
def action_start(self):
self.state = "В процессе сбора яиц"
print("Начинаем собирать яйца")
def action_stop(self):
self.state = "Отдыхает"
print("Собрали сколько смогли яиц")
class Goat(Animals):
type_animals = "Коза"
sound = "Ме-е-е-е"
def action_start(self):
self.state = "В процессе дойки"
print("Начинаем доить")
def action_stop(self):
self.state = "Отдыхает"
print("Закончили доить")
class Duck(Animals):
type_animals = "Утка"
sound = "Кря-кря"
def action_start(self):
self.state = "В процессе сбора яиц"
print("Начинаем собирать яйца")
def action_stop(self):
self.state = "Отдыхает"
print("Собрали сколько смогли яиц")
def choose_animal():
"""
Выбор животное пользователем
"""
print('\nВы приехали помогать на ферму Дядюшки Джо и видите вокруг себя множество разных животных: \
\nгусей "Серый" (g1) и "Белый" (g2) \
\nкорову "Маньку" (c1)\
\nовец "Барашек" (s1) и "Кудрявый" (s2)\
\nкур "Ко-Ко" (h1) и "Кукареку" (h2)\
\nкоз "Рога" (g1) и "Копыта" (g2)\
\nи утку "Кряква" (d1)')
user_command = input("\nВыберите животного: ")
if user_command == "g1":
return goose1
elif user_command == "g2":
return goose2
elif user_command == "c1":
return cow1
elif user_command == "s1":
return sheep1
elif user_command == "s2":
return sheep2
elif user_command == "h1":
return hen1
elif user_command == "h2":
return hen2
elif user_command == "g1":
return hen1
elif user_command == "g2":
return hen2
elif user_command == "d1":
return duck1
else:
print("Извините, других животных тут нет")
def which_animal_is_yours(choose):
"""
Поиск животное в базе фермы
"""
for animal in farm:
if animal == choose:
print(f"Вы выбрали - {animal.type_animals} {animal.name}")
return animal
def which_animal_is_heaviest():
"""
Подсчет самого тяжелого животного
"""
name = ""
weight = 0
marker = 1
for animal in farm:
if animal.weight > weight:
name = animal.name
weight = animal.weight
elif animal.weight == weight:
marker = 0
else:
pass
if marker:
print(f"Самое тяжелое животное на ферме: {name}")
else:
print("Самое тяжелое животное нельзя определить, потому что их несколько")
def total_weight():
"""
Подсчет общего веса всех животных
"""
weight = 0
for animal in farm:
weight += animal.weight
print(f"Общий вес всех животных на ферме: {weight}")
def what_should_u_do(animal):
"""
Взаимодейтсвие с животными
"""
print('Со всеми животными вы можете как-то взаимодействовать: \
\nкормить (f)\
\nкорову и коз доить (start/stop)\
\nовец стричь (start/stop)\
\nсобирать яйца у кур, утки и гусей (start/stop)\
\nразличать по голосам (коровы мычат, утки крякают и т.д.) (v)')
user_command = input("Выберите действие: ")
if user_command == "f":
animal.feed()
elif user_command == "start":
animal.action_start()
elif user_command == "stop":
animal.action_stop()
print(animal.state)
elif user_command == "v":
animal.voice()
print(f"{animal.type_animals} {animal.name} издает звук {animal.sound}")
else:
print("Этого сделать нельзя")
def main():
"""
Основная функция программы
"""
my_animal = which_animal_is_yours(choose_animal())
what_should_u_do(my_animal)
total_weight()
which_animal_is_heaviest()
goose1 = Goose("Белый", 10)
goose2 = Goose("Серый", 15)
cow1 = Cow("Манька", 120)
sheep1 = Sheep("Барашек", 120)
sheep2 = Sheep("Кудрявый", 100)
hen1 = Hen("Ко-ко", 20)
hen2 = Hen("Кукареку", 20)
goat1 = Goat("Рога", 90)
goat2 = Goat("Копыта", 130)
duck1 = Duck("Кряква", 30)
farm = (goose1, goose2, cow1, sheep1, sheep2, hen1, hen2, goat1, goat2, duck1)
main()
|
import random
def choose():
#List of the words that are used.Can be changed according to you.
words=["umbrella","america","programming","debugging","festival","holidays","randomly","permutation","combination","outstanding","wonders","chocolate","cricket","football","volleyball","smartphone","smartwatch","facebook","instagram"]
chosen=random.choice(words)
return chosen
def jumbled(words):
jumbled="".join(random.sample(words, len(words)))
return jumbled
def play_game():
turn=0
score1=0
score2=0
p1=input("Player 1, Please enter your name:",)
p2=input("Player 2, Please enter your name:",)
while(1):
word=choose()
W=jumbled(word)
print("\n",W,"\n")
if(turn%2==0):
print(p1,"'s turn.")
p1ans=input("Guess the word I am thinking...",)
if(p1ans==word):
score1=score1+1
print("Correct! Your score is:",score1)
else:
print("Unfortunately that was Incorrect.The word I thought was:",word,"\n Your score remains:",score1)
else:
print(p2,"'s turn.")
p2ans=input("Guess thee word I am thinking....",)
if(p2ans==word):
score2=score2+1
print("Correct! Your score is:",score2)
else:
print("Unfortunately that was Incorrect.The word I thought was:",word,"\n Your score remains:",score2)
c=input("If you want to continue press 1 for yes 0 for no.",)
if (c=="0"):
print("Thank you for playing with us.",p1,"and",p2,"Your scores are:",score1,",",score2,"respectively.")
break
turn=turn+1
play_game()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''游戏逻辑类-总类'''
import random
import copy
# session暂时存储:
# row,col,array(暂时使用一维数组即可)
# 测试专用方法
# 行数,列数,种类数
def test(row_s, col_s, type_s):
row = 5
col = 5
type = 1
if row_s != '':
try:
row = int(row_s)
except:
row = 5
if col_s != '':
try:
col = int(col_s)
except:
col = 5
if type_s != '':
try:
type = int(type_s)
except:
type = 1
result = "{\"r\":" + str(row) + ",\"c\":" + str(col) + ",\"t\":" + str(type) + ",\"d\":[";
for i in range(0, row):
for j in range (0, col):
value = random.randint(0, type); # 0-type
result += str(value); # 1.0
if (i != (row - 1) or j != (col - 1)):
result += ",";
result += "]}";
return result
#####直接模拟
def getFirstMap(row, col):
l = [[random.choice((0, 1)) for i in range(row)] for i in range(col)] # 当前的0-1界面矩阵
return l
def getNextMap(l, row, col):
k = [[0 for i in range(row)] for i in range(col)] # 下一个0-1界面矩阵
for x in range(row):
for y in range(col):
m = getNextElement(l, x, y, row, col)
if m == 2:
k[x][y] = l[x][y]
elif m == 3:
k[x][y] = 1
else:
k[x][y] = 0
l = copy.deepcopy(k)
return l
def getNextElement(l, x, y, row, col):
m = 0
for i in (x - 1, x, x + 1):
for j in (y - 1, y, y + 1):
if i == x and y == j:
continue
if (i < 0 or i > row - 1 or j < 0 or j > col - 1):
continue
if (l[i][j]):
m += 1
return m
def getMapJson(l, row, col):
result = "{\"r\":" + str(row) + ",\"c\":" + str(col) + ",\"t\":1,\"d\":[";
for i in range(0, row):
for j in range (0, col):
value = l[i][j]; # 0-type
result += str(value); # 1.0
if (i != (row - 1) or j != (col - 1)):
result += ",";
result += "]}";
return result
#######################################以上为测试代码
|
counts = dict()
line = input(' ')
words = line.split()
for word in words :
counts[word] = counts.get(word,0) + 1
print(counts)
|
numero_filas=5
numero_columnas= 14
meses = ["","En","Feb","Mar","Ab","May","Jun","Jul","Agos","Sep","Oct","Nov","Diciem","Total "]
materias = ["","Español ","Matematicas","Geografia ","Total "]
def llenar(matriz,num_filas,num_columnas,mensaje):
print(mensaje)
res1 = 0
res2 = 0
res3 = 0
res4 = 0
res5 = 0
res6 = 0
res7 = 0
res8 = 0
res9 = 0
res10 = 0
res11 = 0
res12 = 0
mat1 = 0
elemento0 = 0
elemento2 = 0
elemento3 = 0
elemento4 = 0
elemento5 = 0
elemento6 = 0
elemento7 = 0
elemento8 = 0
elemento9 = 0
elemento10 = 0
elemento11 = 0
elemento12 = 0
final = 0
mayor=0
posicion=0
for fila in range(0, num_filas):
matriz.append( [] ) # añade una fila
for columna in range(0, num_columnas):
#elemento = int(input("Ingresa un valor "))
if fila == 0:
elemento = meses[columna]
matriz[fila].append(elemento)
if columna == 1 and fila>0:
elemento0 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[1],materias[fila])))
if columna == 1 and fila ==4 :
matriz[fila].append(res1)
else:
res1 = res1 + elemento0
matriz[fila].append(elemento0)
if columna == 2 and fila>0:
elemento2 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[2],materias[fila])))
if columna == 2 and fila == 4:
matriz[fila].append(res2)
else:
res2 = res2 + elemento2
matriz[fila].append(elemento2)
if columna == 3 and fila>0:
elemento3 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[3],materias[fila])))
if columna == 3 and fila == 4:
matriz[fila].append(res3)
else:
res3 = res3 + elemento3
matriz[fila].append(elemento3)
if columna == 4 and fila>0:
elemento4 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[4],materias[fila])))
if columna == 4 and fila == 4:
matriz[fila].append(res4)
else:
res4 = res4 + elemento4
matriz[fila].append(elemento4)
if columna == 5 and fila>0:
elemento5 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[5],materias[fila])))
if columna == 5 and fila == 4:
matriz[fila].append(res5)
else:
res5 = res5 + elemento5
matriz[fila].append(elemento5)
###
if columna == 6 and fila>0:
elemento6 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[6],materias[fila])))
if columna == 6 and fila == 4:
matriz[fila].append(res6)
else:
res6 = res6 + elemento6
matriz[fila].append(elemento6)
###
if columna == 7 and fila>0:
elemento7 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[7],materias[fila])))
if columna == 7 and fila == 4:
matriz[fila].append(res7)
else:
res7 = res7 + elemento7
matriz[fila].append(elemento7)
####
if columna == 8 and fila>0:
elemento8 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[8],materias[fila])))
if columna == 8 and fila == 4:
matriz[fila].append(res8)
else:
res8 = res8 + elemento8
matriz[fila].append(elemento8)
###
if columna == 9 and fila>0:
elemento9 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[9],materias[fila])))
if columna == 9 and fila == 4:
matriz[fila].append(res9)
else:
res9 = res9 + elemento9
matriz[fila].append(elemento9)
####
if columna == 10 and fila>0:
elemento10 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[10],materias[fila])))
if columna == 10 and fila == 4:
matriz[fila].append(res10)
else:
res10 = res10 + elemento10
matriz[fila].append(elemento10)
###
if columna == 11 and fila>0:
elemento11 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[11],materias[fila])))
if columna == 11 and fila == 4:
matriz[fila].append(res11)
else:
res11 = res11 + elemento11
matriz[fila].append(elemento11)
###
if columna == 12 and fila>0:
elemento12 = int(input("Mes: {0} \nIngresa el numero de horas para la materia de {1} ".format(meses[12],materias[fila])))
if columna == 12 and fila == 4:
matriz[fila].append(res12)
else:
res12 = res12 + elemento12
matriz[fila].append(elemento12)
if columna == 0:
elemento= materias[fila]
matriz[fila].append(elemento)
mat1 = int(elemento0) + int(elemento2) + int(elemento3) + int(elemento4) + int(elemento5) + int(elemento6) + int(elemento7) + int(elemento8) + int(elemento9) + int(elemento10) + int(elemento11) + int(elemento12)
if columna == 13:
elemento = mat1
matriz[fila].append(elemento)
final += mat1
if mat1> mayor:
mayor= mat1
posicion=fila
print("De la materia {0} estudiaste la cantida de {1} horas ".format(materias[fila],mat1))
matriz[4][13]=38
print("De la materia {0} estudiaste un total de {1} horas ".format(materias[posicion],mayor))
def imprimir(matriz):
cadena = ''
for i in range(len(matriz)):
cadena += '['
for j in range(len(matriz[i])):
cadena += ' {:>4s} '.format(str(matriz[i][j]))
cadena += ' ]\n '
return cadena
matris=[]
llenar(matris,numero_filas,numero_columnas,"Matris")
m = imprimir(matris)
print(m)
|
class Persona:
def __init__(self,nom, ed, indj):
self.nombre = nom
self.edad = ed
self.ind = indj
def mostrar(self):
print("Nombre: {} \nEdad: {}\nIND: {}".format(self.nombre, self.edad, self.ind))
def mayor(self):
if (self.edad >= 18):
print ("Es mayor de edad")
elif(self.edad < 18):
print("Es menor de edad")
name = ""
age = ""
idd = ""
name = input("Ingresa tu nombre: ")
age = int(input("Ingresa tu edad: "))
idd = input("Ingresa tu DNI: ")
Humano = Persona(name,age, idd)
Humano.mostrar()
Humano.mayor()
|
#13.1. Pide al usuario el nombre de un fichero. Si el fichero existe, muestra su contenido
#(pero no como lista, sino las líneas una a una) y si no existe, escribe un mensaje de error adecuado
try:
frase = input("Dime el nombre de un fichero: ")
fichero = open(frase, "r")
except:
print("No se ha podido acceder al fichero")
else:
lineas = fichero.readlines()
fichero.close()
for i in range(0, len(lineas) ):
print( lineas[i].rstrip() )
|
numero = int(input("Dígame cuántas palabras tiene la lista: "))
if numero < 1:
print("¡Imposible!")
else:
lista = []
i = 0
while(i < numero):
print("Ingresa la palabra",str(i+1)+ ": ", end="")
palabra = input()
lista += [palabra]
i=i+1
print("La lista creada es:", lista)
buscar_palabra = input("Dígame la palabra a remplasar: ")
sustituir = input("fue remplazada por la palabra: ")
for i in range (len(lista)):
if lista[i] == buscar_palabra:
lista[i] = sustituir
print("Nueva lsita ", lista)
|
'''
EJERCICIO 1:
Escribir un programa que almacene una cadena de caracteres de contraseña en una variable,
ingresada por el usuario, pregunte al usuario por la contraseña e imprima por pantalla si
la contraseña introducida por el usuario coincide con la guardada en la variable sin tener
en cuenta mayúsculas y minúsculas.
'''
print("Ejercicio No. 1")
llave= "contraseña"
password=input("Introduce la Contraseña: ")
if llave== password.lower():
print("La contraseña coincide")
else:
print("La contraseña no coincide")
print("\n")
'''
Los alumnos de un curso se han dividido en dos grupos A y B de acuerdo al sexo y el nombre.
El grupo A esta formado por las mujeres con un nombre anterior a la M y los hombres con un
nombre posterior a la N y el grupo B por el resto. Escribir un programa que pregunte al
usuario su nombre y sexo, y muestre por pantalla el grupo que le corresponde.
'''
print("Ejercicio No. 2 ")
nombre= input("¿Como te llamas?")
genero= input("¿Cual es tu sexo (M o H)? ")
if genero == "M":
if nombre.lower()< "m":
grupo= " A"
else:
grupo= " B"
else:
if nombre.lower()>"n":
grupo= " A"
else:
grupo= " B"
print("Tu grupo es: "+ grupo)
|
# TODO Create an empty list to maintain the player names
# TODO Ask the user if they'd like to add players to the list.
# If the user answers "Yes", let them type in a name and add it to the list.
# If the user answers "No", print out the team 'roster'
# TODO print the number of players on the team
# TODO Print the player number and the player name
# The player number should start at the number one
# TODO Select a goalkeeper from the above roster
# TODO Print the goal keeper's name
# Remember that lists use a zero based index
players = []
answer = input("Would you like to add players to the list? (Yes/No) ").lower()
while answer == 'yes':
player = input("\nEnter the name of the player to add to the team: ")
players.append(player)
answer = input("Would you like to add another player? (Yes/No) ").lower()
# First solution
# count = len(players)
# print("\nThere are {} players on the team.".format(count))
# for player in range(count):
# print("Player {}: {}".format(player+1, players[player]))
# Cleaner solution
print("\nThere are {} players on the team.".format(len(players)))
count = 1
for player in players:
print("Player {}: {}".format(count, player))
count += 1
player_num = int(input("Please select the goal keeper by selecting the player number. (1-{}) ".format(len(players))))
print("Great!!! The goal keeper for the game will be {}!".format(players[player_num-1]))
|
def solution(A):
#print(A)
if len(A) == 0:
return -1
sort_a = sorted(A)
#print(sort_a)
l = len(A) // 2
#print("median:",l)
domi_candidate = sort_a[l]
B=[]
#print(A.count(domi_candidate))
if A.count(domi_candidate) > l:
for i in range(len(A)):
if A[i] == domi_candidate:
B.append(i)
return(B)
return -1
def solution1(A):
# write your code in Python 3.6
if len(A) == 0:
return -1
sort_a = sorted(A)
l = len(A) // 2
domi_candidate = sort_a[l]
if A.count(domi_candidate) > l:
return A.index(domi_candidate)
return -1
#A=[3,3,3,2,6,-1,3,3]
A=[3, 4, 3, 2, 3, -1, 3, 3]
C=[]
C=solution(A)
print("Dominator index from array is:",C)
|
CLOSING = {
']': '[',
')': '(',
'}': '{',
}
def solution(S):
stack = []
for ch in S:
if ch in CLOSING:
if not stack:
# encountered closing bracket but stack is already empty!
return 0
last = stack.pop()
if last != CLOSING[ch]:
# wrong bracket encountered
return 0
else:
stack.append(ch)
if stack:
# there are still opened brackets on a stack
return 0
else:
return 1
|
def array_count9(nums):
print (nums)
count = 0
for i in range (len(nums)):
if nums[i] == 9:
count = count + 1
print (count)
return count
array_count9([1, 2, 9, 9, 9])
|
# This program is to simulate the result of state meet by using the hypothesized distribution of win rate
# The result will be used to do the chi-square test to check if the events are independent
import multiprocess as mp
import pandas as pd
import numpy as np
import sys
import random
def test(repeat, desired, p, mp, pd, random, np):
"""
this function is used to simulate the frequency of different combinations of outcomes of which schools get into top 16
params:
repeat: how many time of repeat
desired: which schools are the users want to simulate
p: number of process
mp: multiprocess
pd: pandas
random: random
np: numpy
return:
freq3:
freq2:
freq1:
"""
def run_once(desired):
"""
this function calculate the result of single running match
params:
desired: a list of school ID, each time we use desired[0] for one school simulation and desired[0:1] for two schools and all of them for three schools
return:
ret: a list of result for the simulation for one school, two schools and three schools
"""
ret = []
# current_all is a dataframe include schools in division one
current_all = pd.read_csv(r"top1_freq.csv")
current_all = current_all.sort_values("pop").reset_index().loc[:, ["ID","pop","freq"]]
temp = np.empty(shape=16, dtype=np.int64)
current_total_pop = current_all["freq"].sum()
count = 0
# repeat 16 times to simulate the top 16 runners
for _ in range(16):
rand_num = random.random()
cumulative_prob = 0
for index in current_all.index:
current_prob = cumulative_prob + current_all.loc[index, "freq"] / current_total_pop
# if the proportion of population is in the range then we think the runner get into top 16
if cumulative_prob <= rand_num < current_prob:
temp[count] = index
count += 1
current_total_pop -= current_all.loc[index, "freq"]
current_all = current_all.drop(index)
break
cumulative_prob = current_prob
# different combination of runners get into top 16
# freq1:
# 0: True
# 1: False
# freq2:
# 0: s1 and s2
# 1: s1
# 2: s2
# 3: not s1 and not s2
# freq3:
# 0: neither
# 1: s3
# 2: s2
# 3: s2 & s3
# 4: s1
# 5: s1 & s3
# 6: s2 & s3
# 7: s1 & s2 & s3
if np.isin(desired[0], temp) and np.isin(desired[1], temp) and np.isin(desired[2], temp):
ret.append(7)
elif np.isin(desired[0], temp) and np.isin(desired[1], temp):
ret.append(6)
elif np.isin(desired[1], temp) and np.isin(desired[2], temp):
ret.append(3)
elif np.isin(desired[0], temp) and np.isin(desired[2], temp):
ret.append(5)
elif np.isin(desired[0], temp):
ret.append(4)
elif np.isin(desired[1], temp):
ret.append(2)
elif np.isin(desired[2], temp):
ret.append(1)
else:
ret.append(0)
if np.isin(desired[0], temp) and np.isin(desired[1], temp):
ret.append(0)
elif np.isin(desired[0], temp):
ret.append(1)
elif np.isin(desired[1], temp):
ret.append(2)
else:
ret.append(3)
if np.isin(desired[0], temp):
ret.append(0)
else:
ret.append(1)
if np.isin(desired[1], temp):
ret.append(0)
else:
ret.append(1)
if np.isin(desired[2], temp):
ret.append(0)
else:
ret.append(1)
return ret
percent = 0
freq3 = {i: [0] for i in range(8)}
freq2 = {i: [0] for i in range(4)}
freq1_1 = {i: [0] for i in range(2)}
freq1_2 = {i: [0] for i in range(2)}
freq1_3 = {i: [0] for i in range(2)}
for _ in range(repeat):
res = run_once(desired)
freq3[res[0]][0] += 1
freq2[res[1]][0] += 1
freq1_1[res[2]][0] += 1
freq1_2[res[3]][0] += 1
freq1_3[res[4]][0] += 1
if _%(repeat/100) == repeat/100 - 1 and p == 1:
percent += 1
print("progress: {}%".format(percent))
return freq3, freq2, freq1_1, freq1_2, freq1_3
if __name__ == '__main__':
"""
this program use three system:
sys.argv: repeat, repeat_simulation_once, target[s1, s2, s3] <- s1,s2,s3 are the index of schools in the DataFrame only include schools from div I
"""
current_all = pd.read_csv(r"top1_freq.csv")
current_all = current_all.sort_values("pop").reset_index().loc[:, ["ID","pop","freq"]]
desired = np.array([int(i) for i in sys.argv[3][1:-1].split(",")], dtype=np.int64)
print(current_all.iloc[desired])
print("\n\n")
print("simulation start")
temp = []
pool = mp.Pool(processes=mp.cpu_count())
for i in range(int(sys.argv[1])):
temp.append(pool.apply_async(test, (int(sys.argv[2]), desired, i, mp, pd, random, np)))
pool.close()
pool.join()
df3 = pd.DataFrame({i: [] for i in range(8)})
df2 = pd.DataFrame({i: [] for i in range(4)})
df1_1 = pd.DataFrame({i: [] for i in range(2)})
df1_2 = pd.DataFrame({i: [] for i in range(2)})
df1_3 = pd.DataFrame({i: [] for i in range(2)})
for i in temp:
df3 = pd.concat([df3, pd.DataFrame(i.get()[0])], ignore_index=True)
df2 = pd.concat([df2, pd.DataFrame(i.get()[1])], ignore_index=True)
df1_1 = pd.concat([df1_1, pd.DataFrame(i.get()[2])], ignore_index=True)
df1_2 = pd.concat([df1_2, pd.DataFrame(i.get()[3])], ignore_index=True)
df1_3 = pd.concat([df1_3, pd.DataFrame(i.get()[4])], ignore_index=True)
df3.columns = ["none", "S2", "S1", "S1&S2", "S0", "S0&S2", "S0&S1", "all"]
df2.columns = ["S1&S2", "S1", "S2", "neither"]
df1_1.columns = ["True", "False"]
df1_2.columns = ["True", "False"]
df1_3.columns = ["True", "False"]
for col in df3.columns:
df3[col].astype("int64")
for col in df2.columns:
df2[col].astype("int64")
for col in df1_1.columns:
df1_1[col].astype("int64")
for col in df1_2.columns:
df1_2[col].astype("int64")
for col in df1_3.columns:
df1_3[col].astype("int64")
df3.to_csv("ind3.csv", index=False)
df2.to_csv("ind2.csv", index=False)
df1_1.to_csv("ind1_1.csv", index=False)
df1_2.to_csv("ind1_2.csv", index=False)
df1_3.to_csv("ind1_3.csv", index=False)
print("\n\n")
print("simulation finish")
|
from bs4 import BeautifulSoup
print ("starting to scrape")
#Use code below when file to import is on web server :
response = urllib2.urlopen("http://www.goheels.com/SportSelect.dbml?DB_OEM_ID=3350&SPID=12960&SPSID=668154&SITE=UNC&DB_OEM_ID=3350")
html = response.read()
#end server version
#Use this code when file is local:
#with open ("transcript.html", "r") as tempFile:
#html=tempFile.read();
#end local version
#print html;
soup = BeautifulSoup(html)
tabledata = soup.find("table", {"id" : "roster-table"}) #find the proper table
player_names = [] #list to stor every player in the table
player_links = []
for link in tabledata.find_all('a'):
player_links.append(link.get('href'))
player_names.append(link.get('title'))
for position in tabledata.find_all("td", {"class" : "position"}):
player_position.append(position.text.strip())
#print player_names
print player_position
#player_name = (soup.find_all)
print player_links
|
#!/usr/bin/python3
#
# czz78 made this script for OSCP preparation
#
from concurrent.futures import ThreadPoolExecutor
import argparse
duplicates = []
def read_words(inputfile):
with open(inputfile, 'r') as f:
while True:
buf = f.read(10240)
if not buf:
break
# make sure we end on a space (word boundary)
while not str.isspace(buf[-1]):
ch = f.read(1)
if not ch:
break
buf += ch
words = buf.split()
for word in words:
yield word
yield '' #handle the scene that the file is empty
def process_file(inputfile):
for word in read_words(inputfile):
if word not in duplicates:
duplicates.append(word)
print("{}".format(word))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Make unique words list from file text')
parser.add_argument('filename', help='file name or multiple files separated by coma ex: /tmp/file1.txt,/tmp/file2.txt')
args = parser.parse_args()
myfiles = args.filename.split(',')
# multithreading
with ThreadPoolExecutor() as executor:
result = executor.map(process_file, myfiles)
|
# Name:
# Date:
# proj01: A Simple Program
# This program asks the user for his/her name and age.
# Then, it prints a sentence that says when the user will turn 100.
# If you complete extensions, describe your extensions here!
name = raw_input("Enter your name: ")
age = int(raw_input("Enter your age: "))
if age>100:
print "This won't work at all now, good job...."
bday = raw_input("Has your birthday happened this year? Enter Y or N: ")
if bday == "Y":
year = 2017
else:
year = 2016
year2= year
while 100 - age + year > year2:
print str(year2)
year2= year2 +1
print name, "will turn 100 in the year ", year2,"."
|
def solution(dic):
max_value = 0
min_value = 0
list1 = sorted(dict1.iteritems())
max_value = max(list1, key=lambda list1:list1[1])
min_value = min(list1, key=lambda list1:list1[1])
#print max_value
#print min_value
tuple_numbers = max_value[1], min_value[1]
return tuple_numbers
dict1 = {'x': 500, 'y': 5874, 'z': 560}
solution(dict1)
|
# Ask the user for a sentence. Sort the sentence and then
# return the sentence backwards.
# use a lambda function in this process
# Get our sentence and split on the words
our_sent = input("Please enter a sentence to reverse: ").split()
# Print the words sorted reverse by the last letter of the word
print(sorted(our_sent, key=lambda words: words[::-1]))
# OR just print the words in reverse from how they were entered
print(our_sent[::-1])
|
person_list = {
'first_name': 'Clair',
'last_name':'Hommes',
'age':'38',
'city':'New York, NY',
'hair_color':'blonde',
'eyes': 'green'
}
for freaky in person_list.values():
print(freaky)
|
# Simple earnings application
# Ask for their name, hourly wage, how many hours were worked.
# Calculate the money made.
# NOTE: Added looping with while and try statements to correct information entered.
def earnings_info():
while True:
name = input("What is your name: ")
hourly_wage = input("What is your hourly wage: ")
hours_worked = input("How many hours did you work this week: ")
name = name.strip()
try:
if name == "" or hourly_wage == "" or hours_worked == "":
print("Please enter valid information!")
continue
elif float(hours_worked) < 5 or float(hours_worked) > 120:
print("Please enter reasonable hours worked!")
continue
elif float(hourly_wage) < 7.5:
print("Are you working for pennies? Please enter a reasonable wage!")
continue
elif float(hourly_wage) > 120:
print("Are you REALLY making all that cash? Please enter a normal wage!")
continue
else:
wage_earned = float(hourly_wage) * float(hours_worked)
print(f'{name.title()}\'s gross pay is ${wage_earned:.2f} this week!')
break
except Exception as e:
print(e)
print("""
Welcome to the Simple Earnings application!
Please enter the relevant information to
calculate your wages! """)
earnings_info()
|
# def costOfDisneyFor(number_of_adults, number_of_children, number_of_days):
#1. How many parameters did we use to define this function?
#2 What datatype will we use as arguments when we call the function?
#3 What datatype will the return value be?
#4 How many internal lines of code are there in this function?
#5 Right now, if we ran this program, nothing would actually happen. Why is that?
#6.How would I compute the cost of bringing 43 adults and 67 children to Disney for 5 days?"
|
"""
NumPy functionality to compute distance-related functions on large matrices.
"""
import numpy as np
import sklearn.metrics
def NearestAB_N_NeighbourIdx_IgnoreNans(A, B, N):
"""
Find the indices of the N nearest neighbours in A for every point in B
Result is a 2D array of observation indices for A, of shape (#observations in B, N)
Result[:,0] represents the nearest neighbour indices, and Result[:,N-1] the Nth neighbour
"""
(n_trn, n_dim1)= A.shape
(n_tst, n_dim2)= B.shape
assert n_dim1 == n_dim2, "Matrices A and B have incompatible dimensions!"
assert N < n_trn, "N too large for number of training points!"
n_dim= n_dim1
acc= np.zeros((n_tst, n_trn), dtype=np.float32)
incr= np.empty_like(acc).T
#In order to reduce memory consumption, do this one dimension at a time, via an accumulator matrix
#Also do this in 32 bit precision (since numbers are already normalized to a reasonable range)
for D in range(n_dim):
incr= A.astype(np.float32)[:,D].reshape(n_trn,1) - B.astype(np.float32)[:,D].reshape(n_tst,1).T
np.square(incr,incr)
incr[np.isnan(incr)]= 0
acc+= incr.T
np.sqrt(acc,acc)
#Returning [:, 0:N] would mean that the nearest neighbour for P would be P itself - obviously wrong!
return acc.argsort(axis=1)[:,1:N + 1]
def AB_NeighbourDistances_IgnoreNans(A, B):
"""
Find the distance to every point in A for every point in B
Result is a 2D array of observation indices for A, of shape (#observations in B, #observations in A)
"""
(n_trn, n_dim1)= A.shape
(n_tst, n_dim2)= B.shape
assert n_dim1 == n_dim2, "Matrices A and B have incompatible dimensions!"
n_dim= n_dim1
acc= np.zeros((n_tst, n_trn),dtype=np.float32)
incr= np.empty_like(acc).T
#In order to reduce memory consumption, do this one dimension at a time, via an accumulator matrix
#Also do this in 32 bit precision (since numbers are already normalized to a reasonable range)
for D in range(n_dim):
incr= A.astype(np.float32)[:,D].reshape(n_trn,1) - B.astype(np.float32)[:,D].reshape(n_tst,1).T
np.square(incr,incr)
incr[np.isnan(incr)]= 0
acc+= incr.T
np.sqrt(acc,acc)
return acc
def DistanceToIdx(A, B, idx):
"""
For the ith point in B, find the distance to the point in A addressed by the ith index in array 'idx'
"""
C= A[idx]
return np.sqrt(np.sum(np.square(C-B),axis=1,keepdims=True))
def MutualInformation(x, y, bins):
"""
Calculates the MI of a set of two-dimensional vectors, separated into the arrays x and y.
Discretises the distribution into an amount of bins.
"""
hist_xy, x_edges, y_edges = np.histogram2d(x, y, bins)
return sklearn.metrics.mutual_info_score(None, None, hist_xy)
|
import view
from computerboard import ComputerBoard
import sys
NUMSHIPS = 3
view.welcome()
def run():
if len(sys.argv) > 1 and sys.argv[1] == "--cheat":
cheat = True
else:
cheat = False
# generate computer's board
size = view.ask_boardsize()
board = ComputerBoard(size, size)
while board.count_symbol('S') < NUMSHIPS:
board.random_ship()
while not board.no_ships():
if cheat:
print(board)
else:
view.show_board(board)
x, y = view.get_attack_coords(board)
if board.attack(x, y):
view.hit()
else:
view.miss()
view.goodbye()
# start main loop
# display current player view of board
# player makes attacks
# if no ships left, exit loop
# print goodbye message
if __name__ == "__main__":
run()
|
'''
@Description:
@Version: 2.0
@Author: yunruowu
@Date: 2020-01-02 10:12:30
@LastEditors : yunruowu
@LastEditTime : 2020-01-02 10:48:25
'''
#
# @lc app=leetcode.cn id=70 lang=python3
#
# [70] 爬楼梯
#
# https://leetcode-cn.com/problems/climbing-stairs/description/
#
# algorithms
# Easy (47.46%)
# Likes: 767
# Dislikes: 0
# Total Accepted: 116.7K
# Total Submissions: 245.8K
# Testcase Example: '2'
#
# 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
#
# 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
#
# 注意:给定 n 是一个正整数。
#
# 示例 1:
#
# 输入: 2
# 输出: 2
# 解释: 有两种方法可以爬到楼顶。
# 1. 1 阶 + 1 阶
# 2. 2 阶
#
# 示例 2:
#
# 输入: 3
# 输出: 3
# 解释: 有三种方法可以爬到楼顶。
# 1. 1 阶 + 1 阶 + 1 阶
# 2. 1 阶 + 2 阶
# 3. 2 阶 + 1 阶
#
#
#
# @lc code=start
class Solution:
def climbStairs(self, n: int) -> int:
a = list(range(0, n + 1))
a[0] = 1
a[1] = 2
i = 2
while i < n:
a[i] = a[i - 1] + a[i - 2]
i = i + 1
return a[n - 1]
# @lc code=end
|
'''
@Description:
@Version: 2.0
@author: yunruowu
@Date: 2020-01-01 18:46:05
@LastEditors : yunruowu
@LastEditTime : 2020-01-01 18:58:51
'''
#
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] x 的平方根
#
# https://leetcode-cn.com/problems/sqrtx/description/
#
# algorithms
# Easy (37.30%)
# Likes: 276
# Dislikes: 0
# Total Accepted: 81.7K
# Total Submissions: 219.1K
# Testcase Example: '4'
#
# 实现 int sqrt(int x) 函数。
#
# 计算并返回 x 的平方根,其中 x 是非负整数。
#
# 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
#
# 示例 1:
#
# 输入: 4
# 输出: 2
#
#
# 示例 2:
#
# 输入: 8
# 输出: 2
# 说明: 8 的平方根是 2.82842...,
# 由于返回类型是整数,小数部分将被舍去。
#
#
public int mySqrt(int a) {
long x0 = a;
while (x0*x0 > a) {
x0 = (x0 + a / x0) / 2;
}
return (int)x0;
# @lc code=start
class Solution:
def mySqrt(self, x: int) -> int:
x0 = x
while(X0*x0>x){
x0=(x0+x/x0)/2
}
return (int)x0
# @lc code=end
|
number = input("Enter any positive number: ")
number = int(number)
if number % 2 == 0:
print("This is Even number")
else:
print("This is Odd number")
|
def semordnilap(str1, str2):
if len(str1) != len(str2):
return False
elif len(str1) == len(str2) == 1:
return str1 == str2
elif str1[0] == str2[-1]:
return semordnilap(str1[1:], str2[:-1])
else:
return False
str1 = raw_input("first string: ")
str2 = raw_input("second string: ")
print semordnilap(str1, str2)
|
def monthlyCalculation (bal, inter, pay):
unpaid = bal - pay
return {
'remain': unpaid + unpaid*inter/12.0,
'pay_min': pay
}
def annualCalculation(bal, inter, pay):
remaining = bal
totalPaid = 0
for i in range(12):
monthly = monthlyCalculation(remaining, interest, pay)
remaining = monthly['remain']
totalPaid += monthly['pay_min']
return{'remain': remaining, 'paid': totalPaid}
def calculateBound(bal, monthlyInterestRate):
return{
'lower': bal/12,
'upper': (bal*((1 + monthlyInterestRate)**12))/12.0
}
balance = int(raw_input("balance:"))
interest = float(raw_input("interest rate:"))
monthlyInterestRate = interest/12.0
bound = calculateBound(balance, monthlyInterestRate)
monthlyLowerBound = bound['lower']
monthlyUpperBound = bound['upper']
#payment = float(raw_input("payment rate:"))
monthlyPaid = (monthlyLowerBound + monthlyUpperBound)/2
pay = 0
remain = balance
while abs(remain) > 0.01:
annual = annualCalculation(balance, interest, monthlyPaid)
pay = annual['paid']
remain = annual['remain']
if remain < 0:
monthlyUpperBound = monthlyPaid
else:
monthlyLowerBound = monthlyPaid
#monthlyPaid += 10
monthlyPaid = (monthlyLowerBound + monthlyUpperBound)/2
print('Lowest Payment: ' + str(round(monthlyPaid, 2)))
|
# initializing the number of vertices
nV = 8
# initializing the infinity as an extremely large number
INF = 999
# function which implements the Floyd algorithm
def floyd_algorithm(source_graph):
# initialisation of the minimal distances matrix
distance = list(map(lambda i: list(map(lambda j: j, i)), source_graph))
# adding vertices to the graph in a loop
for k in range(nV):
for i in range(nV):
for j in range(nV):
# the matrix element is the sum of minimal distances between the required vertices
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
# printing the solution to the console
# the solution is the matrix of minimal distances
print_solution(distance)
# Printing the solution
def print_solution(distance):
for i in range(nV):
for j in range(nV):
if distance[i][j] == INF:
print("INF", end=" ")
else:
print(distance[i][j], end=" ")
print(" ")
# filling the adjacency matrix for the task graph
graph = [[0, 8, 2, 4, 3, INF, INF, INF],
[8, 0, INF, INF, 6, 3, INF, INF],
[2, INF, 0, INF, INF, 7, INF, 4],
[4, INF, INF, 0, 1, INF, INF, INF],
[3, 6, INF, 1, INF, 0, 4, INF],
[INF, 3, 7, INF, INF, 0, 3, 1],
[INF, INF, INF, INF, 4, 3, 0, 5],
[INF, INF, 4, INF, INF, 1, 5, 0]]
print('The matrix of minimal distances:')
# calling the previously defined function for the Floyd algorithm
floyd_algorithm(graph)
|
import graphics as g
import random
import sched, time
enemycounter = 5
score = 0
class board:
def __init__(self,w):
self.w = w
self.create()
self.instructions()
self.scorecounters()
self.deathline()
def create(self):
self.area = g.Rectangle(g.Point(50,0), g.Point(750,800))
self.area.setFill('white')
self.area.draw(self.w)
def instructions(self):
self.welcomemsg = g.Text(g.Point(1000, 100), "Shoot your Shot")
self.welcomemsg.setFill('white')
self.instructions = g.Text(g.Point(1000, 200), "Left and Right Arrow keys to move \n Up Arrow key to Fire")
self.instructions.setFill('white')
self.instructions.draw(self.w)
self.welcomemsg.draw(self.w)
def scorecounters(self):
global enemycounter
self.enemy_counter = g.Text(g.Point(1000, 500), f"Lives Remaining: {enemycounter}")
self.enemy_counter.setFill('red') #enemy_counter is actual object
self.enemy_counter.setSize(30) #enemycounter is global variable starting at 10
self.enemy_counter.draw(self.w)
self.score = g.Text(g.Point(1000, 400), f"Your Score: {score}")
self.score.setFill('green') #enemy_counter is actual object
self.score.setSize(30) #enemycounter is global variable starting at 10
self.score.draw(self.w)
def deathline(self):
self.line = g.Line(g.Point(50, 700), g.Point(750, 700))
self.line.setFill('red')
self.line.draw(self.w)
class Enemy1:
def __init__(self, w, x, y):
self.w = w
self.x = x
self.y = y
self.create()
self.enemywin()
self.move()
def create(self):
#creating enemy
self.p = g.Polygon(g.Point(self.x, self.y), g.Point(self.x + 80, self.y), g.Point(self.x + 40, self.y + 80))
self.e = g.Oval(g.Point(self.x + 15, self.y + 10), g.Point(self.x + 60, self.y + 40))
self.c = g.Circle(g.Point(self.e.getCenter().getX(), self.e.getCenter().getY()), 10)
#coloring enemy
self.p.setFill('blue')
self.e.setFill('white')
self.c.setFill('red')
#draw enemy
for obj in [self.p, self.e, self.c]:
obj.draw(self.w)
def get_center(self):
return self.c.getCenter()
def move(self):
import random
if self.c.getCenter().getY() < 750:
self.p.move(0, 0.1)
self.e.move(0, 0.1)
self.c.move(0, 0.1)
elif self.c.getCenter().getY() >= 750:
self.p.undraw()
self.e.undraw()
self.c.undraw()
self.p.move(0, 0.1)
self.e.move(0, 0.1)
self.c.move(0, 0.1)
self.w.after(2, self.move)
def hit(self):
global EnemyList
global score
self.p.undraw()
self.e.undraw()
self.c.undraw()
EnemyList.remove(self)
score += 1
B.score.undraw()
B.score.setText(f"Your Score: {score}")
B.score.draw(self.w)
def enemywin(self):
global enemycounter
global EnemyList
global E
if self.c.getCenter().getY() >= 700:
self.hit()
#EnemyList.remove(E)
enemycounter -= 1
B.enemy_counter.undraw()
B.enemy_counter.setText(f"Lives Remaining: {enemycounter}")
B.enemy_counter.draw(self.w)
class Tank:
def __init__(self,window,x,y):
self.w = window
self.x=x
self.y=y
self.tank_life=1
self.drawTank()
def drawTank(self):
'''BUILDING THE TANK FROM GROUND UP TO GET THE CORRECT OVERLAPS
'''
#MAKING THE TRACKs NOW
#LEFT TRACK
self.left_main_track=g.Rectangle(g.Point(self.x-10,self.y-10),g.Point(self.x+10,self.y+85))
self.left_main_track.setFill('black')
self.left_main_track.setOutline('brown')
#RIGHT TRACK
self.right_main_track=g.Rectangle(g.Point(self.x+40,self.y-10),g.Point(self.x+60,self.y+85))
self.right_main_track.setFill('black')
self.right_main_track.setOutline('brown')
#MAKING THE BODY PARTS OF THE TANK FROM BOTTOM UP
#MAIN BODY OF THE TANK
self.tank_main_body_rectangle=g.Rectangle(g.Point(self.x,self.y),g.Point(self.x+50,self.y+75))
self.tank_main_body_rectangle.setFill('green')
self.tank_main_body_rectangle.setOutline('black')
#SECOND BODY OF THE TANK THAT GOES ON TOP OF THE MAIN BODY
self.second_body_rectangle=g.Rectangle(g.Point(self.x+7,self.y+30),g.Point(self.x+43,self.y+68))
self.second_body_rectangle.setFill('green')
self.second_body_rectangle.setOutline('black')
#HATCH ON TOP OF THE SECOND BODY
self.hatch=g.Circle(g.Point(self.x+25,self.y+49),7)
self.hatch.setFill('green')
self.hatch.setOutline('black')
#CANNON PART 1 THAT GOES ON TOP OF MAIN BODY AND HAS THE SECOND BODY DRAW OVER IT
self.cannon_part1=g.Rectangle(g.Point(self.x+20,self.y+22),g.Point(self.x+30,self.y+35))
self.cannon_part1.setFill('green')
self.cannon_part1.setOutline('black')
#CANNON PART 2 THAT IS LONG AND CONNECTS TO CANNON PART 1
self.cannon_part2=g.Rectangle(g.Point(self.x+22,self.y-13),g.Point(self.x+28,self.y+25))
self.cannon_part2.setFill('green')
self.cannon_part2.setOutline('black')
#CANNON PART 3 THAT CONNECTS TO THE END OF CANNON PART 2
self.cannon_part3=g.Rectangle(g.Point(self.x+20,self.y-20),g.Point(self.x+30,self.y-10))
self.cannon_part3.setFill('green') #9 tall and
self.cannon_part3.setOutline('black')
#DRAWING ALL THE OBJECTS
#dont change this sequence of code
self.left_main_track.draw(self.w)
self.right_main_track.draw(self.w)
self.tank_main_body_rectangle.draw(self.w)
self.cannon_part2.draw(self.w)
self.cannon_part1.draw(self.w) #has this specific sequence to draw so the tank looks realistic
self.cannon_part3.draw(self.w)
self.second_body_rectangle.draw(self.w)
self.hatch.draw(self.w)
def tank_controls(self,key):
#CONTROLS FOR GOING LEFT
if key=='Left': #ANDREW you will have to change the values for all the parts below to not go outside the border you have put in
if self.left_main_track.getCenter().getX()>=65+2:
self.left_main_track.move(-7,0)
self.right_main_track.move(-7,0)
self.tank_main_body_rectangle.move(-7,0)
self.cannon_part2.move(-7,0)
self.cannon_part1.move(-7,0) #has this specific sequence to draw so the tank looks realistic
self.cannon_part3.move(-7,0)
self.second_body_rectangle.move(-7,0)
self.hatch.move(-7,0)
#CONTROLS FOR GOING RIGHT
if key=='Right':
if self.right_main_track.getCenter().getX()<=736.8-2:
self.left_main_track.move(7,0)
self.right_main_track.move(7,0)
self.tank_main_body_rectangle.move(7,0)
self.cannon_part2.move(7,0)
self.cannon_part1.move(7,0) #has this specific sequence to draw so the tank looks realistic
self.cannon_part3.move(7,0)
self.second_body_rectangle.move(7,0)
self.hatch.move(7,0)
#CONTROLS FOR SHOOTING BULLET IS UP ARROW
if key=='Up':
Bullet(self.w,self.cannon_part3.getCenter().getX()-2.45,self.cannon_part3.getCenter().getY()-27.5)
#ANDREW UNCOMMENT THESE THINGS
#HIT DETECTION OF ENEMY1 HITTING TANK
# if (self.enemy1.getCenter().getY()<=self.tank_main_body_rectangle.getCenter().getY()+10) and (self.tank_main_body_rectangle.getCenter().getX()>=self.enemy1.getCenter().getX()-10 and self.tank_main_body_rectangle.getCenter().getX()<=self.enemy1.getCenter().getX()+10):
# self.tank_life=0
# self.left_main_track.undraw()
# self.right_main_track.undraw()
# self.tank_main_body_rectangle.undraw()
# self.cannon_part2.undraw()
# self.cannon_part1.undraw() #has this specific sequence to draw so the tank looks realistic
# self.cannon_part3.undraw()
# self.second_body_rectangle.undraw()
# self.hatch.undraw()
#HIT DETECTION OF ENEMY2 HITTING TANK
# if (self.enemy2.getCenter().getY()<=self.tank_main_body_rectangle.getCenter().getY()+10) and (self.tank_main_body_rectangle.getCenter().getX()>=self.enemy2.getCenter().getX()-10 and self.tank_main_body_rectangle.getCenter().getX()<=self.enemy2.getCenter().getX()+10):
# self.tank_life=0
# self.left_main_track.undraw()
# self.right_main_track.undraw()
# self.tank_main_body_rectangle.undraw()
# self.cannon_part2.undraw()
# self.cannon_part1.undraw() #has this specific sequence to draw so the tank looks realistic
# self.cannon_part3.undraw()
# self.second_body_rectangle.undraw()
# self.hatch.undraw()
class Bullet(Tank):
def __init__(self,window,x,y):
self.w=window
self.x=x
self.y=y
self.drawBullet()
self.fireBullet()
def drawBullet(self):
#RED OVAL THAT IS THE HEAD OF THE BULLET
self.bullet_body=g.Oval(g.Point(self.x,self.y),g.Point(self.x+5,self.y+15))
self.bullet_body.setFill('red')
self.bullet_body.setOutline('black')
#THIS IS THE BLACK RECTANGLE ON TOP OF THE RED OVAL (SHELL)
self.bullet_shell=g.Rectangle(g.Point(self.x,self.y+7.5),g.Point(self.x+5,self.y+22))
self.bullet_shell.setFill('black')
#DRAWING THE BULLET
self.bullet_body.draw(self.w)
self.bullet_shell.draw(self.w)
def fireBullet(self):
#MOVING THE HEAD AND SHELL
self.bullet_body.move(0,-10)#making the bullet go up
self.bullet_shell.move(0,-10)
self.w.after(10,self.fireBullet)#making the bullet move every 10 milliseconds
for enemy in EnemyList:
#ANDREW UNCOMMENT THESE THINGS
#BULLET HITTING ENEMY1
#THESE ENEMY NAMES MIGHT NEED TO BE CHANGED
if (enemy.get_center().getY()-25 <=self.bullet_body.getCenter().getY()<=enemy.get_center().getY()+25) and (self.bullet_body.getCenter().getX()>=enemy.get_center().getX()-25 and self.bullet_body.getCenter().getX()<=enemy.get_center().getX()+25):
self.bullet_body.undraw()
self.bullet_shell.undraw()
enemy.hit()
class Two_Life_Enemy:
#This is an enemy that requires two shots to kill
def __init__(self, w, x, y,is_big = True):
self.w = w
self.x = x
self.y = y
self.speed = 1.5
self.direction = 1
self.enemy_counter = 1
self.is_big = is_big
if self.is_big:
self.create_big()
else:
self.create_small()
self.move()
def create_big(self):
#This creates the first life of the enemy
self.body = g.Rectangle(g.Point(self.x, self.y), g.Point(self.x + 100, self.y + 100))
self.body.setFill('lavender')
self.body.draw(self.w)
def create_small(self):
#This creates the second life of the enemy
self.body = g.Rectangle(g.Point(self.x, self.y), g.Point(self.x + 50, self.y + 50))
self.body.setFill('teal')
self.body.draw(self.w)
def move(self):
#This is the move function for the big square it moves diagonally while the little square moves straight down
if self.is_big == True:
if self.body.getCenter().getX() <= 100:
self.direction = 1
elif self.body.getCenter().getX() >= 700:
self.direction = -1
self.body.move(self.direction * self.speed, .5)
else:
self.body.move(0, .5)
self.w.after(10, self.move)
def hit(self):
#This function respawns the little square after getting hit with a bullet
global score
self.body.undraw()
if self.is_big == True:
x = self.body.getCenter().getX()
y = self.body.getCenter().getY()
EnemyList.append(Two_Life_Enemy(self.w, x, y-40, False))
EnemyList.remove(self)
score += 1
B.score.undraw()
B.score.setText(f"Your Score: {score}")
B.score.draw(self.w)
def enemywin(self):
#This is the function that removes a life and the enemy if it gets to the line of death
global enemycounter
global EnemyList
global E
if self.body.getCenter().getY() >= 700:
self.hit()
#EnemyList.remove(self)
enemycounter -= 1
B.enemy_counter.undraw()
B.enemy_counter.setText(f"Lives Remaining: {enemycounter}")
B.enemy_counter.draw(self.w)
def get_center(self):
return self.body.getCenter()
def spawnenemy():
#This is the function that spawns 4 enemies every 15 seconds
global EnemyList
global Q
global E
global enemycounter
global w
listcounter = 0
while enemycounter > 0 and listcounter < 4:
E = Enemy1(w, random.randint(100,700), 50)
EnemyList.append(E)
Q = Two_Life_Enemy(w, random.randint(100,700), 50)
EnemyList.append(Q)
listcounter += 2
w.after(15000,spawnenemy)
def main():
#The function to actually run the game
global EnemyList, B, enemycounter, E, Q, w
w = g.GraphWin('GAME!!', 1200,800)
w.setBackground('black')
B = board(w)
T=Tank(w,475,710)
# c = Two_Life_Enemy(w,rand.randint(80,940), 100)
# c.move()
EnemyList = []
spawnenemy()
key=None
while key != 'q':
for enemy in EnemyList:
enemy.enemywin()
key = w.checkKey()
T.tank_controls(key)
if enemycounter <= 0:
w.close()
w.close()
if __name__ == "__main__":
main()
|
'''fitnes function
creating individual
creating gen
selection from population
new gens(N-Best/M-random)
creating child
creating children
mutating word
mutating population
'''
#password==password que tentamos saber
#individual== a palavra escolhida
import random
import operator
#import time
def fitnessfunc(password,individual):
fitness=0.0
if len(password)!=len(individual):
fitness=0.0
return fitness
else:
for i in range(len(password)+1):
if i<len(password):
if individual[i]==password[i]:
fitness+=1
return (fitness/len(password)*100)#return
def creatingindividual(password):
individual=''
for i in range(len(password)):
individual=individual+(vlist[int(random.random()*36)])
return individual #return
def creatingfirstgen(populationsize,password):
population={}
for i in range(populationsize):
individual=creatingindividual(password)
population[individual]=fitnessfunc(password,individual)
return population #return
def gensort(population,password):
populationsort={}
for individual in population:
populationsort[individual]=fitnessfunc(password,individual)
return (sorted(populationsort.items(), key = operator.itemgetter(1), reverse=True))
def genselect(gensorted,n,m):
newgen=[]
for i in range(n):
newgen.append(gensorted[i][0])
for i in range(m):
newgen.append(random.choice(gensorted)[0])
random.shuffle(newgen)
return newgen #return
def creatingchild(individual1,individual2):
child=''
for i in range(len(individual1)):
if int(random.random()*100)<50:
child+=individual1[i]
else:
child+=individual2[i]
return child
def creatingchildren(sourcepopulation):
children=[]
for i in range(int(len(sourcepopulation)/2)):
children.append(creatingchild(sourcepopulation[i],sourcepopulation[len(sourcepopulation) -1 -i]))
return children
def mutatingword(word):
index=int(random.random()*len(word))
if (index==0):
word=chr(97+int(random.random()*26))+word[1:]
else:
word=word[:index]+vlist[int(random.random()*36)]+word[index+1:]
return word
def mutatingpopulation(population,probmutation):
for i in range(len(population)):
if int(random.random()*100)<probmutation:
population[i]=mutatingword(population[i])
return population
secret=input('Your password: ')
result=secret
secret=secret.lower()
"secret='pa9823ss'"
n=19
m=83
prob=35
gera=[]
vlist=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
def program():
#start = time.time()
i=0
while i<1:
firstgen=creatingfirstgen(100,secret)
firstgensorted=gensort(firstgen,secret)
genlist1=genselect(firstgensorted,n,m)
childs=creatingchildren(genlist1)
mutated=mutatingpopulation(childs,prob)
x=[x for x in mutated if x==secret]
i+=1
try:
if x[0]==secret:
print('Your password is, "%s"'%(result))
#end = time.time()
#print(end - start)
break
except IndexError:
print('Fail first')
fmutated=mutated
j=0
while True:
gensorti=gensort(fmutated,secret)
genselecti=genselect(gensorti,n,m)
createchildreni=creatingchildren(genselecti)
fmutated=mutatingpopulation(createchildreni,prob)
x=[x for x in fmutated if x==secret]
i+=1
j+=1
try:
if x[0]==secret:
print('Your password is, "%s",in Generation %d'%(result,i))
#end = time.time()
#print(end - start)
print(j)
break
except IndexError:
pass
program()
input('Press to exit')
#x=['pljsk', 'rhweu', 'bkwnm', 'qqxij', 'fmful', 'nlnpv', 'gnrdd', 'ewrek', 'fmful', 'nlnpv', 'nmjrx', 'gixdy', 'tovdu', 'tplic', 'dnlah', 'kksoo', 'todgj', 'jbyhl', 'twvhu', 'xtsar', 'hqxrp', 'lqpec', 'ettke', 'ewrek', 'mogku', 'sofum', 'jbyhl', 'fmful', 'dipha', 'vxcpt', 'qoksm', 'jbyhl', 'gixdy', 'idooc', 'iigdr', 'gixdy', 'iigdr', 'mkeia', 'bkwnm', 'ngrab', 'mlpkb', 'aoluk', 'ihkbv', 'mgesu', 'sxdyw', 'csqcf', 'xilah', 'qqbxl', 'tpddi', 'bkxsk', 'fflnd', 'xbith', 'muaes', 'ngrab', 'nrqyy', 'ghwed', 'erdgl', 'gnrdd', 'iigdr', 'bhbap', 'sxdyw', 'ebiwo', 'wmwkv', 'ettke', 'vxrst', 'obxbw', 'qqbxl', 'xbith', 'ebiwo', 'tovdu', 'qqxij', 'aeven', 'tlwel', 'pljsk', 'qaqab', 'twvhu', 'tpari', 'feptd', 'kuhud', 'bhbap', 'kksoo', 'qoksm', 'xbith', 'xjicv', 'ghwed', 'mkeia', 'cdkro', 'xtsar', 'mogku', 'gnrdd', 'nlnpv', 'gixdy', 'rtmmi', 'hyxuq', 'bkwnm', 'xmtbi', 'fencl', 'xjicv', 'aeven', 'qqxij']
#fitnessfunc('trial','tria')
#creatingindividual('trial')
#creatingfirstgen(100,'sara')
#gensort(creatingfirstgen(1000,'trial'),'trial')
#genselect(gensort(creatingfirstgen(100,'trial'),'trial'),20,80)
#creatingchildren(x)
#mutatingpopulation(creatingchildren(x),40)
|
def reverse(array): #reverse array
print(array[::-1])
def middle(array): #select elements in the middle of the array
print(array[1:-1])
def edges(array): #select only first and last
print(max(array),min(array))
def totalsum(array): # sum of all elements (countable)
print(sum(array))
def nlist(n,array): # same list but with n elements
print([x for x in array if x<=n])
def sum_even_odd(array): # sum of even numbers and odd numbers in array
par,impar=0,0
for i in array:
if i%2==0:
par+=i
else:
impar+=i
return par,impar
def mix_lists(l1=[1,2,3,4,5,6,7],l2=['a','b','c','d','e']):
#Ex:[1,a,2,b.....]
l=[]
if len(l1)==len(l2):
for i in range(len(l2)):
l=l+[l1[i]]+[l2[i]]
elif len(l1)>len(l2):
for i in range(len(l2)):
l=l+[l1[i]]+[l2[i]]
l=l+l1[len(l2):]
elif len(l2)>len(l1):
for i in range(len(l1)):
l=l+[l2[i]]+[l1[i]]
l=l+l2[len(l1):]
return l
def x_smaller(n,array):
#only numbers smaller than "n"
return (len([x for x in array if x<n]))
def even_chance(n):
#probability of sum of two dices being even
import random
res = []
result = 0
for i in range(n):
d1 = random.randint(1,6)
d2 = random.randint(1,6)
res = res + [d1+d2]
if (d1+d2)%2 == 0:
result+= 1
print(res,'\n',(result/n))
def sequence_sum(array=[1,2,3]):
#sum one number to the last (Sequential)
val = 0
new = []
for i in array:
val = val+i
new = new+[val]
print(new)
def negative(image):
import copy
replace=copy.deepcopy(image)
for line in range(len(image)):
for col in range(len(image[0])):
replace[line][col]^=1
return replace
#simple way
def vegatives(image):
import copy
replace = copy.deepcopy(image)
for line in range(len(image)):
for col in range(len(image[0])):
if replace[line][col]==0:
replace[line][col]=1
else:
replace[line][col]=0
return replace
##68
def rotation(matrix):
import copy
replace=copy.deepcopy(matrix)
new=[]
for column in range(len(matrix[0])):
for line in matrix:
new+=[line[column]]
for line in range(len(new)):
new[line] = new[line]
return new
##69
def main_turtle(n):
import turtle
little = turtle.Turtle()
guide = controlls(n)
navigator(guide,little)
turtle.exitonclick()
def controlls(n):
import random
array=[]
for i in range(n):
array.append(random.randint(0,3))
return array
def navigator(com,tart):
tart.dot('green')
for i in com:
if i==0:
tart.fd(50)
if i==1:
tart.left(50)
if i==2:
tart.right(50)
if i==3:
tart.bk(50)
tart.dot('red')
##610
def positions(text):
dicio={}
for i in range(len(text)):
if text[i] in 'AEIOUaeiou':
dicio.setdefault(text[i],[]).append(i)
print(dicio)
autor={"php":"Rasmus Lerdorf","perl":"Larry Wall","tcl":"John Ousterhout","awk":"Brian Kernighan","java":"James Gosling","parrot":"Simon Cozens","python":"GuidovanRossum","xpto":"zxcv"}
def dict_call(dicio):
return 'c++' in dicio
dicio.setdefault(lf[i],[]).append(lq[i])
recipe ={'dreams':'flour', 'French Toast':'bread','cake':'water'}
def upsidown(dicio):
book={}
for key,value in dicio.items():
book.setdefault(value,[]).append(key)
print(book)
def brother(a,i1,i2):
for key in a.keys():
if i1 in a[key]:
i1=key
if i2 in a[key]:
i2=key
return i2==i1
def grand_children(a,p):
arrayn = []
for key,value in a.items():
if p == key:
for i in value:
arrayn = arrayn+a[i]
print(arrayn)
def grandpa(a,p):
father,grandpa='',''
for key in a:
if p in a[key]:
father = key
for key in a:
if father in a[key]:
grandpa = key
print(grandpa)
|
import turtle
def star(dim):
rot = 144
x = 0
for i in range(15):
turtle.forward(dim)
turtle.right(144)
dim+= 5
turtle.exitonclick()
if __name__ == '__main__':
star(100)
|
import turtle
import math
def ball(pencil,color,radius):
y = 0
x = 0
#des
pencil.right(90)
for i in range(5):
pencil.pensize(5)
if i%2==0:
if i==0:
color = "blue"
elif i==2:
color = "black"
elif i==4:
color = "red"
##y=y+radius*(5/3)
y = 0
x += radius
turtle.colormode(255)
pencil.pencolor(color)
pencil.pu()
pencil.goto(x,y)
pencil.pd()
pencil.circle(radius)
else:
if i==1:
color="yellow"
else:
color="green"
##x=x+(radius*(4/3))
x += radius
y = -radius
turtle.colormode(255)
pencil.pencolor(color)
pencil.pu()
pencil.goto(x,y)
pencil.pd()
pencil.circle(radius)
if __name__=='__main__':
radius = eval(input("Radius: "))
turtle.title("Olimpic Symbol")
pencil = turtle.Turtle()
turtle.setworldcoordinates(-radius*7,-radius*7,radius*10,radius*10)
turtle.hideturtle()
ball(pencil,"blue",radius)
turtle.exitonclick()
|
import random
#Retrieves the sum of Even and Odd numbers in a list
def evenOdd(array):
even = 0
odd = 0
for value in array:
if value%2 == 0:
even+= value
else:
odd+= value
print(array,even,odd)
#Ex: Insert 1º element of l1 and then 1º elem l2 and then 2º elem l1 and ...
def insertionOrder(list1,list2):
size = len(list1)
list3 = []
for i in range(size):
list3.append(list1[i])
list3.append(list2[i])
return list3
#Retrieves the number of elements bigger than "n"
def biggerThan(n,array,start=0):
for i in array:
if n > i:
k+= 1
return k
#Function that gives the probability of two "dices" giving an even number
def evenCount(n):
count = 0
for i in range(n):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
if dice1%2 == 0:
count+= 1
elif dice2%2 == 0:
count+= 1
return (count/n)
#Sums the previous element in a list
def previousSum(array):
array2 = [sum(array[:i+1]) for i in range(len(array))]
return array2
#Given a list of lists it gives back itself
def lists(lst):
return [[elem for elem in array] for array in lst]
|
#####################################################
##Curso em Vídeo
##Aula 013 - Reajuste Salarial
##https://youtu.be/cTkivN8XcJ0
#####################################################
print('Calculando o reajuste salarial de um funcionário')
salario_atual = float(input('Qual é o salário do funcionário? R$ '))
aumento_percentual = 15 / 100 #Representação matemática de 15%
salario_novo = salario_atual * (1 + aumento_percentual)
print('Um funcionário que ganhava R$ {:.2f}, com 15% de aumento, passa a receber R$ {:.2f}'.format(salario_atual, salario_novo))
|
#####################################################
##Curso em Vídeo
##Aula 016 - Quebrando um número
##https://youtu.be/-iSbDpl5Jhw
#####################################################
print('Qual a porção inteira de um número?')
n = float(input('Digite um valor: '))
#print('O valor digitado foi {} e a sua porção inteira é {}'.format(n, int(n)))
#import math
#print('O valor digitado foi {} e a sua porção inteira é {}'.format(n, math.trunc(n)))
from math import trunc
print('O valor digitado foi {} e a sua porção inteira é {}'.format(n, trunc(n)))
|
#####################################################
##Curso em Vídeo
##Aula 011 - Pintando Parede
##https://youtu.be/mzSJpn9ldt4
#####################################################
print('Qual a metragem quadrada da parede?')
largura = float(input('Informe a largura da parede: '))
altura = float(input('Informe a altura da parede: '))
área = largura*altura
print('Sua parede tem a dimensão de {:.2f}x{:.2f} e sua área é de {:.2f}m2.'.format(largura, altura, área))
tinta = área / 2
print('Para pintar essa parede, será necessário {}l de tinta.'.format(tinta))
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#时间结构体
class time_convert():
def __init__(self):
self.time = 0
self.year = 0
self.month = 0
self.day = 0
self.hour = 0
self.min = 0
self.second = 0
def input(self):
# time = input("pls input time")
flag = True
timeNum = int(self.time)
if timeNum < 10000000000000 or timeNum > 99999999999999:
flag = False
else:
self.year = int(self.time[0:4])
self.month = int(self.time[4:6])
if self.month < 1 or self.month > 12:
flag = False
self.day = int(self.time[6:8])
if self.month == 2:
if self.day < 0 or self.day > 29:
flag = False
else:
if self.day < 0 or self.day > 28:
flag = False
self.hour = int(self.time[8:10])
if self.hour < 0 or self.hour > 23:
flag = False
self.min = int(self.time[10:12])
if self.min < 0 or self.min > 59:
flag = False
self.second = int(self.time[12:])
if self.second < 0 or self.min > 59:
flag = False
if flag == False:
print("Wrong Time")
else:
print(str(self.year) + "-" + str(self.month).zfill(2) + "-" + str(self.day).zfill(2) + " " + str(self.hour).zfill(2) + ":" + str(self.min).zfill(2) + ":" + str(self.second).zfill(2))
t = time_convert()
t.time = input("pls input time")
t.input()
|
# -*- coding: utf-8 -*-
"""
@author: Trajan
"""
# Use Hungary Algorithm to get transformed matrix
def hungary(matrix_ori):
matrix = matrix_ori.copy()
# step 1
for i in range(len(matrix)):
matrix[i] = [k-min(matrix[i]) for k in matrix[i]]
# step 2
for i in range(len(matrix)):
colmin = min([matrix[k][i] for k in range(len(matrix))])
for k in range(len(matrix)):
matrix[k][i] -= colmin
line_count = 0
while (line_count < len(matrix)):
# step 3
line_count = 0
row_zero_count = [] # The number of zeros in each row.
col_zero_count = [] # The number of zeros in each column.
for i in range(len(matrix)):
row_zero_count.append(matrix[i].count(0))
for i in range(len(matrix)):
col_zero_count.append([matrix[k][i] for k in range(len(matrix))].count(0))
delete_count_of_row = [] # the lines through rows.
delete_count_of_col = [] # the lines through columns.
zero_add_zero = [] # zeros to be the only one in its column and row.
zero_add_one = [] # zeros to be the only one in its column or row.
zero_add_two = [] # other zeros
for i in range(len(matrix)):
for j in range(len(matrix)):
if matrix[i][j] == 0:
if row_zero_count[i] == 1 and col_zero_count[j] == 1:
zero_add_zero.append([i,j])
elif row_zero_count[i] == 1 or col_zero_count[j] == 1:
zero_add_one.append([i,j])
else:
zero_add_two.append([i,j])
if zero_add_zero:
for add in zero_add_zero:
if (add[1] not in delete_count_of_col) and (add[0] not in delete_count_of_row):
if row_zero_count[add[0]] >= col_zero_count[add[1]]:
delete_count_of_row.append(add[0])
for i in range(len(matrix)):
if matrix[add[0]][i] == 0:
col_zero_count[i] -= 1
elif row_zero_count[add[0]] < col_zero_count[add[1]]:
delete_count_of_col.append(add[1])
for i in range(len(matrix)):
if matrix[i][add[1]] == 0:
row_zero_count[i] -= 1
if zero_add_one:
for add in zero_add_one:
if (add[1] not in delete_count_of_col) and (add[0] not in delete_count_of_row):
if row_zero_count[add[0]] >= col_zero_count[add[1]]:
delete_count_of_row.append(add[0])
for i in range(len(matrix)):
if matrix[add[0]][i] == 0:
col_zero_count[i] -= 1
elif row_zero_count[add[0]] < col_zero_count[add[1]]:
delete_count_of_col.append(add[1])
for i in range(len(matrix)):
if matrix[i][add[1]] == 0:
row_zero_count[i] -= 1
if zero_add_two:
for add in zero_add_two:
if (add[1] not in delete_count_of_col) and (add[0] not in delete_count_of_row):
if row_zero_count[add[0]] >= col_zero_count[add[1]]:
delete_count_of_row.append(add[0])
for i in range(len(matrix)):
if matrix[add[0]][i] == 0:
col_zero_count[i] -= 1
elif row_zero_count[add[0]] < col_zero_count[add[1]]:
delete_count_of_col.append(add[1])
for i in range(len(matrix)):
if matrix[i][add[1]] == 0:
row_zero_count[i] -= 1
left_mat = [x for i, x in enumerate(matrix) if i not in delete_count_of_row]
for i in range(len(left_mat)):
left_mat[i] = [x for i, x in enumerate(left_mat[i]) if i not in delete_count_of_col]
# step 4
line_count = len(delete_count_of_row) + len(delete_count_of_col)
if line_count == len(matrix):
break
if 0 not in sum(left_mat,[]):
row_sub = list(set(range(len(matrix))) - set(delete_count_of_row))
min_value = min(sum(left_mat,[])) # the smallest value in the rest of the matrix
for i in row_sub:
for k in range(len(matrix)):
matrix[i][k] -= min_value
for i in delete_count_of_col:
for k in range(len(matrix)):
matrix[k][i] += min_value
return matrix
# Use the transformed matrix to get the assignment, similar to step3.
def assignment(matrix):
row_zero_count = []
for i in range(len(matrix)):
row_zero_count.append(matrix[i].count(0))
col_zero_count = []
for i in range(len(matrix)):
col_zero_count.append([matrix[k][i] for k in range(len(matrix))].count(0))
path = []
while len(path)<len(matrix):
for i in range(len(matrix)):
if row_zero_count[i] == 1:
col_zero_count[matrix[i].index(0)] -= 1
row_zero_count[i] = 0
if [i, matrix[i].index(0)] not in path:
path.append([i, matrix[i].index(0)])
for i in range(len(matrix)):
if col_zero_count[i] == 1:
row_zero_count[[matrix[k][i] for k in range(len(matrix))].index(0)] -= 1
col_zero_count[i] = 0
if [[matrix[k][i] for k in range(len(matrix))].index(0),i] not in path:
path.append([[matrix[k][i] for k in range(len(matrix))].index(0),i])
return path
if __name__ == "__main__":
matrix = [
[7, 53, 183, 439, 863, 497, 383, 563,79, 973, 287, 63,343, 169, 583],
[627, 343, 773, 959, 943, 767, 473, 103, 699, 303, 957, 703, 583, 639, 913],
[447, 283, 463, 29, 23, 487, 463, 993, 119, 883, 327, 493, 423, 159, 743],
[217, 623, 3, 399, 853, 407, 103, 983, 89, 463, 290, 516, 212, 462, 350],
[960, 376, 682, 962, 300, 780, 486, 502, 912, 800, 250, 346, 172, 812, 350],
[870, 456, 192, 162, 593, 473, 915, 45, 989, 873, 823, 965, 425, 329, 803],
[973, 965, 905, 919, 133, 673, 665, 235, 509, 613, 673, 815, 165, 992, 326],
[322, 148, 972, 962, 286, 255, 941, 541, 265, 323, 925, 281, 601, 95, 973],
[445, 721, 11, 525, 473, 65, 511, 164, 138, 672, 18, 428, 154, 448, 848],
[414, 456, 310, 312, 798, 104, 566, 520, 302, 248, 694, 976, 430, 392, 198],
[184, 829, 373, 181, 631, 101, 969, 613, 840, 740, 778, 458, 284, 760, 390],
[821, 461, 843, 513, 17, 901, 711, 993, 293, 157, 274, 94, 192, 156, 574],
[34, 124, 4, 878, 450, 476, 712, 914, 838, 669, 875, 299, 823, 329, 699],
[815, 559, 813, 459, 522, 788, 168, 586, 966, 232,308, 833,251, 631, 107],
[813, 883, 451, 509, 615, 77, 281, 613, 459, 205, 380, 274, 302, 35, 805]
]
# import time
# start = time.time()
for i in range(len(matrix)):
for j in range(len(matrix)):
matrix[i][j] = 1000-matrix[i][j]
zero_matrix = hungary(matrix)
path = assignment(zero_matrix)
add = 0
for p in path:
add += matrix[p[0]][p[1]]
print("The largest value is:", 15000-add)
# end = time.time()
# print("Run time: ",end-start)
|
from win_keybindings import Keybinding
class TextInterpreter:
def __init__(self, transcription):
self.transcription = transcription
self.trigger = "Zelda"
self.keyboard = Keybinding()
self.commands = {
0: "turn off microphone",
1: "turn on microphone",
2: "turn off video",
3: "turn on video",
4: "type message",
5: "send message",
6: "quick message",
7: "raise hand",
8: "lower hand",
9: "start local recording",
10: "stop local recording",
11: "share screen",
12: "stop screen sharing",
13: "read speaker name",
14: "switch camera"
}
self.keypress_switch = {
0: self.keyboard.enable_disable_mic,
1: self.keyboard.enable_disable_mic,
2: self.keyboard.enable_disable_vid,
3: self.keyboard.enable_disable_vid,
4: self.type_message,
5: self.keyboard.send_chat_message,
6: self.quick_message,
7: self.keyboard.raise_lower_hand,
8: self.keyboard.raise_lower_hand,
9: self.keyboard.start_stop_local_recording,
10: self.keyboard.start_stop_local_recording,
11: self.keyboard.share_stop_screen,
12: self.keyboard.share_stop_screen,
13: self.keyboard.read_speaker_name,
14: self.keyboard.switch_camera
}
#interpret what the audio command is and return a command
def interpret_text(self):
if self.trigger in self.transcription:
selected_command = ''
for command in self.commands:
if self.commands[command] in self.transcription:
selected_command = command
self.simulate_keypress(selected_command)
else:
return
#Based on command, simulate the key press
def simulate_keypress(self, command):
self.keypress_switch[command]()
#Helper functions
def type_message(self):
message = self.transcription.split(self.trigger + " " + self.commands[4])[1].strip()
self.keyboard.type_chat_message(message)
def quick_message(self):
message = self.transcription.split(self.trigger + " " + self.commands[6])[1].strip()
self.keyboard.quick_message(message)
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head):
if head is None:
return head
last = None
while True:
tmp = head.next
head.next = last
last = head
if tmp is None:
return head
head = tmp
if __name__ == "__main__":
head = ListNode(1)
tmp = head
for i in range(2, 5):
tmp.next = ListNode(i)
tmp = tmp.next
tmp = head
while tmp is not None:
print(tmp.val, end=' ')
tmp = tmp.next
print(' ')
solution = Solution()
tmp = solution.reverseList(head)
while tmp is not None:
print(tmp.val, end=' ')
tmp = tmp.next
print(' ')
|
import sys
def happy_ladybugs(bugs):
mappings = {}
free_cell = False
happy = True
for i, bug in enumerate(bugs):
if i == 0 and i + 1 < len(bugs):
happy = bug == bugs[i + 1]
elif i == len(bugs) - 1:
happy = bugs[i - 1] == bug and happy
else:
happy = happy and (bugs[i - 1] == bug or bugs[i + 1] == bug)
# count the bugs
if bug == '_':
free_cell = True
elif bug in mappings:
mappings[bug] += 1
else:
mappings[bug] = 1
singles = 0
for bug, count in mappings.items():
if count == 1:
singles += 1
if singles > 0:
return 'NO'
if not free_cell:
return 'YES' if happy else 'NO'
return 'YES'
games = int(input())
for _ in range(games):
n = int(input())
b = input()
print(happy_ladybugs(b))
|
l12,l22=input().split()
if l12[:len(l12)-1]==l22[:len(l22)-1]:
print("yes")
else:
print("no")
|
a = {"name": "Chetan", "age": 27}
print a # {"name": "Chetan", "age": 27}
b = dict({"name": "Vivek"})
print b # {"name":"Vivek"}
b = dict([("name","Vivek"), ("age",27)])
print b # {'age': 27, 'name': 'Vivek'}
# Accessable by key
print b['name'] # Vivek
# Update the value
# dict.update() does the same
# Updating key directly is 3 times faster
b["name"] = "Naveen"
print b # {'age': 27, 'name': 'Naveen'}
# -------------------------------------------------------------------------------------
# Dictionary key cannot be updated(immutable)
# They are stored in hash
# A key can only be an int or string. No iterable object like list or set
# Value can be anything
# -------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------
# Removing items from dictionary
# -------------------------------------------------------------------------------------
# Pop
# Removes one element reading the key
b.pop("name")
print b # {'age': 27}
# clear
# Clears all the elements
b.clear()
print b # {}
'''
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
'''
# -------------------------------------------------------------------------------------
# Copy
# -------------------------------------------------------------------------------------
c = a.copy()
print c # {'age': 27, 'name': 'Chetan'}
# -------------------------------------------------------------------------------------
# Fromkeys
# Default value is set to None
# -------------------------------------------------------------------------------------
keys = {'a', 'e', 'i', 'o', 'u' }
vowels = dict.fromkeys(keys,"vowel")
print(vowels) # {'i': 'vowel', 'u': 'vowel', 'e': 'vowel', 'a': 'vowel', 'o': 'vowel'}
# -------------------------------------------------------------------------------------
# Get
# Gets a value by passing the name
# if no key then None
# Can return default value if None using comma separator
# -------------------------------------------------------------------------------------
print c.get("name") # Chetan
print c.get("lastname") # None
print c.get("lastname", "Patige") # Patige
# -------------------------------------------------------------------------------------
# Haskey
# -------------------------------------------------------------------------------------
if c.has_key("name"):
print "Exists" # Exists
# -------------------------------------------------------------------------------------
# Items
# Converts to a list
# -------------------------------------------------------------------------------------
i = c.items()
print i # List # [('age', 27), ('name', 'Chetan')]
print i[0][1] # 27
# -------------------------------------------------------------------------------------
# Iteritems
# -------------------------------------------------------------------------------------
for x,y in c.iteritems(): # name Chetan
print x,y # age 27
for item in c.iteritems(): # This is not the ideal way to do
print item # (name, Chetan)
print type(item) # Tuple
# -------------------------------------------------------------------------------------
# Iterkeys
# Same with itervalues()
# -------------------------------------------------------------------------------------
for item in c.iterkeys():
print item # age
print type(item) # string
# -------------------------------------------------------------------------------------
# Keys
# Same with values()
# -------------------------------------------------------------------------------------
print c.keys() # ['age', 'name']
print type(c.keys()) # List
# -------------------------------------------------------------------------------------
# Pop
# Delete element via key
# if element not there, raises error
# default value can be given
# -------------------------------------------------------------------------------------
c.pop("name")
print c # {'age': 27}
print c.pop("name", "No keys") # No keys
# -------------------------------------------------------------------------------------
# Setdefault
# returns value if key found
# else if sets the key with a default value or None
# -------------------------------------------------------------------------------------
output = c.setdefault("age")
print output # 27
output = c.setdefault("phno", "123")
print output # 123
print c # {'phno': '123', 'age': 27}
|
# ----------------------------------------------------------------------------------------
# Tuples are immutable - cannot change
# Mutable objects within a tuple are mutable
# Tuples are faster than lists
# ----------------------------------------------------------------------------------------
a = (1, 2, {"name": "Chetan"}, "hello", [1,2])
print a # (1, 2, {'name': 'Chetan'}, 'hello', [1,2])
print a[0] # 1
print a[-1] # hello
print a[-1][0] # 1
b = (5)
print type(b) # int
b = (5,)
print type(b) # tuple # use a , operator if there is just one element in the tuple
# ----------------------------------------------------------------------------------------
# Mutable objects within a tuple are mutable
a[-1][1] = 9
print a # (1, 2, {'name': 'Chetan'}, 'hello', [1,9])
# ----------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------
# Iterating a tuple
# ----------------------------------------------------------------------------------------
for i in a:
print i # (1, 2, {'name': 'Chetan'}, 'hello', [1,9])
'''
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
'''
# ----------------------------------------------------------------------------------------
# Concantenate tuples
# ----------------------------------------------------------------------------------------
a = (1,2,3)
b = (4,5,6)
print a + b # 1,2,3,4,5,6
print type(a + b) # tuple
# ----------------------------------------------------------------------------------------
# Count
# ----------------------------------------------------------------------------------------
print a.count(2) # 1 # Number of times an object is repeated
# ----------------------------------------------------------------------------------------
# Index
# ----------------------------------------------------------------------------------------
print a.index(1) # 0
|
# Dictionaries have a .get() method to search for a value instead of the my_dict[key] notation we have been using.
# If the key you are trying to .get() does not exist, it will return None by default:
# Delete a Key
available_items = {"health potion": 10, "cake of the cure": 5, "green elixir": 20, "strength sandwich": 25, "stamina grains": 15, "power stew": 30}
health_points = 20
#add the corresponding value of the key "stamina grains" to the health_points variable and remove the item "stamina grains" from the dictionary.
#If the key does not exist, add 0 to health_points
health_points += available_items.pop("stamina grains", 0)
#add the value of "power stew" to health_points and remove the item from the dictionary. If the key does not exist, add 0 to health_points.
health_points += available_items.get("power stew", 0)
available_items.pop("power stew", 0)
#add the value of "mystic bread" to health_points and remove the item from the dictionary. If the key does not exist, add 0 to health_points.
health_points += available_items.get("mystic bread", 0)
available_items.pop("mystic bread", 0)
print(available_items)
print(health_points)
# Get All Keys
# .keys() method that returns a dict_keys object. A dict_keys object is a view object,
# which provides a look at the current state of the dicitonary, without the user being able to modify anything.
user_ids = {"teraCoder": 100019, "pythonGuy": 182921, "samTheJavaMaam": 123112, "lyleLoop": 102931, "keysmithKeith": 129384}
num_exercises = {"functions": 10, "syntax": 13, "control flow": 15, "loops": 22, "lists": 19, "classes": 18, "dictionaries": 18}
users = user_ids.keys()
lessons = num_exercises.keys()
print(users)
print(lessons)
# Get All Values
num_exercises = {"functions": 10, "syntax": 13, "control flow": 15, "loops": 22, "lists": 19, "classes": 18, "dictionaries": 18}
total_exercises = 0
for num in num_exercises.values():
total_exercises += num
print(total_exercises)
# Get All Items
pct_women_in_occupation = {"CEO": 28, "Engineering Manager": 9, "Pharmacist": 58, "Physician": 40, "Lawyer": 37, "Aerospace Engineer": 9}
for job, num in pct_women_in_occupation.items():
print("Women make up " + str(num) + " percent of " + job + "s")
# Review
tarot = { 1: "The Magician", 2: "The High Priestess", 3: "The Empress", 4: "The Emperor", 5: "The Hierophant",
6: "The Lovers", 7: "The Chariot", 8: "Strength", 9: "The Hermit", 10: "Wheel of Fortune", 11: "Justice",
12: "The Hanged Man", 13: "Death", 14: "Temperance", 15: "The Devil", 16: "The Tower", 17: "The Star", 18: "The Moon",
19: "The Sun", 20: "Judgement", 21: "The World", 22: "The Fool"}
spread = {}
spread["past"] = tarot.pop(13)
spread["present"] = tarot.pop(22)
spread["future"] = tarot.pop(10)
for key, value in spread.items():
print("Your "+ key +" is the "+ value +" card.")
# SUMA LOS VALORES DE UN DICCIONARIO
def sum_values(my_dictionary):
suma = 0
for num in my_dictionary.values():
suma += num
return suma
print(sum_values({"milk":5, "eggs":2, "flour": 3}))
# should print 10
print(sum_values({10:1, 100:2, 1000:3}))
# should print 6
# SUMA LOS NUMEROS PARES DE UN DICCIONARIO
def sum_even_keys(my_dictionary):
total = 0
for key in my_dictionary.keys():
if key % 2 == 0:
total += my_dictionary[key]
return total
print(sum_even_keys({1:5, 2:2, 3:3}))
# should print 2
print(sum_even_keys({10:1, 100:2, 1000:3}))
# should print 6
# SUMA 10 A CADA VALOR
def add_ten(my_dictionary):
suma = 0
for i in my_dictionary.keys():
my_dictionary[i] += 10
return my_dictionary
print(add_ten({1:5, 2:2, 3:3}))
# should print {1:15, 2:12, 3:13}
print(add_ten({10:1, 100:2, 1000:3}))
# should print {10:11, 100:12, 1000:13}
# Largest Value
def max_key(my_dictionary):
largest_key = float("-inf")
largest_value = float("-inf")
for key, value in my_dictionary.items():
if value > largest_value:
largest_value = value
largest_key = key
return largest_key
print(max_key({1:100, 2:1, 3:4, 4:10}))
# should print 1
print(max_key({"a":100, "b":10, "c":1000}))
# should print "c"
# Word Length Dict
def word_length_dictionary(words):
w_len = {}
for w in words:
w_len[w] = len(w)
return w_len
print(word_length_dictionary(["apple", "dog", "cat"]))
# should print {"apple":5, "dog": 3, "cat":3}
print(word_length_dictionary(["a", ""]))
# should print {"a": 1, "": 0}
# Frequency Count
def frequency_dictionary(words):
freqs = {}
for word in words:
if word not in freqs:
freqs[word] = 0
freqs[word] += 1
return freqs
print(frequency_dictionary(["apple", "apple", "cat", 1]))
# should print {"apple":2, "cat":1, 1:1}
print(frequency_dictionary([0,0,0,0,0]))
# should print {0:5}
# Unique Values
def unique_values(my_dictionary):
seen_values = []
for value in my_dictionary.values():
if value in seen_values:
continue
else:
seen_values.append(value)
return len(seen_values)
print(unique_values({0:3, 1:1, 4:1, 5:3}))
# should print 2
print(unique_values({0:3, 1:3, 4:3, 5:3}))
# should print 1
# Count First Letter
def count_first_letter(names):
letters = {}
for key in names:
first_letter = key[0]
if first_letter not in letters:
letters[first_letter] = 0
letters[first_letter] += len(names[key])
return letters
print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Lannister": ["Jaime", "Cersei", "Tywin"]}))
# should print {"S": 4, "L": 3}
print(count_first_letter({"Stark": ["Ned", "Robb", "Sansa"], "Snow" : ["Jon"], "Sannister": ["Jaime", "Cersei", "Tywin"]}))
# should print {"S": 7}
|
import sys # Module to modify error message
try:
x = int(input("x= "))
y = int(input("y= "))
except ValueError:
print("no puedes dividir entre palabras gafo")
sys.exit(1) # algo salio mal
try:
result = x / y
except ZeroDivisionError: # si algo sale mal entonces...
print("No puedes dividir entre 0 gafo")
sys.exit(1) # algo salio mal
print(f"{x} / {y} = {result}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.