text
stringlengths 37
1.41M
|
---|
print("Donam el radi de la circunferencia")
entrada1=input()
radi=int(entrada1)
import math
print("la seva area es",math.pi*radi**2)
print("el seu perimetre es:",2*math.pi*2)
|
import numpy as np
import matplotlib.pyplot as plt
import innout as io
def plot_cities(cities, route):
plt.ion()
plt.figure()
#plt.scatter(cities[:,0], cities[:,1], s=1, c='black', alpha=0.5)
plt.plot(cities[route[0],0], cities[route[0],1], c='red', alpha=0.5)
plt.axis('tight')
plt.hold(True)
plt.figure()
plt.plot(cities[route[1],0], cities[route[1],1], c='green', alpha=0.5)
plt.axis('tight')
plt.show()
|
# Вывод приветствия.
# Здесь мы создаем две функции, которые вызываются из третьей функции.
# Здесь мы можем рассмотреть работу стека вызовов.
# ----------
# Printing greetings.
# Here we create two functions, that are called by the third function.
# Here we can see how a call stack works.
# Создаем функцию "how_are_you", которая выводит на экран текст "How are you, username ?" при помощи функции "print()".
# Эта функция принимает один входной параметр: имя "username" того, кого приветствуют.
# ----------
# Create the function "how_are_you" that prints the message "How are you, username ?" to the screen
# using the function "print()".
# This function accepts one parameter: the name "username" of the person being greeted.
def how_are_you(username):
print("How are you,", username, "?")
# Создаем функцию "bye", которая выводит на экран текст "Ok, bye!" при помощи функции "print()".
# Эта функция не принимает никаких входных параметров.
# ----------
# Create the function "bye" that prints the message "Ok, bye!" to the screen using the function "print()".
# This function doesn't have any parameters.
def bye():
print("Ok, bye!")
# Создаем функцию "greet", которая выводит на экран текст "Hello, username !" при помощи функции "print()",
# а также вызывает функции "how_are_you" и "bye".
# Эта функция принимает один входной параметр: имя "username" того, кого приветствуют.
# ----------
# Create the function "greet" that prints the message "Hello, username !" to the screen using the function "print()"
# and calls the functions "how_are_you" and "bye".
# This function accepts one parameter: the name "username" of the person being greeted.
def greet(username):
# Стек вызовов содержит функцию "greet".
# Функция "greet" выполняет свою работу: выводит на экран
# сообщение "Hello, username !" при помощи функции "print()".
# ----------
# The call stack contains the function "greet".
# The function "greet" does its work: it prints
# the message "Hello, username !" to the screen using the function "print()".
print("Hello,", username, "!")
# Функция "greet" вызывает функцию "how_are_you".
# В стеке вызовов работа функции "greet" приостанавливается.
# В стек вызовов наверх добавляется функция "how_are_you".
# Функция "how_are_you" выполняет свою работу: выводит на экран сообщение "How are you, username ?"
# ----------
# The function "greet" calls the function "how_are_you".
# The function "greet" is suspended in the call stack.
# The function "how_are_you" is added to the call stack.
# The function "how_are_you" does its work: it prints the message "How are you, username ?" to the screen.
how_are_you(username)
# Функция "how_are_you" завершает свою работу, передает управление функции "greet" и убирается из стека вызовов.
# Функция "greet" возобновляет свою работу и выводит на экран
# текст "Ok, bye in 3 .. 2 .. 1" при помощи функции "print()".
# ----------
# The function "how_are_you" stops its work, transfers control to the function "greet"
# and is removed from the call stack.
# The function "greet" resumes its work and prints
# the message "Ok, bye in 3 .. 2 .. 1" to the screen using the function "print()".
print("Ok, bye in 3 .. 2 .. 1")
# Функция "greet" вызывает функцию "bye".
# В стеке вызовов работа функции "greet" снова приостанавливается.
# В стек вызовов наверх добавляется функция "bye".
# Функция "bye" выполняет свою работу: выводит на экран сообщение "Ok, bye!"
# ----------
# The function "greet" calls the function "bye".
# The function "greet" is suspended again in the call stack.
# The function "bye" is added to the call stack.
# The function "bye" does its work: it prints the message "Ok, bye!" to the screen.
bye()
# Функция "bye" завершает свою работу, передает управление функции "greet" и убирается из стека вызовов.
# Функция "greet" возобновляет свою работу.
# Функция "greet" завершает свою работу убирается из стека вызовов.
# ----------
# The function "bye" stops its work, transfers control to the function "greet" and is removed from the call stack.
# The function "greet" resumes its work.
# The function "greet" stops its work and is removed from the call stack.
# Пытаемся поприветствовать пользователя John Shepard.
# ----------
# Try to greet user John Shepard.
greet("John Shepard")
|
from random import randint as random
print('welcome mubas')
'''
this program is called dice rolling simulator
the program will randomly pick a number from 1 - 6 and ask the user if he will
like to continue or not
'''
while True:
first_num = random(1, 6)
second_num = random(1, 6)
print(f'({first_num} , {second_num})')
user_input = input('would you like to continue if yes type y or yes else n or no: ').upper()
if user_input == 'Y' or user_input == 'YES':
continue
elif user_input == 'N' or user_input == 'NO':
print('ok')
break
else:
print('wrong input it will terminate now')
break
print('thank for dicing')
|
import datetime
class Person:
def __init__(self, name, age):
super().__init__()
self.name = name
self.age = age
@staticmethod
def is_teen(age):
"""This is a toolbox function - it does not affect class properties"""
return age in range(13, 20)
def check_teenager(self):
return self.age in range(13, 20)
@classmethod
def from_birthyear(cls, name, year):
"""Method bound to the class itself. As results it will return Person class
Used for factories - creating collection of classes"""
age = datetime.datetime.now().year - year
return cls(name=name, age=age)
factory_parameters = {
'Jeff': 2001,
'Mike': 1895,
'James': 2013,
'Kilo': 2016,
'Lima': 1985,
}
# created a collection of classes from factory_parameters
factory = [Person.from_birthyear(key, value) for key, value in factory_parameters.items()]
print(factory)
|
from dogClass import Dog
patient1 = Dog()
patient2 = Dog()
patient3 = Dog()
patient4 = Dog()
patient5 = Dog()
currentPatients = [patient1, patient2, patient3, patient4, patient5]
currentRoster = [patient1.name, patient2.name, patient3.name, patient4.name, patient5.name]
def printCurrentRoster():
counter = 1
for x in currentRoster:
print(f'{counter}' + ': ' + f'{x}')
counter += 1
def customDog():
name = input("Enter the dog's name")
weight = int(input("Enter the dog's weight"))
breed = input("Enter the dog's breed")
age = input("Enter the dog's age")
color = input("Enter the dog's color")
patient = Dog(name, weight, breed, age, color, True)
currentPatients.append(patient)
currentRoster.append(patient.name)
def doStuff():
printCurrentRoster()
action = int(input(
"Enter the number of the dog you'd like to know more about, or enter 0 to check in a new patient."
))
if(0 < action <= len(currentRoster)):
currentPatients[action-1].printDog()
doStuff()
elif(action == 0):
customDog()
doStuff()
else:
print('Invalid Input')
doStuff()
doStuff()
|
from threading import Thread,Lock
import time
num = 0
def test1():
global num
mutex.acquire()
for x in range(1000000):
num += 1
mutex.release()
print("---test1---num=%d"%num)
def test2():
global num
mutex.acquire()
for x in range(1000000):
num += 1
mutex.release()
print("---test2---num=%d"%num)
mutex = Lock()
thread = Thread(target = test1)
thread.start()
#time.sleep(3)
thread = Thread(target = test2)
thread.start()
|
def single_letter_count(string,letter):
return string.lower(). count(letter.lower())
print(single_letter_count('sangram','A'))
def multiple_letter_count(string):
return {letter: string.count(letter) for letter in string}
print(multiple_letter_count('sojoeijeoaioie'))
def multiple_letter_count1(stringg):
return [stringg.count(letterr) for letterr in stringg]
print(multiple_letter_count1('sojoeijeoaioie'))
|
def str (name):
return "hello, to" + name
print ("A sweet"), str("Eleni")
if not true:
print "haha"
if (2*2)>2:
print "hoho"
if str("Eleni") != b:
print "haha"
def add(a,b):
return a+b
x = 0
if not false and (true and false) or false:
print x
if ((add(1,2))-- != 3) and (not (x<1)):
print "haha"
|
operations = {
1: '+',
2: '-',
3: '*',
4: '/'
}
try:
# Displaying the possibilities
for key, value in operations.items():
print(f"Enter {key} to perform {value} operation")
user_input = int(input())
# Taking Numbers from user
first_num = int(input("Enter the first number: "))
second_num = int(input("Enter the second number: "))
# Logic of the programme
if user_input == 1:
print(f"The result is {first_num + second_num}")
elif user_input == 2:
print(f"The result is {first_num - second_num}")
elif user_input == 3:
print(f"The result is {first_num * second_num}")
elif user_input == 4:
print(f"The result is {first_num / second_num}")
else:
print("You have entered an invalid input!")
except:
print("Sorry, the programme can't handle this")
|
class Employee:
number_of_leaves=8
def __init__(self,name,salary,role):
self.name=name
self.salary=salary
self.role=role
def printdetail(self):
return f"The name is {self.name}.\nsalary is {self.salary}.\nrole is {self.role}"
@classmethod
def change_leaves(cls,newleaves):
cls.number_of_leaves=newleaves
@classmethod
def from_dash(cls,string):
return cls(*string.split("-"))
class programmer(Employee):
def __init__(self,name,salary,role,languages):
self.name=name
self.salary=salary
self.role=role
self.languages=languages
def printprog(self):
return f"The programmer's name is {self.name}.\nsalary is {self.salary}.\nrole is {self.role}.\nlanguages are {self.languages}"
pratik=Employee("Pratik",50000,"Student")
jack=Employee("Jack",60000,"super visor")
john=programmer("john",795,"programmer",["python"])
karan=programmer("karan",365,"programmer",["python","Cpp"])
print(karan.printprog())
|
class Parent:
def __init__(self,name):
print('Parent__init__',name)
class Parent2:
def __init__(self,name):
print('Parent2__init__',name)
class Child(Parent2,Parent):
def __init__(self):
print('Child__init__')
super().__init__('max')
child=Child()
print(child.__dict__)
print(child.__repr__())
|
from array import *
vals=array('i',[2,3,4,5])
for i in range(4):
print(vals[i])
#
# for i in vals:
# print(i)
#
# for i in range(len(vals)):
# print(vals[i])
|
# -*- coding: utf-8 -*-
"""
Nelson: Exercise 2.7
Created on Thu Nov 13 11:17:48 2014
@author: sbroad
"""
import numpy as np
import matplotlib.pyplot as plt
"""
Calculate demand on any given day according to the data in the book.
"""
inv_f = np.array([415,704,214,856,620,353,172,976,735,433,217,860,598,833])
ordered = np.array([0 if (i%2==1 or q > 1000) else 1000- q for (i,q) in zip(range(np.size(inv_f)),inv_f)])
inv_i = np.concatenate(([700],(inv_f+ordered)[:-1]))
demd = inv_i-inv_f
mu = np.mean(demd)
sigma = np.std(demd)
"""
Implement the stochastic process
S(n) = (I(n),O(n),L(n),R(n))
I(n) = start of day inventory
O(n) = number ordered, orders only take place on odd days
, and received on even days
L(n) = number of lost sales
R(n) = number of completed sales
T(n) = day number, advances by 1 each day
Y(t) = state at time t
e0 = start simulation
e1 = customer buying hamburgers on a day
e2 = placing an order
e3 = receiving an order
"""
inv_init = 700
order_thresh = 600
inv_max = 1000
demand_mu = 250
demand_sigma = 50
C = [0, np.inf, np.inf, np.inf]
S = [700, 0, 0, 0]
N = 100
T = 0
out_f = open('state.csv', mode = 'w')
out_f.write('Step (n),Time (t),Event (i),Inventory (I),Order(O),Lost Sales (L),Sales (R)\n')
for j in range(N):
T = min(C)
I = np.argmin(C)
event_state = [j, T, I] + S
out_f.write(','.join([str(v) for v in event_state]) + '\n')
if I == 0: # start simulation
C[0] = np.inf
C[1] = 1
S = [inv_init, 0, 0, 0]
elif I == 1: # buy hamburgers
# reset the clock for tomorrow
C[1] = T + 1
# randomly generate the demand
D = int(np.random.normal(loc=demand_mu,scale=demand_sigma))
S[0] -= D
S[3] += D
# compute sales losses
if S[0] < 0:
S[2] -= S[0] # add to the lost sales
S[3] += S[0] # subtract from made sales
S[0] = 0 # reset inventory to 0
# do we need to place an order?
if T % 2 >= 1 and S[0] < order_thresh:
C[2] = T + 0.5 # schedule the order event
elif I == 2: # order hanmburgers
C[2] = np.inf # don't know when next order will be placed
C[3] = T + 1 # receive the order tomorrow
S[1] = inv_max - S[0] # setup the number of patties ordered
elif I == 3:
C[3] = np.inf # don't know when next order will arrive
S[0] += S[1] # add inventory from order
S[1] = 0 # reset the order amount
else:
print 'Weird.... how did we get here?!?!'
print S, 'Percent Loss:', S[2]*100./S[3]
out_f.close()
|
# -*- coding: utf-8 -*-
"""
Exponential least squares
Created on Fri Aug 22 11:41:12 2014
@author: sbroad
"""
import numpy as np
import matplotlib.pyplot as plt
# the x and y data
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
y = np.array([0.12, 0.24, 0.72, 1.30, 1.90])
# plot this data
plt.plot(x, y, '+')
# compute the log of all y values
logy = np.log(y)
# linear fit the logy data to the x data
p = np.polyfit(x, logy, 1) # the one is the degree of the polynomial
print p
# make a function from the polynomial fit
logf = np.poly1d(p)
# plot the fit function
X = np.linspace(-1, 5, 21) # a range of values that encompass all x data
# the fit is logarithmic so we must compose the exponential function
plt.plot(X, np.exp(logf(X)),'--')
# plot the fits for the original data points
plt.plot(x, np.exp(logf(x)), 'o')
|
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 17 10:00:49 2014
@author: sbroad
"""
import numpy as np
import matplotlib.pyplot as plt
def empirical_cdf(xvals,data=np.random.random(50)):
"""
Compute the cumulative probabilities of possible outcomes of a random
variable, given an empirical data set as the basis of an empirical
cumulative distribution function.
xvals --> The values for which cumulative probabilities are required.
May be a multidimensional array.
data --> The empirical data on which to base these probabilities.
Default value: 50 observations from a uniform random variable on
the interval [0,1]
Note: this function is designed to be plot-able i.e., if x is a vector of
input values, and d is an empirical data set, then
plot(x, empirical_cdf(x,d))
produces a plot of the empirical CDF.
"""
n = float(np.size(data)) # determine the size of the empirical data
# copy and flatten the input value array. we will reshape it later.
cdfvals = np.copy(xvals).flatten()
# compute the empirical cumulative probability for each input value
for i in range(len(cdfvals)):
# first we need to know how many empirical data points are less than
# the input value
ks = np.where(data<cdfvals[i])
# the cumulative empirical probability is the proportion of the
# data points that are less than or equal to the input value
cdfvals[i] = np.size(ks)/n
# we have now computed all cumulative probabilities
# return the reshaped cumulative probability array
return np.reshape(cdfvals,np.shape(xvals))
'''
Example: obtain the general shape of the cdf of a normal random variable.
Mean = 0, Standard Deviation = 1
Use 100 different empirical data sets to generate pictures of the cdfs.
'''
d = np.random.binomial(n=2, p=0.50, size=50)
xs = np.linspace(-1,3,1001)
plt.plot(xs,empirical_cdf(xs,data=d),'.')
|
import random
SUIT_LIST = ["♠", "♥", "♦", "♣"]
RANK_DICTIONARY = {
"A": 11, # Special case - sometimes this can be 1
"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "J": 10, "Q": 10, "K": 10}
def create_card_deck():
card_deck = []
for suit in SUIT_LIST:
for rank in RANK_DICTIONARY:
card = rank + suit
card_deck.append(card)
return card_deck
def shuffle_card_deck(card_deck):
random.shuffle(card_deck)
return card_deck
def draw_card(card_deck):
card = card_deck.pop()
return card
def draw_hand(card_deck):
return [
draw_card(card_deck),
draw_card(card_deck)
]
def get_card_rank(card):
suit_string = ''.join(SUIT_LIST)
return card.strip(suit_string)
def evaluate_hand(hand_of_cards):
hand_value = 0
ace_is_present = False
for card in hand_of_cards:
rank = get_card_rank(card)
card_value = RANK_DICTIONARY[rank]
hand_value += card_value
if card_value == 11:
ace_is_present = True
player_is_bust = is_player_bust(hand_value)
if ace_is_present and player_is_bust:
hand_value -= 10
return hand_value
def is_player_bust(hand_value):
return hand_value > 21
def get_players_choice(choice_description, valid_choice_list):
while True:
choice = input(choice_description).upper()
if choice in valid_choice_list:
return choice
print("Invalid choice")
def get_players_move(card_deck, players_hand):
while True:
print(players_hand)
players_hand_value = evaluate_hand(players_hand)
if players_hand_value >= 21:
break
players_choice = get_players_choice("[H]it or [S]tand? ", ["H", "S"])
if players_choice == "S":
break
another_card = draw_card(card_deck)
players_hand.append(another_card)
return players_hand_value
def check_for_blackjack(hand_of_cards):
hand_value = evaluate_hand(hand_of_cards)
if hand_value != 21:
return
if len(hand_of_cards) > 2:
return
for card in hand_of_cards:
rank = get_card_rank(card)
card_value = RANK_DICTIONARY[rank]
if card_value == 11:
print("Blackjack!")
def play_round_of_cards():
card_deck = create_card_deck()
card_deck = shuffle_card_deck(card_deck)
dealers_hand = draw_hand(card_deck)
players_hand = draw_hand(card_deck)
players_hand_value = get_players_move(card_deck, players_hand)
dealers_hand_value = evaluate_hand(dealers_hand)
print("I have:", dealers_hand)
if is_player_bust(players_hand_value):
print("You are bust")
elif players_hand_value > dealers_hand_value:
print("You win")
check_for_blackjack(players_hand)
elif players_hand_value < dealers_hand_value:
print("I win")
check_for_blackjack(dealers_hand)
else:
print("draw")
def main():
play_again = True
while play_again:
play_round_of_cards()
play_again = get_players_choice("Play [A]gain or [Q]uit?", ["A", "Q"])
if __name__ == '__main__':
main()
|
from AIPlayer import AIPlayer
from HumanPlayer import HumanPlayer
from GameBoard import GameBoard
def main():
clear_screen()
print('Welcome to our Naughts & crosses game. Do you feel lucky punk?')
while True:
play_game()
if players_are_bored():
break
def play_game():
global game_board
game_board = GameBoard(3, 3)
players = get_players()
player_number = 1
for move_number in range(1, game_board.width * game_board.height):
message = f'Player {game_board.get_player_letter(player_number)}''s turn.'
print(message)
game_board.draw_ascii_board()
players[player_number - 1].make_move()
if game_board.player_has_won(player_number):
finish_game(player_number)
return
clear_screen()
player_number = 3 - player_number
print("It's a draw - how dull.")
def get_players():
print("Which game mode do you wish to use?")
choices = [('A', 'Computer vs Computer', get_ai_vs_ai_opponents()),
('B', 'Human vs Human', get_human_vs_human_opponents()),
('C', 'Computer vs Human', get_ai_vs_human_opponents())]
for choice in choices:
print('{0} {1}'.format(choice[0], choice[1]))
while True:
game_mode = input(': ').upper()
for choice in choices:
if choice[0] == game_mode:
return choice[2]
def get_ai_vs_human_opponents():
return (
AIPlayer(1, game_board),
HumanPlayer(2, game_board)
)
def get_human_vs_human_opponents():
return (
HumanPlayer(1, game_board),
HumanPlayer(2, game_board)
)
def get_ai_vs_ai_opponents():
p1 = AIPlayer(1, game_board)
p2 = AIPlayer(2, game_board)
return p1, p2
def finish_game(winning_player):
clear_screen()
print(f"Well done player {game_board.get_player_letter(winning_player)}, you won!")
game_board.draw_ascii_board()
def clear_screen():
print('\n' * 3)
def players_are_bored():
while True:
are_they_bored = input('Are you bored yet [y/n]? ').lower()
if are_they_bored == 'y':
print('Charming! Bye then...')
return True
if are_they_bored == 'n':
clear_screen()
print('Excellent! Another game, goody...')
return False
print('Huh? ')
main()
|
import pygame
from Cell import Direction
from Point import Point
class Player:
def __init__(self, maze, location):
self.maze = maze
self.point = Point(location)
self.colour = pygame.Color("yellow")
self.direction = Direction.UP
self.look()
def look(self):
directions = (
self.direction,
self.direction.rotate_clockwise(),
self.direction.rotate_anticlockwise()
)
for direction in directions:
visible_cell = self.current_cell
for distance in range(0, 5):
visible_cell.visible = True
if direction not in visible_cell.exits:
break
adjacent_point = visible_cell.point.get_adjacent_point(direction)
visible_cell = self.maze.cells[adjacent_point]
def update(self):
self.maze.draw_polygon(self.__get_points(), self.point, self.direction.angle_in_radians,
self.colour)
@staticmethod
def __get_points():
return (
(.3, .9),
(.5, .1),
(.7, .9)
)
def handle(self, event):
if event.type != pygame.KEYDOWN:
return
if event.key == pygame.K_UP:
self.__move_if_possible(self.direction)
return
if event.key == pygame.K_DOWN:
self.__move_if_possible(self.direction.opposite)
return
if event.key == pygame.K_LEFT:
self.direction = self.direction.rotate_anticlockwise()
elif event.key == pygame.K_RIGHT:
self.direction = self.direction.rotate_clockwise()
self.look()
def __move_if_possible(self, direction):
if direction not in self.current_cell.exits:
return
self.point.move(direction)
self.look()
if self.current_cell.is_end:
self.current_cell.is_end = False
self.maze.randomly_place_end(self.point, 20)
@property
def current_cell(self):
return self.maze.cells[self.point.location]
|
def main():
x1,y1,x2,y2 = eval(input("Enter two points x1, y1, x2, y2: "))
p2 = Point(x2,y2)
p1 = Point(x1,y1)
distance = p2.distance(p1)
print("The distance between the two points is: "+format(distance,"0.2f"))
if(p2.isNearBy(p1)):
print("The two points are near each other")
else:
print("The two points are not near each other")
#print(p1)
class Point():
def __init__(self,x=0.0,y=0.0):
self.__x= x
self.__y =y
def get_x(self):
return self.__x
def get_y(self):
return self.__y
def set_x(self, value):
self.__x = value
def set_y(self, value):
self.__y = value
def distance(self,p1):
distance = ((self.__y-p1.get_y())**2+(self.__x-p1.get_x())**2)**0.5
return distance
def isNearBy(self,p1):
if(self.distance(p1)>5):
return False
else:
return True
def __str__(self,p1):
return str("(") + str(p1.get_x()) + str(",") + str(p1.get_y()) + str(")")
main()
|
n1,n2 = eval(input("Enter two integers to find their GCD: "))
gcd_found = False
if n1 > n2:
d = n2
else:
d = n1
while d > 1:
if n1%d == 0 and n2%d == 0:
gcd_found = True
print("The GCD of ",n1," and ",n2," is ",d)
break
d -= 1
if not gcd_found:
print("The GCD of ",n1," and ",n2," is 1")
|
number_elements = eval(input("Enter the number of elements: "))
numbers = []
for count in range(number_elements):
number = eval(input("Enter a number: "))
numbers.append(number)
rev_numbers = []
for count in range(len(numbers),0,-1):
rev_numbers.append(numbers[count-1])
print("Entered Elements: ",numbers)
print("Elements in reverse order: ",rev_numbers)
|
import time
class Time:
def __init__(self):
total_seconds = int(time.time())
self.__second = total_seconds % 60
total_minutes = total_seconds // 60
self.__minute = total_minutes % 60
total_hours = total_minutes // 60
self.__hour = total_hours % 24
def getHour(self):
return self.__hour
def getMinute(self):
return self.__minute
def getSecond(self):
return self.__second
def setTime(self,elapsedTime):
if int(elapsedTime) > 0:
total_seconds = int(elapsedTime)
self.__second = total_seconds % 60
total_minutes = total_seconds // 60
self.__minute = total_minutes % 60
total_hours = total_minutes // 60
self.__hour = total_hours % 24
|
def sumDigits(n):
digit = n%10
rem = n//10
if n != 0:
return digit + sumDigits(rem)
else:
return 0
input_int = eval(input("Enter an integer: "))
print("The sum of digits in ",input_int," is ",sumDigits(input_int))
|
str1 = input("Enter the first string: ").strip()
str2 = input("Enter the second string: ").strip()
def isASubstring(s1, s2):
index_start = 0
rem_len = len(s2)
while len(s1) <= rem_len:
if s1!= s2[index_start : index_start + len(s1)]:
index_start += 1
rem_len += 1
else:
return index_start
return -1
if isASubstring(str1,str2) != -1:
print("First string is a substring of the second string")
else:
print("First string is not a substring of the second string")
|
import turtle
turtle.pensize(2)
turtle.penup()
turtle.goto(-120, -120)
turtle.pendown()
turtle.color("black")
for grid_square in range(0,4,1):
turtle.forward(240)
turtle.left(90)
for y_axis in range(-120, 90, 60):
for x_axis in range(-120, 120, 60):
turtle.penup()
turtle.goto(x_axis, y_axis)
turtle.pendown()
turtle.begin_fill()
for k in range(0,4,1):
turtle.forward(30)
turtle.left(90)
turtle.end_fill()
for y_axis in range(-90, 120, 60):
for x_axis in range(-90, 120, 60):
turtle.penup()
turtle.goto(x_axis, y_axis)
turtle.pendown()
turtle.begin_fill()
for k in range(4):
turtle.forward(30)
turtle.left(90)
turtle.end_fill()
turtle.hideturtle()
turtle.done()
|
import random
random_card_number = random.randint(0, 51)
rank_number = random_card_number % 13
if rank_number == 0:
rank = "Ace"
elif rank_number == 10:
rank = "Jack"
elif rank_number == 11:
rank = "Queen"
elif rank_number == 12:
rank = "King"
else:
rank = str(rank_number)
suit_number = random_card_number // 13
if suit_number == 0:
suit = "Clubs"
elif suit_number == 1:
suit = "Diamonds"
elif suit_number == 2:
suit = "Hearts"
elif suit_number == 3:
suit = "Spades"
print("Random card number is: ",random_card_number)
print("The card you picked is the ",rank," of ",suit)
|
def bubbleSort(lst):
for i in range(len(lst)):
for j in range(len(lst)-1,i,-1):
if lst[i] > lst[j]:
temp = lst[j]
lst[j] = lst[i]
lst[i] = temp
print(lst)
input_list = input("Enter a list of 10 numbers: ")
input_items = input_list.split()
lst = [eval(x) for x in input_items]
bubbleSort(lst)
|
import numbers
import collections
import abc
x = 30
y = [20, 30]
print(type(x))
def f(x):
if isinstance(x, int):
x += 20
if isinstance(x, list):
x += [20]
return x
print(f(x))
print(x)
print(f(y))
print(y)
|
raspuns_corect = "is reading"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
puncte = 10
print("")
print("Pune verbele din paranteza la Prezent Continuu.")
print("")
print("Exemplu: My sister (watch) is watching TV.")
print("")
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("1) Father _______ (read) the newspaper now.")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
raspuns_corect = "is cooking"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("2) She _______ (cook) in the kitchen at the moment.")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
raspuns_corect = "is snowing"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("3) Look! It _______ (snow).")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
raspuns_corect = "is watching"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("4) My sister _______ (watch) TV.")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
raspuns_corect = "are not playing"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("5) The children _______ (not/play) football now.")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
raspuns_corect = "is sleeping"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("6) He _______ (sleep) at the moment.")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
raspuns_corect = "is playing"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("7) Listen! Mother _______ (play) the piano.")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
raspuns_corect = "is doing"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("8) Ann _______ (do) her homework.")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
raspuns_corect = "am going"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("9) I _______ (go) to church.")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
raspuns_corect = "are swimming"
raspuns_primit = ""
numar_raspunsuri = 0
limita_raspunsuri = 3
limita_depasita = False
while raspuns_primit != raspuns_corect and not(limita_depasita):
if numar_raspunsuri < limita_raspunsuri:
raspuns_primit = input("10) The girls _______ (swim) in the sea now.")
numar_raspunsuri = numar_raspunsuri + 1
else:
limita_depasita = True
if limita_depasita:
print("Ai depasit limita de raspunsuri! Pierzi un punct")
puncte = puncte -1
else:
print("Felicitari! Nu pierzi niciun punct")
if puncte > 5:
print("Felicitari, ai trecut testul cu nota " + str(puncte) + "!")
else:
print("Imi pare rau! Ai picat testul cu nota " + str(puncte) + "!")
|
import secrets
import string
def password_generator(length):
chars = string.ascii_letters + string.digits + string.punctuation
pwd = ''.join(secrets.choice(chars) for _ in range(length))
print('The password generated by python is:', pwd)
length = int(input('Enter the length of the password: '))
password_generator(length)
|
# List project on inviting guest for dinner
# If you could invite anyone, living or deceased, to dinner, who
# would you invite? Make a list that includes at least three people you’d like to
# invite to dinner. Then use your list to print a message to each person, inviting
# them to dinner.
#
guest = ['raj', 'dhruv', 'mahesh', 'sonali', 'teju']
print('Hi ' + guest[0].title() + ' i would like you to invite'
' for dinner at my place.\nIt will be great if you can join us.')
print('Hi ' + guest[1].title() + ' i would like you to invite'
' for dinner at my place.\nIt will be great if you can join us.')
print('Hi ' + guest[2].title() + ' i would like you to invite'
' for dinner at my place.\nIt will be great if you can join us.')
print('Hi ' + guest[3].title() + ' i would like you to invite'
' for dinner at my place.\nIt will be great if you can join us.')
print('Hi ' + guest[4].title() + ' i would like you to invite'
' for dinner at my place.\nIt will be great if you can join us.')
print('looks like ' + guest[0] + ' is not coming')
notComing_guest = guest.pop(0)
print(guest)
print(notComing_guest + ' will be not coming.Just got confirmation')
guest.append('Vishal')
print(guest)
print("we' got bigger table!")
guest.insert(0,'amol')
guest.insert(3,'yash')
guest.append('rahul')
print('Hi ' + guest[0].title() + ' i would like you to invite'
' for dinner at my place.\nIt will be great if you can join us.')
print('Hi ' + guest[3].title() + ' i would like you to invite'
' for dinner at my place.\nIt will be great if you can join us.')
print('Hi ' + guest[-1].title() + ' i would like you to invite'
' for dinner at my place.\nIt will be great if you can join us.')
print(guest)
print('sorry to inform you that we only have space for two members')
notComing_guest = guest.pop()
print(notComing_guest)
notComing_guest = guest.pop()
print(notComing_guest)
print(guest)
notComing_guest = guest.pop()
print(notComing_guest)
guest.pop()
print(guest)
guest.pop()
guest.pop()
print(guest)
print(guest[0] + ' you are invited to dinner')
print(guest[1] + ' you are invited to dinner')
del guest[0]
del guest[0]
print(guest)
print("list is empty")
|
## NICHOLAS BROWN
## CPS 300
def one ():
# replace this for-loop with a while loop
# don't change any more than is necessary
## for j in range(20):
## print ("{0:2} x 2 = {1:<2}".format(j,j*2))
##
j = 0
while j < 20:
print ("{0:2} x 2 = {1:<2}".format(j,j*2))
j+=1
def two ():
low = 3
hi = 50
total = 0
# replace this for-loop with a while loop
# don't change any more than is necessary
##
## for m in range (hi, low-1,-2):
## total = total + m
##
m = hi
while m > low-1:
total = total + m
m-=2
return total
def three ():
# replace this for-loop with a while loop
# don't change any more than is necessary
## for word in "This is a boring sentence".split ():
## print (word,len(word))
##
phrase = "This is a boring sentence".split ()
i = 0
while i < len(phrase):
print(phrase[i], len(phrase[i]))
i += 1
def four ():
# replace these for-loops with while loops
# don't change any more than is necessary
## for salute in ["hello","hi","greetings","hey!","<nod>"]:
## for person in ["Jane","Charles","Fitz"]:
## print (salute,person)
## i = 0
## w = 0
## salute = ["hello","hi","greetings","hey!","<nod>"]
## person = ["Jane","Charles","Fitz"]
##
## while i < len(salute):
## i += 1
## for p in person:
## print(salute[i],p)
i = 0
salute = ["hello","hi","greetings","hey!","<nod>"]
person = ["Jane","Charles","Fitz"]
while i < len(salute):
w = 0
while w < len(person):
print(salute[i],person[w])
w += 1
i += 1
def syracuse ():
# replace the next line with your code to
# (1) prompt user to enter an int
# (2) read the integer
# (3) print out (on one line) the Syracuse sequence
# that starts with the number entered by user
#
# For example, if user enters 5, following should be printed:
# 5 16 8 4 2 1
#
user_in = int(input("Enter a number: "))
printstring = str(user_in)
while user_in != 1:
if user_in % 2 == 0:
user_in = user_in // 2
else:
user_in = user_in*3 + 1
printstring = printstring + " " + str(user_in)
print (printstring)
|
#
# Name: Nicholas Brown
# CPS 300
# Homework 1
#
# Use this program and the accompanying library graphics.py to draw a house
#
from graphics import *
#################################################################
#
# Refinement Task 1: Allow user to set colors
#
#################################################################
# Options window
options_win = GraphWin("Select Your Color Options",400,400)
options_win.setCoords(0,0,400,400)
options_win.setBackground("white")
# Variables allow easy tweaking of GUI elements location
left_align = 100
verticle_align = 290
# Color Options
options_list = Text(Point(200,370),"Valid Color Options Include: ")
options_list_colors = Text(Point(200,340),"red, orange, yellow, green, blue, cyan, \n indigo, violet, purple, tan, grey, brown, black")
options_list_colors.setFace("arial")
options_list_colors.setSize(14)
options_list.setFace("arial")
options_list.setStyle("bold")
options_list.setSize(14)
options_list.draw(options_win)
options_list_colors.draw(options_win)
# House Color Query
wall_query = Text(Point(left_align,verticle_align),"Wall Color: ")
wall_query.setFace("arial")
wall_query.setStyle("bold")
wall_query.setTextColor("black")
wall_query.draw(options_win)
# House Color Response
wall_response = Entry(Point(left_align+90,verticle_align),10)
wall_response.setText("tan")
wall_response.setFill("grey")
wall_response.draw(options_win)
# Roof Color Query
roof_query = Text(Point(left_align,verticle_align-40),"Roof Color: ")
roof_query.setFace("arial")
roof_query.setStyle("bold")
roof_query.draw(options_win)
# Roof Color Response
roof_response = Entry(Point(left_align+90,verticle_align-40),10)
roof_response.setText("brown")
roof_response.setFill("grey")
roof_response.draw(options_win)
# Door Color Query
door_query = Text(Point(left_align,verticle_align-80),"Door Color: ")
door_query.setFace("arial")
door_query.setStyle("bold")
door_query.draw(options_win)
# Door Color Response
door_response = Entry(Point(left_align+90,verticle_align-80),10)
door_response.setText("red")
door_response.setFill("grey")
door_response.draw(options_win)
# Window Color Query
window_query = Text(Point(left_align,verticle_align-120),"Window Color: ")
window_query.setFace("arial")
window_query.setStyle("bold")
window_query.draw(options_win)
# Window Color Response
window_response = Entry(Point(left_align+90,verticle_align-120),10)
window_response.setText("cyan")
window_response.setFill("grey")
window_response.draw(options_win)
# Submit Button
submit_button = Rectangle(Point(left_align+10,verticle_align-150),Point(left_align+170,verticle_align-170))
submit_button.setFill("cyan")
submit_button.draw(options_win)
# Submit Button Text
submit_text = Text(Point(left_align+90,verticle_align-160), "Press Anywhere to Submit")
submit_text.setFace("arial")
submit_text.setStyle("bold")
submit_text.draw(options_win)
# Check for submit button press
if options_win.getMouse():
wall_color = wall_response.getText()
roof_color = roof_response.getText()
door_color = door_response.getText()
window_color = window_response.getText()
options_win.close()
###################################################################
#
# House Drawing Code with Instruction Steps Window
#
###################################################################
# Instructions Window
inst_win = GraphWin ("Instructions",400,400)
inst_win.setCoords(0,0,400,400)
inst_win.setBackground("white")
# Alignment Variables
inst_left_align = 200
inst_vert_align = 340
# Instruction Steps Text
inst_title = Text(Point(inst_left_align,inst_vert_align),"Follow the steps")
inst_title.setFace("arial")
inst_title.setSize(14)
inst_title.setStyle("bold")
inst_title.draw(inst_win)
# Step 1 Text
inst_step1 = Text(Point(inst_left_align + 10,inst_vert_align-40),"Step 1: Select bottom lefthand corner of house")
inst_step1.setSize(14)
inst_step1.draw(inst_win)
# Step 2 Text
inst_step2 = Text(Point(inst_left_align ,inst_vert_align-75),"Step 2: Select top righthand corner of house")
inst_step2.setSize(14)
inst_step2.draw(inst_win)
# Step 3 Text
inst_step3 = Text(Point(inst_left_align - 62,inst_vert_align-110),"Step 3: Select roof peak")
inst_step3.setSize(14)
inst_step3.draw(inst_win)
# Step 4 Text
inst_step4 = Text(Point(inst_left_align - 35, inst_vert_align-145),"Step 4: Select top corner of door")
inst_step4.setSize(14)
inst_step4.draw(inst_win)
# Step 5 Text
inst_step5 = Text(Point(inst_left_align - 47, inst_vert_align-180),"Step 5: Select window center")
inst_step5.setSize(14)
inst_step5.draw(inst_win)
# Done Text
inst_done = Text(Point(inst_left_align - 120, inst_vert_align-215),"Done !")
inst_done.setSize(14)
inst_done.draw(inst_win)
# Instruction Pointer
inst_pointer = Circle(Point(inst_left_align - 160, inst_vert_align-40),10)
inst_pointer.setFill("cyan")
inst_pointer.draw(inst_win)
# Open House Drawing Window
win = GraphWin ("Draw-a-house",800,800)
win.setCoords(0,0,800,800)
win.setBackground("white")
# Main Wall Coords
lower_left = win.getMouse()
inst_pointer.move(0,-35)
upper_right = win.getMouse()
# Main Wall Object
wall = Rectangle(lower_left,upper_right)
wall.setFill(wall_color)
wall.draw(win)
inst_pointer.move(0,-35)
# Get Roof Point
roof_point = win.getMouse()
# Upper Left Main Wall Coords
upper_left = Point(lower_left.getX(), upper_right.getY())
# Roof Object
roof = Polygon(roof_point,upper_right,upper_left)
roof.setFill(roof_color)
roof.draw(win)
inst_pointer.move(0,-35)
# Get Door Coords
door_upper_corner = win.getMouse()
door_other_corner = Point(roof_point.getX(),lower_left.getY())
# Door Object
door = Rectangle(door_other_corner,door_upper_corner)
door.setFill(door_color)
door.draw(win)
inst_pointer.move(0,-35)
# Get Window Coords
window_center_point = win.getMouse()
# Calculate Door Width
# Uses abs() function incase result is negative
door_width = abs((door_upper_corner.getX() - door_other_corner.getX()))
window_width = door_width/4
# Calculate Window Points
window_point1 = Point(window_center_point.getX() + window_width, window_center_point.getY() + 20)
window_point2 = Point(window_center_point.getX() - window_width, window_center_point.getY() - 20)
# Window Object
window = Rectangle(window_point1,window_point2)
window.setFill(window_color)
window.draw(win)
inst_pointer.move(0,-35)
|
#!/usr/bin/env python
import itertools
sums = {}
sums[1] = 1
sums[2] = 1
def flatten(listOfLists):
return itertools.chain.from_iterable(listOfLists)
def combs(n):
if n == 1:
combs = [1]
else:
if n == 2:
combs = [1, 1]
else:
combs = []
for k in xrange(1,int(round(n/2.0))):
combs.append([k, n-k])
return combs
def Sums(n):
c = combs(n)
res = [item for item in flatten(c)]
res = sum(map(lambda x: sums[x], res))
return res
def bruteforce(n):
gen = itertools.product(range(n), repeat=n)
cont = 0
while 1:
try:
if sum(gen.next()) == n:
cont += 1
except StopIteration:
break
return cont
if __name__ == "__main__":
for a in range(3, 10):
s = Sums(a)
sums[a] = s
print a, s
|
#!/usr/bin/python2.7
from utils import isprime
def p(n, c):
return n*n + c
if __name__ == "__main__":
limit = 1000000
cs = (3, 7, 9, 13, 27)
print "Generating groups"
groups = [[n, p(n, 1)] for n in xrange(limit) if isprime(p(n,1))]
for c in cs:
groups = [item + [p(item[0], c)] for item in groups]
groups = filter(lambda x: isprime(x[-1]), groups)
print "Filter: ", len(groups)
print "Suma: ", sum(cs)
|
#!/usr/bin/python
def sumdigs(num):
return sum(map(lambda x: int(x), str(num)))
if __name__ == "__main__":
m = 0
for a in xrange(1,100):
for b in xrange(1,100):
num = pow(a,b)
s = sumdigs(num)
if s > m:
print a,b,s
m = s
|
import os
import sys
def main():
# return usage information and exit if incorrect number of command-line arguments
if len(sys.argv) != 2:
exit("Usage: python bleep.py dictionary")
filename = sys.argv[1]
# return error message if dictionary file does not exit
if not os.path.isfile(filename):
exit("Error: file '{}' does not exist".format(filename))
# read banned words from dictionary and strip newline characters from end of strings
wordlist = [line.rstrip() for line in open(filename, 'r').readlines()]
# get text to censor as input from user
text = input("What would you like to censor? ")
# replace banned words in text with asterisks
for word in text.split():
if word.lower() in wordlist:
text = text.replace(word, '*' * len(word))
# display censored output
print(text)
if __name__ == "__main__":
main()
|
#Specifying types isn't commonly seen in Python as Python does not make you statically type.
#In the line below we define the subtraction function. We specify that Five and ten are integers and that the result should be an integer as well.
def subtraction(five: int, ten: int) -> int:
print (ten - five)
subtraction(10, 5)
|
#Requests is a library that you can use to make API calls.
import requests
from bs4 import BeautifulSoup
#This line creats the get request
page = requests.get('https://michaellevan.net')
#This line pulls all of the content form the entire website.
soup = BeautifulSoup(page.content, 'html.parser')
#This line gets the title of the page in text format.S
page_title = soup.title.text
#This line gets the header of the page.
page_head = soup.head
#These two lines pull the h1 headers in text format.
first_h1 = soup.select('h1')[0].text
second_h1 = soup.select('h1')[1].text
#These two lines print the first two headers in text format by calling the variable.
print(first_h1)
print(second_h1)
|
participants = 62
if participants < 50:
print('it is not busy here')
elif 30 <= participants < 40:
print('at least some are here')
elif 20 <= participants < 30:
print ('I expected more than that')
elif 50 <= participants < 70:
print ('I like it')
# if not enough people are around, be critical
def hi():
print('huuhu')
print('alles ok?')
hi()
|
# -*- coding: utf-8 -*-
#listeler değiştirilir tuplelar değiştirilmez.
ogrenci1 = "Engin"
ogrenci2 = "Derin"
ogrenci3 = "Salih"
ogrenciler = ["Engin","Derin","Salih"]
ogrenciler.append("Ahmet") # append ekleme yapar.
ogrenciler[0] = "Veli"
print(ogrenciler[3])
ogrenciler.remove("Salih") # .remove kaldırır.
print(ogrenciler)
#list liste oluşturucudur
sehirler = list(("Ankara","İstanbul","Ankara"))
print(len(sehirler)) #len kaç elemandan oluştuğunu gösterir.
#diğer fonksiyonlar
#print(sehirler.clear()) # .clear ile liste temizler
print("Ankara sayısı = " + str(sehirler.count("Ankara"))) # .count kaç tane olduğunu gösterir.
print("Ankara indexi = " + str(sehirler.index("Ankara"))) # .index ankarayı bulur ilk nerde bulursa orda durur
sehirler.pop(1) # .pop ta 1 deki sehiri kaldırır elle yazmayız remove gibi.
sehirler.insert(0,"İstanbul") # .insert 0.index e ekleme yapar.
sehirler.reverse() # .reverse ters çevirir.
print(sehirler)
sehirler3= sehirler.copy() # .copy direk kopya aldı.
sehirler2 = sehirler # = ile sehirlerin yedeğini aldık aynısı.
sehirler2[0]="İzmir"
print(sehirler)
print(sehirler2)
print(sehirler3)
sehirler.extend(sehirler3) # .extend birleştirir.
sehirler.sort() # .sort alfabetik yada sayısal listelemeye yarar. a-z
sehirler.reverse() # .reverse tersten yazdırır. z-a
print(sehirler)
|
from random import sample, shuffle
def myshuffle(str):
l = list(str)
shuffle(l)
result = ''.join(l)
return result
print("Welcome to The Game of Guesses!")
print("The purpose of the game is to guess the number I'm thinking. There are a few rules to play this game:")
print("1- The number in my mind will be a 4-digit one with different digits.")
print("2- You will see a - sign for every digit you guess correcly and a + sign if the digit is in the correct place.")
print("3- You only have 10 attempts.")
print("4- You will not lose an attempt if you enter any other value than a 4-digit one.")
print("Good luck! \n")
input("Press any key to begin. \n")
while True:
r = sample(range(10), 4)
if r[0] > 0:
break
remaining = 10
while remaining > 0:
while True:
try:
g = [int(i) for i in input("Guess:")]
break
except ValueError:
print("Please enter a numerical value!")
print("Remaining Attempts: %d \n" % remaining)
a = int(''.join(str(n) for n in g))
if a > 9999 or a < 1000:
print("Please enter a 4-digit value!")
print("Remaining Attempts: %d \n" % remaining)
continue
#print(r)
result = ""
for x, i in enumerate(r):
for y, j in enumerate(g):
if x == y and i == j:
result += "+"
elif x != y and i == j:
result += "-"
print("Result: [%s]" % myshuffle(result))
if result == "++++":
print("Congratulations! You have guessed the number correctly. You must be a mind-reader. \n")
input("Press any key to exit.")
break
remaining -= 1
print("Remaining Attempts: %d \n" % remaining)
else:
print("Sorry, you couldn't guess the number correctly! The number was: %s \n" % ''.join(str(m) for m in r))
input("Press any key to exit")
|
# -*- coding: utf-8 -*-
# [] bir listedir.
lights = ["red","yellow","green"]
currentLight = lights[0]
print(currentLight)
if currentLight == "red":
print("STOP!")
if currentLight == "yellow":
print("READY!")
if currentLight == "green":
print("GO!")
|
# -*- coding: utf-8 -*-
def topla(sayi1,sayi2):
return sayi1 + sayi2
def cikar(sayi1,sayi2):
return sayi1 - sayi2
def carp(sayi1,sayi2):
return sayi1 * sayi2
def bol(sayi1,sayi2):
return sayi1 / sayi2
print("Operasyon:")
print("=======================")
print("1 : Topla")
print("2 : Çıkar")
print("3 : Çarp")
print("4 : Böl")
secenek = input("Operasyon seçiniz?")
sayi1 = int(input("Birinci sayı?"))
sayi2 = int(input("İkinci sayı?"))
if secenek == "1":
print("Toplam : " +str(topla(sayi1, sayi2)))
elif secenek == "2":
print("Çıkarma : " +str(cikar(sayi1, sayi2)))
elif secenek == "3":
print("Çarpma : " +str(carp(sayi1, sayi2)))
elif secenek == "4"and sayi2 != 0:
print("Bölme : " +str(bol(sayi1, sayi2)))
else:
print("Hatalı kodladınız")
|
from typing import List
def maxProfit(prices: List[int]) -> int:
# arg - got bitten by 0 in a boolean context
holding = False
transactions = []
buyAt = None
sellAt = None
for idx in range(len(prices)-1,-1,-1):
today = prices[idx]
if not holding:
sellAt = today
holding = True
else:
if buyAt is not None and today > buyAt:
transactions.append((buyAt, sellAt))
buyAt = None
sellAt = today
elif buyAt is None and today > sellAt:
sellAt = today
elif buyAt is None or today < buyAt:
buyAt = today
if buyAt is not None and sellAt is not None:
transactions.append((buyAt, sellAt))
profit = 0
for b,s in transactions:
profit += s-b
return profit
|
def merge(nums1, n, nums2, m):
q = len(nums1)-1
def push(k):
for i in range(q, k, -1):
nums1[i] = nums1[i-1]
n1idx = 0
n2idx = 0
mCount = 0
while n2idx < n and mCount < m:
print(f"{n1idx},{n2idx},{nums1}")
n1 = nums1[n1idx]
n2 = nums2[n2idx]
if n1 >= n2:
push(n1idx)
nums1[n1idx] = n2
n2idx += 1
else:
mCount += 1
n1idx += 1
if n2idx != n:
while n2idx < n:
print(f"> {n1idx},{n2idx},{nums1}")
nums1[n1idx] = nums2[n2idx]
n2idx += 1
n1idx += 1
print(nums1)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# okay that's ugly, and shortcuts were taken. but it passed!
def generateTrees(self, n: int) -> List[TreeNode]:
# tree must not be None!
def ins(tree, val):
if val < tree.val:
if tree.left:
ins(tree.left, val)
else:
tree.left = TreeNode(val=val)
else:
if tree.right:
ins(tree.right, val)
else:
tree.right = TreeNode(val=val)
def parse(tree):
path = []
nodes = [tree]
while nodes:
node = nodes.pop()
if node:
path.append(node.val)
nodes.append(node.left)
nodes.append(node.right)
return tuple(path)
values = {v for v in range(1,n+1)}
# this essentially creates all the permutations
# could have used a built-in most likely
pipeline = [[v] for v in values]
insert_paths = []
while pipeline:
path = pipeline.pop()
if len(path) == n:
insert_paths.append(path)
# remaining digits
for value in values.difference(set(path)):
pipeline.append([*path,value])
ret = []
seen = set()
# now create trees for each insert path
for path in insert_paths:
root = TreeNode(val=path.pop())
for val in path:
ins(root, val)
computed_path = parse(root)
if computed_path in seen:
continue
seen.add(computed_path)
ret.append(root)
return ret
|
def firstBadVersion(n: int):
"""
:type n: int
:rtype: int
"""
start, end = 1, n
while True:
midpoint = start + (end-start) // 2
if isBadVersion(midpoint):
# then it must be before
end = midpoint
else:
# then it's after
start = midpoint
if end - start <= 1:
return start if isBadVersion(start) else end
|
def removeDuplicates(nums: List[int]) -> int:
count = 0
curr = None
for elem in nums:
if elem == curr:
next
else:
curr = elem
nums[count] = curr
count += 1
return count
|
# Problem Set 4
# Name: Alvin Zhu
# Collaborators:
# Time Spent: 5:30
# Late Days Used: 0
import matplotlib.pyplot as plt
import numpy as np
from ps4_classes import BlackJackCard, CardDecks, Busted
#############
# PROBLEM 1 #
#############
class BlackJackHand:
"""
A class representing a game of Blackjack.
"""
hit = 'hit'
stand = 'stand'
def __init__(self, deck):
"""
Parameters:
deck - An instance of CardDeck that represents the starting shuffled
card deck (this deck itself contains one or more standard card decks)
Attributes:
self.deck - CardDeck, represents the shuffled card deck for this game of BlackJack
self.player - list, initialized with the first 2 cards dealt to the player
and updated as the player is dealt more cards from the deck
self.dealer - list, initialized with the first 2 cards dealt to the dealer
and updated as the dealer is dealt more cards from the deck
Important: You MUST deal out the first four cards in the following order:
player, dealer, player, dealer
"""
self.deck = deck
self.player = [deck.deal_card()]
self.dealer = [deck.deal_card()]
self.player += [deck.deal_card()]
self.dealer += [deck.deal_card()];
# You can call the method below like this:
# BlackJackHand.best_val(cards)
@staticmethod
def best_val(cards):
"""
Finds the best sum of point values given a list of cards, where the
"best sum" is defined as the highest point total not exceeding 21.
Remember that an Ace can have value 1 or 11.
Hint: If you have one Ace, give it a value of 11 by default. If the sum
point total exceeds 21, then give it a value of 1. What should you do
if cards has more than one Ace?
Parameters:
cards - a list of BlackJackCard instances.
Returns:
int, best sum of point values of the cards
"""
#Sums up all the cards
sums = 0
aces = 0
for card in cards:
sums += card.get_val()
if card.get_rank() == 'A':
aces += 1
#Accounting for when sums should bust but there are aces
while sums > 21 and aces > 0:
sums -= 10
aces -= 1
return sums;
def get_player_cards(self):
"""
Returns:
list, a copy of the player's cards
"""
return self.player
def get_dealer_cards(self):
"""
Returns:
list, a copy of the dealer's cards
"""
return self.dealer
def get_dealer_upcard(self):
"""
Returns the dealer's face up card. We define the dealer's face up card
as the first card in their hand.
Returns:
BlackJackCard instance, the dealer's face-up card
"""
return self.get_dealer_cards()[0]
def set_initial_cards(self, player_cards, dealer_cards):
"""
Sets the initial cards of the game.
player_cards - list, containing the inital player cards
dealer_cards - list, containing the inital dealer cards
used for testing, DO NOT MODIFY
"""
self.player = player_cards[:]
self.dealer = dealer_cards[:]
# Strategy 1
def mimic_dealer_strategy(self):
"""
A playing strategy in which the player uses the same metric as the
dealer to determine their next move.
The player will:
- hit if the best value of their cards is less than 17
- stand otherwise
Returns:
str, "hit" or "stand" representing the player's decision
"""
if self.best_val(self.player) < 17:
return self.hit
return self.stand
# Strategy 2
def peek_strategy(self):
"""
A playing strategy in which the player knows the best value of the
dealer's cards.
The player will:
- hit if the best value of their hand is less than that of the dealer's
- stand otherwise
Returns:
str, "hit" or "stand" representing the player's decision
"""
if self.best_val(self.player) < self.best_val(self.dealer):
return self.hit
return self.stand;
# Strategy 3
def simple_strategy(self):
"""
A playing strategy in which the player will
- stand if one of the following is true:
- the best value of player's hand is greater than or equal to 17
- the best value of player's hand is between 12 and 16 (inclusive)
AND the dealer's up card is between 2 and 6 (inclusive)
- hit otherwise
Returns:
str, "hit" or "stand" representing the player's decision
"""
playerVal = self.best_val(self.player)
dealerUp = self.get_dealer_upcard().get_val()
if playerVal >= 17 or (playerVal >=12 and playerVal <= 16 and dealerUp >= 2 and dealerUp <= 6):
return self.stand
return self.hit;
def play_player(self, strategy):
"""
Plays a full round of the player's turn and updates the player's hand
to include new cards that have been dealt to the player. The player
will be dealt a new card until they stand or bust.
Parameter:
strategy - function, one of the the 3 playing strategies defined in BlackJackHand
(e.g. BlackJackHand.mimic_dealer_strategy)
This function does not return anything. Instead, it:
- Adds a new card to self.player each time the player hits.
- Raises Busted exception (imported from ps4_classes.py) if the
best value of the player's hand is greater than 21.
"""
#Keep adding cards until your strategy tells you to stand
while strategy(self) == self.hit:
self.player.append(self.deck.deal_card())
#Raise Busted error if passed 21
if self.best_val(self.player) > 21:
raise Busted
def play_dealer(self):
"""
Plays a full round of the dealer's turn and updates the dealer's hand
to include new cards that have been dealt to the dealer. The dealer
will get a new card as long as the best value of their hand is less
than 17, or they bust.
This function does not return anything. Instead, it:
- Adds a new card to self.dealer each time the dealer hits.
- Raises Busted exception (imported from ps4_classes.py) if the
best value of the dealer's hand is greater than 21.
"""
#Keep hitting if value less than 17
while self.best_val(self.dealer) < 17:
self.dealer.append(self.deck.deal_card())
#Raise Busted error if passed 21
if self.best_val(self.dealer) > 21:
raise Busted
def __str__(self):
"""
Returns:
str, representation of the player and dealer and dealer hands.
Useful for debugging. DO NOT MODIFY.
"""
result = 'Player: '
for c in self.player:
result += str(c) + ','
result = result[:-1] + ' '
result += '\n Dealer '
for c in self.dealer:
result += str(c) + ','
return result[:-1]
#############
# PROBLEM 2 #
#############
def play_hand(deck, strategy, bet=1.0):
"""
Plays a hand of Blackjack and determines the amount of money the player
gets back based on their inital bet.
The player will get:
- 2.5 times their original bet if the player's first two cards equal 21,
and the dealer's first two cards do not equal 21.
- 2 times their original bet if the player wins after getting more
cards or the dealer busts.
- the original amount they bet if the game ends in a tie. If the
player and dealer both get blackjack from their first two cards, this
is also a tie.
- 0 if the dealer wins or the player busts.
Parameters:
deck - an instance of CardDeck
strategy - function, one of the the 3 playing strategies defined in BlackJackHand
(e.g. BlackJackHand.mimic_dealer_strategy)
bet - float, the amount that the player bets (default=1.0)
Returns:
float, the amount the player gets back
"""
hand = BlackJackHand(deck)
playerCards = hand.get_player_cards()
dealerCards = hand.get_dealer_cards()
#Blackjack check
playerVal = hand.best_val(playerCards)
dealerVal = hand.best_val(dealerCards)
if playerVal == 21 or dealerVal == 21:
if playerVal == 21:
if dealerVal == 21:
return bet
return bet*2.5
return 0;
#Player busts or stays
try:
hand.play_player(strategy)
except Busted:
return 0;
#Dealer busts or stays
try:
hand.play_dealer()
except Busted:
return bet*2;
#No one busts so check whose best value is larger
playerVal = hand.best_val(playerCards)
dealerVal = hand.best_val(dealerCards)
if playerVal > dealerVal:
return bet * 2
elif playerVal == dealerVal:
return bet
else:
return 0;
#############
# PROBLEM 3 #
#############
def run_simulation(strategy, bet=2.0, num_decks=8, num_hands=20, num_trials=100, show_plot=False):
"""
Runs a simulation and generates a box plot reflecting the distribution of
player's rates of return across all trials.
The box plot displays the distribution of data based on the five number
summary: minimum, first quartile, median, third quartile, and maximum.
We also want to show the average on the box plot. You can do this by
specifying another parameter: plt.boxplot(results, showmeans=True)
For each trial:
- instantiate a new CardDeck with the num_decks and type BlackJackCard
- for each hand in the trial, call play_hand and keep track of how
much money the player receives across all the hands in the trial
- calculate the player's rate of return, which is
100*(total money received-total money bet)/(total money bet)
Parameters:
strategy - function, one of the the 3 playing strategies defined in BlackJackHand
(e.g. BlackJackHand.mimic_dealer_strategy)
bet - float, the amount that the player bets each hand. (default=2)
num_decks - int, the number of standard card decks in the CardDeck. (default=8)
num_hands - int, the number of hands the player plays in each trial. (default=20)
num_trials - int, the total number of trials in the simulation. (default=100)
show_plot - bool, True if the plot should be displayed, False otherwise. (default=False)
Returns:
tuple, containing the following 3 elements:
- list of the player's rate of return for each trial
- float, the average rate of return across all the trials
- float, the standard deviation of rates of return across all trials
"""
returns = []
totalbet = bet*num_hands
for trial in range(num_trials):
#Calculate the gains from every hand of a single trial and record rate of return
earnHands = 0
deck = CardDecks(num_decks, BlackJackCard)
for hand in range(num_hands):
earnHands += play_hand(deck, strategy, bet)
returns.append(100.0 * (earnHands-totalbet)/totalbet)
#Calculate mean and standard deviation
mean = np.mean(returns)
std = np.std(returns)
if show_plot:
plt.boxplot(returns, showmeans=True)
plt.title("Player ROI on Playing 20 Hands (" + strategy.__name__ + ")\n(mean = " + str(mean) + "%, SD = " + str(std) + "%)")
plt.ylabel("% Returns")
plt.xticks([1],[strategy.__name__])
plt.show()
return (returns, mean, std);
def run_all_simulations(strategies):
"""
Runs the simulation for each strategy in strategies and generates a single
graph with one box plot for each strategy. Each box plot should reflect the
distribution of rates of return for each strategy.
Make sure to label each plot with the name of the strategy.
Parameters:
strategies - list of strategies to simulate
"""
#Instantiate lists to use for later plotting
runs = []
stratTicks = []
i = 1
strats = []
#Run the simulation for each strategy with the default values
for strategy in strategies:
runs.append(run_simulation(strategy))
stratTicks.append(i)
i += 1
strats.append(strategy.__name__)
plt.boxplot([runs[0][0], runs[1][0], runs[2][0]], showmeans=True)
plt.title("Player ROI Using Different Stategies")
plt.ylabel("% Returns")
plt.xticks(stratTicks, strats)
plt.show()
if __name__ == '__main__':
# uncomment to test each strategy separately
run_simulation(BlackJackHand.mimic_dealer_strategy, show_plot=True)
run_simulation(BlackJackHand.peek_strategy, show_plot=True)
run_simulation(BlackJackHand.simple_strategy, show_plot=True)
# uncomment to run all simulations
run_all_simulations([BlackJackHand.mimic_dealer_strategy,
BlackJackHand.peek_strategy, BlackJackHand.simple_strategy])
pass
|
# 6.0002 Problem Set 2
# Graph Optimization
# Name: Alvin Zhu
# Collaborators:
# Time: 4
#
# A set of data structures to represent the graphs that you will be using for this pset.
#
class Node(object):
"""Represents a node in the graph"""
def __init__(self, name):
self.name = str(name)
def get_name(self):
''' return: the name of the node '''
return self.name
def __str__(self):
''' return: The name of the node.
This is the function that is called when print(node) is called.
'''
return self.name
def __repr__(self):
''' return: The name of the node.
Formal string representation of the node
'''
return self.name
def __eq__(self, other):
''' returns: True is self == other, false otherwise
This is function called when you used the "==" operator on nodes
'''
return self.name == other.name
def __ne__(self, other):
''' returns: True is self != other, false otherwise
This is function called when you used the "!=" operator on nodes
'''
return not self.__eq__(other)
def __hash__(self):
''' This function is necessary so that Nodes can be used as
keys in a dictionary, Nodes are immutable
'''
return self.name.__hash__()
## PROBLEM 1: Implement this class based on the given docstring.
class WeightedEdge(object):
"""Represents an edge with an integer weight"""
def __init__(self, src, dest, total_time, color):
""" Initialize src, dest, total_time, and color for the WeightedEdge class
src: Node representing the source node
dest: Node representing the destination node
total_time: int representing the time travelled between the src and dest
color: string representing the t line color of the edge
"""
self.src = src;
self.dest = dest;
self.total_time = int(total_time);
self.color = color;
def get_source(self):
""" Getter method for WeightedEdge
returns: Node representing the source node """
return self.src;
def get_destination(self):
""" Getter method for WeightedEdge
returns: Node representing the destination node """
return self.dest;
def get_color(self):
""" Getter method for WeightedEdge
returns: String representing the t-line color of the edge"""
return self.color;
def get_total_time(self):
""" Getter method for WeightedEdge
returns: int representing the time travelled between the source and dest nodes"""
return self.total_time;
def __str__(self):
""" to string method
returns: string with the format 'src -> dest total_time color' """
return self.src.get_name() +' -> ' + self.dest.get_name() + " " + str(self.total_time) + " " + self.color;
## PROBLEM 1: Implement methods of this class based on the given docstring.
## DO NOT CHANGE THE FUNCTIONS THAT HAVE BEEN IMPLEMENTED FOR YOU.
class Digraph(object):
"""Represents a directed graph of Node and WeightedEdge objects"""
def __init__(self):
self.nodes = set([])
self.edges = {} # must be a dictionary of Node -> list of edges starting at that node
def __str__(self):
edge_strs = []
for edges in self.edges.values():
for edge in edges:
edge_strs.append(str(edge))
edge_strs = sorted(edge_strs) # sort alphabetically
return '\n'.join(edge_strs) # concat edge_strs with "\n"s between them
def get_edges_for_node(self, node):
''' param: node object
return: a copy of the list of all of the edges for given node.
empty list if the node is not in the graph
'''
return [item for item in self.edges[node]];
def has_node(self, node):
''' param: node object
return: True, if node is in the graph. False, otherwise.
'''
return node in self.nodes;
def add_node(self, node):
""" param: node object
Adds a Node object to the Digraph.
Raises a ValueError if it is already in the graph."""
if node in self.nodes:
raise ValueError;
self.nodes.add(node); #Add to a set
self.edges[node] = []; #Instantiate a key in edges {}.
def add_edge(self, edge):
""" param: WeightedEdge object
Adds a WeightedEdge instance to the Digraph.
Raises a ValueError if either of the nodes associated with the edge is not in the graph."""
#Check if both nodes of an edge are in the digraph and whether the edge has already been added.
if edge.get_source() in self.nodes and edge.get_destination() in self.nodes:
if edge not in self.edges[edge.get_source()]:
self.edges[edge.get_source()] += [edge];
else: raise ValueError;
|
'''
定义一个学生类,用来形容学生
'''
# 定义一个空的类
class Student():
# 一个空类,pass 代表直接跳过
# 此处pass 必须有
pass
# 定义一个对象
# mingyue 就是一个对象,属于Student()类中的一个个体
mingyue = Student()
# 在定义一个类,用来描述听python的学生
class PythonStudent(): # class关键字 + PythonStudent() 类名单词首字母大写 + 冒号:
# 用None 给不确定的值赋值
# 定义变量的属性名及赋值
name = None
age = 18
course = "Python"
# 需要注意
# 1. def doHomework的缩进层级,小于class的缩进层级,与变量的缩进平级
# 2. 系统默认有一个self参数
def doHomework(self):
print("I 在做作业")
# 推荐在函数末尾使用return语句
return None
# 实例化一个叫yueyue的学生,是一个具体的人
yueyue = PythonStudent()
print(yueyue.name)
print(yueyue.age)
print(yueyue.course)
# 注意成员函数的调用没有传递进入参数
yueyue.doHomework()
# 打印查看PythonStudent类内所有的成员
print(PythonStudent.__dict__)
import random
print(random.randint(0,9999999999999999999))
# 定义一个类
class A():
# 定义属性
name = "chunhua"
age = 18
def say(self):
self.name = "guochunhua"
self.age = 30
# 此案例说明
'''
类实例的属性(A.name)和其对象实例的属性(a.name),如果不进行对象的实例属性赋值(a.name!= "xxx"),
则两者指向的为同一个变量(id值不变)
'''
# 此时,A称为类的实例
print(A.name)
print(A.age)
print("-" * 30)
# id 可以鉴别两个变量 是否为同一个变量
print(id(A.name))
print(id(A.age))
print("-" * 30)
# 定义一个对象
a = A()
# 此时,a称为对象的实例,借用了A()类实例的属性
print(a.name)
print(a.age)
print(id(a.name))
print(id(a.age))
'''
类实例的属性(A.name)和其对象实例的属性(a.name),如果对对象的实例属性进行赋值(a.name = "xxx"),
则两者指向的内容不是同一个变量了(id值已变化)
'''
# 此时,A称为类的实例
print("*" * 30)
print(A.name)
print(A.age)
print("-" * 30)
# id 可以鉴别一个变量与另外一个变量 是否为同一个变量
print(id(A.name))
print(id(A.age))
# 查看A内所有的属性值
print(A.__dict__)
print(a.__dict__)
print("分隔符----" * 10)
# 定义一个对象
a = A()
# 进行对象实例赋值
a.name = "huihui" # 等价于 self.name = "huihui"
a.age = 20 # 等价于 self.age = 20
# 打印查看对象实例赋值后,对象实例的成员
print(a.__dict__)
print(a.name)
print(a.age)
print(id(a.name))
print(id(a.age))
# self 使用
print("this is self ------------------------")
class StudentA():
name = "chunhua"
age = 18
def myInfo(self):
self.name = "huahua"
self.age = 200
print("My name is {0}".format(self.name))
print("My age is {0}".format(self.age))
my = StudentA()
# 对象my把自己作为第一个参数传入函数myInfo()中
# 即self.name 等价于 my.name ; self.age 等价于 my.age
my.myInfo()
# 有self 与 没有self的区别
print("有self 与 没有self的区别示例")
class Teacher():
name = "laoshi"
age = 20
# 定义一个非绑定类的方法
def heSelf(self):
self.name = "liudana"
self.age = 30
print("My name is {0}".format(self.name))
print("My age is {0}".format(self.age))
# 定义一个绑定类的方法
def heHe():
print("他说他是python老司机...")
ta = Teacher()
# 调用非绑定类函数使用对象名
# 对象ta会作为参数传入函数中
ta.heSelf()
# 调用绑定类函数使用类名
# 此时类名不会作为参数传入函数中
Teacher.heHe()
# 使用类 访问绑定类方法,且方法中需要访问类中的成员
print("使用类 访问绑定类方法,且方法中需要访问类中的成员,使用 __class__.方法的示例------------------------------")
class MyInfo():
name = "过去"
age = 18
def nowSelf(self):
self.name = "现在"
self.age = 30
print("我{0}很年轻{1},做错很多事,很不开心!!!".format(__class__.name, __class__.age))
print("我{0}年纪大了,已经{1},但很开心。。。".format(self.name, self.age))
def nowBefor():
print("{0}的都已经成为历史,{0}的算了。。。".format(__class__.name))
print("其实我还很年轻,我现在心态是{0}岁。。。".format(__class__.age))
wo = MyInfo()
wo.nowSelf()
# 访问绑定类的方法时,使用对象名.函数名 访问时出错。
# wo.nowBefor()
# 访问绑定类方法时 需使用类名.函数名 访问。
MyInfo.nowBefor()
# self 案例
class B():
name = "学生"
age = 18
# 构造函数
def __init__(self):
self.name = "程序员"
self.age = 30
def say(self):
print(self.name)
print(self.age)
class C():
name = "C++"
age = 35
# 实例化
a = B()
# 此时,a为对象实例 访问非绑定类的方法时,系统会默认把a作为第一参数传入say函数
a.say()
# 此时,B为类实例,访问非绑定类的方法时,需要手动将对象a作为参数传入say函数,即self被a替换
B.say(a)
# 此时,把B作为参数传入say函数,即self被B替换了,即调用B类中的 name 和 age 成员(前提条件时,B类中必须存在name和age属性成员,否则报错)
B.say(B)
# 同理,可以把类C 作为参数传入say函数,同样C类中也必须存在name和age属性成员,否则报错
B.say(C)
# 以上代码 利用了鸭子模型(看起来像鸭子、具有鸭子的属性<有翅膀、会游泳、嘎嘎嘎叫...>,就认为你是鸭子)
# 同理以上代码中使用的 B类和 C类 不管是否为同一类型,只要存在函数say中所需要的属性<name, age>,即认为B和C是同一类
# 私有变量示例
class Person():
# name 是公有的成员
name = "chunhua"
# __age 就是私有成员,在age前面添加两个下划线即可
__age = 18
_stature = "slender"
p = Person()
# name 作为公有变量,在外部访问,没毛病...
print(p.name)
# __age 做为私有变量,此时在外部方式,则报错。。。'object has no attribute'
# print(p.__age)
# name mangling 技术
# 查看类内所有成员
print(Person.__dict__)
p._Person__age = 180
# private 私有
print(p._Person__age)
print(Person.__dict__)
# protected 受保护的
print(Person.__dict__)
p._stature = "tall"
print(p._stature)
print(Person.__dict__)
|
# -*- coding:utf-8 -*-
from collections import Iterable
#Iterable
print(isinstance([],Iterable))
print(isinstance('abc',Iterable))
#Iterator
from collections import Iterator
print('Iterator')
print(isinstance((x for x in range(10)),Iterator))
#True
print(isinstance([],Iterator))
#False
print("把Iterable变成Iterator可以使用iter()")
print(isinstance(iter([]), Iterator))
#True
|
# -*- coding:utf-8 -*-
#
print("__str__方法:")
class Student(object):
def __init__(self,name):
self.name = name
def __str__(self):
return 'student[name:%s]' % (self.name)
s = Student("ZhangSan")
print(s)
#
print("__iter__()方法:斐波那契数列")
class Fib(object):
def __init__(self):
self.a,self.b = 0,1
def __iter__(self):
return self #实例本身就是迭代对象,返回自己
def __next__(self):
self.a, self.b = self.b, self.a+self.b
if self.a>1000:
raise StopIteration()
return self.a #返回下一个值
def __getitem__(self, n):
a,b = 1,1
for x in range(n):
a,b = b,a+b
return a
#for n in Fib():
# print(n)
f = Fib()
print(f[10])
#
print("获取斐波那契数列的一个切片:")
class Fib(object):
def __getitem__(self, n):
if isinstance(n, int): #索引
a,b=1,1
for x in range(n):
a,b = b, a+b
return a
if isinstance(n, slice): #n是切片
start = n.start
stop = n.stop
if start is None:
start = 0
a,b = 1,1
L = []
for x in range(stop):
if x>=start:
L.append(a);
a,b = b,a+b
return L
f = Fib()
print(f[0:5])
print(f[:10])
#
print("__getattr__方法:")
class Student(object):
def __init__(self,name):
self.name = name
s = Student('ZhangSan')
print(s.name)
#print(s.sex) #类没有这个属性,那么会抛出异常
print("通过__getattr__(),动态返回一个属性:")
class Student(object):
def __init__(self,name):
self.name = name
def __getattr__(self, attr):
if attr=='sex':
return '男'
s = Student("Wang")
print(s.name)
print(s.sex)
print(s.age) #我们明明没有定义age,但是这里也不会报错的,因为__getattr__默认返回的是None
print("也可以在getattr中返回一个方法,这个时候调用的也要做相应的改变:")
class Student(object):
def __init__(self,name):
self.name = name
def __getattr__(self, attr):
if attr=='sex':
return '男'
elif attr=='age':
return lambda:25
s = Student("Zhang")
print(s.age()) #这个时候调用的不是属性而是方法
#
print("利用完全动态的__getattr__,写一个链式调用:")
class Chain(object):
def __init__(self,path=""):
self._path = path
def __getattr__(self,path):
return Chain('%s/%s' % (self._path, path))
def __str__(self):
return self._path
__repr__ = __str__
print( Chain().status.user.timeline.list )
#
print("__call__方法:")
class Student(object):
def __init__(self, name):
self.name = name
def __call__(self):
print( 'My name is %s.' % self.name)
s = Student("ZhangSan")
s() #调用这个实例本身
#
print("判断一个变量是对象还是一个函数:callable")
print(callable(Student('Lisi'))) #True
print(callable(max)) #True
print(callable([1,2,3])) #False
print(callable(None)) #False
print(callable('str')) #False
|
# -*- coding:utf-8 -*-
from enum import Enum
print("定义一个月份的枚举:")
Month = Enum('MonthTest', ('Jan','Feb','Mar','Apr','May','Jun','Aug','Sep','Oct','Nov','Dec'))
for name,member in Month.__members__.items():
print(name,'==>',member,',',member.value)
print(Month.Feb, Month.Feb.value)
#MonthTest.Feb 2
print("如果想要更精确的控制枚举类型,可以从`Enum`派生出自定义类:")
from enum import Enum, unique
#unique装饰器可以帮助我们检查保证没有重复值
@unique
class Weekday(Enum):
Sun=0 #Sun的value被设定为0
Mon = 7
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
day1 = Weekday.Mon
print(day1)
print(Weekday['Tue'])
print(Weekday(7)) #Weekday.Mon,这里括号里面的值对应的是Mon=后面的值,而不是数组,切记
print(day1 == Weekday.Mon)
print(day1==Weekday(1)) #这里会报错,因为1找不到
|
# -*- coding:utf-8 -*-
age=20
if age>=18:
print("可以枪毙了!")
print("冒号下面所有缩进的代码是一个代码块。")
age=16
if age>=18:
print("18岁以上")
elif age>14:
print("大于14小于18岁")
else:
print("还不满14岁")
l1 = []
print("对于0、空字符串、空list,都等于False")
if l1:
print(True)
else:
print(False)
print("输入进行if判断:")
birth=input("出生日期:")
#int()把一个字符串转成int类型
if(int(birth)<2000):
print("00前")
else:
print("00后")
|
# -*- coding:utf-8 -*-
print("打印方法的名称:")
def now():
print('now 方法内部。')
f = now
f()
print(now.__name__)
print(f.__name__)
print("定义一个打印日志的装饰器:")
def log(func):#接收一个函数作为参数,并返回一个函数
def wrapper(*args, **kw):
print("call %s():" % func.__name__)
return func(*args, ** kw)
return wrapper
@log
def test1():#把@log放在test1前面,那么调用test1的时候就相当于调用了log(test1)
print("in test1")
test1()
print("装饰器本身带参数:")
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print("%s %s()" % (text,func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log('字符串参数')
def now():
print("2015")
now()
print("这里的now函数的名称已经变了,这里不符合我们的要求。", now.__name__)
print("利用functools.wraps将原始函数的一些属性复制到wrapper函数中:")
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s:' % func.__name__)
return wrapper
@log
def now():
print("in now")
now()
print("方法名称:",now.__name__)
print("将带参数的decorator的一些属性复制到新方法中:")
def log(text):
def decorator(func):
@functools.wraps(func)#将func的一些属性复制到wrapper中
def wrapper(*args, **kw):
print("%s %s():" % (text,func.__name__))
func(*args, **kw)
return wrapper
return decorator
@log('hehe')
def now():
print("in now!")
now()
print("方法名称:", now.__name__)
#
print("请编写一个decorator,能在函数调用的前后打印出'begin call'和'end call'的日志。")
print('同时,改装饰者既支持有参数,也支持无参数。')
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('begin call:', text)
func(*args, **kw)
print('end call')
return wrapper
#return decorator(text) if callable(text) else decorator
if callable(text): # 这一种实现方式和上面的实现方式结果是一样的。
return decorator(text)
else:
return decorator
@log
def f1():
print('f without param')
@log('parm')
def f2():
print('f with param')
f1()#相当于执行了 log(f1)
f2()#相当于执行了 log('parm')(f2)
|
# -*- coding:utf-8 -*-
#切片
L=[1,2,3,4,5,6,7]
print(L[0:3])#[0:3]前包后不包,取了0、1、2三个位置的三个数
print(L[-2:])#倒数第一个是-1
L100 = list(range(100))
print(L100)
#
print("前10个数,每两个取一个:")
print(L100[:10:2])
#
print("所有数,每五个取一个:")
print(L100[::5])
#
print("原样复制一个list:")
L100Copy = L100[:]
print(L100Copy)
#迭代
for ch in 'ABC':
print(ch)
print("判断一个对象是否可迭代")
from collections import Iterable
print(isinstance('abc',Iterable)) # str是否可以迭代
print("迭代的时候同时访问索引和元素本身:")
#enumerate函数可以把一个list变成索引-元素对
for i,value in enumerate(['A','B','C']):
print(i,value)
print('在for循环中,同时引用两个变量')
for x,y in [(1,2),(3,4),(5,6)]:
print(x,y)
for i,x in enumerate([(1,2),(3,4),(5,6)]):
print(i,x[0],x[1])
#列表生成式
#
print('生成1到10=')
print(list(range(1,11)))
#
print('生成=[1x1, 2x2, 3x3, ..., 10x10]')
print("把要生成的元素x*x放前面,后面for循环,就可以把list创建出来。")
l=[x*x for x in range(1,11)]
print(l)
print("生成偶数的平方=")
l=[x*x for x in range(1,11) if x%2==0]
print(l)
print('两层循环生成排列=')
l=[m+n for m in 'ABC' for n in 'xyz']
print(l)
#
print("一行代码列出当前目录的所有文件和目录=")
import os
l=[d for d in os.listdir('.')]#os.listdir可以列出文件和目录
print(l)
#
print("列表生成式同时使用两个变量来生成list=")
d={"zhang":"zhangsan","li":"lisi"}
l=[k+'='+v for k,v in d.items()]
print(l)
#
print('把链表中的所有字符串变成小写=')
L = ["A",'B','C']
l = [s.lower() for s in L]
print(l)
#
print("列表生成式中使用if")
L = ['Hello', 'World', 18, 'Apple', None]
l=[s.lower() for s in L if isinstance(s,str)]
print(l)
#生成器
print("生成器定义=")
g=(x*x for x in range(1,10))
print(g)#打印出来的是一个对象,而不是具体的值
print('通过next来取值(没有的时候抛出异常)=')
print(next(g),next(g))
print('通过next来取值太变态了,可以通过for循环来取值=')
for n in g:
print(n)
#输出斐波拉切数列
print("输出斐波拉切数列:")
def fib(num):
c=0
cur=1
bac=0
while c<num:
yield cur
temp=cur
cur=bac+cur
bac=temp
c = c+1
f=fib(6)
print(next(f))
print(next(f))
for v in f:
print(v)
#输出杨辉三角
def yhsj(num):
ol=[1]
n=1
while n<=num:
print(ol)
nl=[]
nl
|
#!/usr/bin/python3
from sys import argv
if __name__ == "__main__":
narg = len(argv) - 1
args = "argument" if narg == 1 else "arguments"
if narg == 0:
print('{} {}.'.format(narg, args))
else:
print('{} {}:'.format(narg, args))
for idx, arg in enumerate(argv):
if idx != 0:
print('{}: {}'.format(idx, arg))
|
import tweepy
import csv
#Twitter API credentials
consumer_key = "IWSVC6OEOK41wPBtwJPNXQAT4"
consumer_secret = "8DOZOOmT2gQN3CVnQ0MCXghyif3m3R80AFQPSU2y5Fa5D2DX9K"
access_key = "4360002133-HIi8Mun9T1Ig61XcCKPGZBJIUsWQ5KR8q6OiGsc"
access_secret = "CtwLUfKqg8jl7LYuuOXD7vgJVfqJz9MKIeZ2XWrHKzOq0"
def get_all_tweets(screen_name):
#Twitter only allows access to a users most recent 3240 tweets with this method
#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
#initialize a list to hold all the tweepy Tweets
alltweets = []
#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name = screen_name,count=200)
#save most recent tweets
alltweets.extend(new_tweets)
#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
#keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
print( "getting tweets before %s" % (oldest))
#all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)
#save most recent tweets
alltweets.extend(new_tweets)
#update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
print ("...%s tweets downloaded so far" % (len(alltweets)))
#print( tweet ) # u can use tweet.text if u want to print only tweet not other features
# i print latest 500 tweets a person whose i used as a screen_name or username u can print total tweets
#or no of tweets according to your choice change range in given list
barray = alltweets[0:500]
for tweet in barray:
print(tweet)
if __name__ == '__main__':
get_all_tweets("MichelleObama") #pass in the username of the account you want to download I used "narendramodi".
|
# persons = {'Jack':34, 'Anna':27}
# # for item in persons.items():
# # print(item)
# persons_other = {'Anna':42, 'Jack':67,}
# persons.update(persons_other)
# print(persons)
products = [{"name": "water", "price": 12, "title": "bonaqua"},
{"name": "bread", "price": 9, "title": "Whitebread"},
{"name":"apple", "price": 25, "title":"Golden"}]
for product in products:
if product["name"] == 'bread':
# bread_prices.append(products['price'])
product['price'] *= 2
print(products)
|
# 2)You're given strings J representing the types of stones that are jewels, and S representing the
# stones you have. Each character in S is a type of stone you have. You want to know how many of the
# stones you have are also jewels.
# The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case
# sensitive, so "a" is considered a different type of stone from "A".
#
# Example 1:
# Input: J = "aA", S = "aAAbbbb"
# Output: 3
#
# Example 2:
# Input: J = "z", S = "ZZ"
# Output: 0
#
# Note:
# S and J will consist of letters and have length at most 50.
# The characters in J are distinct.
#
# Code:
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
cnt = 0
for i in J:
cnt += S.count(i)
return cnt
|
import math
oz = float(raw_input("Enter an amount in ounces: "))
lb = oz * 0.0625;
print(str(oz) +"oz is "+str(lb)+" lbs")
|
"""
Напишите простой калькулятор, который считывает с пользовательского ввода три строки: первое число, второе число и операцию, после чего применяет операцию к введённым числам ("первое число" "операция" "второе число") и выводит результат на экран.
Поддерживаемые операции: +, -, /, *, mod, pow, div, где
mod — это взятие остатка от деления,
pow — возведение в степень,
div — целочисленное деление.
Если выполняется деление и второе число равно 0, необходимо выводить строку "Деление на 0!".
Обратите внимание, что на вход программе приходят вещественные числа.
"""
a = float(input())
b = float(input())
action = input()
if action == '+':
print(a + b)
elif action == '-':
print(a - b)
elif action in ('/', 'mod', 'div') and b == 0.0:
print("Деление на 0!")
elif action == '/':
print(a / b)
elif action == '*':
print(a * b)
elif action == 'mod':
print(a % b)
elif action == 'pow':
print(a ** b)
elif action == 'div':
print(a // b)
|
"""
Вам дается текстовый файл, содержащий некоторое количество непустых строк.
На основе него сгенерируйте новый текстовый файл, содержащий те же строки в обратном порядке.
Пример входного файла:
ab
c
dde
ff
Пример выходного файла:
ff
dde
c
ab
"""
# Первый вариант
# lst = []
# with open('file.txt', 'r') as file:
# for line in file:
# lst.append(line.strip())
#
# print(lst)
# lst.reverse()
# print(lst)
#
# with open('file_2.txt', 'w') as file:
# for line in lst:
# file.write(line + '\n')
# Еще варианты:
lines = open("file.txt").readlines()
print(lines)
print(lines[::-1])
print(reversed(lines))
with open("file_2.txt", "w") as file:
file.writelines(reversed(lines))
|
"""
Напишите программу, которая считывает список чисел lstlst из первой строки и число xx из второй строки,
которая выводит все позиции, на которых встречается число xx в переданном списке lstlst.
Позиции нумеруются с нуля, если число xx не встречается в списке,
вывести строку "Отсутствует" (без кавычек, с большой буквы).
Позиции должны быть выведены в одну строку, по возрастанию абсолютного значения.
"""
myList = [int(i) for i in input().split()]
num = int(input())
pos = 0
posList = []
for i in myList:
if i == num:
posList.append(pos)
pos += 1
if len(posList) == 0:
print('Отсутствует')
else:
print(*posList)
|
"""Write a guessing game where the user has to guess a secret number. After every guess the program
tells the user whether their number was too large or too small. At the end the number of tries needed
should be printed. It counts only as one try if they input the same number multiple times consecutively."""
import numpy as np
x = int(input("Welcome to the guessing game, choose a number: "))
print(x)
secretNumber = np.random.randint(1, 100)
guesses = []
while x != secretNumber:
if x > secretNumber:
x = int(input("Too large guess, try again: "))
if x not in guesses: guesses.append(x)
elif x < secretNumber:
x = int(input("Too small guess, try again: "))
if x not in guesses: guesses.append(x)
print("You won after",len(guesses),"guesses !")
|
"""Write a function that computes the running total of a list."""
def total_of_list(L):
total = 0
for i in L:
total += i
return total
# Test
test_list = [-5, -10, -15, 1, 10, 11, 14, 2, 4, 7]
x = total_of_list(test_list)
print(x)
|
"""Write a function that combines two lists by alternatingly taking elements, e.g. [a,b,c], [1,2,3] → [a,1,b,2,c,3]."""
def combine_two_lists_alternatingly(L1, L2):
L = []
for i, j in zip(L1, L2):
L.append(i)
L.append(j)
return L
a = ['a','b','c']
b = [1,2,3]
print(combine_two_lists_alternatingly(a,b))
|
#problem-a
'''a=int(input("Enter the height of the triangle:"))
for i in range(1,a+1):
for j in range(5):
print('*',end='')
print('\n')
for i in range(1,a+1):
print('*'*a)'''
#Problem-b
'''a=int(input("Enter the height of the triangle:"))
for i in range(1,a+1):
for j in range(i):
print('*',end='')
print("\n")
#alternate
for i in range(1,a+1):
print('*'*i)'''
#Problem-c
'''a=int(input("Enter the heigt of the triangle:"))
for i in range(1,a+1):
for j in range(1,a-i+2):
print(" ",end='')
for k in range(1,i+1):
print("*",end='')
print(' ')
#Alternate
for i in range(1,a+1):
print(" "*(a-i+1),"*"*i)'''
#Problem-d
'''a=int(input("Enter the height of the triangle:"))
for i in range(1,a+1):
for j in range(1,a-i+2):
print('*',end='')
for k in range(1,i):
print(' ',end='')
print('\n')
#alternate
for i in range(1,a+1):
print("*"*(a-i+1),' '*(i-1))'''
#Problem-e
'''a=int(input("Enter the height of the triangle:"))
for i in range(1,a+1):
for j in range(1,i):
print(' ',end='')
for k in range(1,a-i+2):
print('*',end='')
print('\n')
#alternate
for i in range(0,a):
print(" "*i,end='')
print("*"*(a-i))'''
#Problem-f
'''a=int(input("Enter the height of the triangle"))
for i in range(1,a+1):
for j in range(1,a-i+2):
print(" ",end='')
for k in range(1,i+1):
print('*',end='')
for l in range(1,i):
print('*',end='')
print('\n')
for i in range(1,a+1):
print(' '*(a-i),end='')
print('*'*(2*i-1),end='')
print('\n')'''
#Problem-2
'''a=input("Enter a binary number:")
d=0
b=len(a)
for i in range(0,b):
d=d+(int(a[i])*2**(b-i-1))
print(d)'''
#problem-3
'''a=input("Enter a string:")
b=len(a)
for i in range(b):
print(a[b-i-1],end='')'''
#Problem-4
'''a=input("Enter a string for Pelindrome test:")
b=len(a)
for i in range(0,b//2):
if a[i]!=a[b-i-1]:
print("Not Pelindrome")
break
else:
print("Pelindrome")'''
#Problem-5
'''a=int(input("Enter a integer for prime number test: "))
for i in range(2,a):
if a%i==0:
print("Not Prime")
break
else:
print("Prime")'''
#problem-6
'''a=int(input("Enter the value of n: "))
for i in range(2,a+1):
for j in range(2,i):
if i%j==0:
break
else:
print(i,end=' ')'''
#problem-f1
'''fo=open("Hello.txt",'w')
fo.write("Hello Python")
fo.close()
fo=open("Hello.txt",'r+')
print(fo.readline())'''
#Problem-f2
'''fo=open("dummy.txt",'r+')
while True:
x=fo.readline()
if x=='':
break
x1=x.split('.')
for i in range(len(x1)):
print(x1[i])
print('\n')
fo.close()'''
#Problem-f3
'''fo=open("marks.csv",'r+')
x=fo.readline()
ct1=0
ct2=0
count=0
while True:
x=fo.readline()
if x=='':
break
x1=x.split(',')
ct1=ct1+int(x1[1])
ct2 = ct2 + int(x1[2])
count+=1
print(count)
print("Avereage CT1 Marks are: ",(ct1)/count)'''
#Problem-f4
'''fo=open("marks.csv",'r+')
x=fo.readline()
x1=[]
while True:
x=fo.readline()
if x=='':
break
x2=x.split(',\t')
for i in range(len(x2)):
x1.append(x2[i])
print(int(x1[2]))
print(x1)'''
class Point:
def __init__(self,*t):
if len(t)>0:
self.x=float(t[0])
self.y=float(t[1])
else:
self.x=0.0
self.y=0.0
def print(self):
print('(',self.x,self.y,')')
p1=Point(2,3)
p1.print()
p2=Point()
p2.print()
class Cloud(Point):
maxlimit=30
def __init__(self):
self.poincount=0
self.points=[]
def pointchech(self,point):
if point in self.points:
print("The point is in the cloud")
def isFull(self):
if self.pointcount<maxlimit:
print("The cloud is full")
def isEmpty(self):
if self.poincount==0
print("The cloud is empty")
def add(self,point):
self.points.append([point.x,point.y])
|
s=input("Enter the string:")
a=int(input("Enter the value of n:"))
for i in range(len(s)):
print(s[i+a-len(s)],end='')
|
n = int(input())
wardrobe = {}
items = []
while n > 0:
items = []
n -=1
user_input = input().split(' -> ')
key = user_input[0]
values = user_input[1].split(',')
if key not in wardrobe.keys():
wardrobe[key] = values
else:
wardrobe[key] += values
user_input3 = input().split(' ', 1)
key_to_search=user_input3[0]
value_to_search=user_input3[1]
for key, value in wardrobe.items():
print(f'{key} clothes:')
repeatables = []
for item in value:
if value.count(item) > 1:
if item in repeatables:
continue
else:
if key == key_to_search and item == value_to_search:
print(f'* {item} - {value.count(item)} (found!)')
repeatables.append(item)
else:
print(f'* {item} - {value.count(item)}')
repeatables.append(item)
continue
if key == key_to_search and item == value_to_search:
print(f'* {item} - {value.count(item)} (found!)')
else:
print(f'* {item} - {value.count(item)}')
|
book = {}
user_input = input().split(' : ')
while user_input[0] != 'Over':
if user_input[1].isdigit():
value = user_input[1]
key = user_input[0]
book[key] = value
else:
value = user_input[0]
key = user_input[1]
book[key] = value
user_input = input().split(' : ')
for key,value in sorted(book.items()):
print(f'{key} -> {value}')
|
class Human:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@property
def first_name(self):
return self.__first_name
@first_name.setter
def first_name(self, value):
for i in value:
if i.isupper():
pass
else:
raise Exception('Expected upper case letter! Argument: firstName')
break
if len(value) <= 3:
raise Exception('Expected length at least 4 symbols! Argument: firstName')
else:
self.__first_name = value
@property
def last_name(self):
return self.__last_name
@last_name.setter
def last_name(self, value):
for i in value:
if i.isupper():
pass
else:
raise Exception('Expected upper case letter! Argument: lastName')
break
if len(value) <= 2:
raise Exception('Expected length at least 3 symbols! Argument: lastName')
else:
self.__last_name = value
class Worker(Human):
def __init__(self, first_name, last_name, week_salary:int, work_hours_per_day:int):
Human.__init__(self,first_name, last_name)
self.week_salary = week_salary
self.work_hours_per_day = work_hours_per_day
def calculate_salary_per_hour(self):
salary_per_hour = self.week_salary / 5 / self.work_hours_per_day
return salary_per_hour
def __str__(self):
return f'First Name:{self.first_name}\nLast Name:{self.last_name}\nWeek Salary:{self.week_salary:.2f}' \
f'\nHours per day:{self.work_hours_per_day:.2f}\nSalary per hour: {self.calculate_salary_per_hour():.2f}'
@property
def week_salary(self):
return self.__week_salary
@week_salary.setter
def week_salary(self, value):
if int(value) <= 10:
raise Exception('Expected value mismatch! Argument: weekSalary')
else:
self.__week_salary = int(value)
@property
def work_hours_per_day(self):
return self.__work_hours_per_day
@work_hours_per_day.setter
def work_hours_per_day(self, value):
if 1 < int(value) < 12:
self.__work_hours_per_day = int(value)
else:
raise Exception('Expected value mismatch! Argument: workHoursPerDay')
class Student(Human):
def __init__(self, first_name, last_name, faculty_number):
Human.__init__(self,first_name, last_name)
self.faculty_number = faculty_number
def __str__(self):
return f'First Name:{self.first_name}\nLast Name:{self.last_name}\nFaculty Number:{self.faculty_number}'
@property
def faculty_number(self):
return self.__faculty_number
@faculty_number.setter
def faculty_number(self, value):
if 5 < len(value) < 10:
self.__faculty_number = value
else:
raise Exception('Invalid faculty number!')
try:
student = input().split()
worker = input().split()
student1 = Student(student[0], student[1], student[2])
worker1 = Worker(worker[0], worker[1], int(worker[2]), int(worker[3]))
print(student1)
print()
print(worker1)
except Exception as f:
print(f)
|
import math
class Point:
def __init__(self, x:int, y:int):
self.x = x
self.y = y
def create_point(self):
point = [self.x, self.y]
return point
@staticmethod
def calculate_distance(point_1:[], point_2:[]):
side_a = abs(point_1.x - point_2.x)
side_b = abs(point_1.y - point_2.y)
side_c = math.sqrt(side_a**2 + side_b**2)
return side_c
n = int(input())
total_points = []
while n > 0:
n -= 1
a, b = [int(x) for x in input().split()]
point = Point(a, b).create_point()
total_points.append(point)
segment_list = []
for index_1 in range(len(total_points)):
for index_2 in range(len(total_points)):
if index_1 != index_2:
segment = Point(total_points[index_1][0], total_points[index_2][0])
segment_list.append(segment)
|
user_input = input()
count_of_letters = {}
for item in user_input:
if item in count_of_letters:
count_of_letters[item] += 1
else:
count_of_letters[item] = 1
for key,value in count_of_letters.items():
print(f'{key} -> {value}')
|
class Zadacha():
my_number = input()
def calculate(self):
sum_even = 0
sum_odd = 0
for i in self.my_number:
if i == '-':
continue
i = int(i)
if i % 2 == 0:
sum_even += i
if i % 2 != 0:
sum_odd += i
return [sum_even, sum_odd]
def multiple(self):
n = Zadacha().calculate()
x, y = n
result = x * y
return result
if __name__ == '__main__':
print(Zadacha().multiple())
|
##zadacha2 part 1 CountReal
user_input = list(map(float, input().split()))
#user_input = [8, 2.5, 2.5, 8, 2.5]
my_dict = {}
for num in user_input:
counter = user_input.count(num)
my_dict[num] = counter
my_dict_sorted = sorted(my_dict.items())
for item in my_dict_sorted:
print(f'{item[0]} -> {item[1]} times')
|
##optimized banking system
class BankAccount:
def __init__(self, name:str, bank:str, balance:str):
self.name = name
self.bank = bank
self.balance = balance
def sort_data(self):
pass
def __str__(self):
return f'{self.name} -> {self.balance} ({self.bank})'
def collect_data():
user_input = input().split(' | ')
data_list = []
while user_input[0] != 'end':
bank = user_input[0]
name = user_input[1]
balance = user_input[2]
account = BankAccount(name, bank, balance)
data_list.append(account)
user_input = input().split(' | ')
return data_list
data_list= collect_data()
for item in data_list:
print(item)
|
user_input = input().split(' -> ')
data_dict = {}
while user_input[0] != 'login':
key = user_input[0]
value = user_input[1]
data_dict[key] = value
user_input = input().split(' -> ')
login_attempt = input().split(' -> ')
failure = 0
while login_attempt[0] != 'end':
if login_attempt[0] in data_dict.keys():
if data_dict[login_attempt[0]] == login_attempt[1]:
print(f'{login_attempt[0]}: logged in successfully')
else:
print(f'{login_attempt[0]}: login failed')
failure += 1
else:
print(f'{login_attempt[0]}: login failed')
failure += 1
login_attempt = input().split(' -> ')
print(f'unsuccessful login attempts: {failure}')
|
smallest = 0
i = 20
numbers = [i for i in range(10, 21)]
# bogus solution; will update with prime factorization
def isDivisible(n, numbers):
for number in numbers:
if n % number != 0:
return False
return True
while smallest == 0:
if isDivisible(i, numbers):
smallest = i
i += 20
print(smallest)
|
file=input('Enter file name:\n')
x=open(file,'rt',encoding='UTF8')
text=x.read()
list=[]
for c in text:
list.append(ord(c))
for c in range(len(list)):
list[c]=128-list[c]
for c in range(len(list)):
list[c]=chr(list[c])
print(list)
for c in list:
print(c[::-1],end=" ")
x.close()
|
from datetime import date
def meetup_day(year, month, weekday, day):
"""
year: int
month: int
weekday: str, full name of weekday (e.g, "Monday", "Sunday")
day: str, nth occurance of day (e.g., 1st, 2nd, 3rd, etc) or "last"
"""
if day == 'teenth':
searchRange = range(13, 20)
elif day == 'last':
searchRange = range(31, 0, -1)
else:
searchRange = range(1, 8)
for numday in searchRange:
try:
if date(year, month, numday).strftime("%A") == weekday:
if day != 'teenth' and day != 'last':
nth = int(day[0]) - 1
return date(year, month, numday + nth*7)
else:
return date(year, month, numday)
except ValueError:
pass
raise ValueError('Nonexistant day of the month')
print(meetup_day(2015, 2, 'Sunday', 'last'))
|
def is_isogram(word):
wordLow = word.lower()
charCount = {}
for char in wordLow:
if char in 'abcdefghijklmnopqrstuvxyz':
if char in charCount and charCount[char] > 0:
return False
else:
charCount[char] = 1
return True
|
#C:/Anadonda/python.exe
import numpy as np
from FuncionesI import *
print("########## BIENVENIDO AL MULTIPLICADOR DE MATRICES ##########")
print("Solo se permite operar dos matrices.")
print("Recuerde que la cantidad de columnas de la primera matriz debe de ser \
igual al número de filas de la segunda matriz.")
cantidad1, f1,c1 = leer_matriz('primera')
cantidad2, f2 ,c2 = leer_matriz('segunda')
while (c1 != f2):
print("Las matrices no se pueden multiplicar.")
print("Vuelva a intentarlo.")
cantidad1, f1,c1 = leer_matriz('primera')
cantidad2, f2 ,c2 = leer_matriz('segunda')
print("PRIMERA MATRIZ")
matriz1 = leer_consola(cantidad1)
while (cantidad1 != len(matriz1)):
print("Ocurrio un error al digitar los números vuelva a intentarlo")
matriz1 = leer_consola(cantidad1)
print("SEGUNDA MATRIZ")
matriz2 = leer_consola(cantidad2)
while (cantidad2 != len(matriz2)):
print("Ocurrio un error al digitar los números vuelva a intentarlo")
matriz2 = leer_consola(cantidad2)
matriz1 = np.array(matriz1,dtype="int").reshape(f1,c1)
matriz2 = np.array(matriz2,dtype="int").reshape(f2,c2)
fR , cR = f1 , c2
R = np.zeros((fR,cR),dtype="int")
for i in range(0,fR):
for j in range(0,cR):
for k in range(0,c1):
R[i,j] += (matriz1[i,k] * matriz2[k,j])
print("LA MATRIZ RESULTANTE ES:")
print(R)
|
#!/usr/bin/env python3
"""
Author : mattmiller899
Date : 2019-03-14
Purpose: Rock the Casbah
"""
import argparse
import sys
# --------------------------------------------------
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Bottles of beer song',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-n',
'--num_bottles',
help='',
metavar='INT',
type=int,
default=10)
return parser.parse_args()
# --------------------------------------------------
def warn(msg):
"""Print a message to STDERR"""
print(msg, file=sys.stderr)
# --------------------------------------------------
def die(msg='Something bad happened'):
"""warn() and exit with error"""
warn(msg)
sys.exit(1)
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
num_bottles = args.num_bottles
if num_bottles < 1:
die("N {} must be a positive integer".format(num_bottles))
for i in reversed(range(1, num_bottles+1)):
print_str = "{} bottle{} of beer on the wall,\n{} bottle{} of beer,\nTake one down, pass it around,\n\
{} bottle{} of beer on the wall!".format(i, "s" if i != 1 else "", i, "s" if i != 1 else "", i-1, "s" if i-1 != 1 else "")
print(print_str)
if i != 1:
print()
# --------------------------------------------------
if __name__ == '__main__':
main()
|
# coding: utf-8
""" 判断点是否在多边形内
Reference: http://www.cnblogs.com/yym2013/p/3673616.html
"""
class Point(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
# 求p1p0和p2p0的叉积,如果大于0,则p1在p2的顺时针方向
def multiply(p1, p2, p0):
return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y)
def in_convex_polygon(polygon, target):
"""
:type polygon: list[Point]
:type target: Point
:rtype: bool
判断点target 是否在 凸多边形polygon内部
:param polygon:Point数组,代表凸多边形的顶点,顺时针给出
:param target: Point对象,代表待查询的顶点
:return: ture - target在凸多边形内
"""
eps = 1e-10
n = len(polygon) - 1
# 在第一个点为起点的扇形之外或在边上
if multiply(target, polygon[1], polygon[0]) <= eps or multiply(target, polygon[n], polygon[0]) >= -eps:
return False
left = 2
right = n
while right - left != 1:
mid = (left+right) / 2
if multiply(target, polygon[mid], polygon[0]) > eps:
left = mid
else:
right = mid
# 在边之外或在边上
if multiply(target, polygon[right], polygon[left]) <= eps:
return False
return True
|
# efficient way to multiply two numbers say x, y
# let x = 10^(n/2)a + b
# and y = 10^(n/2)c + d
# then the product x*y can be recursively computed as
# => xy = 10^(n)ac + 10^(n/2)(ad + bc) + bd
# but we know, (a + b)(c + d) = ac + bd + ad + bc
# using this we can reduce the number of calls from 4 to 3
# => xy = 10^(n)ac + 10^(n/2)[(a + b)(c + d) - (ac + bd)] + bc
# let z0 = ac, z1 = bd, z2 = (a + b)(c + d)
# => xy = 10^(n)z0 + 10^(n/2)(z2 - z1 - z0) + z1
def karatsuba(x, y):
strx, stry = str(x), str(y)
if x < 10 or y < 10:
return x * y
else:
length = len(str(x))
position = int(length / 2) if (length % 2 == 0) else int(length / 2 + 1)
a, b, c, d = int(strx[:int(length / 2)]), int(strx[int(length / 2):]), int(stry[:int(length / 2)]), int(stry[int(length / 2):])
z0, z1, z2 = karatsuba(a, c), karatsuba(b, d), karatsuba((a + b), (c + d))
return 10 ** (2 * position) * z0 + 10 ** (position) * (z2 - z1 - z0) + z1
# main script
print(karatsuba(122, 122))
|
def readFile1(fileName):
with open(fileName) as file:
data = file.read()
print(data)
def readFile2(fileName):
with open(fileName) as file:
data = file.read()
while True:
print(data)
for i in range(10):
print(data)
def readFile3(fileName):
with open(fileName) as file:
data = file.read()
while True:
pass
for i in range(10):
with open(fileName) as file:
data = file.read
print(data)
def func1():
for x in range(10):
if x < 10:
print x
else:
print x+10
def func2(n):
x = 0
while x < n:
if x < 10:
print x
else:
print x+10
x += 1
with open("x.out") as file:
for line in file:
print line
if x > n:
print "A Lot of Lines"
def h():
sum = 0
for x in range(3):
for y in range(4):
for z in range(5):
sum += z
return sum
f()
g(3)
h()
readFile1("x.out")
readFile2("x.out")
readFile3("x.out")
|
#PYTHON 3
#NOT PYTHON 2
def scoreVal(state):
if uin[0] == uin[1] and uin[1] == uin[2]:
return -10
elif uin[2] == "B" and uin[1] == "A":
if uin[0] == "L":
return 10
return 2
elif uin[2] == "B" and uin[1] == "L":
if uin[0] == "M":
return 20
return 2
elif uin[2] == "M" and uin[1] != "M":
return 1
elif uin[2] == "L" and uin[1] != "L":
return 1
else:
return -1
uin = ["M","M","M"]
score = 0
val_ins = ["A","B","C","D"]
num_inputs = 30
for i in range(num_inputs):
letter_in = input(str(i) + ": Next Input (A, B, C, or D): ")
while(letter_in not in val_ins):
print("Invalid Input")
letter_in = input(str(i) + ": Next Input (A, B, C, or D): ")
if(letter_in == "A"):
uin.append("M")
elif(letter_in == "B"):
uin.append("L")
elif(letter_in == "C"):
uin.append("A")
elif (letter_in == "D"):
uin.append("B")
uin.pop(0)
score = score + scoreVal(uin)
print("Observation: " + uin[0]+uin[1]+uin[2])
print("Score: " + str(score))
print("Final Score: " + str(score))
|
#!/usr/bin/env python3
def revLine(line):
"""Reverse the words in a line of text"""
simpleLine = line.strip()
words = simpleLine.split()
revWords = reversed(words)
newLine = ' '.join(revWords)
return newLine
# Read lines of text from a file, reverse it and then write to output
from sys import exit
infile = open("myFile", "r")
outfile = open("yourFile", "w")
for line in infile:
newLine = revLine(line) + "\n" # Text needs "\n"
try:
outfile.write(newLine)
except:
pass # Nowhere to write the error!
# Tidy up before exit -- this could fail as well
infile.close()
outfile.close()
exit(-1)
infile.close()
outfile.close()
|
leeftijd= eval(input('Wat is je leeftijd: '))
paspoort= input('Ben je in het bezit van een nederlandse paspoort: ')=='ja'
if leeftijd >= 18 and paspoort==True:
print('Gefeliciteerd, je mag stemmen!')
|
stations = ['Schagen', 'Heerhugowaard','Alkmaar','Castricum','Zaandam','Amsterdam Sloterdijk','Amsterdam Centraal','Amsterdam Amstel','Utrecht Centraal','’s-Hertogenbosch','Eindhoven','Weert','Roermond','Sittard','Maastricht']
def inlezen_beginstation(stations):
beginstation = input('Voer hier uw vertrekpunt in: ')
while beginstation not in stations:
beginstation = input('Voer hier een nieuw vertekpunt in: ')
return beginstation
def inlezen_eindstation(stations, beginstation):
eindstation = input('Voer hier uw bestemming in: ')
while eindstation not in stations:
eindstation= input('Voer hier uw nieuwe bestemming in: ')
while stations.index(beginstation)>=stations.index(eindstation):
eindstation= input('Geef een nieuwe bestemming aan: ')
return eindstation
def omroepen_reis(stations, beginstation, eindstation):
NummerB=stations.index(beginstation)+1
NummerE=stations.index(eindstation)+1
afstand= NummerE-NummerB
print('\nHet beginstation {} is het {}e station in het traject.'.format(beginstation,NummerB))
print('Het eindstation {} is het {}e station in het traject.'.format(eindstation,NummerE))
print('De afstand bedraagt {} station(s).',format(afstand))
print('De prijs van de kaartjes is '+str(((stations.index(eindstation)-stations.index(beginstation))*5))+' euro.')
print('Je stapt in de trein in: {}'.format(beginstation))
for i in range(NummerB, NummerE-1):
print('-'+stations[i])
print('Je stapt uit in: {}'.format(eindstation))
beginstation= inlezen_beginstation(stations)
eindstation= inlezen_eindstation(stations, beginstation)
omroepen_reis(stations, beginstation, eindstation)
|
def swap(lijst):
if len(lijst) >1:
lijst[0],lijst[1]=lijst[1],lijst[0]
return lijst
lijst =[4,0,1,-2]
abc= swap(lijst)
print(abc)
|
'''Basic Program to print area of square'''
side = 10
area = side**2
print('Area of square is: ',area)
|
'''
Write a program to evaluate the factorial of a number n
This program demonstrates a pattern called as 'guardian'
'''
def calc_factorial(n):
if not isinstance(n, int):
print('Factorial is only defined for Integers')
elif n < 0:
print('Factorial is not defined for negative Integers')
elif n == 0:
return 1
else:
recurse = calc_factorial(n-1)
result = n*recurse
return result
ans = calc_factorial(10)
print(ans)
|
from collections import Counter
alphanumeric_string = "12abcbacbaba344ab"
str_int=[]
str_alp = []
for i in alphanumeric_string:
if i.isalpha():
str_alp.append(i)
else:
str_int.append(i)
print(str_int)
print(str_alp)
print(Counter(str_alp))
|
"""
Datastore.py will establish a connection with the database that will fill in the content
of this application. It will be the persistent data store for the classes and student
status.
Authors:
(RegTools)
Joseph Goh
Mason Sayyadi
Owen McEvoy
Ryan Gurnick
Samuel Lundquist
References: https://www.tutorialspoint.com/sqlite/sqlite_python.htm
Priority credit to:
Ryan Gurnick - 2/27/20 Creation
"""
import sqlite3
import RequirementModel
class DB:
def __init__(self, db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
self.db = db_file
conn = None
try:
conn = sqlite3.connect(db_file, timeout=1)
self.conn = conn
return
except Error as e:
print(e)
self.conn = conn
return
def ret(self):
return self
def _create_table(self, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = self.conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def generateTables(self):
"""
This function will generate all of the required tables within the sqlite file for
us and allow us to start with a common basis in sql.
Example Usage:
ds = Datastore.Datastore('testing.db')
ds.generateTables()
"""
if self.conn is not None:
self._create_table("""CREATE TABLE "classes" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"term" integer NOT NULL,
"name" text NOT NULL,
"subject" text NOT NULL,
"number" text NOT NULL,
"credits" text NOT NULL,
"total_count" INTEGER DEFAULT 0,
"lecture_count" INTEGER DEFAULT 0,
"lab_count" INTEGER DEFAULT 0,
"discussion_count" INTEGER DEFAULT 0,
"other_count" INTEGER DEFAULT 0,
"sections" text NOT NULL,
"created_at" datetime NOT NULL,
"updated_at" datetime NOT NULL,
CONSTRAINT "class_unique" UNIQUE("term","subject","number")
);""")
self._create_table("""CREATE TABLE students (
id integer NOT NULL CONSTRAINT students_pk PRIMARY KEY AUTOINCREMENT,
name varchar(255) NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL
);""")
self._create_table("""CREATE TABLE students_classes (
id integer NOT NULL CONSTRAINT students_classes_pk PRIMARY KEY AUTOINCREMENT,
students_id integer NOT NULL,
classes_id integer NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL
);""")
self._create_table("""CREATE TABLE requirements (
id integer NOT NULL CONSTRAINT requirements_pk PRIMARY KEY AUTOINCREMENT,
term integer NOT NULL,
major varchar(255) NOT NULL,
type varchar(255) NOT NULL,
data text NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL
);""")
self._create_table("""CREATE TABLE "roadmap_toggles" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"requirements_id" INTEGER,
"students_id" INTEGER,
"highlight" TEXT,
"created_at" datetime,
"updated_at" datetime
);""")
rm = RequirementModel.RequirementModel(self.db)
rm.setupTable()
|
# 7-4
list_pizza = "\nPlease enter minue:"
list_pizza += "\n Enter 'quiet' when you are finished"
while True:
minue = raw_input(list_pizza)
if minue == 'quiet':
break
else:
print("I will aad " + minue + ' to pizza!')
# 7-5
message = "\nHow old are you? "
message += "\n Enter 'quiet' to finished"
active = True
while active:
age = raw_input(message)
if age == 'quiet':
active = False
else:
age = int(age)
if age < 3:
price = 0
elif age >= 3 and age < 12:
price = 10
else:
price = 15
print('\nYou sould pay: $' + str(price))
num = 3
while num < 15:
print(num)
num += 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.