text
stringlengths 37
1.41M
|
---|
def printRepeating(arr):
print("The repeating elements are: ")
size = len(arr)
for i in range(0, size):
print(abs(arr[i]))
# print(arr[abs(arr[i])])
if arr[abs(arr[i])] >= 0:
arr[abs(arr[i])] = -arr[abs(arr[i])]
else:
print("Duplicate")
# print(abs(arr[i]), end=" ")
print(printRepeating([12313,1,2,2,3,4,3,4,5,6,7,8,8,1])) |
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) == 0 or len(p) == 0:
return 0
# initialise
s = {}
indexs_array = []
substring_map = {}
i = 0
# get the substring map
for char in p:
if char in substring_map.keys():
substring_map[char] += 1
else:
substring_map[i] = 1
temp_substring_map = substring_map
# check substrings occurence
while i != len(s) - 1:
if s[i] in substring_map.keys():
j = i
while s[j] in temp_substring_map.keys() and temp_substring_map[s[j]] > 0:
j += 1
temp_substring_map[s[j]] -= 1
if j == len(p):
index_array.append(i)
i += 1
print(index_array)
|
class Solution(object):
def shortestPalindrome(self,s):
n=len(s)
longest=1
for length in range(n,1,-1):
rev=s[0:length]
if rev==rev[::-1]:
longest=length
break
print longest
suffix=s[longest:]
print suffix
prefix=suffix[::-1]
result=prefix+s
return result
def centers(self,s,beg,end):
while(beg>=0 and end<len(s) and s[beg]==s[end]):
beg-=1
end+=1
if beg==-1:
return end
else:
return None
def shortestPalindromeCenters(self,s):
if len(s)<2:
return s
mid=len(s)/2
for i in range(mid,-1,-1):
end=self.centers(s,i,i+1)
if(end!=None):
suffix=s[end:]
prefix=suffix[::-1]
return prefix+s
end=self.centers(s,i,i)
if(end!=None):
suffix=s[end:]
prefix=suffix[::-1]
return prefix+s
return ""
obj=Solution()
print obj.shortestPalindromeCenters("cabba")
print obj.shortestPalindromeCenters("c")
print obj.shortestPalindromeCenters("aba")
print obj.shortestPalindromeCenters("aabba")
|
def readint(prompt, min, max):
val=int(input(prompt))
assert val<=max and val>=min
return val
try:
v = readint("Enter a number from -10 to 10: ", -10, 10)
print("The number is:", v)
except ValueError:
print("Error: wrong input")
except AssertionError:
print("Error: the value is not within permitted range (-10..10)")
|
class StudentsDataException(Exception):
pass
class BadLine(StudentsDataException):
def __init__(self):
print("Bad line in the file")
class FileEmpty(StudentsDataException):
def __init__(self):
print("This file is empty!")
fileName = input("Enter the file name: ")
students={}
try:
file = open("C:\\cryptographer\\" + fileName + ".txt", mode="r+t", encoding="UTF-8")
lines=file.readlines()
if len(lines) == 0:
raise FileEmpty()
for student in lines:
if student == "":
raise BadLine()
studentData=student.split()
studentName=studentData[0]+" "+studentData[1]
if studentName not in students.keys():
students[studentName]=float(studentData[2])
else:
students.update({studentName:students[studentName]+float(studentData[2])})
file.close()
for key,value in sorted(students.items(),key=lambda kv:kv[0]):
print(key,value,sep=" ")
except Exception as e:
print("Exception ",e) |
#This is the User class that contains the user's information
class User:
def __init__(self,name, age, bio):
self.name = name
self.age = age
self.bio = bio
self.connections = []
def set_age(self, age):
self.age = age
def set_bio(self, biography):
self.bio = (biography)
def __str__(self):
string_to_print = "Name:" + self.name + "\n" + "Age: " + self.age + "\n" + "Bio:" + self.bio
return string_to_print
#This is the Network class that contains the multiple users.
class Network:
def __init__(self):
self.users = []
def add_users(self, user):
self.users.append(user)
def delete_users(self, user):
self.users.remove(user)
def addUserToConnections(self, user1, user2):
user1.connections.append(user2)
def main():
net = Network()
isQuitting = False
name1 = input("Enter name: ")
age1 = input("Enter your age: ")
bio1 = input("Enter a short biography (3-5 sentences) : ")
user1 = User(name1, age1, bio1)
net.add_users(user1)
while not isQuitting:
user_input3 = input("Press ENTER to view your user's information" + "\n" + "Press d to delete a user" + "\n" + "Press c to add a user" + "\n" + "Press b to add a connection" + "\n" + "Press a to show all the users" + "\n" "Press q to quit the program ")
if user_input3 == "":
print(user1)
elif user_input3 == "c":
name1 = input("Enter name: ")
age1 = input("Enter your age: ")
bio1 = input("Enter a short biography (3-5 sentences) : ")
user1 = User(name1, age1, bio1)
net.add_users(user1)
elif user_input3 == "b":
your_name = input("What is your name?") #user1
other_username = input("Who would you like to connect with?") #user2
for user in net.users: #find user2
if user.name == other_username:
user2 = user
for user in net.users: #find user1
if user.name == your_name:
user1_ = user
net.addUserToConnections(user1_, user2)
print("Here are your connections: ")
for connect in user1_.connections:
print(connect.name)
elif user_input3 == "a":
for people in net.users:
print (people.name)
elif user_input3 == "q":
isQuitting = True
elif user_input3 == "d":
input1 = input("Which user do you want to take out? ")
for people in net.users: #find user2
if people.name == input1:
net.delete_users(people)
main()
|
import random
from typing import Optional
import a2_game_tree
import a2_minichess
def generate_complete_game_tree(root_move: str, game_state: a2_minichess.MinichessGame,
d: int) -> a2_game_tree.GameTree:
"""Generate a complete game tree of depth d for all valid moves from the current game_state.
For the returned GameTree:
- Its root move is root_move.
- Its `is_white_move` attribute is set using the current game_state.
- It contains all possible move sequences of length <= d from game_state.
For each node in the tree, its subtrees appear in the same order that their
moves were returned by game_state.get_valid_moves(),
- If d == 0, a size-one GameTree is returned.
Note that some paths down the tree may have length < d, because they result in an end state
(win or draw) from game_state in fewer than d moves.
Preconditions:
- d >= 0
- root_move == GAME_START_MOVE or root_move is a valid chess move
- if root_move == GAME_START_MOVE, then game_state is in the initial game state
Implementation hints:
- This function must be implemented recursively.
- In the recursive step, use the MinichessGame.copy_and_make_move method to create
a copy of the game state with one new move made.
- You'll need to review the public interface of the MinichessGame class to see what
methods are available to help implement this function.
WARNING: we recommend not calling this function with depth greater than 6, as this will
likely take a very long time on your computer.
"""
game_tree = a2_game_tree.GameTree(root_move, game_state.is_white_move())
if game_state.get_winner() == 'White':
game_tree.white_win_probability = 1.0
if d == 0 or game_state.get_valid_moves() == []:
return game_tree
else:
for move in game_state.get_valid_moves():
this_game_state = game_state.copy_and_make_move(move)
game_tree.add_subtree(generate_complete_game_tree(move, this_game_state, d - 1))
return game_tree
class GreedyTreePlayer(a2_minichess.Player):
"""A Minichess player that plays greedily based on a given GameTree.
See assignment handout for description of its strategy.
"""
# Private Instance Attributes:
# - _game_tree:
# The GameTree that this player uses to make its moves. If None, then this
# player just makes random moves.
_game_tree: Optional[a2_game_tree.GameTree]
def __init__(self, game_tree: a2_game_tree.GameTree) -> None:
"""Initialize this player.
Preconditions:
- game_tree represents a game tree at the initial state (root is '*')
"""
self._game_tree = game_tree
def make_move(self, game: a2_minichess.MinichessGame, previous_move: Optional[str]) -> str:
"""Make a move given the current game.
previous_move is the opponent player's most recent move, or None if no moves
have been made.
Preconditions:
- There is at least one valid move for the given game
"""
if previous_move is None:
# White chooses best opening move
temp_subtree = self._game_tree.get_subtrees()[0]
for subtree in self._game_tree.get_subtrees():
if subtree.white_win_probability > temp_subtree.white_win_probability:
temp_subtree = subtree
self._game_tree = temp_subtree
return temp_subtree.move
white_move = game.is_white_move()
for subtree in self._game_tree.get_subtrees():
if previous_move == subtree.move:
self._game_tree = subtree
break
if self._game_tree is not None and self._game_tree.get_subtrees() != [] and white_move:
# white turn
temp_subtree = self._game_tree.get_subtrees()[0]
for subtree in self._game_tree.get_subtrees():
if subtree.white_win_probability > temp_subtree.white_win_probability:
temp_subtree = subtree
self._game_tree = temp_subtree
return temp_subtree.move
elif self._game_tree is not None and self._game_tree.get_subtrees() != []:
# black turn
temp_subtree = self._game_tree.get_subtrees()[0]
for subtree in self._game_tree.get_subtrees():
if subtree.white_win_probability < temp_subtree.white_win_probability:
temp_subtree = subtree
self._game_tree = temp_subtree
return temp_subtree.move
else:
# random player ai
return random.choice(game.get_valid_moves())
def part2_runner(d: int, n: int, white_greedy: bool) -> None:
"""Create a complete game tree with the given depth, and run n games where
one player is a GreedyTreePlayer and the other is a RandomPlayer.
The GreedyTreePlayer uses the complete game tree with the given depth.
If white_greedy is True, the White player is the GreedyTreePlayer and Black is a RandomPlayer.
This is switched when white_greedy is False.
Precondtions:
- d >= 0
- n >= 1
Implementation notes:
- Your implementation MUST correctly call a2_minichess.run_games. You may choose
the values for the optional arguments passed to the function.
"""
game = a2_minichess.MinichessGame()
if white_greedy:
white_player = GreedyTreePlayer(generate_complete_game_tree('*', game, d))
black_player = a2_minichess.RandomPlayer()
else:
black_player = GreedyTreePlayer(generate_complete_game_tree('*', game, d))
white_player = a2_minichess.RandomPlayer()
a2_minichess.run_games(n, white_player, black_player)
if __name__ == '__main__':
import python_ta
python_ta.check_all(config={
'max-line-length': 100,
'max-nested-blocks': 4,
'disable': ['E1136'],
'extra-imports': ['random', 'a2_minichess', 'a2_game_tree']
})
# Sample call to part2_runner (you can change this, just keep it in the main block!)
# part2_runner(5, 50, False)
|
'''
kata : https://www.codewars.com/kata/565f448e6e0190b0a40000cc
'''
def actually_really_good(foods):
sentence = "You know what's actually really good? "
if not foods:
return sentence + "Nothing!"
return sentence + '{} and {}.'.format(foods[0].capitalize(), foods[1].lower() if len(foods) > 1 else 'more {}'.format(foods[0].lower()))
|
var_A = input('Variable A')
var_B = input('Variable B')
try:
var_A = int(var_A)
var_B = int(var_B)
if var_A<var_B:
print('mas pequeño')
elif var_A>var_B:
print('mas grande')
else:
print('igual')
except ValueError:
print('String involucrado')
|
import re
def reggex(string):
match = re.search(r'[A-Z]{1}[a-z]+\s\d+', string)
if match :
print(match.group())
else:
print('no result found')
reggex("Kampakkers 52")
reggex("5503 LL Veldhoven") |
import sys
input = sys.stdin.readline
## 집합 개념으로 이해하면 쉽다.
# 특정 원소가 속한 집합을 찾기
def find_parent(parent, x):
# 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
# 두 원소가 속한 집합을 합치기
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
n, m = map(int, input().split())
parent = [0] * (n + 1) # 부모 테이블
# 순환이 발생할 수도 있지만 일단 두개를 합친다.
for i in range(n):
data = list(map(int, input().split()))
for j in range(n):
if data[j] == 1:
union_parent(parent, i+1, j+1)
plan = list(map(int, input().split()))
result = True
for i in range(m-1):
if find_parent(parent, plan[i] != find_parent(parent, plan[i+1])): # 부모 노드가 다르면 연결되지 않았다는 뜻이다.
result = False
if result:
print("YES")
else:
print("NO") |
#Michael McPhee, 05/09/21, fraction math practice program
import random
#gcd function using eucludian algorithm
def gcd(numeranswer, denomanswer):
while denomanswer:
numeranswer, denomanswer = denomanswer, numeranswer % denomanswer
return numeranswer
#addition function
def add(numer1, numer2, denom1, denom2):
numeranswer = ((numer1 * denom2) + (numer2 * denom1))
denomanswer = (denom1 * denom2)
z = gcd(numeranswer, denomanswer)
denomanswer = denomanswer / z
numeranswer = numeranswer / z
return numeranswer, denomanswer
#subtraction function
def subtract(numer1, numer2, denom1, denom2):
numeranswer = ((numer1 * denom2) - (numer2 * denom1))
denomanswer = (denom1 * denom2)
z = gcd(numeranswer, denomanswer)
denomanswer = denomanswer / z
numeranswer = numeranswer / z
return numeranswer, denomanswer
#multiply function
def multiply(numer1, numer2, denom1, denom2):
numeranswer = numer1 * numer2
denomanswer = denom1 * denom2
z = gcd(numeranswer, denomanswer)
denomanswer = denomanswer / z
numeranswer = numeranswer / z
return numeranswer, denomanswer
#divide function
def divide(numer1, numer2, denom1, denom2):
numeranswer = numer1 * denom2
denomanswer = denom1 * numer2
z = gcd(numeranswer, denomanswer)
denomanswer = denomanswer / z
numeranswer = numeranswer / z
return numeranswer, denomanswer
#operation type function
def operationtype(numer1, numer2, denom1, denom2):
#generate random number between 1 and 4
x = int(random.randint(1,4))
#each number is a diffent operation
if x == 1:
print (numer1 , "/", denom1, "plus ", numer2, "/", denom2)
numeranswer, denomanswer = add(numer1, numer2, denom1, denom2)
elif x == 2:
print (numer1 , "/", denom1, "subtract ", numer2, "/", denom2)
numeranswer, denomanswer = subtract(numer1, numer2, denom1, denom2)
elif x == 3:
print (numer1 , "/", denom1, "multiplied by ", numer2, "/", denom2)
numeranswer, denomanswer = multiply(numer1, numer2, denom1, denom2)
else:
print (numer1 , "/", denom1, "divided by ", numer2, "/", denom2)
numeranswer, denomanswer = divide(numer1, numer2, denom1, denom2)
return numeranswer, denomanswer
#function that determines if answer is correct
def correct(numeranswer, denomanswer, useranswer, counter):
#split user answer into numberator and denominator intergers
answer = useranswer.split("/")
usernumer = int(answer[0])
userdenom = int(answer[1])
#determine if answer is correct
if usernumer == numeranswer and userdenom == denomanswer:
print("Correct!")
#add to correct answer counter
counter = counter + 1
else:
#print correct answer
print("Incorrect, the answer was ", numeranswer, "/", denomanswer)
return counter
counter = 0
while True:
#generate fractions
numer1 = int(random.randint(1,10))
denom1 = int(random.randint(1,10))
numer2 = int(random.randint(1,10))
denom2 = int(random.randint(1,10))
#generate operation type
numeranswer, denomanswer = operationtype(numer1, numer2, denom1, denom2)
#obtain user answer
useranswer = input("Enter answer: ")
counter = correct(numeranswer, denomanswer, useranswer, counter)
#ask user if they wish to continue
y = input("Do you wish to continue (Enter yes/no): ")
if y == "no":
print("You had", counter, "correct answer(s)! Thanks for playing.")
break |
#Michael McPhee, 03/05/21, develops equation of linear graph from 2 points
x1 = int(input("Enter x1 "))
y1 = int(input("Enter y1 "))
x2 = int(input("Enter x2 "))
y2 = int(input("Enter y2 "))
#calculate numerator and denominator of the slope
slopenumerator = int(y2-y1)
slopedenominator = int(x2-x1)
#calculate numerator and denominator of the slope
yinterceptdenominator = int(slopedenominator*y1)
yinterceptnumerator = int((y1-slopenumerator/slopedenominator*x1)*yinterceptdenominator)
print("The equation of the line that passes through these points is y=",slopenumerator,"/",slopedenominator,"x +",yinterceptnumerator,"/",yinterceptdenominator) |
import matplotlib.pyplot as plt
import numpy as np
l = input("Ingrese la longitud de la varilla: ")
x=np.linspace(0,l/2,1000)
y=np.sqrt(-(2*x)**2+l**2)/2
plt.plot(x,y, label = "Pos. Centro de masa")
plt.legend()
plt.title("Posicion centro de masa varrilla", fontsize=16, fontweight='bold')
plt.xlabel("m")
plt.ylabel("m")
plt.show()
quit()
|
square= lambda num:num**2
i=square(5)
print(i)
mynum=[1,2,3,4,5,6]
mylist=list(map(lambda num:num**2,mynum))
print (mylist) |
# Convolutional Neural Network
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initializing the CNN
classifier = Sequential()
# Step 1: Convolution
classifier.add(Convolution2D(filters=32, kernel_size=3, input_shape=(64, 64, 3), activation='relu', data_format='channels_last'))
# Step 2: Pooling
classifier.add(MaxPooling2D(pool_size=2))
# Step 1: Convolution
classifier.add(Convolution2D(filters=32, kernel_size=3, activation='relu', data_format='channels_last'))
# Step 2: Pooling
classifier.add(MaxPooling2D(pool_size=2))
# Step 1: Convolution
classifier.add(Convolution2D(filters=64, kernel_size=3, activation='relu', data_format='channels_last'))
# Step 2: Pooling
classifier.add(MaxPooling2D(pool_size=2))
# Step 3: Flattening
classifier.add(Flatten())
# Step 4: Full Connection
classifier.add(Dense(units=128, activation='relu'))
classifier.add(Dense(units=1, activation='sigmoid'))
# Compiling the CNN!!!
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Fitting CNN to the images
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.7
set_session(tf.Session(config=config))
from keras.preprocessing.image import ImageDataGenerator
from PIL import Image
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory(
'Neural Networks/CNN/dataset/training_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
test_set = test_datagen.flow_from_directory(
'Neural Networks/CNN/dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
classifier.fit_generator(
training_set,
steps_per_epoch=8000,
epochs=25,
validation_data=test_set,
validation_steps=2000)
classifier.save('Neural Networks/CNN/model.txt') |
import pygame
import math
import random
"""Colors"""
white = [255,255,255]
black = [0,0,0]
red = [255,0,0]
blue = [0,0,255]
green = [0,255,0]
"""Initializing and setup pygame"""
pygame.init()
pygame.display.set_caption("Double Pendulum Simulation")
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode([screen_width,screen_height])
screen.fill(white)
pygame.display.update()
myFont = pygame.font.SysFont("comicsansms",20)
text = myFont.render("Click to Start",1,black)
pygame.draw.circle(screen, black, (300,300), 5)
screen.blit(text, (250, 70))
clock = pygame.time.Clock()
clock.tick(0)
crashed = False
start = False
"""Pendulum Variables"""
"""Changeable Variables"""
origin = (300,300)
r1, r2 = 100, 100
m1, m2 = 10, 10
g = 1
ang1, ang2 = random.uniform(0,2*math.pi) , random.uniform(0,2*math.pi)
"""Do not Change"""
a1vel, a2vel = 0, 0
a1accel, a2accel = 0, 0
paths1, paths2 = [], []
"""Calculating initial x and y coordinates for both objects"""
x1 = int(r1 * math.sin(ang1))
y1 = int(r1 * math.cos(ang1))
x2 = int(r2 * math.sin(ang2))
y2 = int(r2 * math.cos(ang2))
object1 = [origin[0] + x1, origin[1] + y1]
object2 = [object1[0] + x2, object1[1] + y2]
"""Drawing function"""
def draw(list1, list2, color1, color2, color3, color4, object1pos, object2pos, mass1, mass2):
for dots in list1:
pygame.draw.circle(screen, color1, dots, 1)
for dots in list2:
pygame.draw.circle(screen, color2, dots, 1)
pygame.draw.line(screen, color3, origin, object1pos, 3)
pygame.draw.line(screen, color3, object1pos, object2pos, 3)
pygame.draw.circle(screen, color4, object1pos, mass1)
pygame.draw.circle(screen, color4, object2pos, mass2)
pygame.display.update()
screen.fill(white)
draw(paths1,paths2,blue,green,black,red,object1,object2,m1,m2)
while not crashed:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
start = True
if event.type == pygame.QUIT:
crashed = True
if not start:
continue
else:
clock.tick(60)
"""Calculating x and y coordinates for both objects"""
x1 = int(r1 * math.sin(ang1))
y1 = int(r1 * math.cos(ang1))
x2 = int(r2 * math.sin(ang2))
y2 = int(r2 * math.cos(ang2))
object1 = [origin[0] + x1, origin[1] + y1]
object2 = [object1[0] + x2, object1[1] + y2]
"""Equations for Velocity and Acceleration"""
a1vel += a1accel
a2vel += a2accel
ang1 += a1vel
ang2 += a2vel
"""Introduce a slight reduction to act as air resistance"""
a1vel = a1vel * 0.999
a2vel = a2vel * 0.999
"""Combining equations for the Equation of Motion for object 1"""
eqp1 = -g * (2 * m1 + m2) * math.sin(ang1)
eqp2 = -m2 * g * math.sin(ang1 - 2 * ang2)
eqp3 = -2 * math.sin(ang1 - ang2) * m2
eqp4 = (a2vel ** 2) * r2 + (a1vel ** 2) * r1 * math.cos(ang1 - ang2)
eqden = r1 * (2 * m1 + m2 - m2 * math.cos(2 * ang1 - 2 * ang2))
a1accel = (eqp1 + eqp2 + (eqp3 * eqp4)) / eqden
"""Combining Equations for the equation of motion for object 2"""
eqp5 = 2 * math.sin(ang1 - ang2)
eqp6 = (a1vel ** 2) * r1 * (m1 + m2)
eqp7 = g * (m1 + m2) * math.cos(ang1)
eqp8 = (a2vel ** 2) * r2 * m2 * math.cos(ang1 - ang2)
eqden2 = r2 * (2 * m1 + m2 - m2 * math.cos(2 * ang1 - 2 * ang2))
a2accel = eqp5 * (eqp6 + eqp7 + eqp8) / eqden2
"""Removes clutter from excessive trailing dots"""
paths1.append(object1)
paths2.append(object2)
if len(paths1) >= 500:
paths1.remove(paths1[0])
if len(paths2) >= 500:
paths2.remove(paths2[0])
"""Calls Draw Function and update Frames"""
draw(paths1,paths2,blue,green,black,red,object1,object2,m1,m2)
pygame.quit()
quit() |
# In this problem, you'll create a program that guesses a secret number!
#
# The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, the computer will guess the user's secret number!
#
# Here is a transcript of an example session:
#
# Please think of a number between 0 and 100!
# Is your secret number 50?
# Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
# Is your secret number 75?
# Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
# Is your secret number 87?
# Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
# Is your secret number 81?
# Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
# Is your secret number 84?
# Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
# Is your secret number 82?
# Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
# Is your secret number 83?
# Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
# Game over. Your secret number was: 83
high = 100
low = 0
guess = (high + low) // 2
clue = ""
print("Please think of a number between " + str(low) + " and " + str(high) + "!")
while clue != "c":
print("Is your secret number " + str(guess) + "?")
clue = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if clue == "c":
break
elif clue == "h":
high = guess
guess = (high + low) // 2
elif clue == "l":
low = guess
guess = (high + low) // 2
else:
print("Sorry, I did not understand your input.")
print("Game over. Your secret number was: " + str(guess))
|
import os
import re
def is_alphanumeric(input_string, exact_length=0):
"""Return True if input is a valid alphanumeric, False otherwise
Keyword arguments:
input_string -- string value to check
exact_length -- strict string length check, if 0, it's omitted (default 0)
"""
if exact_length > 0 and len(input_string)!=exact_length:
return False
# search for any non-alphanumeric in string
pattern=re.compile("[^a-zA-Z0-9_]+")
# if we find a non-alphanumeric char, return false
if re.search(pattern, input_string):
return False
return True
|
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# @Author : shiqi.chang
# @Email : [email protected]
# @Time : 2019/6/17 上午10:18
# @Filename : palindrome_number.py
# @Software : PyCharm
class Solution:
def is_palindrome(self, x: int) -> bool:
"""回文数
解题思路:
int 转换成 str, 利用 [::-1] 性质判断
:param x:
:return:
"""
string = str(x)
reverse_string = string[::-1]
if string == reverse_string:
return True
else:
return False
if __name__ == '__main__':
print(Solution().is_palindrome(-121))
|
# coding: utf-8
# In[ ]:
a = {'那堤' : '$105',
'冰那堤' : '$105',
'焦糖瑪奇朵' : '$125',
'冰焦糖瑪奇朵' : '$125',
'摩卡' : '$120',
'冰摩卡' : '$120',
'卡布奇諾' : '$105',
'美式咖啡' : '$85',
'冰美式咖啡' : '$85',
'濃粹那堤' : '$120',
}
print('選單:')
print('那堤, 冰那堤, 焦糖瑪奇朵, 冰焦糖瑪奇朵, 摩卡, 冰摩卡, 卡布奇諾, 美式咖啡, 冰美式咖啡, 濃粹那堤')
while True:
menu=input('請輸入產品名稱 (註:容量設定為中杯)')
if menu == '停止查詢':
break
else:
b=a.get(menu,'查無此商品')
print (b)
# In[ ]:
|
# board = [-1] * 9
# 1 -> cross
# 0 -> circle
def checkFree(ind1, ind2, board):
if(board[ind1]==-1 and board[ind2]==-1):
return True
else:
return False
def checkBlocked(ind1, ind2, ind3, value, board):
if(board[ind1]==value and board[ind2]==value):
if(board[ind3]==-1):
return ind3
if(board[ind2]==value and board[ind3]==value):
if(board[ind1]==-1):
return ind1
if(board[ind1]==value and board[ind3]==value):
if(board[ind2]==-1):
return ind2
return -1
def checkBetween(value, board):
if checkBlocked(0, 1, 2, value, board) != -1:
return checkBlocked(0, 1, 2, value, board)
if checkBlocked(3, 4, 5, value, board) != -1:
return checkBlocked(3, 4, 5, value, board)
if checkBlocked(6, 7, 8, value, board) != -1:
return checkBlocked(6, 7, 8, value, board)
if checkBlocked(0, 3, 6, value, board) != -1:
return checkBlocked(0, 3, 6, value, board)
if checkBlocked(1, 4, 7, value, board) != -1:
return checkBlocked(1, 4, 7, value, board)
if checkBlocked(2, 5, 8, value, board) != -1:
return checkBlocked(2, 5, 8, value, board)
if checkBlocked(2, 5, 8, value, board) != -1:
return checkBlocked(2, 5, 8, value, board)
if checkBlocked(0, 4, 8, value, board) != -1:
return checkBlocked(0, 4, 8, value, board)
if checkBlocked(2, 4, 6, value, board) != -1:
return checkBlocked(2, 4, 6, value, board)
else:
return -1
def compMove(moves, board):
if(moves == 0):
return 8
elif moves == 1:
if(board[4]==-1):
return 4
else:
return 8
elif moves == 2:
if(board[4]==-1):
return 4
else:
return 8
elif moves == 3:
val = checkBetween(0, board)
if val != -1:
if(board[val] == -1):
return val
val = checkBetween(1, board)
if val != -1:
if(board[val] == -1):
return val
if board[4]==0 :
if checkFree(0, 8, board):
return 0
elif checkFree(2, 6, board):
return 2
elif checkFree(1, 7, board):
return 7
elif checkFree(3, 5, board):
return 3
if board[4]==1:
return 6
for ind in range(9):
if(board[ind]==-1):
return ind
elif moves >= 5:
val = checkBetween(0, board)
if val != -1:
if(board[val] == -1):
return val
val = checkBetween(1, board)
if val != -1:
if(board[val] == -1):
return val
for ind in range(9):
if(board[ind]==-1):
return ind
|
import random
import time
chosenPath =
correctPath = 0
def displayIntro():
print("North Korea, The USA, one giant war")
print("North Korea has 11 nuclear weapons")
print("USA hsa over 750,000 soldiers ")
print("USA also has 35,000 troops on the border between South Korea")
print("Perks on the way are available")
print("USA has less power but an excessive amount of soldiers")
print("North Korea has a very slow firing rate but more power")
print("Each team starts with 500 health plus any shield held")
print("Which team will you choose in the ultimate throw down of USA vs NK")
def choosePath = ''
while path != "USA" and path != "North Korea" and path!= "Russia":
path = input("Which Country Do You Go With? (North Korea, USA, Russia")
return path
def checkPath(choice, correctPath):
if choice == "North Korea":
print("One nuclear bomb ready to fire")
time.sleep(2)
print("Fire in the hole")
time.sleep(2)
print("Reports are in.. Kim Jun Un, thats a miss on the bomb")
time.sleep(2)
print("Keep realoading we need to destroy this iggnorant country")
time.sleep(2)+
print("Miss again")
time.sleep(2)
print("I am just going to keep hitting the button then!!")
if choice == "USA":
print("Troops grt ready!")
time.sleep(2)
print("70,000 troops are off to NK")
time.sleep(2)
print("He is going down today...")
time.sleep(2)
print("3 nuclear bomb sites down 1 to go")
time.sleep(2)
print("Bomb sites clear, Back home we go!")
if choice == "Russia"
print("")
time.sleep(2)
print("")
time.sleep(2)
print("")
time.sleep(2)
print("")
correctPath = random.randint(1, 2)
if chosenPath == correctPath:
print("Mission Complete")
print("Target down")
else:
print("An extremely energetic burst of gamma rays pass through you")
print("causing all of the energy in your body to explode")
print("there is no record left of any war...")
count = 0
playAgain = True
while playAgain:
displayIntro()
choice = choosePath() ######
checkPath(choice, correctPath)
ans = input("Do you want to play again? (yes or no to continue playing): ")
count += 1
if ans == 'yes':
playAgain = True
if ans == 'no':
playAgain = False
if count > 3:
playAgain = False
|
#!/usr/bin/env python
#
# Raspberry Pi Robot Costume
'''
In this project, we're making a Raspberry Pi Robot Costume. The costume will count candy placed in a bin, and speak out loud to the giver.
Well use the GrovePi, with an Ultrasonic Sensor, an LED Bar graph, 4 Chainable LED's, and the RGB LCD Display. We'll also use a small
portable speaker to give the robot a voice.
Each time a piece of candy is placed in the robot, it says "Thank you for the candy" and reads aloud the count of candy.
'''
#
import os
import random
import time
import grovepi
import sys
import random
from subprocess import call
from grove_rgb_lcd import *
candy_count = 10
bar_level = 0
led1 = 14
led2 = 15
led3 = 16
grovepi.pinMode(led1,"OUTPUT")
grovepi.pinMode(led2,"OUTPUT")
grovepi.pinMode(led3,"OUTPUT")
# Connect the Grove LED Bar to digital port D5
# DI,DCKI,VCC,GND
ledbar = 5
grovepi.pinMode(ledbar,"OUTPUT")
time.sleep(1)
i = 0
# Connect the Grove Ultrasonic Ranger to digital port D4
# SIG,NC,VCC,GND
ultrasonic_ranger = 4
# Connect first LED in Chainable RGB LED chain to digital port D7
# In: CI,DI,VCC,GND
# Out: CO,DO,VCC,GND
ledpin = 7 # RGB LED's are on D7
# First LED input socket connected to GrovePi, output socket connected to second LED input and so on
numleds = 4 #If you only plug 1 LED, change to 1
grovepi.pinMode(ledpin,"OUTPUT")
time.sleep(1)
# Connect the Grove 4 Digit Display to digital port D2
# CLK,DIO,VCC,GND
display = 2
grovepi.pinMode(display,"OUTPUT")
# test colors used in grovepi.chainableRgbLed_test()
testColorBlack = 0 # 0b000 #000000
testColorBlue = 1 # 0b001 #0000FF
testColorGreen = 2 # 0b010 #00FF00
testColorCyan = 3 # 0b011 #00FFFF
testColorRed = 4 # 0b100 #FF0000
testColorMagenta = 5 # 0b101 #FF00FF
testColorYellow = 6 # 0b110 #FFFF00
testColorWhite = 7 # 0b111 #FFFFFF
# patterns used in grovepi.chainableRgbLed_pattern()
thisLedOnly = 0
allLedsExceptThis = 1
thisLedAndInwards = 2
thisLedAndOutwards = 3
def initalize_chained_led():
print("Test 1) Initialise")
# init chain of leds
grovepi.chainableRgbLed_init(ledpin, numleds)
time.sleep(.5)
grovepi.chainableRgbLed_test(ledpin, numleds, random.randint(0,7))
time.sleep(.5)
def chained_led():
try:
# set led 1 to green
grovepi.chainableRgbLed_pattern(pin, thisLedOnly, 0)
time.sleep(.5)
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 2b) Test Patterns - blue")
# test pattern 1 blue
grovepi.chainableRgbLed_test(pin, numleds, testColorBlue)
time.sleep(1)
print ("Test 2c) Test Patterns - green")
# test pattern 2 green
grovepi.chainableRgbLed_test(pin, numleds, testColorGreen)
time.sleep(1)
print ("Test 2d) Test Patterns - cyan")
# test pattern 3 cyan
grovepi.chainableRgbLed_test(pin, numleds, testColorCyan)
time.sleep(1)
print ("Test 2e) Test Patterns - red")
# test pattern 4 red
grovepi.chainableRgbLed_test(pin, numleds, testColorRed)
time.sleep(1)
print ("Test 2f) Test Patterns - magenta")
# test pattern 5 magenta
grovepi.chainableRgbLed_test(pin, numleds, testColorMagenta)
time.sleep(1)
print ("Test 2g) Test Patterns - yellow")
# test pattern 6 yellow
grovepi.chainableRgbLed_test(pin, numleds, testColorYellow)
time.sleep(1)
print ("Test 2h) Test Patterns - white")
# test pattern 7 white
grovepi.chainableRgbLed_test(pin, numleds, testColorWhite)
time.sleep(1)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 3a) Set using pattern - this led only")
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# set led 3 to red
grovepi.chainableRgbLed_pattern(pin, thisLedOnly, 2)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 3b) Set using pattern - all leds except this")
# change color to blue
grovepi.storeColor(0,0,255)
time.sleep(.5)
# set all leds except for 3 to blue
grovepi.chainableRgbLed_pattern(pin, allLedsExceptThis, 3)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 3c) Set using pattern - this led and inwards")
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set leds 1-3 to green
grovepi.chainableRgbLed_pattern(pin, thisLedAndInwards, 2)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 3d) Set using pattern - this led and outwards")
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set leds 7-10 to green
grovepi.chainableRgbLed_pattern(pin, thisLedAndOutwards, 6)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 4a) Set using modulo - all leds")
# change color to black (fully off)
grovepi.storeColor(0,0,0)
time.sleep(.5)
# set all leds black
# offset 0 means start at first led
# divisor 1 means every led
grovepi.chainableRgbLed_modulo(pin, 0, 1)
time.sleep(.5)
# change color to white (fully on)
grovepi.storeColor(255,255,255)
time.sleep(.5)
# set all leds white
grovepi.chainableRgbLed_modulo(pin, 0, 1)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 4b) Set using modulo - every 2")
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# set every 2nd led to red
grovepi.chainableRgbLed_modulo(pin, 0, 2)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
print ("Test 4c) Set using modulo - every 2, offset 1")
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set every 2nd led to green, offset 1
grovepi.chainableRgbLed_modulo(pin, 1, 2)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 4d) Set using modulo - every 3, offset 0")
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# set every 3nd led to red
grovepi.chainableRgbLed_modulo(pin, 0, 3)
time.sleep(.5)
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set every 3nd led to green, offset 1
grovepi.chainableRgbLed_modulo(pin, 1, 3)
time.sleep(.5)
# change color to blue
grovepi.storeColor(0,0,255)
time.sleep(.5)
# set every 3nd led to blue, offset 2
grovepi.chainableRgbLed_modulo(pin, 2, 3)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 4e) Set using modulo - every 3, offset 1")
# change color to yellow
grovepi.storeColor(255,255,0)
time.sleep(.5)
# set every 4nd led to yellow
grovepi.chainableRgbLed_modulo(pin, 1, 3)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
print ("Test 4f) Set using modulo - every 3, offset 2")
# change color to magenta
grovepi.storeColor(255,0,255)
time.sleep(.5)
# set every 4nd led to magenta
grovepi.chainableRgbLed_modulo(pin, 2, 3)
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 5a) Set level 6")
# change color to green
grovepi.storeColor(0,255,0)
time.sleep(.5)
# set leds 1-6 to green
grovepi.write_i2c_block(0x04,[95,pin,6,0])
time.sleep(.5)
# pause so you can see what happened
time.sleep(2)
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
time.sleep(.5)
print ("Test 5b) Set level 7 - reverse")
# change color to red
grovepi.storeColor(255,0,0)
time.sleep(.5)
# set leds 4-10 to red
grovepi.write_i2c_block(0x04,[95,pin,7,1])
time.sleep(.5)
except KeyboardInterrupt:
# reset (all off)
grovepi.chainableRgbLed_test(pin, numleds, testColorBlack)
except IOError:
print ("Error")
def led_random():
#print "Change LED Color"
# test pattern 1 blue
try:
grovepi.chainableRgbLed_test(ledpin, numleds, random.randint(0,7))
# time.sleep(1)
except:
print "led_random failure"
def lcd_rgb(text):
c = random.randint(0,255)
setRGB(c,255-c,0)
setText(text)
def lcd_rgb_blue_blank():
setRGB(0,0,255)
#Calls the Espeak TTS Engine to read aloud a sentence
def sound(spk):
# -ven+m7: Male voice
# -s180: set reading to 180 Words per minute
# -k20: Emphasis on Capital letters
cmd_beg=" espeak -ven+m7 -a 200 -s180 -k20 --stdout '"
cmd_end="' | aplay"
print cmd_beg+spk+cmd_end
call ([cmd_beg+spk+cmd_end], shell=True)
def LEDBarGraph(level):
grovepi.ledBar_setLevel(ledbar,level)
time.sleep(0.1)
def random_bar():
global bar_level
# print "Random bar! " + str(bar_level)
try:
ran_bar_sign = random.randint(0,1)
if ran_bar_sign > 0:
bar_level = bar_level + 1
else:
bar_level = bar_level - 1
if bar_level < 0:
bar_level = 0
if bar_level > 10:
bar_level = 10
LEDBarGraph(bar_level)
except:
print "Random Bar Failure"
def random_led():
try:
grovepi.digitalWrite(led1,random.randint(0,1))
grovepi.digitalWrite(led2,random.randint(0,1))
grovepi.digitalWrite(led3,random.randint(0,1))
except:
print "LED Failure!"
def candy_detection():
global candy_count
dist = 100
try:
while dist > 8:
# Read distance value from Ultrasonic
# print(grovepi.ultrasonicRead(ultrasonic_ranger))
dist = grovepi.ultrasonicRead(ultrasonic_ranger)
random_bar()
led_random()
print("Distance Detected: " + str(dist))
candy_count = candy_count + 1
thanks = "Thank you for the candy! " + "I now have " + str(candy_count) + " pieces of candy!"
lcd_rgb(str(thanks))
led_random()
sound(thanks)
except TypeError:
print ("Ultrasonic Error! Error!")
except IOError:
print ("Ultrasonic Error! Error!")
initalize_chained_led() #Starts LED's sets to green.
grovepi.ledBar_init(ledbar, 0)
time.sleep(.5)
while True:
led_random()
random_bar()
try:
led_random()
candy_detection()
except:
print "Error."
lcd_rgb_blue_blank()
random_bar()
random_led()
led_random()
led_random() |
#!/usr/bin/python3
work_hours = [('Abby',100), ('Billy', 4000), ('Cassie',800)]
def employee_check(work_hours):
current_max = 0
employee_of_month = ''
for employee,hours in work_hours:
if hours > current_max:
current_max = hours
employee_of_month = employee
else:
pass
return (employee_of_month,current_max)
x = employee_check(work_hours)
print(x)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 11:02:24 2018
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
i=1
count=0
c=int(input("In the series of prime numbers, which term do you want?"))
while count<=c-1:
k=0
for j in range (1, i+1 , 1):
if i%j==0:
k+=1
if k==2:
count+=1
#print(i)
i+=1
print("Prime number #"+ str(c) +" is: ", i-1) |
''' TO FIND THE SUM OF DIGITS OF A NUMBER'''
number = int(input("Enter a number: "))
def sumdigits(number):
if number==0:
return 0
return (number%10) + sumdigits(number//10)
print(sumdigits(number)) |
# Given a sorted array of numbers, find if a given number ‘key’ is present in the array. Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order. You should assume that the array can have duplicates.
# Write a function to return the index of the ‘key’ if it is present in the array, otherwise return -1.
def binary_search(arr, key):
l, h = 0, len(arr)-1
mid = h+l//2
while l <= h:
if key == arr[mid]:
return mid
if key <= arr[mid]:
h = mid-1
else:
l = mid+1
return -1
def main():
print(binary_search([4, 6, 10], 10))
print(binary_search([1, 2, 3, 4, 5, 6, 7], 5))
print(binary_search([10, 6, 4], 10))
print(binary_search([10, 6, 4], 4))
main()
|
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'rpg' function below.
#
# The function is expected to return a DOUBLE.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER m
# 3. INTEGER k
#
def rpg(n, m, k):
if k==0 or m==0:
return 0
p = 0
recursive_records= {}
def helper(n,m,k):
count = 0
if k==0:
if n<=0:
return 1
else:
return 0
for i in range(m+1):
if (n-i,k-1) in recursive_records:
count+=recursive_records[(n-i,k-1)]
else:
output=helper(n-i,m,k-1)
recursive_records[(n-i,k-1)] = output
count+=output
return count
count = helper(n,m,k)
p = round(count/((m+1)**k),5)
if p != 0:
return p
return '{:0.5f}'.format(0)
if _name_ == '_main_': |
from heapq import *
def minimum_cost_to_connect_ropes(ropeLengths):
result = 0
min_heap = []
for i in ropeLengths:
heappush(min_heap, -i)
n = len(min_heap)-1
for itr in range(n):
rope1 = -min_heap.pop()
rope2 = -min_heap.pop()
combined_rope = rope1+rope2
heappush(min_heap, -combined_rope)
result += combined_rope
return result
def main():
print("Minimum cost to connect ropes: " +
str(minimum_cost_to_connect_ropes([1, 3, 11, 5])))
print("Minimum cost to connect ropes: " +
str(minimum_cost_to_connect_ropes([3, 4, 5, 6])))
print("Minimum cost to connect ropes: " +
str(minimum_cost_to_connect_ropes([1, 3, 11, 5, 2])))
main()
|
def search_min_diff_element(arr, key):
if key < arr[0]:
return arr[0]
if key > arr[len(arr) - 1]:
return arr[len(arr) - 1]
l, h = 0, len(arr)-1
while l <= h:
mid = (l+h)//2
if arr[mid] == key:
return arr[mid]
elif key < arr[mid]:
h = mid - 1
else:
l = mid + 1
if abs(arr[l]-key) < abs(arr[h]-key):
return arr[l]
else:
return arr[h]
def main():
print(search_min_diff_element([4, 6, 10], 7))
print(search_min_diff_element([4, 6, 10], 4))
print(search_min_diff_element([1, 3, 8, 10, 15], 12))
print(search_min_diff_element([4, 6, 10], 17))
main()
|
def find_first_k_missing_positive(nums, k):
n = len(nums)
i = 0
while i < len(nums):
j = nums[i] - 1
if nums[i] > 0 and nums[i] <= n and nums[i] != nums[j]:
nums[i], nums[j] = nums[j], nums[i] # swap
else:
i += 1
missingNumbers = []
extraNumbers = set()
for i in range(n):
if len(missingNumbers) < k:
if nums[i] != i + 1:
missingNumbers.append(i + 1)
extraNumbers.add(nums[i])
# add the remaining missing numbers
i = 1
while len(missingNumbers) < k:
candidateNumber = i + n
# ignore if the array contains the candidate number
if candidateNumber not in extraNumbers:
missingNumbers.append(candidateNumber)
i += 1
return missingNumbers
def main():
print(find_first_k_missing_positive([3, -1, 4, 5, 5], 3))
print(find_first_k_missing_positive([2, 3, 4], 3))
print(find_first_k_missing_positive([-2, -3, 4], 2))
main()
|
# Given an array of intervals representing ‘N’ appointments, find out if a person can attend all the appointments.
def can_attend_all_appointments(intervals):
start, end = 0, 1
for i, interval in enumerate(intervals):
iterator = i + 1
while iterator < len(intervals):
if interval[start] >= intervals[iterator][start] and interval[start] <= intervals[iterator][end]:
return False
if interval[end] >= intervals[iterator][start] and interval[end] <= intervals[iterator][end]:
return False
iterator += 1
return True
def can_attend_all_appointments(intervals):
intervals.sort(key=lambda x: x[0])
start, end = 0, 1
for i in range(1, len(intervals)):
if intervals[i][start] < intervals[i-1][end]:
return False
return True
def main():
print("Can attend all appointments: " +
str(can_attend_all_appointments([[1, 4], [2, 5], [7, 9]])))
print("Can attend all appointments: " +
str(can_attend_all_appointments([[6, 7], [2, 4], [8, 12]])))
print("Can attend all appointments: " +
str(can_attend_all_appointments([[4, 5], [2, 3], [3, 6]])))
main()
|
# We are given an unsorted array containing ‘n’ numbers taken from the range 1 to ‘n’. The array has some duplicates, find all the duplicate numbers without using any extra space.
def find_all_duplicates(nums):
duplicateNumbers = []
itr = 0
while itr < len(nums):
if nums[itr] != itr+1:
if nums[itr] == nums[nums[itr]-1]:
duplicateNumbers.append(nums[itr])
itr += 1
else:
nums[nums[itr]-1], nums[itr] = nums[itr], nums[nums[itr]-1]
else:
itr += 1
return duplicateNumbers
def main():
print(find_all_duplicates([3, 4, 4, 5, 5]))
print(find_all_duplicates([5, 4, 7, 2, 3, 5, 3]))
main()
|
from collections import deque, defaultdict
def is_scheduling_possible(tasks, prerequisites):
if tasks <= 0:
return False
dependency_map = defaultdict(list)
no_of_prerequisites = defaultdict(int)
schedule = deque()
ans = []
for prerequisite, task in prerequisites:
no_of_prerequisites[task] += 1
dependency_map[prerequisite].append(task)
for task in range(tasks):
if no_of_prerequisites[task] == 0:
schedule.append(task)
while schedule:
task = schedule.popleft()
ans.append(task)
for child_task in dependency_map[task]:
no_of_prerequisites[child_task] -= 1
if no_of_prerequisites[child_task] == 0:
schedule.append(child_task)
if len(ans) != tasks:
return False
return True
def main():
print("Is scheduling possible: " +
str(is_scheduling_possible(3, [[0, 1], [1, 2]])))
print("Is scheduling possible: " +
str(is_scheduling_possible(3, [[0, 1], [1, 2], [2, 0]])))
print("Is scheduling possible: " +
str(is_scheduling_possible(6, [[0, 4], [1, 4], [3, 2], [1, 3]])))
main()
|
class Solution:
def frequencySort(self, s: str) -> str:
if not s:
return s
freq = collections.defaultdict(int)
for char in s:
freq[char] += 1
li = []
for char in freq.keys():
li.append((freq[char], char))
li.sort(key=lambda x: -x[0])
return "".join([char*freq for freq, char in li])
|
from __future__ import print_function
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(self):
temp = self
while temp is not None:
print(temp.value, end=" ")
temp = temp.next
print()
def rotate(head, rotations):
# TODO: Write your code here
node = head
idx = 1
while node.next:
node = node.next
idx += 1
le = idx
node.next = head
node = head
prev = None
rotations = rotations % le
while rotations > 0:
rotations -= 1
prev = node
node = node.next
prev.next = None
return node
def main():
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(6)
print("Nodes of original LinkedList are: ", end='')
head.print_list()
result = rotate(head, 3)
print("Nodes of rotated LinkedList are: ", end='')
result.print_list()
main()
|
# Given an array arr of unsorted numbers and a target sum, count all triplets in it such that arr[i] + arr[j] + arr[k] < target where i, j, and k are three different indices. Write a function to return the count of such triplets.
def triplet_with_smaller_sum(arr, target):
arr.sort()
count = 0
for first in range(len(arr)-2):
left, right = first + 1, len(arr) - 1
while (left < right):
if arr[left] + arr[right]+arr[first] < target:
count += right - left
left += 1
else:
right -= 1
return count
def main():
print(triplet_with_smaller_sum([-1, 0, 2, 3], 3))
print(triplet_with_smaller_sum([-1, 4, 2, 1, 3], 5))
main()
|
class ParenthesesString:
def __init__(self, str, openCount, closeCount):
self.str = str
self.openCount = openCount
self.closeCount = closeCount
def generate_valid_parentheses(num):
result = []
return result
def main():
print("All combinations of balanced parentheses are: " +
str(generate_valid_parentheses(2)))
print("All combinations of balanced parentheses are: " +
str(generate_valid_parentheses(3)))
main()
|
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# 0=x1, 1=x2, 2=y1,3=y2
if (rec1[0] == rec1[2] or rec1[1] == rec1[3] or
rec2[0] == rec2[2] or rec2[1] == rec2[3]):
return False
return rec1[0] < rec2[2] and rec2[0] < rec1[2] and rec1[1] < rec2[3] and rec2[1] < rec1[3]
|
from heapq import *
from collections import defaultdict
def reorganize_string(str, k):
if k <= 1:
return str
max_heap = []
feq_map = defaultdict(int)
for char in str:
feq_map[char] += 1
for key in feq_map.keys():
heappush(max_heap, [-feq_map[key], key])
# [prev_char_freq, prev_char] = heappop(max_heap)
que = []
result_str = ''
while max_heap:
[next_char_freq, next_char] = heappop(max_heap)
result_str += next_char
next_char_freq += 1
que.append([next_char_freq, next_char])
if len(que) >= k:
[next_char_freq, next_char] = que.pop(0)
if next_char_freq < 0:
heappush(max_heap, [next_char_freq, next_char])
if len(str) != len(result_str):
return ''
return result_str
def main():
print("Reorganized string: " + reorganize_string("Programming", 3))
print("Reorganized string: " + reorganize_string("mmpp", 2))
print("Reorganized string: " + reorganize_string("aab", 2))
print("Reorganized string: " + reorganize_string("aapa", 3))
main()
|
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
dic = {}
if not head:
return head
res = head
while res:
dic[res] = Node(res.val)
res = res.next
res = head
while res:
dic[res].next = dic.get(res.next)
dic[res].random = dic.get(res.random)
res = res.next
return dic[head]
class Solution:
# @param head, a RandomListNode
# @return a RandomListNode
def copyRandomList(self, head):
dic = collections.defaultdict(lambda: RandomListNode(0))
dic[None] = None
n = head
while n:
dic[n].label = n.label
dic[n].next = dic[n.next]
dic[n].random = dic[n.random]
n = n.next
return dic[head]
|
def backspace_compare(str1, str2):
idx = 0
slow = 0
str1 = list(str1)
str2 = list(str2)
while idx < len(str1):
if str1[idx] == '#':
slow -= 1
else:
str1[slow] = str1[idx]
slow += 1
idx += 1
idx2 = 0
slow2 = 0
while idx2 < len(str2):
if str2[idx2] == '#':
slow2 -= 1
else:
str2[slow2] = str2[idx2]
slow2 += 1
idx2 += 1
idx1, idx2 = 0, 0
# if slow != slow2:
# return False
print(str1[:slow], str2[:slow2])
while idx1 < slow and idx2 < slow2:
print(str1[idx1], str2[idx2])
if str1[idx1] != str2[idx2]:
return False
idx1 += 1
idx2 += 1
return True
print(backspace_compare('xywrrmu#p','xywrrmp'))
|
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
def reverse(s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
reverse(s, 0, len(s)-1)
itr = 0
while itr < len(s)-1:
if s[itr] == ' ':
itr += 1
continue
itr2 = itr
while itr2 < len(s) and s[itr2] != ' ':
itr2 += 1
reverse(s, itr, itr2-1)
itr = itr2
return s
|
'''Crea un programa que sea capaz de contar la cantidad de letras mayúsculas en una string introducida por el usuario.'''
frase_del_usuario = input('Escribe una frase: ')
mayusculas = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','V','W','X','Y','Z']
n_mayusculas = 0
for numero in frase_del_usuario:
if numero in mayusculas:
n_mayusculas += 1
print('Las mayusculas son:{}'.format(n_mayusculas))
|
'''Crea un programa que encuentre el número más pequeño de una serie de números introducidos por el usuario'''
usser_numbers = []
added_number = ''
while len(usser_numbers) < 10:
added_number =input('Elige un numero:')
while not added_number.isdigit():
added_number = input('Elige un numero:')
print('numero añadido')
usser_numbers.append(int(added_number))
min_number =usser_numbers[0]
for number in usser_numbers:
if number < min_number:
min_number = number
print('El numero mas pequeño es:{}'.format(min_number))
|
mi_lista = []
input_usuario = input('Que quieres comprar?')
while input_usuario != 'FIN':
mi_lista.append(input_usuario)
input_usuario = input('Que quieres comprar?')
for item in mi_lista:
print('Tengo que comprar {}'.format(item))
print('Esta es la lista de compra')
|
import random
import string
data= dict()
listname=list()
lowerLetters=string.ascii_lowercase
print(" please enter passcode ")
name = input()
lowercase_letters = [c for c in name if c.islower()]
# print (lowercase_letters)
# print (name)
# print (listname[:10])
if lowercase_letters != [] :
passcode=' '.join(lowercase_letters[:10])
data[passcode] = random.randrange(10,99)
print ("Yourpasscode is " ,data)
else :
for i in range (0,10):
data = ' '.join(random.choice(lowerLetters) for j in range (0,10))
print (" Yourpasscode is", data)
|
class MovieNode:
def __init__(self, movie_dict):
self._type = "movie" # cannot be changed
self._neighbors = [] # preset, will not included if transfer to json format
# set other fields by an actor_dict
for key, value in movie_dict.items():
if key == 'name':
self._name = value
if key == 'year':
self._year = value
if key == 'box_office': # only set when the input is provided_data.json file
self._box_office = value
if key == 'actors':
self._actors = value
@property
def type(self):
return self._type
@property
def name(self):
return self._name
@property
def year(self):
return self._year
@property
def box_office(self):
return self._box_office
@property
def actors(self):
return self._actors
@property
def neighbors(self):
return self._neighbors
def add_actors(self, actor_name):
self._actors.append(actor_name)
def add_neighbors(self, node):
self._neighbors.append(node)
def delete_neighbor(self, node):
if node in self.neighbors:
self.neighbors.remove(node)
if node.name in self.actors:
self.actors.remove(node.name)
def change_to_dict(self):
movie_dict = {"type": "movie",
"name": self.name,
"year": self.year,
"box_office": self.box_office,
"actors": self.actors}
return movie_dict
def change_to_text(self):
return "name: " + self.name + "<br>" + "year: " + str(self.year) + "<br>box_office: " + str(self.box_office)
# update movie_node by info in new_dict
# helper for api PUT method
def update_by_dict(self, update_dict):
for key, value in update_dict.items():
if key == 'name':
self._name = value
if key == 'year':
self._year = value
if key == 'box_office':
self._box_office = value
if key == 'actors':
self._actors = value
|
print('-'*20)
print('LOJA BARATÃO')
print('-'*20)
fim = 'a'
totalpreço = contadorpreço = menor = contador = 0
menorproduto = ''
while True:
produto = str(input('Nome do produto:'))
preço = float(input('Preço: R$'))
totalpreço += preço
contador += 1
if preço > 1000:
contadorpreço += 1
if contador == 1:
menor = preço
else:
if preço < menor:
menor = preço
menorproduto = produto
'''print(totalpreço)'''
while True:
escolha = str(input('Quer continuar ? [S/N]')).lower()
if escolha == 'n':
fim = escolha
if escolha in 'sn':
break
if fim == 'n':
break
print('-'*10,'FIM DO PROGRAMA','-'*10)
print(f'O total da compra foi R${totalpreço:.2f}')
print(f'Temos {contadorpreço} produtos custando mais de R$1000.00')
print(f'O produto mais barato foi {menorproduto} que custa R${menor:.2f} ') |
j = 'João'
v = 'Vitória'
idade = 33
i = 'john'
n = 987.3
print(f'{i:^20} ESPAÇO') #DÁ PARA ALIAR(CENTRALIZAR)
print(f'{i:-^20} ESPAÇO') #DÁ PARA COMPLEMENTAR
print(f'{i:->20} ESPAÇO') #DÁ PARA ALIAR À DIREITA
print(f'{i:-<20} ESPAÇO') #DÁ PARA ALIAR À ESQUERDA
print(f'{i:20} ESPAÇO') #DÁ PARA MODIFICAR O ESPAÇO
print(f'{i} tem {idade} anos e recebi R${n:.2f} de salário.') #DÁ PARA USAR PONTO FLUTUANTE
print(f'Olá, {j} e {v}') # (PYTHON - 3.6+ )
print(f'Ambos, {j} e {v} tem {idade} anos.')
#COM O METODO DE F COM STRING, NÃO PRECISA USAR O FORMAT, DIMINUINDO MAIS AS LINHAS DO ALGARITIMO
print('Ambos, {} e {} tem {} anos'.format(j, v, idade)) #( PYTHON - 3)
'''print('Ola, %s e %d' % (j, v))''' #AQUI É A FORMA MAIS ANTIGA... (PYTHON - 2) |
n = int(input('Digite um número para ver sua tabuada:'))
#print('===========\n6 x 1 = 6 \n6 x 2 = 12 \n6 x 3 = 18 \n6 x 4 = 24 \n6 x 5 = 30 \n6 x 6 = 36'
#'\n6 x 7 = 42 \n6 x 8 = 48 \n6 x 9 = 54 \n6 x 10 = 60\n===========')
#r1 = n*1
#r2 = n*2
#r3 = n*3
#r4 = n*4
#r5 = n*5
#r6 = n*6
#r7 = n*7
#r8 = n*8
#r9 = n*9
#r10 = n*10
#print('===========''\n',n,'x 1 =', r1,'\n',n,'x 2 =',r2,
#'\n',n,'x 3 =',r3,'\n',n,'x 4 =',r4,'\n',n,'x 5 =',r5,
#'\n',n,'x 6 =',r6,'\n',n,'x 7 =',r7,'\n',n,'x 8 =',r8,
#'\n',n,'x 9 =',r9,'\n',n,'x 10 =',r10,'\n===========')
print('='*12)
print('{} x 1 = {:2}'.format(n, n*1))
print('{} x 2 = {:2}'.format(n, n*2))
print('{} x 3 = {:2}'.format(n, n*3))
print('{} x 4 = {:2}'.format(n, n*4))
print('{} x 5 = {:2}'.format(n, n*5))
print('{} x 6 = {:2}'.format(n, n*6))
print('{} x 7 = {:2}'.format(n, n*7))
print('{} x 8 = {:2}'.format(n, n*8))
print('{} x 9 = {:2}'.format(n, n*9))
print('{} x 10 = {}'.format(n, n*10))
print('='*12) |
m = 0
conta = 0
contam = 0
for c in range(1, 8):
n = int(input('Digite o ano de nascimento da {}° pessoa:'.format(c)))
m = 2019 - n
if m >= 21:
conta += 1
else:
contam += 1
print('Existem {} pessoas maior de idade.'.format(conta))
print('E existem {} pessoas menor de idade'.format(contam)) |
#print('='*20)
#print('DEZ TERMOS DE UMA PA')
#print('='*20)
#pt = int(input('Primeri Termo:'))
#raz = int(input('Razão:'))
#for c in range(pt, 11):
# print(pt+ raz + c)
print('='*20)
print('DEZ TERMOS DE UMA PA')
print('='*20)
pt = int(input('Primeri Termo:'))
raz = int(input('Razão:'))
pa = pt + (11 - 1) * raz
for c in range(pt, pa, raz):
print('{}'.format(c), end=' -> ')
print('ACABOU')
|
n1 =int(input('Digite sua idade:'))
n2 =int(input('Digite em que ano nós estamos:'))
n3=n2-n1
print('você nasceu em',n3) |
print('\033[1;7;35;40m#'*5+'\033[1;7;35;40mConfederaçao Nacional De Nataçao'+'\033[1;7;35;40m#'*5)
a = int(input('Digite o ano do seu nascimento: '))
m = 2019 - a
print(m)
if m <= 9:
print('O atleta tem {} anos e sua categoria é mirim.'.format(m))
elif m <= 14:
print('O atleta tem {} anos e sua categoria é infantil.'.format(m))
elif m <= 19:
print('O atleta tem {} anos e sua categoria é junior.'.format(m))
elif m <=20:
print('O atleta tem {} anos e sua categoria é sênior.'.format(m))
else:
print('O atleta tem {} anos e sua categoria é mestre.'.format(m)) |
n1 = int(input('Digite um número:'))
n2 = int(input('Digite outro número:'))
n3 = n1 + n2
n4 = n1 - n2
n5 = n1 * n2
n6 = n1 ** n2
n7 = n1 / n2
n8 = n1 // n2
n9 = n1 % n2
print('A soma é: {}. A diminuição é: {}.'.format(n3, n4))
print('A multiplicação é: {}. A potência é: {}.'.format(n5, n6))
print('A divisão é: {}. A divisão inteira é: {}.'.format(n7, n8))
print('O resto da divisão é: {}.'.format(n9))
|
#o metodo estatico de classe também recebi um decorador --> @staticmethod
from random import randint
class Pessoa:
ano_atual = 2020
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
def get_ano_nascimento(self):
print(self.ano_atual - self.idade)
@classmethod #decorador
def por_ano_nascimento(cls, nome, ano_nascimento):
#cls poderia ser qualquer nome que vc desejaria, mas por conversão colocam como cls.
idade = cls.ano_atual - ano_nascimento
return cls(nome, idade)
@classmethod
def gera_id(): #pode receber parametros como nome, idade, etc... mas aqui queremos apenas
#números aleatorios para a pessoa
rand = randint(1000, 1999)
return rand
#p1 = Pessoa.por_ano_nascimento('luiz',1988)
#p1 = Pessoa('luiz',32)
p1 = Pessoa('luiz', 32)
print(p1)
print(p1.nome, p1.idade)
p1.get_ano_nascimento()
print(Pessoa.gera_id())
print(rand)
print(p1.gera_id()) |
print('Digite uma medida para as retas')
reta1 = float(input('Reta 1:'))
reta2 = float(input('Reta 2:'))
reta3 = float(input('Reta3'))
if (reta1 + reta2) > reta3 and (reta3 + reta2) > reta1 and (reta3 + reta1) > reta2:
print('Dá para fazer um triangulo.')
else:
print('Não dá para fazer um triangulo.') |
n = int(input('digite: '))
print('Digite 1 para converter em binário.')
print('Digite 2 para converter em octal')
print('Digite 3 para converter em hexadécimal')
m = int(input('Digite 1, 2 ou 3: '))
if m == 1:
print('O número {} em binário é {}.'.format(n, bin(n)))
elif m == 2:
print('O número {} em octal é {}.'.format(n, oct(n)))
elif m == 3:
print('O número {} em hexadecimal é {}.'.format(n, hex(n)))
else:
print('Digite um valor válido.')
#print('número: {}.'.format(oct(n))) |
n1 = float(input('Digite a nota do aluno: '))
n2 = float(input('Digite outra nota do aluno: '))
media = (n1 + n2) / 2
print('Média: {}.'.format(media))
if media >= 7.0:
print('Aluno aprovado.')
elif media < 5.0:
print('Aluno reprovado.')
elif media <= 6.9:
print('Aluno em recuperação.')
|
class Carro:
def __init__(self, marca, tipo, modelo):
self.marca = marca
self.tipo = tipo
self.modelo = modelo
def Parado(self):
print('Está parado.')
def Deslocando(self):
print('Esta se deslocando.')
def Informações_do_veiculo(self):
print(self.marca, self.tipo, self.modelo)
perguntas = ['Qual a marca do carro:', 'Qual o tipo do carro:', 'Qual o modelo do carro:']
for c in perguntas:
info = input(c)
marca = info
tipo = info
modelo = info
print(marca, tipo, modelo)
print(info)
print(marca, tipo, modelo)
print(info)
carro1 = Carro('Volksvaguer'+',', 'Não esportivo e Esportivo'+',', 'Palho' )
carro1.Parado()
carro1.Deslocando()
carro1.Informações_do_veiculo() |
valor = list()
impar = list()
par = list()
n = 1
numero = 0
while n < 8:
valor.append(int(input(f'Digite o {n}° valor ')))
n += 1
for c in valor:
if c % 2 == 0:
par.append(c)
else:
impar.append(c)
print(f'Número impar: {impar}')
print(f'Número par{par}') |
from random import randint
sorteio = (randint(1, 10), randint(1, 10), randint(1, 10),randint(1, 10), randint(1, 10))
print(f'VALOR SORTEADO: {sorteio}')
print(f'O MAIRO VALOR FOI: {max(sorteio)}')
print(f'O MENOR VALOR FOI: {min(sorteio)}')
'''contador = maior = menor = 0
while contador < 5:
número = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
contador += 1
sorteio = random.choice(número)
if
print(sorteio, end=',')
print(maior)
print(menor)''' |
adição = 0
for c in range(1, 8):
n = int(input('Digite um número:'))
adição += n
print('A adição do número {}, 7 vez é {}'.format(n, adição)) |
"""Module for undertaking data transformation operations."""
from typing import List, Dict
import pandas as pd
import numpy as np
def count_error_code_occurrences(errors: List[Dict[str, int]]) -> List[Dict[str, int]]:
"""Return the number of occurrences for each distinct error code."""
# Load the errors into a new DataFrame
df_errors = pd.DataFrame(errors)
# Extract the 'code' column as a numpy array
np_error_codes = df_errors['code'].values
# Get the number of occurrences for each distinct error code
codes, occurrences = np.unique(np_error_codes, return_counts=True)
# Load the evaluated data into a new DataFrame with column names
code_occurrences = list(zip(codes.tolist(), occurrences.tolist()))
df_code_occurrences = pd.DataFrame(data=code_occurrences, columns=["code","occurrence"])
# Return the evaluated data as List[Dict]
return df_code_occurrences.to_dict('records')
|
def collatz(number):
if number % 2 == 0:
print(number/2)
return number / 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
print('Enter a number')
while True:
try:
num = int(input())
break
except ValueError:
print("Invalid input")
while num != 1:
num = int(collatz(num))
|
#!/bin/python
# Source: https://www.hackerrank.com/challenges/non-divisible-subset
# Given a set, S, of n distinct integers, print the size of a maximal subset
# S', of S where the sum of any 2 numbers in S' is not evenly divisible by k.
from collections import defaultdict
def max_non_divisible_subset(n, k, a):
remainder_sets = defaultdict(list)
count = 0
for element in a:
remainder_sets[element % k].append(element)
for j in xrange(k // 2 + 1):
if j == 0 or (j == k // 2 and k % 2 == 0):
count += min(1, len(remainder_sets[j]))
else:
count += max(
len(remainder_sets[j]),
len(remainder_sets[k - j]),
)
return count
n, k = [int(num) for num in raw_input().strip().split(' ')]
a = [int(num) for num in raw_input().strip().split(' ')]
result = max_non_divisible_subset(n, k, a)
print result
|
#this program is used to find whether the inputted year is leap year or not
def checkyear(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
opt = int(input("Enter year: "))
if (checkyear(opt)):
print("It is a Leap Year")
else:
print("Not a Leap Year") |
'''
this is my first day on the 100 days python challenge.
wish me luck
'''
print("hello python world")
message = "would you like to learn some python today"
print("hello," +(message))
clientName = "nimah abdulkarim"
print(clientName.title())
print(clientName.lower())
print(clientName.upper())
'''
let us do something crazy now
'''
message = 'Albert Einstein once said\n \t "A person who never made a mistake never tried anything new."'
print(message)
favouriteNumber = 3+2
print(favouriteNumber)
|
import numpy as np
#Definicion de dimensiones de la matriz
num_filas = int(input("Ingrese el numero de filas de la matriz "))
num_col = int(input("Ingrese el numero de columnas de la matriz "))
#Ingresar los valores de la matriz R
print("Si su matriz se ve así")
print("1 2 3")
print("4 5 6")
print("7 8 9")
print("Ingrese los valores separados por espacios así: 1 2 3 4 5 6 7 8 9")
elementos = list(map(float, input("Ingrese los elementos de la matriz:").split()))
#Asignar los elementos a una matriz
R = np.array(elementos).reshape(num_filas,num_col)
#Ingresar los valores de la matriz S
num_filas = int(input("Ingrese el numero de filas de la matriz "))
num_col = int(input("Ingrese el numero de columnas de la matriz "))
elementos = list(map(float, input("Ingrese los elementos de la matriz:").split()))
#Asignar los elementos a una matriz
S = np.array(elementos).reshape(num_filas,num_col)
#Hallar la matriz de composición
C = np.zeros((len(R),len(S[0])))
for i in range(0,len(R)):
for j in range(0,len(S[0])):
lista=[]
for k in range(0,len(R[0])):
lista.append(min(R[i,k],S[k,j]))
C[i,j] = max(lista)
print("La matriz composición R°S es:")
for i in range(0,len(R)):
for j in range(0,len(S[0])):
print("\t",C[i,j],end="")
print() |
import random
def check_valid_input(s):
"""
Check the input (valid or not)
Args:
s (str): The parameter, which is the input from the player.
Returns:
bool: The return value. True for valid input, False for invalid.
>>>check_valid_input("GUN")
False
>>>check_valid_input("paper")
True
>>>check_valid_input("zombee")
False
"""
if s == "gun":
return True
elif s == "zombie":
return True
elif s == "spock":
return True
elif s == "scissors":
return True
elif s == "paper":
return True
elif s == "lizard":
return True
elif s == "rock":
return True
else:
return False
def convert_to_num(s):
"""
Convert string to integer
Args:
s (str): The parameter, which is the player's choice.
Returns:
int: The return value. Convert str to int by returning the right value for each parameter.
>>>convert_to_num("spock")
2
>>>convert_to_num("Scissors")
Error: should not reach this if input is a valid one
>>>convert_to_num("octopus")
Error: should not reach this if input is a valid one
"""
if s == "gun":
return 0
elif s == "zombie":
return 1
elif s == "spock":
return 2
elif s == "scissors":
return 3
elif s == "paper":
return 4
elif s == "lizard":
return 5
elif s == "rock":
return 6
else:
print("Error: should not reach this if input is a valid one")
def convert_to_string(n):
"""
Convert integer to string
Args:
n (int): The parameter, take the computer's choice in an int form.
Returns:
str: The return value. Convert int to str by returning the right value for each parameter.
>>>convert_to_string(3)
spock
>>>convert_to_string(60)
Error: should not reach this if input is a valid one
>>>convert_to_string(0.5)
Error: should not reach this if input is a valid one
"""
if n == 0:
return "gun"
elif n == 1:
return "zombie"
elif n == 2:
return "spock"
elif n == 3:
return "scissors"
elif n == 4:
return "paper"
elif n == 5:
return "lizard"
elif n == 6:
return "rock"
else:
print("Error: should not reach this if input is a valid one")
def game_decision(player_choice_num, computer_choice_num):
"""
Use two integers (from player and computer) to calculate the result
Args:
player_choice_num (int): The first parameter. Get the player's choice in an int form.
computer_choice_num (int): The second parameter. Get the computer's choice in an int form.
Returns:
str: The return value. Return the right result for each conditions.
>>>game_decision(1, 0)
Computer wins!
>>>game_decision(3, 3)
Both ties!
>>>game_decision(4, 2)
Player wins!
"""
if player_choice_num == computer_choice_num:
print("Both ties!")
elif ((player_choice_num + 1) % 3) == computer_choice_num:
print("Player wins!")
else:
print("Computer wins!")
valid = False
while valid == False:
player_choice = input("Enter your choice: ")
valid = check_valid_input(player_choice)
if valid == False:
print("Invalid choice. Enter again.")
computer_choice_num = random.randint(0, 2)
computer_choice = convert_to_string(computer_choice_num)
player_choice_num = convert_to_num(player_choice)
print("Players chooses ", player_choice)
print("Computer chooses ", computer_choice)
game_decision(player_choice_num, computer_choice_num)
|
def check_valid_input(s):
"""Check that input is wrong or not
>>> check_valid_input("rock")
True
>>> check_valid_input("paper")
True
>>> check_valid_input("scissors")
True
>>> check_valid_input("stand")
False
>>> check_valid_input("spock")
True
>>> check_valid_input("lizard")
True
>>> check_valid_input("gun")
True
>>> check_valid_input("zombie")
True
"""
if s == "rock":
return True
elif s == "paper":
return True
elif s == "scissors":
return True
elif s == "spock":
return True
elif s == "lizard":
return True
elif s == "zombie":
return True
elif s == "gun":
return True
else:
return False
def convert_to_num(s):
"""Convert input to number
>>> convert_to_num("rock")
0
>>> convert_to_num("paper")
3
>>> convert_to_num("scissors")
6
>>> convert_to_num("stand")
Error: should not reach this if input is a valid one
>>> convert_to_num("spock")
2
>>> convert_to_num("lizard")
4
>>> convert_to_num("gun")
1
>>> convert_to_num("zombie")
5
"""
if s == "rock":
return 0
elif s == "paper":
return 3
elif s == "scissors":
return 6
elif s == "spock":
return 2
elif s == "lizard":
return 4
elif s == "zombie":
return 5
elif s == "gun":
return 1
else:
print("Error: should not reach this if input is a valid one")
def convert_to_string(n):
"""Convert number to string
>>> convert_to_string(0)
rock
>>> convert_to_string(6)
scissors
>>> convert_to_string(3)
paper
>>> convert_to_string(2)
spock
>>> convert_to_string(4)
lizard
>>> convert_to_string(1)
gun
>>> convert_to_string(5)
zombie
>>> convert_to_string(444)
Error: should not reach this if input is a valid one
"""
if n == 0:
return "rock"
elif n == 3:
return "paper"
elif n == 6:
return "scissors"
elif n == 2:
return "spock"
elif n == 4:
return "lizard"
elif n == 5:
return "zombie"
elif n == 1:
return "gun"
else:
print("Error: should not reach this if input is a valid one")
def game_decision(player_choice_num, computer_choice_num):
"""Check the winner
>>> game_decision(0, 0)
Both ties!
>>> game_decision(0, 1)
Computer wins!
>>> game_decision(0, 2)
Computer wins!
>>> game_decision(0, 3)
Computer wins!
>>> game_decision(0, 4)
Player wins!
>>> game_decision(0, 5)
Player wins!
>>> game_decision(0, 6)
Player wins!
>>> game_decision(1, 0)
Player wins!
>>> game_decision(1, 1)
Both ties!
>>> game_decision(1, 2)
Computer wins!
>>> game_decision(1, 3)
Computer wins!
>>> game_decision(1, 4)
Computer wins!
>>> game_decision(1, 5)
Player wins!
>>> game_decision(1, 6)
Player wins!
>>> game_decision(2, 0)
Player wins!
>>> game_decision(2, 1)
Player wins!
>>> game_decision(2, 2)
Both ties!
>>> game_decision(2, 3)
Computer wins!
>>> game_decision(2, 4)
Computer wins!
>>> game_decision(2, 5)
Computer wins!
>>> game_decision(2, 6)
Player wins!
>>> game_decision(3, 0)
Player wins!
>>> game_decision(3, 1)
Player wins!
>>> game_decision(3, 2)
Player wins!
>>> game_decision(3, 3)
Both ties!
>>> game_decision(3, 4)
Computer wins!
>>> game_decision(3, 5)
Computer wins!
>>> game_decision(3, 6)
Computer wins!
>>> game_decision(4, 0)
Computer wins!
>>> game_decision(4, 1)
Player wins!
>>> game_decision(4, 2)
Player wins!
>>> game_decision(4, 3)
Player wins!
>>> game_decision(4, 4)
Both ties!
>>> game_decision(4, 5)
Computer wins!
>>> game_decision(4, 6)
Computer wins!
>>> game_decision(5, 0)
Computer wins!
>>> game_decision(5, 1)
Computer wins!
>>> game_decision(5, 2)
Player wins!
>>> game_decision(5, 3)
Player wins!
>>> game_decision(5, 4)
Player wins!
>>> game_decision(5, 5)
Both ties!
>>> game_decision(5, 6)
Computer wins!
>>> game_decision(6, 0)
Computer wins!
>>> game_decision(6, 1)
Computer wins!
>>> game_decision(6, 2)
Computer wins!
>>> game_decision(6, 3)
Player wins!
>>> game_decision(6, 4)
Player wins!
>>> game_decision(6, 5)
Player wins!
>>> game_decision(6, 6)
Both ties!
>>> game_decision(44, 444)
Error: should not reach this if input is a valid one
"""
if (computer_choice_num - player_choice_num) % 7 == 0:
print("Both ties!")
elif (computer_choice_num - player_choice_num) % 7 <= 3:
print("Computer wins!")
elif (computer_choice_num - player_choice_num) % 7 <= 6:
print("Player wins!")
valid = False
while valid == False:
player_choice = input("Enter your choice: ")
valid = check_valid_input(player_choice)
if valid == False:
print("Invalid choice. Enter again.")
import random
computer_choice_num = random.randint(0, 6)
computer_choice = convert_to_string(computer_choice_num)
player_choice_num = convert_to_num(player_choice)
print("Players chooses ", player_choice)
print("Computer chooses ", computer_choice)
game_decision(player_choice_num, computer_choice_num) |
#number 1
def ll_sum(t):
"""function that add up all the number in the lists and nested lists
>>> ll_sum([[1,2],[3],[4,5,6]])
21
>>> ll_sum([[1,2,3,4,5]])
15
>>> ll_sum([[3,5,4,7,8]])
27
>>> ll_sum([[111,2],[4,3]])
120
>>> ll_sum([[2,3,4,5]])
14
"""
total = 0
for i in t:
total += sum(i)
return total
#number 2
def cumulative_sum(t):
"""function that take the make a new list that add the sum from the next number and the previous number
>>> cumulative_sum([1,2,3])
[1, 3, 6]
>>> cumulative_sum([3,5,6])
[3, 8, 14]
>>> cumulative_sum([18,30,100])
[18, 48, 148]
>>> cumulative_sum([111,44,5])
[111, 155, 160]
>>> cumulative_sum([0,3,100])
[0, 3, 103]
"""
total=[]
sum_total=0
for i in t:
sum_total +=i
total.append(sum_total)
return total
#number 3
def middle(t):
"""function that return a new list without the first and the last elements
>>> middle([1,2,3,4])
[2, 3]
>>> middle([69,18,19,20,69])
[18, 19, 20]
>>> middle([18,69,69,69,18])
[69, 69, 69]
>>> middle([1,1,3,2001,0])
[1, 3, 2001]
>>> middle(["j","j","e","a","n","n"])
['j', 'e', 'a', 'n']
"""
tnew = t[1:-1]
return tnew
#number 4
def chop(t):
"""function that make a new list without the first and the last elements but return none
>>> t = ([1,2,3,4])
>>> chop(t)
>>> t
[2, 3]
>>> t = ([5,3,2,4,5])
>>> chop(t)
>>> t
[3, 2, 4]
>>> t = ([8,9,1,69,420,1])
>>> chop(t)
>>> t
[9, 1, 69, 420]
>>> t = ([555,444,333,222,111])
>>> chop(t)
>>> t
[444, 333, 222]
>>> t = ([69,111,420,2,3,5,69])
>>> chop(t)
>>> t
[111, 420, 2, 3, 5]
"""
t.pop(0)
t.pop(-1)
#number 5
def is_sorted(t):
"""function that return True if the list is sorted or False if it's not
>>> is_sorted([1, 2, 3])
True
>>> is_sorted([3, 4, 5])
True
>>> is_sorted(['b', 'a'])
False
>>> is_sorted(['j', 'e', 'a', 'n'])
False
>>> is_sorted([69, 69, 420, 360])
False
"""
newt = t[:]
newt.sort()
if newt == t:
return True
else:
return False
#number 6
def front_x(t):
"""function that return a new sorted list that start with a group of string that begin with 'x' first
>>> front_x(['mix','xyz','apple','xanadu','aardvark'])
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
>>> front_x(['xxx','abc','xax'])
['xax', 'xxx', 'abc']
>>> front_x(['drax','axe','xeny'])
['xeny', 'axe', 'drax']
>>> front_x(['jean', 'handsome', 'xay'])
['xay', 'handsome', 'jean']
>>> front_x(['xxx','abc', 'xay','cde'])
['xay', 'xxx', 'abc', 'cde']
"""
xlist = []
for i in t:
if i.startswith("x"):
xlist.append(i)
t.remove(i)
xlist.sort()
t.sort()
newlist = xlist + t
return newlist
#number 7
def even_only(list):
"""function that return a new list of even numbers only
>>> even_only([3,1,4,1,5,9,2,6,5])
[4, 2, 6]
>>> even_only([2,3,4,5,6,7,8])
[2, 4, 6, 8]
>>> even_only([1,3,5,7,8,9])
[8]
>>> even_only([69,420,360,18])
[420, 360, 18]
>>> even_only([6,2,1,5,4,5,5,8,1])
[6, 2, 4, 8]
"""
evenlist = []
for i in list:
if i%2 == 0:
evenlist.append(i)
return evenlist
#number 8
def love(text):
"""function that replace the second last word with "love"
>>> love('I like Python')
'I love Python'
>>> love('Everyone like Jean')
'Everyone love Jean'
>>> love('I really like you')
'I really love you'
>>> love('I really like PJeen')
'I really love PJeen'
>>> love('I hate physic')
'I love physic'
"""
splitt = text.split()
word = splitt[-2]
newt = text.replace(word,"love")
return newt
#number 9
def is_anagram(x,y):
"""
>>> is_anagram('arrange', 'Rear Nag')
True
>>> is_anagram('and','dan')
True
>>> is_anagram('thorn','rntho')
True
>>> is_anagram('jean','jeen')
False
>>> is_anagram('jeejee','jean')
False
>>> is_anagram('jean is cool','loconeajsi')
True
"""
newx = x.upper()
newy = y.upper()
newx2 = newx.split(" ")
newy2 = newy.split(" ")
newx3 = "".join(newx2)
newy3 = "".join(newy2)
newx4 = sorted(newx3)
newy4 = sorted(newy3)
if newx4 == newy4:
return True
else:
return False
#number 10
def has_duplicates(t):
"""Function that return True if there is an element that have more than one or False if there is no duplicate
>>> has_duplicate([1,2,3,4,5])
False
>>> has_duplicate([1,2,3,4,5,2,3,4])
True
>>> has_duplicate([69,69,69,69])
True
>>> has_duplicate([18,19,20])
False
>>> has_duplicate([1,3,2001,2001])
True
"""
dupe = set()
for i in t:
if i in dupe: return True
dupe.add(i)
return False
#number 11
def average(t):
"""
>>> average([1,2,3,4,5])
3.0
>>> average([3,5,8,9,100])
25.0
>>> average([1,1,1,5,5,5,10,10])
4.75
>>> average([69,420,360])
283.0
>>> average([1,30,5,2,4,2,3,9,17])
8.11111111111111
"""
total = 0
total = sum(t)
total = total/len(t)
return total
#number 12
def centered_average(t):
"""
>>> centered_average([1,1,5,5,10,8,7])
5.2
>>> centered_average([10,5,7,3,4,2])
4.75
>>> centered_average([69,69,20,10,5,4,2,1,1])
15.857142857142858
>>> centered_average([1,1,1,1,1,10,10,10])
4.0
>>> centered_average([3,4,70,3,50,70])
31.75
"""
t.sort()
newt = t[1:-1]
total = 0
total = sum(newt)
total = total/len(newt)
return total
#number 13
def reverse_pair(t):
"""
>>> reverse_pair("May the fourth be with you")
'you with be fourth the May'
>>> reverse_pair("Jean is very handsome")
'handsome very is Jean'
>>> reverse_pair("Jean is name my")
'my name is Jean'
>>> reverse_pair("P Jeen very cute")
'cute very Jeen P'
>>> reverse_pair("homework much so is There")
'There is so much homework'
"""
newsentence = t.split()
time = len(newsentence)
reverse = []
while time >= 1:
reverse.append(newsentence[time-1])
time = time-1
reverse = " ".join(reverse)
return reverse
#number 14
def match_ends(t):
"""
>>> match_ends(["hello","wow","gingering"])
2
>>> match_ends(["jean","jeen","jeejeej"])
1
>>> match_ends(["thorn","sabai","eieie"])
1
>>> match_ends(["iii","jeenj","jeejeej"])
3
>>> match_ends(["physic","test","that"])
2
"""
num = 0
for i in t:
if len(i) >= 2:
if i.startswith(i[0]) == i.endswith(i[0]):
num += 1
return num
#number 15
def remove_adjacent(t):
"""
>>> remove_adjacent([1,2,2,3])
[1, 2, 3]
>>> remove_adjacent([1,2,3,3,4,4,5])
[1, 2, 3, 4, 5]
>>> remove_adjacent([1,1,1,1,1,1,1,2])
[1, 2]
>>> remove_adjacent([69,69,420,420,1,1,1,1])
[69, 420, 1]
>>> remove_adjacent([6,2,1,0,5,4,5,5,8,1])
[6, 2, 1, 0, 5, 4, 5, 8, 1]
"""
newt = []
dupe = None
for i in t:
if i != dupe:
newt.append(i)
dupe = i
return newt |
import random
import sys
def convert_to_num(s):
"""This function convert your choice into number.
>>> convert_to_num('rock')
0
>>> convert_to_num('paper')
1
>>> convert_to_num('scissors')
2
"""
if s == "rock":
return 0
elif s == "paper":
return 1
elif s == "scissors":
return 2
def check_input(p1) :
"""This function check whether your input is valid or not.
>>> check_input('scissors')
True
>>> check_input('test')
False
"""
if p1=='rock' or p1=='paper' or p1=='scissors':
return True
else :
return False
def result(p1,ai) :
"""This function return the result.
>>> result('rock','rock')
'Both ties!'
>>> result('paper','rock')
'Player wins!'
>>> result('scissors','rock')
'Computer wins!'
"""
if convert_to_num(p1) == convert_to_num(ai):
return "Both ties!"
elif ((convert_to_num(p1) + 1) % 3) == convert_to_num(ai):
return "Computer wins!"
else:
return "Player wins!"
def choose(ai) :
"""This function print what the ai choose.
>>> choose('rock')
Computer chooses rock
>>> choose('paper')
Computer chooses paper
"""
print(f'Computer chooses {ai}')
def main():
"""
This is your main program
"""
while True :
list1 = ['rock','paper','scissors']
ai = random.choice(list1)
p1 = input('Player chooses ')
if check_input(p1) == False :
print('Invalid input.')
sys.exit()
choose(ai)
print(result(p1,ai))
if __name__ == '__main__':
import doctest
doctest.testmod()
|
#1
def ll_sum(num):
"""this function takes a list of lists of integers and adds up the elements from all of the
nested lists.
>>> t = [[1, 2], [3], [4, 5, 6]]
>>> ll_sum(t)
21
>>> u = [[1, 3], [3], [4, 5, 6]]
>>> ll_sum(u)
22
>>> v = [[1, 2], [5], [4, 5, 6]]
>>> ll_sum(v)
23
>>> w = [[2, 2], [4], [5, 5, 6]]
>>> ll_sum(w)
24
>>> x = [[1], [3], [4, 6, 6, 9]]
>>> ll_sum(x)
29
>>> y = [[1,2,3,4,5,6,7,8,9,10]]
>>> ll_sum(y)
55
"""
result = 0
for item in num:
if type(item) == list:
result += ll_sum(item)
else:
result += item
return result
#2
def cumulative_sum(eiei):
"""this function takes a list of numbers and returns the cumulative sum; that is, a
new list where the ith element is the sum of the first i + 1 elements from the original list.
>>> t = [1, 2, 3]
>>> cumulative_sum(t)
[1, 3, 6]
>>> t = [1, 5, 18]
>>> cumulative_sum(t)
[1, 6, 24]
>>> t = [1, 3, 5]
>>> cumulative_sum(t)
[1, 4, 9]
>>> t = [2, 3, 4, 5, 6]
>>> cumulative_sum(t)
[2, 5, 9, 14, 20]
>>> t = [1, 2]
>>> cumulative_sum(t)
[1, 3]
>>> t = [4, 6, 8]
>>> cumulative_sum(t)
[4, 10, 18]
"""
result = []
jeejee = 0
for number in eiei:
jeejee = jeejee + number
result.append(jeejee)
return result
#3
def middle(a):
"""this function takes a list and returns a new list that contains all but the first and last
elements.
>>> t = [1, 2, 3, 4]
>>> middle(t)
[2, 3]
>>> t = [1, 1, 8, 4]
>>> middle(t)
[1, 8]
>>> t = [1, 2, 3, 4, 5, 6, 7, 8]
>>> middle(t)
[2, 3, 4, 5, 6, 7]
>>> t = [1, 3, 3, 3, 1]
>>> middle(t)
[3, 3, 3]
>>> t = [21, 22, 23, 24, 25]
>>> middle(t)
[22, 23, 24]
>>> t = [99, 98, 97]
>>> middle(t)
[98]
"""
b = len(a) - 1
return a[1:b]
#4
def chop(x):
"""this function takes a list, modifies it by removing the first and last elements, and returns
None.
>>> t = [1, 2, 3, 4]
>>> chop(t)
>>> t
[2, 3]
>>> t = [2, 2, 3, 6]
>>> chop(t)
>>> t
[2, 3]
>>> t = [1, 3, 5, 7, 9]
>>> chop(t)
>>> t
[3, 5, 7]
>>> t = [15, 18, 19, 27, 11, 9, 10]
>>> chop(t)
>>> t
[18, 19, 27, 11, 9]
>>> t = [11, 12, 13, 14, 15]
>>> chop(t)
>>> t
[12, 13, 14]
>>> t = [3, 4, 5, 6, 7]
>>> chop(t)
>>> t
[4, 5, 6]
"""
del x[0::(len(x)-1)]
return None
#5
def is_sorted(j):
"""this function takes a list as a parameter and returns True if the list is sorted in
ascending order and False otherwise.
>>> is_sorted([1, 2, 2])
True
>>> is_sorted(['b', 'a'])
False
>>> is_sorted([1, 3, 2])
False
>>> is_sorted(['a', 'b'])
True
>>> is_sorted([1, 2, 3, 4])
True
>>> is_sorted(['w', 'b'])
False
>>> is_sorted([18, 9, 27])
False
>>> is_sorted(['t', 'z'])
True
>>> is_sorted([1, 2, 2, 3, 4, 5])
True
>>> is_sorted(['d', 'r'])
True
>>> is_sorted([100, 300, 1000])
True
>>> is_sorted(['q', 'a', 'z'])
False
"""
if sorted(j) == j:
return True
else:
return False
#6
def front_x (l) :
"""this function returns a list with the strings in sorted order, except
group all the strings that begin with 'x' first.
>>> l = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
>>> front_x(l)
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
>>> l = ['six', 'abz', 'paruj', 'pwine']
>>> front_x(l)
['abz', 'paruj', 'pwine', 'six']
>>> l = ['pitchapa', 'qwz', 'xcoco']
>>> front_x(l)
['xcoco', 'pitchapa', 'qwz']
>>> l = ['beef', 'xav', 'jeejee']
>>> front_x(l)
['xav', 'beef', 'jeejee']
>>> l = ['xct', 'www', 'pet', 'ox']
>>> front_x(l)
['xct', 'ox', 'pet', 'www']
>>> l = ['xcry', 'or']
>>> front_x(l)
['xcry', 'or']
"""
x = []
for i in l:
if i.startswith("x"):
x.append(i)
l.remove(i)
x.sort()
l.sort()
return x + l
#7
def even_only(list):
"""this function will take a list of integers, and return a new list with only even
numbers.
>>> even_only([3,1,4,1,5,9,2,6,5])
[4, 2, 6]
>>> even_only([9,10,11])
[10]
>>> even_only([2,3,4,5,6])
[2, 4, 6]
>>> even_only([3,6,9])
[6]
>>> even_only([8,9,7,5,6,18])
[8, 6, 18]
>>> even_only([6,9,10,11])
[6, 10]
"""
even = []
for num in list:
if num%2 == 0 :
even.append(num)
return even
#8
def love(text):
"""this function will change the second last word to “love”.
>>> love("I like Python")
'I love Python'
>>> love("I really like Python")
'I really love Python'
>>> love("I hate you")
'I love you'
>>> love("I dont like you")
'I dont love you'
>>> love("You hate me")
'You love me'
>>> love("I really like TParuj")
'I really love TParuj'
>>> love("I like Pwine")
'I love Pwine'
"""
textlist = text.split(' ')
textlist[-2] = 'love'
newt = ' '.join(textlist)
return newt
#9
def is_anagram(str1,str2) :
"""this function takes two strings and returns True if they are anagrams.
>>> is_anagram('arrange','Rear Nag')
True
>>> is_anagram('pitch','stupid')
False
>>> is_anagram('saelim','limsae')
True
>>> is_anagram('apple','mylove')
False
>>> is_anagram('dog','god')
True
"""
a = list(str1.lower())
b = list(str2.lower())
if ' ' in b :
b.remove(' ')
a.sort()
b.sort()
if a == b:
return True
else:
return False
#10
def has_duplicates(list):
"""this that takes a list and returns True if there is any element that
appears more than once. It should not modify the original list.
>>> has_duplicates([1, 2, 3, 4, 5])
False
>>> has_duplicates([1, 2, 3, 4, 5, 2])
True
>>> has_duplicates([6, 9, 18])
False
>>> has_duplicates([1, 1, 1, 1])
True
>>> has_duplicates([8, 9, 11, 12])
False
>>> has_duplicates([4, 6, 8, 4])
True
>>> has_duplicates([5, 6, 7, 5, 8, 9])
True
"""
i = 0
while i < len(list):
if list.count(list[i])>1:
return True
elif i == (len(list)-1):
return False
i = i+1
#11
def average(nums) :
"""this function returns the mean average of a list of numbers.
>>> average([1, 1, 5, 5, 10, 8, 7])
5.285714285714286
>>> average([1, 2, 3])
2.0
>>> average([18, 9, 3])
10.0
>>> average([2, 4])
3.0
>>> average([99, 1])
50.0
>>> average([69, 7, 4, 3, 1])
16.8
"""
a = sum(nums)
b = len(nums)
aver = a/b
return aver
#12
def centered_average(nums) :
"""this function returns a "centered" average of a list of numbers,
which is the mean average of the values that ignores the largest and smallest values in the list. If
there are multiple copies of the smallest/largest value, pick just one copy.
>>> centered_average([1, 1, 5, 5, 10, 8, 7])
5.2
>>> centered_average([1, 3, 5, 7])
4.0
>>> centered_average([18, 9, 3, 2, 1, 5])
4.75
>>> centered_average([3, 6, 7, 8, 1, 2])
4.5
>>> centered_average([2, 4, 6, 8])
5.0
>>> centered_average([1, 2, 4, 6, 9, 5])
4.25
"""
nums.sort()
newnum = nums[1:-1]
aver_num= sum(newnum)/(len(nums)-2)
return aver_num
#13
def reverse_pair(text):
"""this function returns the reverse pair of the input sentence.
>>> reverse_pair("May the fourth be with you")
'you with be fourth the May'
>>> reverse_pair("My name is Jeejee")
'Jeejee is name My'
>>> reverse_pair("eiei is haha")
'haha is eiei'
>>> reverse_pair("Im so tried")
'tried so Im'
>>> reverse_pair("soy bad")
'bad soy'
>>> reverse_pair("Kasetsart unvst")
'unvst Kasetsart'
"""
list = text.split(' ')
newlist = list[::-1]
newtext = " ".join(newlist)
return newtext
#14
def match_ends(text):
"""this function returns the count of the number of strings where the string length is 2 or more and the first and last
chars of the string are the same.
>>> match_ends(["Gingering", "hello", "wow"])
2
>>> match_ends(["pitch", "hi", "sos"])
1
>>> match_ends(["jeejeej", "saeeas", "tot"])
3
>>> match_ends(["muracami", "xox", "xoxo"])
1
>>> match_ends(["bored", "ngo", "ggbbg"])
1
>>> match_ends(["sad", "dad", "mom"])
2
"""
newstr = " ".join(text)
newtext = newstr.upper()
newlst = newtext.split(" ")
start = 0
for i in newlst :
if len(i) >= 2 :
if i[0] == i[-1]:
start = start + 1
else:
start = start + 0
return start
#15
def remove_adjacent(num):
"""this function returns a list where all adjacent elements have been reduced to a single element.
>>> remove_adjacent([1, 2, 2, 3])
[1, 2, 3]
>>> remove_adjacent([2, 4, 5, 6, 6, 7])
[2, 4, 5, 6, 7]
>>> remove_adjacent([18, 19, 19, 20, 21, 22])
[18, 19, 20, 21, 22]
>>> remove_adjacent([1, 1, 3, 5, 7])
[1, 3, 5, 7]
>>> remove_adjacent([2, 4, 6, 6, 8])
[2, 4, 6, 8]
>>> remove_adjacent([69, 70, 71, 71, 72])
[69, 70, 71, 72]
"""
result = []
for i in num:
if len(result) == 0 or i != result[-1]:
result.append(i)
return result
|
import random
# list = ["rock", "scissors", "paper", "Spock", "lizard", "gun", "zombie"]
# player = random.choice(list)#input("Play chooses: ")
# com = random.choice(list)
# print(f"Computer choose {com}")
def strnum(player):
'''
:param player: [str]
:return: [int]
'''
if player == "Scissors":
return 1
if player == "Paper":
return 2
if player == "Rock":
return 3
if player == "Lizard":
return 4
if player == "Gun":
return 5
if player == "Zombie":
return 6
if player == "Spock":
return 7
def more7(x):
'''
:param x: x
:return: return x%7 if x > 7, return x if x <= 7
'''
if x > 7:
return x % 7
else:
return x
def play(player,com):
"""
>>> play('Spock','Paper')
Computer Wins!
>>> play('Spock','Scissors')
Player Win!
>>> play('Lizard','Lizard')
Both tie!
>>> play('Paper','Scissors')
Computer Wins!
>>> play('Zombie','Paper')
Player Win!
>>> play('Gun','Rock')
Player Win!
>>> play('Rock','Rock')
Both tie!
>>> play('Gun','Paper')
Computer Wins!
>>> play('Paper','Zombie')
Computer Wins!
"""
p = strnum(player)
c = strnum(com)
# Ex.1 scissor(1) win: paper(2), lizard(4), zombie(6)
# Ex.2 paper(2) win: rock(3), gun(5), spock(7)
# Ex.3 rock(3) win: scissor(1), lizard(4), zombie(6)
# So we got pattern is if you choose num and you got win
# computer need to choose num+1, num+3, num+5 and
# we need more7 function because in Ex.3 if rock(3)+5 = 8%7 = scissor(1)
if c == more7(int(p)+1) or c == more7(int(p)+3) or c == more7(int(p)+5):
print("Player Win!")
elif p - c == 0:
print("Both tie!")
else:
print("Computer Wins!")
|
def check_valid_input(s):
"""
>>> check_valid_input("rock")
True
>>> check_valid_input("spock")
True
>>> check_valid_input("scissors")
True
>>> check_valid_input("paper")
True
>>> check_valid_input("lizard")
True
"""
if s == "rock":
return True
if s == "spock":
return True
if s == "paper":
return True
if s == "lizard":
return True
if s == "scissors":
return True
else:
return False
#converting input to number
def convert_to_number(s):
"""
>>> convert_to_number("rock")
0
>>> convert_to_number("spock")
1
>>> convert_to_number("paper")
2
>>> convert_to_number("lizard")
3
>>> convert_to_number("scissors")
4
"""
if s == "rock":
return 0
if s == "spock":
return 1
if s == "paper":
return 2
if s == "lizard":
return 3
if s == "scissors":
return 4
#converting number to string
def convert_to_string(s):
"""
>>> convert_to_string(0)
'rock'
>>> convert_to_string(1)
'spock'
>>> convert_to_string(2)
'paper'
>>> convert_to_string(3)
'lizard'
>>> convert_to_string(4)
'scissors'
"""
if s == 0:
return "rock"
if s == 1:
return "spock"
if s == 2:
return "paper"
if s == 3:
return "lizard"
if s == 4:
return "scissors"
# #input from player / choice
# print("task2: rock/ paper/ scissors/ spock/ lizard ")
# valid = True
# while valid == False:
# player_choice = input("Enter you choice: ")
# valid = check_valid_input(player_choice)
# if valid == False:
# print("Invalid choice. Please Enter again.")
# #random output / computer choice
# import random
# computer_choice_number = random.randint(0, 4)
# computer_choice = convert_to_string(computer_choice_number)
# player_choice_number = convert_to_number(player_choice)
# print("player chooses", player_choice)
# print("computer chooses", computer_choice)
def game_decision(player_choice_number,computer_choice_number):
"""
>>> game_decision(0, 1)
COMPUTER WIN !!!
>>> game_decision(1, 1)
BOTH TIE !!!
>>> game_decision(0, 3)
PLAYER WIN !!!
>>> game_decision(4, 2)
PLAYER WIN !!!
>>> game_decision(4, 0)
COMPUTER WIN !!!
>>> game_decision(4, 3)
PLAYER WIN !!!
>>> game_decision(4, 1)
COMPUTER WIN !!!
>>> game_decision(2, 0)
PLAYER WIN !!!
>>> game_decision(2, 3)
COMPUTER WIN !!!
>>> game_decision(2, 1)
PLAYER WIN !!!
>>> game_decision(0, 3)
PLAYER WIN !!!
>>> game_decision(0, 1)
COMPUTER WIN !!!
>>> game_decision(3, 1)
PLAYER WIN !!!
>>> game_decision(2, 4)
COMPUTER WIN !!!
>>> game_decision(0, 4)
PLAYER WIN !!!
>>> game_decision(3, 4)
COMPUTER WIN !!!
>>> game_decision(1, 4)
PLAYER WIN !!!
>>> game_decision(0, 2)
COMPUTER WIN !!!
>>> game_decision(3, 2)
PLAYER WIN !!!
>>> game_decision(1, 2)
COMPUTER WIN !!!
>>> game_decision(3, 0)
COMPUTER WIN !!!
>>> game_decision(1, 0)
PLAYER WIN !!!
>>> game_decision(1, 3)
COMPUTER WIN !!!
>>> game_decision(0, 0)
BOTH TIE !!!
>>> game_decision(4, 4)
BOTH TIE !!!
>>> game_decision(2, 2)
BOTH TIE !!!
>>> game_decision(3, 3)
BOTH TIE !!!
>>> game_decision(1, 1)
BOTH TIE !!!
"""
# game output system
if player_choice_number == computer_choice_number:
print("BOTH TIE !!!")
if (player_choice_number + 1 ) % 5 == computer_choice_number or (player_choice_number + 2) % 5 == computer_choice_number:
print("COMPUTER WIN !!!")
if (player_choice_number + 3 ) % 5 == computer_choice_number or (player_choice_number + 4) % 5 == computer_choice_number:
print("PLAYER WIN !!!")
# game_decision(player_choice_number,computer_choice_number)
import doctest
doctest.testmod()
|
# Chanathip Thumkanon
# 6210546650
import random
NUMOFSYM = 7
def check_valid_input(s):
return convert_to_num(s) >= 0
def convert_to_num(s):
if s == 'rock':
return 0
elif s == 'gun':
return 1
elif s == 'Spock':
return 2
elif s == 'paper':
return 3
elif s == 'lizard':
return 4
elif s == 'zombie':
return 5
elif s == 'scissors':
return 6
return -1
def convert_to_string(n):
if n == 0:
return 'rock'
elif n == 1:
return 'gun'
elif n == 2:
return 'Spock'
elif n == 3:
return 'paper'
elif n == 4:
return 'lizard'
elif n == 5:
return 'zombie'
elif n == 6:
return 'scissors'
return 'Error'
def judgement(a,b):
c = a-b
if abs(c) > NUMOFSYM//2:
return -c
return c
def game_result(player_choice,computer_choice):
"""
>>> game_result('rock','rock')
Player chooses rock
Computer chooses rock
Both Tie!
>>> game_result('rock','gun')
Player chooses rock
Computer chooses gun
Computer wins!
>>> game_result('rock','Spock')
Player chooses rock
Computer chooses Spock
Computer wins!
>>> game_result('rock','paper')
Player chooses rock
Computer chooses paper
Computer wins!
>>> game_result('rock','lizard')
Player chooses rock
Computer chooses lizard
Player wins!
>>> game_result('rock','zombie')
Player chooses rock
Computer chooses zombie
Player wins!
>>> game_result('rock','scissors')
Player chooses rock
Computer chooses scissors
Player wins!
>>> game_result('gun','rock')
Player chooses gun
Computer chooses rock
Player wins!
>>> game_result('gun','gun')
Player chooses gun
Computer chooses gun
Both Tie!
>>> game_result('gun','Spock')
Player chooses gun
Computer chooses Spock
Computer wins!
>>> game_result('gun','paper')
Player chooses gun
Computer chooses paper
Computer wins!
>>> game_result('gun','lizard')
Player chooses gun
Computer chooses lizard
Computer wins!
>>> game_result('gun','zombie')
Player chooses gun
Computer chooses zombie
Player wins!
>>> game_result('gun','scissors')
Player chooses gun
Computer chooses scissors
Player wins!
>>> game_result('Spock','rock')
Player chooses Spock
Computer chooses rock
Player wins!
>>> game_result('Spock','gun')
Player chooses Spock
Computer chooses gun
Player wins!
>>> game_result('Spock','Spock')
Player chooses Spock
Computer chooses Spock
Both Tie!
>>> game_result('Spock','paper')
Player chooses Spock
Computer chooses paper
Computer wins!
>>> game_result('Spock','lizard')
Player chooses Spock
Computer chooses lizard
Computer wins!
>>> game_result('Spock','zombie')
Player chooses Spock
Computer chooses zombie
Computer wins!
>>> game_result('Spock','scissors')
Player chooses Spock
Computer chooses scissors
Player wins!
>>> game_result('paper','rock')
Player chooses paper
Computer chooses rock
Player wins!
>>> game_result('paper','gun')
Player chooses paper
Computer chooses gun
Player wins!
>>> game_result('paper','Spock')
Player chooses paper
Computer chooses Spock
Player wins!
>>> game_result('paper','paper')
Player chooses paper
Computer chooses paper
Both Tie!
>>> game_result('paper','lizard')
Player chooses paper
Computer chooses lizard
Computer wins!
>>> game_result('paper','zombie')
Player chooses paper
Computer chooses zombie
Computer wins!
>>> game_result('paper','scissors')
Player chooses paper
Computer chooses scissors
Computer wins!
>>> game_result('lizard','rock')
Player chooses lizard
Computer chooses rock
Computer wins!
>>> game_result('lizard','gun')
Player chooses lizard
Computer chooses gun
Player wins!
>>> game_result('lizard','Spock')
Player chooses lizard
Computer chooses Spock
Player wins!
>>> game_result('lizard','paper')
Player chooses lizard
Computer chooses paper
Player wins!
>>> game_result('lizard','lizard')
Player chooses lizard
Computer chooses lizard
Both Tie!
>>> game_result('lizard','zombie')
Player chooses lizard
Computer chooses zombie
Computer wins!
>>> game_result('lizard','scissors')
Player chooses lizard
Computer chooses scissors
Computer wins!
>>> game_result('zombie','rock')
Player chooses zombie
Computer chooses rock
Computer wins!
>>> game_result('zombie','gun')
Player chooses zombie
Computer chooses gun
Computer wins!
>>> game_result('zombie','Spock')
Player chooses zombie
Computer chooses Spock
Player wins!
>>> game_result('zombie','paper')
Player chooses zombie
Computer chooses paper
Player wins!
>>> game_result('zombie','lizard')
Player chooses zombie
Computer chooses lizard
Player wins!
>>> game_result('zombie','zombie')
Player chooses zombie
Computer chooses zombie
Both Tie!
>>> game_result('zombie','scissors')
Player chooses zombie
Computer chooses scissors
Computer wins!
>>> game_result('scissors','rock')
Player chooses scissors
Computer chooses rock
Computer wins!
>>> game_result('scissors','gun')
Player chooses scissors
Computer chooses gun
Computer wins!
>>> game_result('scissors','Spock')
Player chooses scissors
Computer chooses Spock
Computer wins!
>>> game_result('scissors','paper')
Player chooses scissors
Computer chooses paper
Player wins!
>>> game_result('scissors','lizard')
Player chooses scissors
Computer chooses lizard
Player wins!
>>> game_result('scissors','zombie')
Player chooses scissors
Computer chooses zombie
Player wins!
>>> game_result('scissors','scissors')
Player chooses scissors
Computer chooses scissors
Both Tie!
"""
computer_num = convert_to_num(computer_choice)
player_num = convert_to_num(player_choice)
print(f"Player chooses {player_choice}")
print(f"Computer chooses {computer_choice}")
c = judgement(player_num,computer_num)
if c == 0:
print("Both Tie!")
elif c > 0:
print("Player wins!")
else:
print("Computer wins!")
print("Rock, Paper, Scissors, Lizard, Spock, Zombie, Gun Game")
while True:
player_choice = input("Type 'quit' to exit or enter your choice: ")
computer_num = random.randint(0,NUMOFSYM-1)
computer_choice = convert_to_string(computer_num)
if player_choice == 'quit':
print("Program exits")
break
if not check_valid_input(player_choice):
print("Invalid choice. Enter again.")
continue
game_result(player_choice,computer_choice) |
if __name__ == "__main__":
import doctest
doctest.testmod()
def this_check_valid_input(t):
""" this function will check that if the input is True or False """
if t == "rock":
return True
elif t == "paper":
return True
elif t == "scissors":
return True
elif t == "lizard":
return True
elif t == "spock":
return True
else:
return False
def this_convert_to_num(t):
""" this function will convert string to a number of choices
>>> this_convert_to_num("rock")
0
>>> this_convert_to_num("paper")
1
>>> this_convert_to_num("scissors")
2
>>> this_convert_to_num("spock")
3
"""
if t == "rock":
return 0
elif t == "paper":
return 1
elif t == "scissors":
return 2
elif t == "spock":
return 3
elif t == "lizard":
return 4
else:
print("Error: should not reach this if input is a valid one")
def this_convert_to_string(x):
""" this function will convert a number of choices to string
>>> this_convert_to_string(0)
'rock'
>>> this_convert_to_string(1)
'paper'
>>> this_convert_to_string(2)
'scissors'
>>> this_convert_to_string(3)
'spock'
"""
if x == 0:
return "rock"
elif x == 1:
return "paper"
elif x == 2:
return "scissors"
elif x == 3:
return "spock"
elif x == 4:
return "lizard"
else:
print("Error: should not reach this if input is a valid one")
def this_game_decision(playchoice, comchoice):
""" this function will get a choices from playchoice and comchoice then it will return the winner!
>>> this_game_decision(0,0)
Both ties!
>>> this_game_decision(0,2)
Player wins!
>>> this_game_decision(2,0)
Computer wins!
>>> game_decision(1,1)
Both ties!
>>> game_decision(4,4)
Both ties!
"""
if playchoice == comchoice:
print("Both ties!")
elif ((playchoice + 1) % 5) or ((playchoice + 3) % 5) == comchoice:
print("Computer wins!")
else:
print("Player wins!")
def this_is_main():
valid = False
while valid == False:
this_player_choice = input("Enter your choice: ")
valid = this_check_valid_input(this_player_choice)
if valid == False:
print("Invalid choice. Enter again.")
import random
this_computer_choice_num = random.randint(0, 2)
this_computer_choice = this_convert_to_string(this_computer_choice_num)
this_player_choice_num = this_convert_to_num(this_player_choice)
print("Players chooses: ", this_player_choice)
print("Computer chooses: ", this_computer_choice)
this_game_decision(this_player_choice_num, this_computer_choice_num)
valid = False
# while valid == False:
# this_player_choice = input("Enter your choice: ")
# valid = check_valid_input(this_player_choice)
# if valid == False:
# print("Invalid choice. Enter again.")
# import random
# this_computer_choice_num = random.randint(0, 4)
# this_computer_choice = this_convert_to_string(this_computer_choice_num)
# this_player_choice_num = this_convert_to_num(this_player_choice)
# print("Players chooses ", this_player_choice)
# print("Computer chooses ", this_computer_choice)
# this_game_decision(this_player_choice_num, this_computer_choice_num)
|
def ll_sum(t):
'''
:param t:[int] list of numbers
:return:[int] sum of numbers in the list
>>> ll_sum([[1,2],[3],[5,6]])
17
>>> ll_sum([[2,7],[1,2,3]])
15
>>> ll_sum([[3,6,8],[1,2,3]])
23
>>> ll_sum([[1,3,4],[5],[8,2]])
23
>>> ll_sum([[2,8,4,3],[2,1]])
20
'''
lst = [] #empty list
for i in t:
for j in range (len(i)): # loop in list (that is also in the list)
lst.append(i[j]) #add it to empty list
return sum(lst) #summation of the list
#=================== 1 ======================
def cumulative_sum(t):
'''
:param t:[int] list of numbers
:return:[int] list of number that is the sum of the first
i + 1 elements from the original list
>>> cumulative_sum([1,2,3])
[1, 3, 6]
>>> cumulative_sum([1,2,3,4,5])
[1, 3, 6, 10, 15]
>>> cumulative_sum([5,6,7,8])
[5, 11, 18, 26]
>>> cumulative_sum([10,2,5])
[10, 12, 17]
>>> cumulative_sum([2,2,2,2])
[2, 4, 6, 8]
'''
lst1 = [t[0]] # a list that have the first number of parameter in the list
lst = t[0] #assign lst has the value as a first number in the list
for i in range(len(t)-1):
lst += t[i+1] #lst plus and equal to the number that was called
lst1.append(lst) #add it to the list that have the first number already
return lst1
#=================== 2 ======================
def middle(t):
'''
:param t: [int] list of numbers.
:return:[int] the same list with the original one but cut
the first one and the last one out.
>>> middle([1,3,4,5])
[3, 4]
>>> middle([2,2,2,3,4,5])
[2, 2, 3, 4]
>>> middle([4,5,6])
[5]
>>> middle([3,4,5,4,3])
[4, 5, 4]
>>> middle([6,7,6,7,6,7])
[7, 6, 7, 6]
'''
return t[1:-1] #cut the first one and the last one out
#==================== 3 =======================
def chop(t):
'''
:param t: [int] list of numbers
:return: [int] the same list with the original one but cut
the first one and the last one out.
>>> t = [1,3,4,5]
>>> chop(t)
>>> t
[3, 4]
>>> t = [2,2,2,3,4,5]
>>> chop(t)
>>> t
[2, 2, 3, 4]
>>> t = [4,5,6]
>>> chop(t)
>>> t
[5]
>>> t = [3,4,5,4,3]
>>> chop(t)
>>> t
[4, 5, 4]
>>> t = [7,6,5]
>>> chop(t)
>>> t
[6]
'''
t.remove(t[0]) # cut the first one
t.remove(t[-1]) # cut the last one
#===================== 4 =======================
def is_sorted(t):
'''
:param t:[str/int] list of number or str
:return: [bool] check whether it arrange value from the least
>>> is_sorted([1,2,3,4])
True
>>> is_sorted([4,3,5,2,7])
False
>>> is_sorted([2,2,1,3,4])
False
>>> is_sorted(['a','r','c','e'])
False
>>> is_sorted(['a','b','c','d'])
True
'''
if t == sorted(t): #if list t equals to list t that is ordered respectively
return True
else:
return False
#================== 5 ======================
def front_x(t):
'''
:param t: [str] list of words
:return: [str] list of word but re-arrange by putting
the word that start with 'X' first respectively
>>> front_x(['xain','bird','any','xie'])
['xain', 'xie', 'any', 'bird']
>>> front_x(['xon','won','tuang'])
['xon', 'tuang', 'won']
>>> front_x(['xion','xauy','khing','jern'])
['xauy', 'xion', 'jern', 'khing']
>>> front_x(['xander','xylan','bob','bambi'])
['xander', 'xylan', 'bambi', 'bob']
>>> front_x(['xanlee','xanlae','acadia','sylvia'])
['xanlae', 'xanlee', 'acadia', 'sylvia']
'''
lst = [] #empty list
lst1 = [] #empty list
for i in t:
if i[0] == 'x': #if the first character of the word is x
lst.append(i) #add it to one list
else:
lst1.append(i) # add it to another list
return sorted(lst)+ sorted(lst1) #re-arrange the list and put it together
#=================== 6 ====================
def even_only(t):
'''
:param t:[int] list of number
:return: [int] list of even number that originated in parameter t
>>> even_only([1,3,2,4,5,5])
[2, 4]
>>> even_only([3,7,9,8,6,4,2])
[8, 6, 4, 2]
>>> even_only([5,7,4,6,3])
[4, 6]
>>> even_only([9,9,7,8,6])
[8, 6]
>>> even_only([5,4,5,4])
[4, 4]
'''
lst = [] #empty list
for i in t:
if i % 2 == 0: # if i divisible by 2
lst.append(i) #add it to the list
return lst
#================== 7 =====================
def love(text):
'''
:param text: [str] sentence
:return:[str]change the second from the last word to 'love'
>>> love('I hate you')
'I love you'
>>> love('I adore you')
'I love you'
>>> love('I sent it to you')
'I sent it love you'
>>> love('miss you')
'love you'
>>> love('all over you')
'all love you'
'''
text = text.split(' ') #split the text form every spaces so,it's gonna be a list
text[-2] = 'love' #the word before the last one replace it with the word 'love'
text = ' '.join(text) #turn list in to a normal text
return text
#====================== 8 =========================
def is_anagram(a,b):
'''
:param a: [str] text
:param b: [str] text you want to check if it's anagram with the word before
:return:[bool] check if it's anagram
>>> is_anagram('considerate','careisnoted')
True
>>> is_anagram('a gentleman','elegant man')
True
>>> is_anagram('boypablo','soypablo')
False
>>> is_anagram('signature','atruesige')
False
>>> is_anagram('school','slouch')
False
'''
al = [] #list of parameter a
bl = [] #list of parameter b
for i in a:
al.append(i) #add it to list a
for i in b:
bl.append(i) #dd it to list b
if sorted(al) == sorted(bl): #if list a that is sorted equal to list b that is sorted as well
return True
else:
return False
#=================== 9 ===========================
def has_duplicates(t):
'''
:param lst: [int] list of numbers
:return:[bool] check the list if there are any number that appear
more than once
>>> has_duplicates([2,2,5,6,4])
True
>>> has_duplicates([2,5,6,4])
False
>>> has_duplicates([2,3,5,6,4,3])
True
>>> has_duplicates([3,3,6,6,4])
True
>>> has_duplicates([1,7,5,6,4])
False
'''
lst = [] # empty list
for i in t:
if i not in lst: #if i not in the list
lst.append(i) #add it to the list
if lst == t: #if that list equal to parameter t
return False
else:
return True
#====================== 10 ======================
def average(nums):
'''
:param nums: [int] list of numbers
:return: [float] an average of numbers in the list
>>> average([1,2,3,4])
2.5
>>> average([2,2,2,2])
2.0
>>> average([1,2,2,5,6,4,4])
3.4285714285714284
>>> average([10,6,2,8])
6.5
>>> average([10,10,10,10,10,10])
10.0
'''
for i in nums:
sum(nums) # summation of all numbers in the list
return sum(nums)/len(nums) #summation divided by amount of number
#=================== 11 =========================
def centered_average(nums):
'''
:param nums:[int] list of numbers
:return:[float] average value that ignore
the largest and the smallest one
>>> centered_average([1,2,3,4])
2.5
>>> centered_average([10,6,2,8])
7.0
>>> centered_average([10,10,10,10,10,10])
10.0
>>> centered_average([2,5,4,6,1])
3.6666666666666665
>>> centered_average([7,8,2,4,6,1])
4.75
'''
a = sorted(nums) # a as a list of parameter nums that is re-ordered
nums = a[1:-1] #nums equal to list a but remove the firt one and the last one
for i in nums:
sum(nums)
return sum(nums)/len(nums)
#===================== 12 =======================
def reverse_pair(t):
'''
:param t: [str] text you want to change
:return: [str] same text with the parameter but order reversely
>>> reverse_pair('I love you')
'you love I'
>>> reverse_pair('I hate you')
'you hate I'
>>> reverse_pair('How are you')
'you are How'
>>> reverse_pair('Good bye')
'bye Good'
>>> reverse_pair('miss you')
'you miss'
'''
t = t.split(' ') # split the text for every space(turns into a list)
t = t[-1::-1] #re-order it from the last one to the first one
t = ' '.join(t) #change it back to normal text
return t
#==================== 13 ========================
def match_ends(t):
'''
:param t:[str] list of words
:return: [int] number of the text that the first and last
character are the same
>>> match_ends(['yong','yay','hi','sas'])
2
>>> match_ends(['roar','ohho','limit','eliminate'])
3
>>> match_ends(['eri','pope','photo','sun'])
0
>>> match_ends(['yong','yay','hi','sas'])
2
>>> match_ends(['krak','ohio','nin','mum'])
4
'''
count = 0
for i in t:
if i[0] == i[-1]: #if the first character is the same as the last character
count += 1 #count equal to 1 and add it up every time the condition is True
return count
#======================= 14 =========================
def remove_adjacent(t):
'''
:param t: [int] list of number
:return: [int] list of number but keep only one number of redundancy
>>> remove_adjacent([2,2,6,5,6])
[2, 6, 5, 6]
>>> remove_adjacent([1,1,5,6])
[1, 5, 6]
>>> remove_adjacent([7,8,9,4])
[7, 8, 9, 4]
>>> remove_adjacent([7,7,7,7,6,5,5,4])
[7, 6, 5, 4]
>>> remove_adjacent([1,3,4,6,4,3,5,2,1,2])
[1, 3, 4, 6, 4, 3, 5, 2, 1, 2]
'''
lst = [] #empty list
for i in range(len(t)):
if t[i] != t[i-1]: #if that number is not the same value as the number before it
lst.append(t[i]) #add it to the list
return lst
#==================== 15 ====================
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True) |
def ll_sum(list_in_list):
'''
This function will gonna sum all the inlist member that is
list in list and return the value in int by using only one parameter
'list_in_list'(list that have list inside)
>>> ll_sum([[1,2],[3],[4,5,6]])
21
>>> ll_sum([[3,4],[7],[8,1,9]])
32
>>> ll_sum([[6,2,5],[3,4],[4,5,6]])
35
>>> ll_sum([[1],[3],[5]])
9
>>> ll_sum([[1,2],[3,4],[5,6]])
21
'''
list_new = []
for i in list_in_list:
a = sum(i)
list_new.append(a)
return(sum(list_new))
def cumulative_sum(list_number):
'''
This function will gonna return the list by each character is
the cumulative sum from their front number by using only one
parameter 'list_number'(list of the number)
>>> cumulative_sum([1,5,6])
[1, 6, 12]
>>> cumulative_sum([2,8,9])
[2, 10, 19]
>>> cumulative_sum([2,4,6,8])
[2, 6, 12, 20]
>>> cumulative_sum([3,6,7,8,9,10])
[3, 9, 16, 24, 33, 43]
>>> cumulative_sum([1,2,3,4,5,6,7,8,9])
[1, 3, 6, 10, 15, 21, 28, 36, 45]
'''
list_new = []
new2 = []
for i in list_number:
list_new.append(i)
a = sum(list_new)
new2.append(a)
return new2
def middle(list_number):
'''
This function will gonna return the list of number except the
first index and last index by using only one parameter
'list_number'(list of number)
>>> middle([2,4,7])
[4]
>>> middle([1,2,5,7,8,9])
[2, 5, 7, 8]
>>> middle([9,8,7,4,5,6,1,2])
[8, 7, 4, 5, 6, 1]
>>> middle([4,5,6,7])
[5, 6]
>>> middle([11,15,46,7,8])
[15, 46, 7]
'''
timing = 0
list_new = []
for i in list_number:
len_num= len(list_number)
if timing>0 and timing<len_num-1:
list_new.append(i)
timing +=1
return list_new
def chop(list_number):
'''
This is just the same as the "middle()" but it only cut but not return
the value. It require to call the function first then print the value
outside the function
Ex. a = chop([1,2,3])
print(a)->[2]
>>> a = [1,2,3,4] ;chop(a) ;print(a)
[2, 3]
>>> a = [1,5,6,7,8] ;chop(a) ;print(a)
[5, 6, 7]
>>> a = [7,8,9,5,6,2] ;chop(a) ;print(a)
[8, 9, 5, 6]
>>> a = [10,11,12,15,6] ;chop(a) ;print(a)
[11, 12, 15]
>>> a = [78,9,5,1,2] ;chop(a) ;print(a)
[9, 5, 1]
'''
list_number.pop(0)
list_number.pop(-1)
def is_sorted(list_number):
'''
This function gonna check the list that this list is sorted or not
if it sorted return true but if not return false by using only one
parameter 'list number'(list of number)
>>> is_sorted([1,2,3,4,5])
True
>>> is_sorted([8,7,5,9])
False
>>> is_sorted([7,4,5,6])
False
>>> is_sorted([1,2,4,5])
True
>>> is_sorted([5,6,8,7,9])
False
'''
sort_list = []
for i in list_number:
sort_list.append(i)
sort_list.sort()
if sort_list == list_number:
return True
else:
return False
def front_x(list_text):
'''
This function gonna sort the text function but it gonna append string
with 'x' is the first character append in the front and all the string
eventhough the 'x'string is all sorted using only one parameter
'list_text'(list of text)
>>> front_x(['apple','income','bubble','xerath'])
['xerath', 'apple', 'bubble', 'income']
>>> front_x(['ball','wave','bang','xayah'])
['xayah', 'ball', 'bang', 'wave']
>>> front_x(['gragas','rekneton','jhin','xborg','xanadu'])
['xanadu', 'xborg', 'gragas', 'jhin', 'rekneton']
>>> front_x(['leona','lulu','malphite','kogmaw','xerox','xylophone'])
['xerox', 'xylophone', 'kogmaw', 'leona', 'lulu', 'malphite']
>>> front_x(['zonya','xpeke','back','door'])
['xpeke', 'back', 'door', 'zonya']
'''
sort_list = []
unsort_list = []
for i in list_text:
if 'x' in i[0].lower() :
sort_list.append(i)
sort_list.sort()
else:
unsort_list.append(i)
unsort_list.sort()
return sort_list+unsort_list
def even_only(list_number):
'''
This function return only even number in the list using only
one parameter 'list_number'(list of number)
>>> even_only([1,2,3,4,5,6,7,8,9,10])
[2, 4, 6, 8, 10]
>>> even_only([22,25,23,24,28,30])
[22, 24, 28, 30]
>>> even_only([31,33,35,36])
[36]
>>> even_only([87,88,89,90])
[88, 90]
>>> even_only([56,40,38])
[56, 40, 38]
'''
odd_list = []
even_list = []
for i in list_number:
if i%2 !=0:
odd_list.append(i)
else:
even_list.append(i)
return even_list
def love(text):
'''
This function gonna change the second last index character to 'love'
by using only one parameter 'text'
>>> love('Indeed a wise choice')
'Indeed a love choice'
>>> love('The unseen blade is the deadliest')
'The unseen blade is love deadliest'
>>> love('Dont you trust me')
'Dont you love me'
>>> love('Fear the assassin with no master')
'Fear the assassin with love master'
>>> love('Nothing can hold me back')
'Nothing can hold love back'
'''
split_text = text.split(' ')
list_new = []
for i in split_text:
list_new.append(i)
list_new.pop(-2)
list_new.insert(-1,'love')
return ' '.join(list_new)
def is_anagram(a,b):
'''
This function gonna check that this is anagram or not if it's anagram
it gonna return True otherwise return False by using two parameter
'a'(The compared text) and 'b'(The anagram)
>>> is_anagram('karma','ARkam')
True
>>> is_anagram('Alistar','Star Ali')
True
>>> is_anagram('Camille','Maille')
False
>>> is_anagram('maoKai','kaioMn')
False
>>> is_anagram('Grave','G R a V e')
True
'''
a.lower()
list_a,list_b = [],[]
for i in a:
list_a.append(i.lower())
for i in b:
if i != ' ':
list_b.append(i.lower())
list_a.sort()
list_b.sort()
if list_a == list_b:
return True
else:
return False
def has_duplicates(list_number):
'''
This function gonna find that this list has the duplicate number
or not if it has return True, else return False by using one parameter
'list_number'(list of number)
>>> has_duplicates([1,2,3,5,5,6])
True
>>> has_duplicates([5,4,3,2,1,1])
True
>>> has_duplicates([9,8,7,65,])
False
>>> has_duplicates([8,9,0])
False
>>> has_duplicates([5,5,5,5])
True
'''
idex = 1
list_number.sort()
count = 0
while idex < len(list_number):
if list_number[idex-1] == list_number[idex]:
count+=1
idex += 1
if count >= 1:
return True
else:
return False
def average(a):
'''
This function calculate the average value in list by using one
parameter 'a'(list_of_number)
>>> average([4,5,6])
5.0
>>> average([10,10,10,10,10,10])
10.0
>>> average([1,2,3,3,2,1])
2.0
>>> average([7,8,2,5,4,3])
4.833333333333333
>>> average([6,8,7,9])
7.5
'''
count = 0
list_new = []
for i in a:
if type(i)==int:
list_new.append(i)
count+=1
return sum(list_new)/count
def centered_average(a):
'''
This function calculate the average only the second to the second last
number(centered average) by using only one parameter 'a'(list of number)
>>> centered_average([10,20,30,40,50])
30.0
>>> centered_average([80,79,56,200])
79.5
>>> centered_average([1,3,5,2,4,6])
3.5
>>> centered_average([56,47,20,23,80])
42.0
>>> centered_average([9,8,7,6,5,4,3,2,1])
5.0
'''
a.sort()
count = 0
list_new=[]
list_newer =[]
for i in a:
list_new.append(i)
for num in list_new:
if num != list_new[0] and num != list_new[-1]:
list_newer.append(num)
count+=1
return sum(list_newer)/count
def reverse_pair(text):
'''
This function gonna print out the reverse sentence
by using only one parameter 'text'(sentence)
>>> reverse_pair('Time to troll')
'troll to Time'
>>> reverse_pair('Embrace the darkness')
'darkness the Embrace'
>>> reverse_pair('Only you can hear me summoner')
'summoner me hear can you Only'
>>> reverse_pair('Dead man walkin')
'walkin man Dead'
>>> reverse_pair('If you buying Im in')
'in Im buying you If'
'''
split_text = text.split(' ')
list_new =[]
for i in split_text:
list_new.append(i)
list_new.reverse()
return ' '.join(list_new)
def match_ends(text):
'''
This function count the text which character more than two
and the string has the same character at the front and the last
by using only one parameter 'text'(list of text)
>>> match_ends(['loom','kok','Ganging'])
2
>>> match_ends(['stone','yey','wow','gong'])
3
>>> match_ends(['Rock','Solid','pop'])
1
>>> match_ends(['Embrace','lol'])
2
'''
count = 0
for i in text:
if len(i) > 2:
if i[0].lower() == i[-1].lower():
count +=1
return count
def remove_adjacent(t):
'''
This function remove the adjacent number in list by using only
one parameter 't'(list of number)
>>> remove_adjacent([1,2,2,3,3])
[1, 2, 3]
>>> remove_adjacent([2,2,2,3,8])
[2, 3, 8]
>>> remove_adjacent([9,8,7,6,6])
[9, 8, 7, 6]
>>> remove_adjacent([1,2,3,4,4])
[1, 2, 3, 4]
>>> remove_adjacent([7,8,8,8])
[7, 8]
'''
list_new = []
index = 0
count = 0
list_newer = []
for i in t:
list_new.append(i)
count +=1
if count >=1:
if list_new[index] != list_new[index-1]:
list_newer.append(i)
index +=1
if list_new[0] != list_newer[0]:
list_newer.insert(0,list_new[0])
return list_newer
|
import random
def computer_check(n):
"""
>>> computer_check(0)
Computer chooses: rock
>>> computer_check(1)
Computer chooses: paper
>>> computer_check(2)
Computer chooses: scissors
>>> computer_check(3)
Computer chooses: spock
>>> computer_check(4)
Computer chooses: lizard
"""
List = ["rock", "paper", "scissors", "spock", "lizard"]
for i in range(5):
if n == i:
print(f"Computer chooses: {List[i]}")
def player_check(n):
"""
>>> player_check("rock")
0
>>> player_check("paper")
1
>>> player_check("scissors")
2
>>> player_check("spock")
3
>>> player_check("lizard")
4
"""
List = ["rock", "paper", "scissors", "spock", "lizard"]
for i in range(5):
if n == List[i]:
return i
print("System Error!")
SystemExit
def check_valid_input(v):
if v == "rock":
return True
elif v == "paper":
return True
elif v == "scissors":
return True
elif v == "spock":
return True
elif v == "lizard":
return True
else:
return False
def convert_to_num(v):
if v == "rock":
return 0
elif v == "paper":
return 1
elif v == "scissors":
return 2
elif v == "spock":
return 3
elif v == "lizard":
return 4
else:
print("Error: should not reach this if input is a valid one")
def convert_to_str(n):
if n == 0:
return "rock"
elif n == 1:
return "paper"
elif n == 2:
return "scissors"
elif n == 3:
return "spock"
elif n == 4:
return "lizard"
else:
print("Error: should not reach this if input is a valid one")
def winner_check(player_choice_number, computer_choice_number):
"""
>>> winner_check(2,2)
Both ties!
>>> winner_check(3,1)
Computer wins!
>>> winner_check(4,1)
Player wins!
>>> winner_check(3,3)
Both ties!
"""
if player_choice_number == computer_choice_number:
print("Both ties!")
elif ((player_choice_number + 1) %5 ) == computer_choice_number or ((player_choice_number +3) %5 ) == computer_choice_number:
print("Computer wins!")
else:
print("Player wins!")
def main():
valid = False
while valid == False:
player_choice = input("Enter your choice: ")
valid = check_valid_input(player_choice)
if valid == False:
print("Invalid choice. Enter again.")
computer_choice_number = random.randint(0,4)
computer_choice = convert_to_str(computer_choice_number)
player_choice_number = convert_to_num(player_choice)
print("Player chooses ", player_choice)
print("Computer chooses ", computer_choice)
winner_check(player_choice_number, computer_choice_number)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
def ll_sum(t):
"""
this function is used to calculate the sum of number in each list combined.
>>> t = [[1],[1,2],[1,2,3]]
>>> ll_sum(t)
10
>>> t = [[3],[1,2],[4,5,6]]
>>> ll_sum(t)
21
>>> t = [[0],[1,2,4],[10,2,3]]
>>> ll_sum(t)
22
>>> t = [[1],[1,2],[4,4,0]]
>>> ll_sum(t)
12
>>> t = [[7],[7,7],[7,7,8]]
>>> ll_sum(t)
43
"""
result = 0
for num in t:
result += sum(num)
return result
def cumulative_sum(t):
"""
this funtion display new list where the ith element is the sum of the first i + 1 elements from the original list.
>>> t = [1,2,3]
>>> cumulative_sum(t)
[1, 3, 6]
>>> t = [1,3,5]
>>> cumulative_sum(t)
[1, 4, 9]
>>> t = [1,8,9,1]
>>> cumulative_sum(t)
[1, 9, 18, 19]
>>> t = [1,1,2]
>>> cumulative_sum(t)
[1, 2, 4]
>>> t = [1,7,4]
>>> cumulative_sum(t)
[1, 8, 12]
"""
a = []
result = 0
for num in t:
result = result + num
a.append(result)
return a
def middle(t):
"""
funtion that return newlist that contain all but not the first and the last.
>>> t =[1,2,3,4]
>>> middle(t)
[2, 3]
>>> t =[1,4,1,2]
>>> middle(t)
[4, 1]
>>> t =[6,2,3,4,9]
>>> middle(t)
[2, 3, 4]
>>> t =[1,6,9,4]
>>> middle(t)
[6, 9]
>>> t =[7,1,1,7,5]
>>> middle(t)
[1, 1, 7]
"""
a = []
for num in t[1:len(t)-1]:
a.append(num)
return a
def chop(t):
"""
funtion that return all but chop the first and the last.
>>> t =[1,2,3,4]
>>> chop(t)
[2, 3]
>>> t =[1,4,1,2]
>>> chop(t)
[4, 1]
>>> t =[6,2,3,4,9]
>>> chop(t)
[2, 3, 4]
>>> t =[1,6,9,4]
>>> chop(t)
[6, 9]
>>> t =[7,1,1,7,5]
>>> chop(t)
[1, 1, 7]
"""
return t[1:len(t)-1]
def is_sorted(t):
"""
function that returns True if the list is sorted in ascending order and False otherwise.
>>> is_sorted([1,2,2])
True
>>> is_sorted(['b','a'])
False
>>> is_sorted([3,2,1])
False
>>> is_sorted([1,1,2])
True
>>> is_sorted(['a','b','c'])
True
"""
a = t.copy()
t.sort()
if t == a:
return True
else:
return False
def front_x(l):
"""
function that returns list with the sorted string, but all the strings that begin with 'x' come first.
>>> front_x(['mix','xyz','apple'])
['xyz', 'apple', 'mix']
>>> front_x(['xray','xtent','john'])
['xray', 'xtent', 'john']
>>> front_x(['xxx','pipe','loli','kiki'])
['xxx', 'kiki', 'loli', 'pipe']
>>> front_x(['spatan','fucking','noob','xd'])
['xd', 'fucking', 'noob', 'spatan']
>>> front_x(['xceed','is','super','good'])
['xceed', 'good', 'is', 'super']
"""
l.sort()
a =[]
b= []
for i in (l):
if 'x' in (i[0]):
a.append(i)
else:
b.append(i)
# print(a + b)
return a + b
def even_only(l):
"""
function the return only even number
>>> even_only([3,1,4,1,5,9,2,6,5])
[4, 2, 6]
>>> even_only([1,3,5,7,8,10,11,12])
[8, 10, 12]
>>> even_only([2,4,6,8,10,21,23,29])
[2, 4, 6, 8, 10]
>>> even_only([1,2,3,4,5])
[2, 4]
>>> even_only([10,20,30,40,15,17,19])
[10, 20, 30, 40]
"""
a = []
for i in l:
if i%2 == 0:
a.append(i)
# print(a)
return a
def love(text):
"""
a function that will change the second last word to “love”
>>> love('I like python')
I love python
>>> love('I really like python')
I really love python
>>> love('like father like son')
like father love son
>>> love("I'm your father")
I'm love father
>>> love('I like you')
I love you
"""
a = text.split(' ')
a[-2] = 'love'
# print(' '.join(a))
return ' '.join(a)
def is_anagram(str1,str2):
"""
this function check if the two string is anagram or not if not return False else return True
>>> is_anagram('arrange','Rear Nag')
True
>>> is_anagram('ant','abe')
False
>>> is_anagram('bird','dirb')
True
>>> is_anagram('evil','live')
True
>>> is_anagram('hulk','herby')
False
"""
a = []
b = []
for char in str1:
a.append(char.lower())
for char in str2:
b.append(char.lower())
if (char in a) == (char in b):
return True
else:
return False
def has_duplicates(l):
"""
a function that takes a list and returns True if there is any element that
appears more than once.
>>> has_duplicates([1,2,3,4,5])
False
>>> has_duplicates([1,2,3,4,5,2])
True
>>> has_duplicates([1,3,5,7,5])
True
>>> has_duplicates([1,2,3,4,5,6])
False
>>> has_duplicates([1,1,0,2,0,0])
True
"""
a =[]
for i in l:
if i not in a:
a.append(i)
if len(a) == len(l):
return False
else:
return True
has_duplicates([1,2,3,4,5])
has_duplicates([1,2,3,4,5,2])
def average(l):
"""
a function that returns the mean average of a list of numbers.
>>> average([1,1,5,5,10,8,7])
5.285714285714286
>>> average([1,1,5,5,10,5,5])
4.571428571428571
>>> average([1,1,0,2,0,0,3])
1.0
>>> average([1,3,5,7,8,9])
5.5
>>> average([4,1,3,5,10,8,27])
8.285714285714286
"""
return sum(l)/len(l)
def centered_average(l):
"""
a function that calculate average of list that exclude max and min
>>> centered_average([1,1,5,5,10,8,7])
5.2
>>> centered_average([1,3,7,9])
5.0
>>> centered_average([2,4,6,8])
5.0
>>> centered_average([2,4,6,8,9,10,11])
7.4
>>> centered_average([1,1,0,2,0,0])
0.5
"""
l.sort()
return sum(l[1:len(l)-1])/(len(l)-2)
def reverse_pair(text):
"""
a function that returns the reverse pair of the input sentence.
>>> reverse_pair('May the fourth be with You')
'You with be fourth the May'
>>> reverse_pair('me love you do')
'do you love me'
>>> reverse_pair('kaopun love jitti')
'jitti love kaopun'
>>> reverse_pair('borrabeam eat the world')
'world the eat borrabeam'
>>> reverse_pair('king kill bill chill boom')
'boom chill bill kill king'
"""
a = text.split(' ')
return (' '.join(a[::-1]))
def match_ends(l):
"""
function that count number of strings when the string length is 2 or more and the first and last
chars of the string are the same.
>>> match_ends(['gingering','wow','hello'])
2
>>> match_ends(['greek','nan','love'])
1
>>> match_ends(['bob','nan','sixties'])
3
>>> match_ends(['greek','nany','love'])
0
>>> match_ends(['greekg','nany','level','go'])
2
"""
count = 0
for char in l:
if len(l) >= 2:
if char[0] == char[-1]:
count += 1
else:
count += 0
return count
def remove_adjacent(l):
"""
a function that removes adjacent and return list without adjacent.
>>> remove_adjacent([1,2,2,3])
[1, 2, 3]
>>> remove_adjacent([1,3,7,9])
[1, 3, 7, 9]
>>> remove_adjacent([1,1,0,2])
[1, 0, 2]
>>> remove_adjacent([1,2,2,3])
[1, 2, 3]
>>> remove_adjacent([2,4,6,8,8])
[2, 4, 6, 8]
>>> remove_adjacent([0,1,2,4,2,0,2,4])
[0, 1, 2, 4]
"""
a =[]
for i in l:
if i not in a:
a.append(i)
return(a)
|
import random
choice = ['scissors', 'paper', 'rock', 'lizard', 'spock']
scissors_win = [1, 3]
paper_win = [2, 4]
rock_win = [3, 0]
lizard_win = [4, 1]
spock_win = [0, 2]
def check_win(x, y):
"""Check if x win y.
>>> check_win(0,0)
False
>>> check_win(0,1)
True
>>> check_win(0,2)
False
>>> check_win(0,3)
True
>>> check_win(0,4)
False
>>> check_win(1,0)
False
>>> check_win(1,1)
False
>>> check_win(1,2)
True
>>> check_win(1,3)
False
>>> check_win(1,4)
True
>>> check_win(2,0)
True
>>> check_win(2,1)
False
>>> check_win(2,2)
False
>>> check_win(2,3)
True
>>> check_win(2,4)
False
>>> check_win(3,0)
False
>>> check_win(3,1)
True
>>> check_win(3,2)
False
>>> check_win(3,3)
False
>>> check_win(3,4)
True
>>> check_win(4,0)
True
>>> check_win(4,1)
False
>>> check_win(4,2)
True
>>> check_win(4,3)
False
>>> check_win(4,4)
False
>>> check_win(5,0)
False
>>> check_win(5,1)
False
"""
if x == 0 and y in scissors_win:
return True
elif x == 1 and y in paper_win:
return True
elif x == 2 and y in rock_win:
return True
elif x == 3 and y in lizard_win:
return True
elif x == 4 and y in spock_win:
return True
else:
return False
def str_to_num(x):
"""change string to number sort according to list
>>> str_to_num('rock')
2
>>> str_to_num('paper')
1
>>> str_to_num('scissors')
0
>>> str_to_num('lizard')
3
>>> str_to_num('spock')
4
>>> str_to_num('Rock')
Error: should not reach this if input is a valid one
>>> str_to_num('ROCK')
Error: should not reach this if input is a valid one
"""
if x == 'scissors':
return 0
if x == 'paper':
return 1
if x == 'rock':
return 2
if x == 'lizard':
return 3
if x == 'spock':
return 4
else:
print('Error: should not reach this if input is a valid one')
def check_valid_input(x):
"""check if player input is valid
>>> check_valid_input('x')
False
>>> check_valid_input('rock')
True
>>> check_valid_input('scissors')
True
>>> check_valid_input('paper')
True
>>> check_valid_input(0)
False
>>> check_valid_input('ROCK')
False
>>> check_valid_input('LizarD')
False
>>> check_valid_input('lizard')
True
>>> check_valid_input('spock')
True
"""
if x in choice:
return True
else:
return False
def game_decision(x,y):
"""check and display winner
>>> game_decision(0,0)
Both tie!
>>> game_decision(0,1)
Player win!
>>> game_decision(0,2)
Computer win!
>>> game_decision(0,3)
Player win!
>>> game_decision(0,4)
Computer win!
>>> game_decision(1,0)
Computer win!
>>> game_decision(1,1)
Both tie!
>>> game_decision(1,2)
Player win!
>>> game_decision(1,3)
Computer win!
>>> game_decision(1,4)
Player win!
>>> game_decision(2,0)
Player win!
>>> game_decision(2,1)
Computer win!
>>> game_decision(2,2)
Both tie!
>>> game_decision(2,3)
Player win!
>>> game_decision(2,4)
Computer win!
>>> game_decision(3,0)
Computer win!
>>> game_decision(3,1)
Player win!
>>> game_decision(3,2)
Computer win!
>>> game_decision(3,3)
Both tie!
>>> game_decision(3,4)
Player win!
>>> game_decision(4,0)
Player win!
>>> game_decision(4,1)
Computer win!
>>> game_decision(4,2)
Player win!
>>> game_decision(4,3)
Computer win!
>>> game_decision(4,4)
Both tie!
>>> game_decision(5,0)
Error: should not reach this if input is a valid one
"""
if x == y:
print("Both tie!")
elif check_win(x, y):
print("Player win!")
elif check_win(y, x):
print("Computer win!")
else:
print("Error: should not reach this if input is a valid one")
########################################################################################################################
def main() -> None:
# get an input from a player and validate
valid = False
while valid != True:
player = input("Player chooses ").lower()
valid = check_valid_input(player)
if valid == False:
print("Invalid choice. Enter again.")
# random a response from a computer and print out computer choices
com = choice[random.randint(0, 4)]
print(f'Computer chooses {com}')
# convert string to number
player = str_to_num(player)
com = str_to_num(com)
# apply the rules of game, check and display winner
game_decision(player, com)
if __name__ == '__main__':
main() |
# 1
def ll_sum(t):
''' make the sum of all number in list
>>> t = [[1,2],[3],[4,5,6]]
>>> ll_sum(t)
21
>>> a = [[1,2],3,[4]]
>>> ll_sum(a)
10
>>> b = [[5,6],[5,7]]
>>> ll_sum(b)
23
>>> c = [1,2,3]
>>> ll_sum(c)
6
>>> d = []
>>> ll_sum(d)
0
'''
b = []
for i in t:
if i in [1,2,3,4,5,6,7,8,9,0]:
b.append(i)
else:
a = sum(i)
b.append(a)
return sum(b)
# 2
def cumulative_sum(t):
''' calculate the seqeunce of the number in list and show every value
>>> t = [1, 2, 3]
>>> cumulative_sum(t)
[1, 3, 6]
>>> a = [4, 5, 6]
>>> cumulative_sum(a)
[4, 9, 15]
>>> b = [1, -3, 10]
>>> cumulative_sum(b)
[1, -2, 8]
>>> c = [0, 0, 1]
>>> cumulative_sum(c)
[0, 0, 1]
>>> d = [1, 1, 1, 1, 1]
>>> cumulative_sum(d)
[1, 2, 3, 4, 5]
'''
new_str = []
series = 0
for i in t:
series += i
new_str.append(series)
return new_str
# 3
def middle(t):
''' cut the first and the last index of list, then return new string
>>> t = [1,2,3,4]
>>> middle(t)
[2, 3]
>>> a = ['cat','dog','fish','pig']
>>> middle(a)
['dog', 'fish']
>>> b = [2, 'cat', 4, 'dog']
>>> middle(b)
['cat', 4]
>>> c = [5,6,7,8]
>>> middle(c)
[6, 7]
>>> d = [1, 2, 3]
>>> middle(d)
[2]
'''
t.remove(t[0])
t.remove(t[-1])
return t
# 4
def chop(t):
''' cut the first and the last index of list, then return None
>>> t = [1,2,3,4]
>>> chop(t)
>>> t
[2, 3]
>>> a = ['cat','dog','fish','pig']
>>> chop(a)
>>> a
['dog', 'fish']
>>> b = [2, 'cat', 4, 'dog']
>>> chop(b)
>>> b
['cat', 4]
>>> c = [5,6,7,8]
>>> chop(c)
>>> c
[6, 7]
>>> d = [0, 1]
>>> chop(d)
>>> d
[]
'''
t.remove(t[0])
t.remove(t[-1])
return None
# 5
def is_sorted(t):
''' return True if list are sorted, otherwise return False
>>> is_sorted([1,2,2])
True
>>> is_sorted(['b','a'])
False
>>> is_sorted(['a','c','b'])
False
>>> is_sorted([1, 2, 3, 4])
True
>>> is_sorted([6, 5])
False
'''
for i in range(len(t)):
if t[i-1] <= t[i]:
value = True
else:
value = False
return value
# 6
def front_x(t):
''' sort list by start with the first 'x' word and following the other
>>> l = ['xyz','apple','xdfs','bdfd']
>>> front_x(l)
['xdfs', 'xyz', 'apple', 'bdfd']
>>> a = []
>>> front_x(a)
[]
>>> b = ['apple','xasd']
>>> front_x(b)
['xasd', 'apple']
>>> c = ['xb','xa']
>>> front_x(c)
['xa', 'xb']
>>> d = ['a','c','b']
>>> front_x(d)
['a', 'b', 'c']
'''
x_lst = []
lst = []
for i in t:
if i[0] == 'x':
x_lst.append(i)
else:
lst.append(i)
x_lst.sort()
lst.sort()
return x_lst+lst
# 7
def even_only(lst):
''' return only even number
>>> even_only([1, 2, 3, 4])
[2, 4]
>>> even_only([1, 3, 5])
[]
>>> even_only([2, 1, 3, 6])
[2, 6]
>>> even_only([7, 9, 11])
[]
>>> even_only([])
[]
'''
even = []
for i in lst:
if i%2 == 0:
even.append(i)
else:
pass
return even
# 8
def love(txt):
''' change the last second word to love
>>> love('I like python')
'I love python'
>>> love('good morning teacher')
'good love teacher'
>>> love('I hate programing')
'I love programing'
>>> love('I hate elab')
'I love elab'
>>> love('I hate doctest')
'I love doctest'
'''
new = txt.split(' ')
new[-2] = 'love'
return ' '.join(new)
# 9
def is_anagram(txt1,txt2):
''' if both of parameter are anagram for each other return True otherwise return False
>>> is_anagram('hello','OLLEH')
True
>>> is_anagram(' i ','i')
True
>>> is_anagram(' ','')
True
>>> is_anagram('good','bad')
False
>>> is_anagram(',','')
False
'''
tx1 = txt1.lower()
tx2 = txt2.lower()
new1 = []
new2 = []
for i in tx1:
if i == ' ':
pass
else:
new1.append(i)
for i in tx2:
if i == ' ':
pass
else:
new2.append(i)
new1.sort()
new2.sort()
if new1 == new2:
return True
else:
return False
# 10
def has_duplicates(lst):
''' return if there are the same value in lst, otherwise return false
>>> has_duplicates([1, 2, 3, 4, 5])
False
>>> has_duplicates([1, 2, 1])
True
>>> has_duplicates([])
False
>>> has_duplicates([1])
False
>>> has_duplicates([5, 6, 7])
False
'''
n = []
for i in lst:
if i in n:
return True
else:
n.append(i)
return False
# 11
def average(lst):
''' return average of number in list
>>> average([1, 2, 3])
2.0
>>> average([1, 1, 2, 3, 4])
2.2
>>> average([0])
0.0
>>> average([1, 1, 1])
1.0
>>> average([1, 2])
1.5
'''
sums = sum(lst)
n = []
count = 0
for i in lst:
n.append(i)
count += 1
return float(sums/count)
# 12
def centered_average(lst):
''' return average of number in list
>>> centered_average([1, 1, 2, 3, 4])
2.0
>>> centered_average([1, 1, 5, 5, 10, 8, 7])
5.2
>>> centered_average([1, 2])
0.0
>>> centered_average([1, 5, 3])
3.0
>>> centered_average([3, 4])
0.0
'''
n = []
count = 0
for i in lst:
n.append(i)
count += 1
n.sort()
n.remove(n[0])
n.remove(n[-1])
if count <= 2:
n = [0]
else:
count -= 2
return float(sum(n)/count)
# 13
def reverse_pair(txt):
''' reverse word form the last to the first
>>> reverse_pair('I hate flower')
'flower hate I'
>>> reverse_pair('weathering with you')
'you with weathering'
>>> reverse_pair(' ')
' '
>>> reverse_pair('I hate elab')
'elab hate I'
>>> reverse_pair('good morning')
'morning good'
'''
new = txt.split(' ')
new.reverse()
lst = ' '.join(new)
return lst
# 14
def match_ends(lst):
''' if the first and the last are same
>>> math_ends(['google', 'facebook', 'twitter'])
0
>>> math_ends(['goog', 'wow', 'face'])
2
>>> math_ends(['txt', 'first'])
1
>>> math_ends(['lol', 'you'])
1
>>> math_ends(['hate', 'elab'])
0
'''
count = 0
for i in lst:
if len(i) >= 2:
if i[0].lower() == i[-1].lower():
count += 1
else:
pass
else:
pass
return count
# 15
def remove_adjacent(lst):
''' make the list have member like the set
>>> remove_adjacent([1, 2, 2, 3])
[1, 2, 3]
>>> remove_adjacent([1, 1, 2, 2, 3])
[1, 2, 3]
>>> remove_adjacent([])
[]
>>> remove_adjacent([1, 1, 1, 1, 1])
[1]
>>> remove_adjacent([0])
[0]
'''
n = []
for i in lst:
if i in n:
pass
else:
n.append(i)
return n |
import random
# n = number of integers you want to generate, x ** y denotes x^y
n =10**5
u = 10**1
# minimum and maximum possible value of random number generated
minn = 1
maxx = 10 ** 7
# first line containing the value of n
# print "n,q"
print(n)
l=n
choices = list(range(maxx))
random.shuffle(choices)
# print(choices.pop())
while l:
print(choices.pop())
l=l-1
print "max"
# print "q value"
for i in range(u):
print "u "+str(i)+" "+str(random.randint(0, n-1))+" "+ str(random.randint(minn, maxx))
# for i in range(t):
# print "t "+str(i)
# for i in range(q):
# x=(random.randint(0,n-2))
# y=(random.randint(x+1,n-1))
# print "q "+str(i)+" "+str(x)+" "+str(y)
print "e" |
"""
Temporary memory database
get_all() - returns a list of unanswered questions. Return list()
get(id) - by the id of the user who asked the question, the question itself is returned. Return String
delete(id) - delete the questions, when answered
add(id, quest) - adding quest in the main list.
"""
class BD:
def __init__(self):
self.quests = {'123/': '====='}
def get_all(self):
a = []
for i in self.quests.keys():
if i == '123/':
a.append('/help')
else:
tr = self.quests.get(i).split(' : ')[1]
a.append(f'<#>{i}: {tr if len(tr[:15]) < 15 else tr[:15] + "..."}')
return a
def get(self, id):
return self.quests.get(id)
def delete(self, id):
try:
self.quests.pop(id)
except KeyError:
pass
def add(self, id, que):
self.quests[id] = que
|
# first
a=-5
if a>0:
if a%2==0:
print(str(a) + " is positive even number")
else:
print(str(a) + " is negative number")
# Output is : -5 is negative number because the outer if statement is evaluated
# and the condition is false so the else statement gets executed.
# second
a=5
if a>0:
if a%2==0 :
print(str(a) + " is positive even number")
else:
print(str(a) + " is odd number")
# Output is : 5 is odd number because the outer if statement is evaluated
# first and the condition is true so the inner if statement gets executed
# abd the condition is false so inner else is evaluated finally |
# Check the output of following code and justify your answer:
x = 50
def func(x):
print('x is',x)
x = 2
print('Changed local x to',x)
func(x)
print('x is now',x)
# Justification : the function did not changed the value of x because
# their are 2 scopes for variable x:
# i. in main
# ii. in function
# Hence the changed value in the function does not
# affect the main variable x scope. |
def maximum(x,y,z):
if x > y and x > z:
return x
if y > x and y > z:
return y
if z > x and z > y:
return z
n1 = int(input("Enter num 1 :"))
n2 = int(input("Enter num 2 :"))
n3 = int(input("Enter num 3 :"))
print(maximum(n1,n2,n3)) |
# Write a program to combine following dictionaries by averaging values for
# common keys.
# D1 = {‘ram’:60, ‘shyam’:70, ‘radha’:70}
# D2 = {‘ram’:70, ‘shyam’:80, ‘gopi’:60}
# output : {‘ram’:65, ‘shyam’:75, ‘radha’:70, ‘gopi’:60}
D1 = {'ram':60, 'shyam':70, 'radha':70}
D2 = {'ram':70, 'shyam':80, 'gopi':60}
output = dict()
for key in D1:
if key in D2:
output[key] = int((D1[key]+D2[key])/2)
else:
output[key] = D1[key]
for key in D2:
if key not in D1 and key not in output:
output[key] = D2[key]
print(output) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 12:21:55 2019
@author: damienrigden
This program crates a graphical window of a clock drawn using sofdot numbers.
It takes as an argument the desired clock face size
"""
from graphics import GraphWin, Point, Circle, Rectangle
from time import strftime
from sofdotClass import Sofdot as Sd
from sys import argv
try:
face = int(argv[1])
if face < 50:
face = 50
except:
print('Argument should be an integer equal to desired clock face size.')
print('Default face size 400 used.')
face = 400
r = face * .075 /2
bgc = '#f8f1e2'
tgc = '#4b3106'
win = GraphWin('Sof-Dot Clock', face, face)
win.setBackground(bgc)
seconds = '%S'
minutes = '%M'
hours = '%H'
def main():
hourflag = strftime(hours)
minuteflag = strftime(minutes)
secondflag = strftime(seconds)
ctrltograph(timetoctrl(seconds), secgeom)
ctrltograph(timetoctrl(minutes), mingeom)
ctrltograph(timetoctrl(hours), hourgeom)
while True:
if strftime(seconds) != secondflag:
ctrltograph(timetoctrl(seconds), secgeom)
secondflag = strftime(seconds)
if strftime(minutes) != minuteflag:
ctrltograph(timetoctrl(minutes), mingeom)
minuteflag = strftime(minutes)
if strftime(hours) != hourflag:
ctrltograph(timetoctrl(hours), hourgeom)
hourflag = strftime(hours)
if win.checkKey() == 'q':
win.close()
def timetoctrl(time):
ctrl = Sd(strftime(time))
return ctrl.getcontrol()
def ctrltograph(ctrl, elements):
for i in range(1,3):
for j in range(7):
elements[0][i][j].undraw()
if ctrl[0][i][j]:
elements[0][i][j].draw(win)
"""Hours Geometry"""
hc8 = Point(face * .1375,face * .1375)
hc10 = Point(face * .2875,face * .1375)
hc12 = Point(face * .4375,face * .1375)
hc14 = Point(face * .5875,face * .1375)
hc1 = Point(face * .1375,face * .31875)
hc3 = Point(face * .2875,face * .31875)
hc5 = Point(face * .4375,face * .31875)
hc7 = Point(face * .5875,face * .31875)
hr5 = Point(face * .1375, face * .175)
hr6 = Point(face * .2875, face * .1)
hr7 = Point(face * .4375, face * .175)
hr8 = Point(face * .5875, face * .1)
hr1 = Point(face * .1375, face * .35625)
hr2 = Point(face * .2875, face * .28125)
hr3 = Point(face * .4375, face * .35625)
hr4 = Point(face * .5875, face * .28125)
H1 = Circle(hc1, r)
H3 = Circle(hc3, r)
H5 = Circle(hc5, r)
H7 = Circle(hc7, r)
H8 = Circle(hc8, r)
H10 = Circle(hc10, r)
H12 = Circle(hc12, r)
H14 = Circle(hc14, r)
H2 = Rectangle(hr1, hr2)
H4 = Rectangle(hr2, hr3)
H6 = Rectangle(hr3, hr4)
H9 = Rectangle(hr5, hr6)
H11 = Rectangle(hr6, hr7)
H13 = Rectangle(hr7, hr8)
#List of graphical elements structured to match the Sofdot control, hours
hourgeom = [([None], [H8, H9, H10, H11, H12, H13, H14], [H1, H2, H3, H4, H5, H6, H7])]
#Set properties for hour elements
#triple nested loops is messy but N is small, getting around sofdot control structure
for u in range(1,3):
for v in range(7):
for geomh in hourgeom:
geomh[u][v].setFill(tgc)
geomh[u][v].setOutline(tgc)
geomh[u][v].draw(win)
"""Minutes Geometry"""
mc8 = Point(face * .1375,face * .68125)
mc10 = Point(face * .2875,face * .68125)
mc12 = Point(face * .4375,face * .68125)
mc14 = Point(face * .5875,face * .68125)
mc1 = Point(face * .1375,face * .8625)
mc3 = Point(face * .2875,face * .8625)
mc5 = Point(face * .4375,face * .8625)
mc7 = Point(face * .5875,face * .8625)
mr5 = Point(face * .1375, face * .71875)
mr6 = Point(face * .2875, face * .64375)
mr7 = Point(face * .4375, face * .71875)
mr8 = Point(face * .5875, face * .64375)
mr1 = Point(face * .1375, face * .9)
mr2 = Point(face * .2875, face * .825)
mr3 = Point(face * .4375, face * .9)
mr4 = Point(face * .5875, face * .825)
M1 = Circle(mc1, r)
M3 = Circle(mc3, r)
M5 = Circle(mc5, r)
M7 = Circle(mc7, r)
M8 = Circle(mc8, r)
M10 = Circle(mc10, r)
M12 = Circle(mc12, r)
M14 = Circle(mc14, r)
M2 = Rectangle(mr1, mr2)
M4 = Rectangle(mr2, mr3)
M6 = Rectangle(mr3, mr4)
M9 = Rectangle(mr5, mr6)
M11 = Rectangle(mr6, mr7)
M13 = Rectangle(mr7, mr8)
#List of graphical elements structured to match the Sofdot control, minutes
mingeom = [([None], [M8, M9, M10, M11, M12, M13, M14], [M1, M2, M3, M4, M5, M6, M7])]
#Set properties for minute elements
#triple nested loops is messy but N is small, getting around sofdot control structure
for w in range(1,3):
for x in range(7):
for geomm in mingeom:
geomm[w][x].setFill(tgc)
geomm[w][x].setOutline(tgc)
geomm[w][x].draw(win)
"""Seconds Geometry"""
sc8 = Point(face * .7375,face * .8625)
sc10 = Point(face * .7375,face * .620833)
sc12 = Point(face * .7375,face * .379167)
sc14 = Point(face * .7375,face * .1375)
sc1 = Point(face * .8625,face * .8625)
sc3 = Point(face * .8625,face * .620833)
sc5 = Point(face * .8625,face * .379167)
sc7 = Point(face * .8625,face * .1375)
sr5 = Point(face * .775, face * .8625)
sr6 = Point(face * .7, face * .620833)
sr7 = Point(face * .775, face * .379167)
sr8 = Point(face * .7, face * .1375)
sr1 = Point(face * .9, face * .8625)
sr2 = Point(face * .825, face * .620833)
sr3 = Point(face * .9, face * .379167)
sr4 = Point(face * .825, face * .1375)
S1 = Circle(sc1, r)
S3 = Circle(sc3, r)
S5 = Circle(sc5, r)
S7 = Circle(sc7, r)
S8 = Circle(sc8, r)
S10 = Circle(sc10, r)
S12 = Circle(sc12, r)
S14 = Circle(sc14, r)
S2 = Rectangle(sr1, sr2)
S4 = Rectangle(sr2, sr3)
S6 = Rectangle(sr3, sr4)
S9 = Rectangle(sr5, sr6)
S11 = Rectangle(sr6, sr7)
S13 = Rectangle(sr7, sr8)
#List of graphical elements structured to match the Sofdot control, seconds
secgeom = [([None], [S8, S9, S10, S11, S12, S13, S14], [S1, S2, S3, S4, S5, S6, S7])]
#Set properties for second elements
#triple nested loops is messy but N is small, getting around sofdot control structure
for y in range(1,3):
for z in range(7):
for geoms in secgeom:
geoms[y][z].setFill(tgc)
geoms[y][z].setOutline(tgc)
geoms[y][z].draw(win)
"""Bar Geometry"""
bc1 = Point(face * .1375,face * .5)
bc3 = Point(face * .5875,face * .5)
br1 = Point(face * .1375,face * .5375)
br2 = Point(face * .5875,face * .4625)
B1 = Circle(bc1, r)
B3 = Circle(bc3, r)
B2 = Rectangle(br1, br2)
bargeom = [B1, B2, B3]
for geomb in bargeom:
geomb.setFill(tgc)
geomb.setOutline(tgc)
geomb.draw(win)
if __name__ == '__main__':
main() |
l = eval(input("Enter the length: "))
w = eval(input("Enter the width: "))
h = eval(input("Enter the heigth: "))
result = l*w*h
print(result) |
# Autor: Ithan Alexis Pérez Sanchez, A01377717
# Descripcion: Calcular la distancia de 2 tiempos de determinados y el tiempo necesario para llegar a un kilometraje determinado
# Escribe tu programa después de esta línea.
Velocidad = int(input("Los Km/h de carro son: "))
Distancia1 = 7 * Velocidad
Distancia2 = 4.5 * Velocidad
Tiempo = 791 / Velocidad
print("La Distancia en Km/h de 7 hrs es: ", Distancia1, "Km/h")
print("La Distancia en Km/h de 4.5 hrs es: ", Distancia2, "Km/h")
print("El Tiempo en Hrs que hace con 791 Km/h es: ", Tiempo, "Hrs")
|
class MyIterator(object):
def __init__(self, step):
self.step = step
def next(self):
if self.step == 0:
raise StopIteration
self.step -= 1
return self.step
def __iter__(self):
return self
def test_simple_iterator():
simple_iter = MyIterator(4)
for i in range(0,4):
print simple_iter.next()
test_simple_iterator()
|
class TeamMembers:
team_members = {}
def add_team_member(self, team_member):
self.team_members[team_member.id] = team_member
def get_team_member_names(self):
names = []
for person in self.team_members.values():
names.append(person.name)
return names
def get_ids(self):
return self.team_members.keys()
def get_team_member(self, team_member_id):
if team_member_id in self.team_members.keys():
return self.team_members[team_member_id]
raise ValueError("Team Member Does Not Exist")
def clear_team_members(self):
self.team_members = {}
|
def larger_sum(lst1, lst2):
sum1 = 0
sum2 =0
for item in lst1:
sum1+=item
for item in lst2:
sum2+=item
if sum1>sum2:
return lst1
elif sum1==sum2:
return lst1
else:
return lst2
print(larger_sum([1, 9, 5][2, 3, 7])) |
# На входной двери подъезда установлен кодовый замок, содержащий десять кнопок с цифрами от 0 до 9.
# Код содержит три цифры, которые нужно нажать одновременно.
#Какова вероятность того, что человек, не знающий код, откроет дверь с первой попытки?
from math import factorial
A = int(factorial(10) / factorial(10 - 3))
print(f'вероятность того, что человек, не знающий код, откроет дверь с первой попытки: 1 к ', A) |
calif1 = float(input("Ingrese la primera calificación: "))
calif2 = float(input("Ingrese la segunda calificación: "))
calif3 = float(input("Ingrese la tercera calificación: "))
prom = (calif1 + calif2 + calif3)/ 3
if prom > 70:
print("Alumno aprobado")
else:
print("Alumno reprobado") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.