blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
e6dfe35066366a6655fabebb82d7c12bdaa9fa63 | Asgavar/pork | /pork/entities.py | 1,024 | 3.84375 | 4 | import abc
class WorldObject(abc.ABC):
@abc.abstractmethod
def description(self) -> str:
pass
class Door(WorldObject):
def __init__(self, door_name: str, door_direction: str,
is_open: bool = False) -> None:
self._door_name = door_name
self.door_direction = door_direction
self.is_open = is_open
def description(self) -> str:
proper_word = 'otwierają' if self.is_open else 'blokują'
return f'Drzwi, które {proper_word} przejście do {self.door_direction}'
class Item(WorldObject):
def __init__(self, item_name: str) -> None:
self._item_name = item_name
def description(self) -> str:
return f'Przedmiot o nazwie {self._item_name}'
class Monster(WorldObject):
def __init__(self, monster_name: str, health: int) -> None:
self.monster_name = monster_name
self.health = health
def description(self) -> str:
return f'Potwór o nazwie {self.monster_name} i HP = {self.health}'
|
9820e6a9b9f14734989d25df899dc3ec78bdda03 | docxed/codeEjust | /Sequence V.py | 239 | 3.578125 | 4 | """main"""
def main():
"""main function"""
num = int(input())
cnt = 0
for j in range(num, 0, -1):
if cnt == 7:
print()
cnt = 0
print(j, end=" ")
cnt += 1
print()
main()
|
700ee9093a2dbd55ebf6fb1028ca1c44eee76a9f | Ldarrah/edX-Python | /PythonII/3.3.3 Coding Problem sumloop.py | 947 | 4.125 | 4 | mystery_int = 7
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#Use a loop to find the sum of all numbers between 0 and
#mystery_int, including bounds (meaning that if
#mystery_int = 7, you add 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7).
#
#However, there's a twist: mystery_int might be negative.
#So, if mystery_int was -4, you would -4 + -3 + -2 + -1 + 0.
#
#There are a lot of different ways you can do this. Most of
#them will involve using a conditional to decide whether to
#add or subtract 1 from mystery_int.
#
#You may use either a for loopor a while loop to solve this,
#although we recommend using a while loop.
#Add your code here!
sumnum = 0
if mystery_int <= 0:
for i in range(mystery_int,0):
sumnum = sumnum + i
print (sumnum)
else:
for i in range(0, mystery_int +1):
sumnum += i
print(sumnum) |
272eb367dcd7f410f9a63a754c8e8635a9306b03 | AnnDWang/python | /DataStructure/ch5/Search.py | 3,596 | 3.84375 | 4 |
def sequentialSearch(alist,item):
pos=0
found=False
while pos<len(alist) and not found:
if alist[pos]==item:
found=True
else:
pos=pos+1
return found
testlist=[1,2,32,8,17,19,42,13,0]
# print(sequentialSearch(testlist,3))
# print(sequentialSearch(testlist,13))
def orderedSequentialSearch(alist,item):
pos=0
found=False
stop=False
while pos<len(alist) and not found and not stop:
if alist[pos]==item:
found=True
else:
if alist[pos]>item:
stop=True
else:
pos=pos+1
return found
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
# print(orderedSequentialSearch(testlist, 3))
# print(orderedSequentialSearch(testlist, 13))
def binarySearch(alist,item):
first=0
last=len(alist)-1
found=False
while first<=last and not found:
midpoint=(first+last)//2 # //表示整数除法
if alist[midpoint]==item:
found=True
else:
if item<alist[midpoint]:
last=midpoint-1
else:
first=midpoint+1
return found
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
# print(binarySearch(testlist, 3))
# print(binarySearch(testlist, 13))
def binarySearch(alist,item):
if len(alist)==0:
return False
else:
midpoint=len(alist)//2
if alist[midpoint]==item:
return True
else:
if item<alist[midpoint]:
return binarySearch(alist[:midpoint],item)
else:
return binarySearch(alist[midpoint+1:],item)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
# print(binarySearch(testlist, 3))
# print(binarySearch(testlist, 13))
class HashTable:
def __init__(self):
self.size=11
self.slots=[None]*self.size
self.data=[None]*self.size
def put(self,key,data):
hashvalue=self.hashfunction(key,len(self.slots))
if self.slots[hashvalue]==None:
self.slots[hashvalue]=key
self.data[hashvalue]=data
else:
if self.slots[hashvalue]==key:
self.data[hashvalue]=data# replace
else:
nextslot=self.rehash(hashvalue,len(self.slots))
while self.slots[nextslot]!=None and self.slots[nextslot]!=key:
nextslot=self.rehash(nextslot,len(self.slots))
if self.slots[nextslot]==None:
self.slots[nextslot]=key
self.data[nextslot]=data
else:
self.data[nextslot]=data
def hashfunction(self,key,size):
return key%size
def rehash(self,oldhash,size):
return (oldhash+1)%size
def get(self, key):
startslot=self.hashfunction(key,len(self.slots))
data=None
stop=False
found=False
position=startslot
while self.slots[position]!=None and not found and not stop:
if self.slots[position]==key:
found=True
data=self.data[position]
else:
position=self.rehash(position,len(self.slots))
if position==startslot:
stop=True
return data
def __getitem__(self,key):
return self.get(key)
def __setitem__(self,key,data):
self.put(key,data)
H=HashTable()
H[54]='cat'
H[26]='dog'
H[93]='lion'
H[17]='tiger'
H[77]='bird'
H[31]='cow'
H[44]='goat'
H[55]='pig'
H[20]='chicken'
print(H.slots)
print(H.data)
H[20]='duck'
print(H.data) |
10a34cf9da0e1b5200f6b1ef43f44b4c7e40db92 | xddongx/study-python | /03.영어 단어 맞추기 게임/englishword-game.py | 1,001 | 3.984375 | 4 | '''
1. 영어단어장 만들기
2. 문제낼 랜덤한 단어장(단어장의 한글) 배열 만들기
3. 단어 맞출 기회
4. 기회만클 정답과 비교
5. 맞추면 정답, 틀리면 정답 출력
'''
import random, os, re
os.system('cls')
word_dict = {
'사자': 'lion',
'호랑이': 'tiger',
'사과': 'apple',
'바나나': 'banana',
'음식': 'food'
}
quiz_word = []
for i in word_dict:
quiz_word.append(i)
random.shuffle(quiz_word)
answer_count = 0
chance = 3
for word in quiz_word:
count = 0
while count < chance:
count += 1
user_input = input(f'{word}의 영어단어를 입력하세요> ')
if user_input.lower() == word_dict[word].lower():
answer_count += 1
print('정답입니다.')
break
else:
print('틀렸습니다')
if count == 3:
print(f'정답은 {word_dict[word].lower()} 입니다.')
print(f'{answer_count}개 맞췄습니다.') |
34f562b3701fc8c596e712c6bf487d807fea2c01 | NoeliaHS/DamM09 | /Ejercicio2.py | 186 | 3.953125 | 4 | '''Ejercicio 2: '''
a = int(input("Introduzca un número: "))
if a >= 10:
print("El número introducido es correcto",a)
else:
print ("El número es inferior a 10")
input()
|
ebeb71ccd8adfbad3659187380967aba61699c88 | sylvaus/presentations | /python/code/exercise_solutions/09_exception.py | 804 | 4.34375 | 4 | """
Exercise 1
Write a code that asks the operator for its name and throws an exception if the string is longer than 20 characters
"""
def exercise1():
name = input("what is your name")
if len(name) > 20:
raise Exception("too long")
exercise1()
"""
Exercise 2
Write a code that asks the operator for its age and tries to convert it to int
Use the int(string) function: https://docs.python.org/3/library/functions.html#int
This function will throw an ValueError if it cannot be converted, use the try-catch-else construct to inform
the user if the age given was correct or not
"""
def exercise2():
age = input("what is your name")
try:
age = int(age)
except ValueError:
print("Invalid Format")
else:
print("Whoa, you're", age)
exercise2()
|
c892e6dfc1d41fb482b41297c643bdcddcbda603 | Kjell-Nina/my_first_python_proyect | /Proyectos_basicos_de_python/converso.py | 712 | 3.765625 | 4 |
def conversor(tipo_moneda,valor_dolar):
moneda = input('¿Cuantos '+ tipo_moneda +' tines?: ')
moneda = float(moneda)
#valor_dolar = 4.025 se quita por que ya se invoca en la parte de función
dolares = moneda / valor_dolar
dolares = round(dolares,2)
dolares = str(dolares)
print('Tienes $'+ dolares + ' dolares')
menu = """
Bienvenidos al conversor de monedas 💰
1 - Soles
2 - Pesos Mexicanos
3 - Pesos Colombianos
Elige una opción: """
opcion = int(input(menu))
if opcion == 1:
conversor('soles',4.09)
elif opcion == 2:
conversor("pesos mexicanos", 18)
elif opcion == 3:
conversor("pesos argentinos",204)
else:
print("Escribe una opción correcta por favor")
|
37ab352a7cc7c78f25815b7f0a474873b43c0abe | shreyaspadhye3011/algoexpert | /Heaps/min_heap.py | 3,897 | 3.859375 | 4 | # Do not edit the class below except for the buildHeap,
# siftDown, siftUp, peek, remove, and insert methods.
# Feel free to add new properties and methods to the class.
# Approach: Look at conceptual overview.
# The implementation is based on two basic methods: siftUp & siftDown
# peek: return min. heap[0]
# siftUp: works on last element. compare with parent and keep swapping if parent is larger in value
# siftDown: works on top if no index passed. compare with smaller child and keep swapping if smaller child is smaller than the parent
# insert: insert in end and siftUp
# remove: removes top (heap only works on top - min value). First swap top with last element. Remove last (easier -- simple pop). Then siftDown
# buildHeap: initialize with given array. Call siftDown on all on-leaf nodes starting from the last non-leaf node
# extra:
# 1. maintain heap size all the time (start from buildHeap) and keep updating on every insert / remove call so that it can be used in internal calls in constant time
# 2. Indexing:
# parent = int((index - 1)/2)
# left_child = 2*index + 1
# right_child = 2*index + 2
# TODO: Write approach down
# TODO: watch code walkthrough
# Learning: As long as you understand the conceptual overview, code will be fine. Eg loko at the code. It might look complicated but the underlying logic is pretty straight forward (Look at conceptual overview)
import math
import sys
class MinHeap:
def __init__(self, array):
# Do not edit the line below.
self.heap = self.buildHeap(array)
# O(N) time when implemented with siftDown (not nlogn cz majority siftDown calls take less time. It's only upper levels that take logn time). Look at conceptual overview
def buildHeap(self, array):
# initialize heap with given array and its size
self.size = len(array)
self.heap = array
last_idx = self.size - 1
# get last element's parent
parent = math.floor((last_idx-1)/2)
while parent >= 0:
array = self.siftDown(parent)
parent = parent - 1
return array
# O(logN) time
# index used for buildHeap() when you need to siftDown every parent
def siftDown(self, index=None):
if self.size > 0:
if index is None:
current = 0
else:
current = index
child = self.getSmallerChild(current)
while child is not None and child < self.size:
if self.heap[current] > self.heap[child]:
self.heap[current], self.heap[child] = self.heap[child], self.heap[current]
current = child
child = self.getSmallerChild(current)
else:
break
return self.heap
# O(logN) time
def siftUp(self):
current = self.size - 1
parent = math.floor((current-1)/2)
while parent >= 0:
if self.heap[current] < self.heap[parent]:
self.heap[current], self.heap[parent] = self.heap[parent], self.heap[current]
current = parent
parent = math.floor((current-1)/2)
else:
break
return
# O(1) time
def peek(self):
if len(self.heap) > 0:
return self.heap[0]
return None
# O(logN) time including balancing
def remove(self):
removed = None
if self.size > 0:
# swap top with last element so that it can be removed
self.heap[0], self.heap[self.size-1] = self.heap[self.size-1], self.heap[0]
removed = self.heap.pop()
self.size -= 1
self.siftDown()
return removed
# O(logN) time including balancing
def insert(self, value):
self.heap.append(value)
self.size += 1
self.siftUp()
return
# helper method. O(1) time
def getSmallerChild(self, current):
left = 2*current+1 if 2*current+1 < self.size else None
right = 2*current+2 if 2*current+2 < self.size else None
child = None
if left is not None and right is not None:
child = left if self.heap[left] < self.heap[right] else right
elif left is not None:
child = left
elif right is not None:
child = right
return child
|
c4560293be628519f242be511c861de46a0e4e1c | ongsuwannoo/Pre-Pro-Onsite | /Super Extra Center_justify.py | 151 | 3.5 | 4 | """ [Super Extra] Center_justify """
def main():
''' input '''
num = int(input())
cha = input()
print(cha.center(num))
main()
|
2a67548049882a5870467afba3d7db9050e5281c | SalyaW/Binus_TA_Session_Semester_1 | /Driving simulation.py | 576 | 3.828125 | 4 | u = 0
vlimit = 60
s = int(input("input distance:"))
a = float(input("insert acceleration:"))
t = int(input("input time:"))
for i in range(0,t+1):
s2 = int(0.5 * a * i * i )
s2 = int(s2/10)
print("Duration:",i,"Distance:","*"* (s2))
v = t * a
if v <= 60:
v = t * a
print("Was not over the speed limit,max speed was",v,"m/s")
else:
print("Over the speed limit,max speed was",v,"m/s")
s1 = 0.5 * t * t * a
if s1 >= s:
print("they reached their destination","they reaced",s1)
else:
print("they didn't reach their destination","they reaced",s1)
|
9dc2e48cef08f424f58a59e02558711b18d8c459 | daniel-reich/ubiquitous-fiesta | /xdSKkXQkkMroNzq8C_17.py | 127 | 3.90625 | 4 |
def count_d(sentence):
count = 0
for x in sentence:
if 'd' == x or 'D' == x:
count = count + 1
return count
|
a18d266c0e5d0157c7941e72a1b5cd10e58bfb68 | Keerti-Gautam/PythonLearning | /Functions/FuncWithMultipleArgs.py | 2,261 | 5 | 5 | # You can define functions that take a variable number of positional args, which will be interpreted as a tuple by using *
# Writing args and kwargs are not necessary, you can write var or vars and it would work the same
def varargs(*args):
return args
print varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of keyword args as well, which will be interpreted as a dict by using **
def keyword_args(**kwargs):
return kwargs
# Let's call it to see what happens
print keyword_args(big="foot", loch="ness", x=5) # => {"big": "foot", "loch": "ness", "x": 5} note that here x is treated as a dict element with a key and a value
# You can do both at once too
def all_the_args(*args, **kwargs):
print args
print kwargs
return kwargs #return args+kwargs Will show error as dict to tuple concatenation isn't possible.
# Multiplication with two isn't possible with return statement as dict cannot be multiplied with int
print all_the_args(1, 2, a="lion", b=4) # prints
# All_the_args(a="lion", b=4, 1, 2) # Cannot do this because either all kwargs or args, and together the order of kwargs after args should be maintained.
# When calling functions, you can do the opposite of args/kwargs!
def all_these_args(*kwargs, **args):
print args
print kwargs
print all_these_args(1, 2, a="lion", b=4)
"""
def all_these_args(*args, **kwargs):
print args
print kwargs
print all_these_args(a="tiger", b="hey", 2, 3)
Doesn't work because keyword arguments cannot be followed by non keyword arguments
"""
# Use * to expand positional args and use ** to expand keyword args.
def all_such_args(*kwargs, **args):
print args
print kwargs
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_such_args(*args) # equivalent to foo(1, 2, 3, 4)
all_such_args(**kwargs) # equivalent to foo(a=3, b=4)
all_such_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
# you can pass args and kwargs along to other functions that take args/kwargs by expanding them with * and ** respectively
def pass_all_the_args(*args, **kwargs):
all_the_args(*args, **kwargs)
print varargs(*args)
print keyword_args(**kwargs)
pass_all_the_args(200, 300, name="tom", pet="rat", food="pizza")
|
e3ce81207237709eccd7a8fe5d6d73578df0bf0f | YuanLiuLawrence/SoftwareForEmbeddedSytem | /Lab0/program4.py | 474 | 3.8125 | 4 | #Lab0-Program4-liu1827
def program4():
date = {
"Albert Einstein": "03/14/1879",
"Benjamin Franklin": "01/17/1706",
"Ada Lovelace": "12/10/1815"
}
print("Welcome to the birthday dictionary. We know the birthdays of:")
print("Albert Einstein");
print("Benjamin Franklin");
print("Ada Lovelace");
name = input("Who’s birthday do you want to look up?\n")
print("{}'s birthday is {}.".format(name, date[name]))
return
if __name__ == "__main__":
program4() |
88dc1ced4d71688f3adb938977db8f2d07e51580 | jbanerje/Beginners_Python_Coding | /tic_tac_toe_test.py | 1,901 | 3.890625 | 4 |
# This is the basic gaming structure
print("***-----------Tic Tac Toe table---------------------------***")
print(" [1,2,3]\n","[4,5,6]\n","[7,8,9]")
print("***-------------------End---------------------------------***")
play_count = 0
player1=[[1,2,3],[4,5,6],[7,8,9]]
#Total 9 opportunities will be present for 2 players
while (play_count <= 9):
#print("play_count:",play_count)
player_1_pos = int(input("Player_1: Enter your position:"))
if ( player_1_pos == 1) :
player1[0][0] = 'P1'
elif ( player_1_pos == 2) :
player1[0][1] = 'P1'
elif ( player_1_pos == 3) :
player1[0][2] = 'P1'
elif ( player_1_pos == 4) :
player1[1][0] = 'P1'
elif ( player_1_pos == 5) :
player1[1][1] = 'P1'
elif ( player_1_pos == 6) :
player1[1][2] = 'P1'
elif ( player_1_pos == 7) :
player1[2][0] = 'P1'
elif ( player_1_pos == 8) :
player1[2][1] = 'P1'
else :
player1[2][2] = 'P1'
play_count = play_count + 1
print(player1)
player_2_pos = int(input("Player_2: Enter your position:"))
if ( player_2_pos == 1) :
player1[0][0] = 'P1'
elif ( player_2_pos == 2) :
player1[0][1] = 'P1'
elif ( player_2_pos == 3) :
player1[0][2] = 'P1'
elif ( player_2_pos == 4) :
player1[1][0] = 'P1'
elif ( player_2_pos == 5) :
player1[1][1] = 'P1'
elif ( player_2_pos == 6) :
player1[1][2] = 'P1'
elif ( player_2_pos == 7) :
player1[2][0] = 'P1'
elif ( player_2_pos == 8) :
player1[2][1] = 'P1'
else :
player1[2][2] = 'P1'
play_count = play_count + 1
print(player1)
|
6c4f20fdfa7688452addaa77d00914b66828f365 | legolas-zeng/scripts | /test.py | 1,118 | 3.84375 | 4 | # coding=utf-8
# @author: zwa❤lqp
# @time: 2021/2/27 17:47
import os,re
# a = 0
# b = 1
# n = 10
#
# for i in range(n):
# a,b = b,a+b
# print(a)
# def fib_yield_while(max):
# a, b = 0, 1
# while max > 0:
# a, b = b, a + b
# max -= 1
# yield a
#
#
# def fib_yield_for(n):
# a, b = 0, 1
# for _ in range(n):
# a, b = b, a + b
# yield a
#
#
# for i in fib_yield_for(10):
# print(i, end=' ')
a = ['A', '', 'B', None, 'C', ' ']
# filter()函数把传入的函数一次作用于每个元素,然后根据返回值是True 还是 False决定保留还是丢弃该元素
print(list(filter(lambda s : s and s.strip(), a)))
s = lambda x:"yes" if x==1 else "no"
print(s(1))
foo=[-5,8,0,4,9,-4,-20,-2,8,2,-4]
# 正数从小到大,负数从大到小
a = sum(range(1,101))
print(sum(range(1,101)))
b =[1,2,3,4,5]
def fn(x):
return x**2
print(list(map(fn,b)))
print(list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])))
print([i for i in [1,2,3,4,5] if i >3])
fn1 = lambda **kwargs:kwargs
print(fn1(name='lily',age=18))
print(lambda a=1,b=2:a if a > b else b)
|
fa15d06e0c9d40cfce38398d6bc557656173bc4f | marrerap/python_project | /window_choice2.py | 636 | 3.6875 | 4 | import time
def Window2():
print()
print()
time.sleep(2)
print('For some reason the idea of ending it all seems to be the best option')
time.sleep(2)
print('Why continue this game you\'re bored of.')
time.sleep(2)
print('You rush to the window, it opens as fast as you run to it.')
time.sleep(2)
print("You go to jump through the opening... And holy ish... who would have")
time.sleep(2)
print('thought trying to put an end to the game that is your life would end this game as well...')
time.sleep(2)
print('CONGRATULATIONS!!!! YOU\'VE WON')
return False
|
f27b1eef630572110df5e8cc72e06d6f700cd92b | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_200/5107.py | 279 | 3.53125 | 4 | t = int(input())
a = 0
while(a<t):
thing = 0
num = int(input())
for i in range(num+1):
word = str(i)
arr = list(word)
if sorted(arr) == arr:
thing = arr
ans = ''.join(thing)
print("Case #" + str(a+1) +":" , ans)
a=a+1 |
a1804f5612208fcf8618d5c72b238e993689fb83 | ZirvedaAytimur/Reinforcement_Learning_For_Maze | /RandomActions.py | 2,660 | 3.703125 | 4 | import pygame
from time import sleep
from random import randint as r
from common_functions import create_maze, act_random, layout, calculate_mse, is_done, is_user_exit, move
n, display_maze, reward, obstacles, states = create_maze()
actions = {"up": 0, "down": 1, "left": 2, "right": 3} # all actions
current_position = [1, 1]
# method to choose an action
def select_an_action(current_state):
global current_position
possible_actions = []
action = act_random(current_position, possible_actions, actions, r)
return action
# screen parameters
screen_x = n * 70
screen_y = n * 70
screen = pygame.display.set_mode((screen_x, screen_y))
# main method
background = (240, 228, 246) # reset the screen
run = True # is program running
cumulative_rewards = [] # cumulative rewards for all episodes
cumulative_reward = 0 # cumulative reward for one episode
iterations = [] # number of iterations for all episodes
iteration = 0 # iteration for one episode
episodes = [] # all episodes
mean_squared_errors = []
episode_number = 0
while run:
sleep(0.01)
screen.fill(background)
layout(screen_x, screen_y, screen, display_maze, current_position)
done = is_done(current_position)
# if agent reached the goal reset
if done or iteration == 20000:
# print episode result
print(f"Episode {episode_number}: final score is {cumulative_reward} with {iteration} iterations")
# add results for plot
iterations.append(iteration)
cumulative_rewards.append(cumulative_reward)
episodes.append(episode_number)
# calculate mean squared error
mse = calculate_mse(iterations)
mean_squared_errors.append(mse)
print(f"The mean squared error for first {episode_number} episode is: {mse}")
# reset
current_position = [1, 1]
iteration = 0
cumulative_reward = 0
episode_number += 1
run = is_user_exit(run)
pygame.display.flip()
# exit if reach 100 episodes
if episode_number > 100:
run = False
# select action
current_state = states[(current_position[0], current_position[1])]
action = select_an_action(current_state)
current_position = move(action, current_position)
# increase cumulative reward and iteration number
cumulative_reward += reward[current_position[0], current_position[1]]
iteration += 1
new_state = states[(current_position[0], current_position[1])]
if new_state in obstacles:
current_position = [1, 1]
pygame.quit()
def return_randomaction_solution():
return episodes, cumulative_rewards, iterations, mean_squared_errors
|
be9930856e8fd84bf2e320d7547b60ee8389b389 | Zedomas/HackerRank | /Python/Starecase.py | 149 | 3.984375 | 4 | def staircase(n):
for x in range(1, n+1):
if x < n:
print((" " * (n - x)) + "#" * x)
else:
print("#" * x) |
06c93b90caf8819524c527446b24795dc3e444fb | ayush879/python | /12.py | 163 | 4.40625 | 4 | #12) Return the year of the date from a given string.
import re
string = input("Enter a date : ")
pattern = '.*([1-3][0-9]{3})'
print(re.findall(pattern, string))
|
65f74f5018e3e78a6a8784469f56bb98d1f90a6c | YaoCheng8667/PythonLearn | /sort.py | 473 | 3.65625 | 4 | '''
Test sort
'''
print('==========================Test Sort====================================')
l = [('ASDD',123,0.9),('DsdD',13,0.817),('JKKll',781,0.776),('OOkl',89,1.514)]
print(sorted(l,key=lambda x : x[0]))
print(sorted(l,key=lambda x : x[1]))
print(sorted(l,key=lambda x : x[2], reverse = True))
print('-----------------------------------------------------------------------')
l2 = [101,-3.5,99.8,7,-66]
print(sorted(l2,key=abs))
print(sorted(l2,reverse=True))
|
53ef184707069c63d1b2344b7001f6c1bc97fe52 | pieisland/ProjectEuler | /pro3_3.py | 714 | 3.625 | 4 | #coding:utf-8
"""
2019.03.14.Thu
<소인수분해>
효율적인 버전.
다른 분이 푸신 걸 보고 다시 풀어봄
"""
def primeNumber(n):
"""
소인수분해하는 함수
n이 큰 수라도, 나눈 결과로 다시 되기 떄문에 빠르게 수행이 되는 듯.
result 자체에 중복되는 소수가 들어가지 않게 in 을 추가로 더 넣어봄.
"""
i=2
result=[]
while(i<=n):
if(n%i==0):
n=n//i
if i not in result:
result.append(i)
else:
i+=1
return result
def main():
n=600851475143
tmp=primeNumber(n)
print(tmp)
print(max(tmp))
if __name__=="__main__":
main()
|
1ddc9d8413d0dc87340b4093ec536ee7a3822617 | Dvyabharathi/My_python_code | /fizz.py | 378 | 3.90625 | 4 | def fizzBuzz(n):
for i in range(1, n+1):
if i%3==0 and i%5==0:
print("Fizzbuzz")
elif i%3==0:
print("Fizz")
elif i%5==0:
print("Buzz")
else:
print(i)
fizzBuzz(15)
def Reverse(lst):
new_lst = lst[::-1]
return new_lst
print(Reverse([10, 11, 12, 13, 14, 15]))
|
36202b91575b81066d92f8ed757dd6f991be9588 | Fea-Sin/python-core-50day | /src/ch8/pyd.py | 953 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/12 2:39 下午
# @Author : FEASIN
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(f'{self.name}正在吃饭')
def sleep(self):
print(f'{self.name}正在睡觉')
class Student(Person):
def __init__(self, name, age):
super().__init__(name, age)
def study(self, course_name):
print(f'{self.name}正在学习{course_name}')
class Teacher(Person):
def __init__(self, name, age, title):
super().__init__(name, age)
self.title = title
def teach(self, course_name):
print(f'{self.name}-{self.title}正在教授{course_name}')
stu1 = Student('元白芳', 21)
stu2 = Student('狄仁杰', 22)
teacher = Teacher('武则天', 35, '副教授')
stu1.eat()
stu2.sleep()
teacher.teach('Python程序设计')
stu1.study('Python程序设计') |
fc63ca3e0d73586720e34b5de1d1fb19aee44c0b | ekirlilar/Game_of_RPS_PythonHW-master | /gameFiles/compare.py | 2,036 | 3.703125 | 4 | import time
from random import randint
def comparing (player, computer):
global player_lives
global computer_lives
global player
global computer
global choices
if ( player == computer ):
print("*******Tie!*******")
elif ( player == "rock" ):
if (computer == "paper"):
print("*******You Lose!*******", computer, "covers", player, "\n")
player_lives = player_lives - 1
gameVars.computer_lives = gameVars.computer_lives + 1
print("************¯\_(ツ)_/¯************\n")
elif (gameVars.computer == "scissors"):
print("*******You WIN!*******", player, "smashes", gameVars.computer, "\n")
gameVars.computer_lives = gameVars.computer_lives - 1
player_lives = player_lives + 1
print("************ʕ→ᴥ←ʔ************\n")
elif ( player == "paper"):
if (gameVars.computer == "scissors"):
print("*******You Lose!*******", gameVars.computer, "cuts", player, "\n")
player_lives = player_lives - 1
gameVars.computer_lives = gameVars.computer_lives + 1
print("************(^◡^)っ✂❤ ************\n")
elif (gameVars.computer == "paper"):
print("*******You WIN!*******", player, "covers", gameVars.computer, "\n")
gameVars.computer_lives = gameVars.computer_lives - 1
player_lives = player_lives + 1
print("************(ㆁᴗㆁ✿)************\n")
elif ( player == "scissors" ):
if (gameVars.computer == "rock"):
print("*******You Lose!*******", gameVars.computer, "smashes", player, "\n")
player_lives = player_lives - 1
gameVars.computer_lives = gameVars.computer_lives + 1
print("************¯\_(ツ)_/¯************\n")
elif (player == "rock"):
print("*******You WIN!*******", player, "smashes", computer, "\n")
computer_lives = computer_lives - 1
player_lives = player_lives + 1
print("************ʕ·ᴥ- ʔ************\n")
else:
print("******************************\n")
print("That's not a valid choice, try again")
print("******************************\n") |
e5d9330d0986de75e21279942ae6704da947cead | cicekozkan/python-examples | /datetime.py | 2,010 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 13 19:13:58 2014
@author: ocicek
"""
import datetime
def print_today():
today=datetime.date.today()
print "Year=%d, month=%d, day=%d" %(today.year, today.month, today.day)
def find_age_birthday(year, month, day):
"""takes a birthday as input and prints the user’s age and the number of
days, hours, minutes and seconds until their next birthday."""
today=datetime.date.today()
age = abs(today.year - year)
print 'Age=%d'%age
next_birthday = datetime.date(today.year, month, day)
if next_birthday < today:
next_birthday = next_birthday.replace(year = today.year + 1)
time_to_birthday = abs(next_birthday - today)
#print "Next birthday is %d days, %d hours, %dminutes and %d seconds later"\
print "Next birthday is %d days later"\
%(time_to_birthday.days)
def double_day(year1,month1,day1,year2,month2,day2):
"""For two people born on different days, there is a day when one is
twice as old as the other. That’s their Double Day. Write a program
that takes two birthdays and computes their Double Day."""
bd1=datetime.date(year1,month1,day1)
bd2=datetime.date(year2,month2,day2)
dif = abs(bd1-bd2)
if bd1 < bd2:
dd = bd2 + dif
else:
dd = bd1 + dif
print 'the double day is %d/%d/%d'%(dd.year, dd.month, dd.day)
def n_day(n,year1,month1,day1,year2,month2,day2):
"""the more general version of double_day that computes the day when one
person is n times older than the other."""
assert n > 1
bd1=datetime.date(year1,month1,day1)
bd2=datetime.date(year2,month2,day2)
oneyear = datetime.date(1,1,1)
twoyear = datetime.date(2,1,1)
one_age = twoyear - oneyear
if (year1<year2):
nyear = (year2-year1)/(n-1)
nd = bd2 + nyear*one_age
else:
nyear = (year1-year2)/(n-1)
nd = bd1 + nyear*one_age
print 'the n day is %d/%d/%d'%(nd.year, nd.month, nd.day)
|
8d80a6c2fe9c7443f89eb28bb38d44e251e6add9 | LuoJiaji/LeetCode-Demo | /Contest/biweekly-contest-10/A.py | 479 | 3.6875 | 4 | class Solution(object):
def arraysIntersection(self, arr1, arr2, arr3):
"""
:type arr1: List[int]
:type arr2: List[int]
:type arr3: List[int]
:rtype: List[int]
"""
ans = []
for i in arr1:
if i in arr2 and i in arr3:
ans.append(i)
return ans
arr1 = [1,2,3,4,5]
arr2 = [1,2,5,7,9]
arr3 = [1,3,4,5,8]
res = Solution().arraysIntersection(arr1, arr2, arr3)
print(res) |
bb6a579de50a5ad8fc691fac4adf8885d0323e69 | NickKletnoi/Python | /03_Algorithms/03_Misc/06_TravelItinerary.py | 2,805 | 3.546875 | 4 |
#Copyright (C) 2017 Interview Druid, Parineeth M. R.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
from __future__ import print_function
import sys
def handle_error() :
print( 'Error occured')
sys.exit(1)
#tickets: list which stores the information about the tickets bought.
# ticket[i][0] stores the starting city of the ith ticket
# ticket[i][1] stores the destination city of the ith ticket
# There should be no loop in the trip
# There should be at least 1 ticket
#Return value: list containing the names of cities in the order of travel
def reconstruct_trip(tickets) :
num_tickets = len(tickets)
next_hop = {}
destinations = set()
#Store the starting city (key) and destination city (value) in next_hop
#dictionary. Store the destination cities in destinations set
for start, dest in tickets:
next_hop[start] = dest
destinations.add(dest)
#Search the starting city of each ticket in the destinations
#Only the first city of the entire trip will NOT be in destinations
start_index = -1
i = 0
for start, dest in tickets:
if (start not in destinations) :
#We didn't find the city in the destinations.
#So this must be the first city of the entire trip
start_index = i
break
i += 1
if (start_index == -1):
return None
result = []
#add the first city of entire trip into the result
result.append(tickets[start_index][0])
#Search for the first city of the entire trip in the next_hop dictionary
next_city = next_hop.get(tickets[start_index][0])
while (next_city) :
#Store the destination city in the result
result.append(next_city)
#make the destination city as the next starting city
#and search for it in the next_hop dictionary
next_city = next_hop.get(next_city)
return result
def verify(result) :
expected = ['LA', 'SF', 'TOKYO', 'BEIJING', 'DELHI', 'ROME']
for result_city, expected_city in zip(result, expected) :
if (result_city != expected_city):
handle_error()
def test() :
tickets = [['TOKYO', 'BEIJING'], ['LA', 'SF'], ['DELHI', 'ROME'], ['SF', 'TOKYO'], ['BEIJING', 'DELHI']]
num_tickets = 5
for i in range(num_tickets):
print( tickets[i][0] + ' -> ' + tickets[i][1] )
print( 'The order of visiting: ', end='')
result = reconstruct_trip(tickets)
for city in result :
print(city + ' ', end='')
print('')
verify(result)
if (__name__ == '__main__'):
test()
print( 'Test passed ')
|
1afc36f53654b03e2f353e64b656b39dff8c2e0e | HannaRF/Linguagens-de-Programacao | /aula_testes.py | 2,772 | 3.578125 | 4 | # programação via testes (tdt)
import unittest
class Biblioteca:
def __init__(self,artigos):
self.artigos = artigos
self.autores = set(list(a))
def get_vizinhos(self,autor):
art = [t for t in self.artigos if autor in t]
for a in art:
v = a[0] if a[1] != autor else a[1]
viz.append(v)
return viz
def get_num_erdos(self,autor):
if autor in get_vizinhos("erdos"):
return 1
else:
return 2
# assert (condição) se True passa ,se False retorna erro
class TestErdos(unittest.TestCase):
def SetUp(self):
self.B = Biblioteca([("francisco","hanna"),("erdos","hanna"),("erdos","francisco")])
def test_verifica_numero_artigos_maior_que_zero(self):
B = Biblioteca(artigos=[("francisco","leo"),("erdos","hanna")])
self.assertGreater(len(B.artigos),0) # verifica se a primeira é maior que a primeira
def test_arg_erdos(self):
B = Biblioteca(artigos=[("francisco","leo"),("erdos","hanna")])
a = False
for i in B.artigos:
#a = True if ("erdos" in i) else a
#a = a or ("erdos" in i)
a |= "erdos" in i
assert(a)
def test_são_vizinhos(self):
viz = self.B.get_vizinhos("joão")
assert("hanna" in viz)
def test_numero_1(self):
assert(self.B.)
def test_existe_lista_autores(self):
assert("autores" in dir (self.B))
if __name__ == "__main__":
unittest.main() # executa os testes e retorna um relatório,com o tempo de execução
# monitoria,09/10/19
import unittest
def fun(x):
return x + 1
class MyTest(unittest.TestCase): # TestCase é a classe padrao de destes da biblioteca unittest,que precisamos impor a herança
def test(self):
self.assertEqual(fun(3),4) # metodo padrao da TestCase
def test2(self):
self.assertEqual(fun(4),5)
a = MyTest()
a.test()
## dicas criar modulos
# __eq__ : =
# __add__ : +
# __str__ : printar (print)
# __iter__ : iterar (for)
# __contains__ : checar se tem o valor
## obs : @property
# chama um método sem botar os parentesis vazios
# ao ser colocada logo antes da def da função
## dicas erros:
# try ... :
# except ... :
def div(a/b):
try:
return a/b
except:
0
# se der algum erro retorna 0
#raise ... : força um erro
#estrutura do erro
class my error(Exception): #Exception herdado
def __init__(self,lista):
Exception.__init__(self,"0 in {},divisão por zero não existe".format(lista)) # printa o erro
# curso python 3 completo do iniciante ao avançado udemy
# programar livro Structure and Interpretation of Computer Programs
|
c23e40d49ad9d8899150984b68a335a287bf44b9 | MeabhG/Python-Games | /02. Guess the number.py | 2,507 | 4.28125 | 4 | # Mini-project #2 - Guess the number
#
# 'Introduction to Interactive Programming in Python' Course
# RICE University - coursera.org
# by Joe Warren, John Greiner, Stephen Wong, Scott Rixner
# run the code using www.codesculptor.org
# link to code http://www.codeskulptor.org/#user28_5wDR9vkBbB_0.py
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import math
# initialize global variables
num_range = 100
secret_num = 0
remaining = 0
# helper function to start and restart the game
def new_game():
if num_range == 100:
range100()
elif num_range == 1000:
range1000()
else:
print "Num_range fault!"
# button that changes range to range [0,100) and restarts
def range100():
global secret_num
secret_num = random.randrange(1, 101)
global remaining
remaining = 7
global num_range
num_range =100
print
print "New game. Range is from 0 to 100"
print "Number of remaining guesses is 7"
# button that changes range to range [0,1000) and restarts
def range1000():
global secret_num
secret_num = random.randrange(1, 1001)
global remaining
remaining = 10
global num_range
num_range =1000
print
print "New game. Range is from 0 to 1000"
print "Number of remaining guesses is 10"
#input player guess check to see if right update guesses remaining
def get_input(guess):
player_num = int(guess)
global remaining
if remaining >= 1:
remaining = remaining -1
else:
print "Remaining Error"
print
print "Guess was", player_num
print "Number of remaining guesses is", remaining
if secret_num == player_num:
print "Correct!"
new_game()
elif (secret_num > player_num) and (remaining == 0):
print "Higher!"
new_game()
elif (secret_num < player_num) and (remaining == 0):
print "Lower!"
new_game()
elif secret_num > player_num :
print "Higher!"
elif secret_num < player_num:
print "Lower!"
else:
print "Error!"
# create frame
f=simplegui.create_frame("Guess the number!", 200, 200)
# register event handlers for control elements
f.add_button("Range is (0, 100)", range100, 200)
f.add_button("Range is (0, 1000)", range1000, 200)
f.add_input("Enter a guess", get_input, 200)
# call new_game and start frame
f.start()
new_game()
|
55cb9282bea6be1a0a3c80c9f9629f6800a0f80e | appscluster/stock-market-simulator-1 | /best_strategy.py | 1,093 | 3.5625 | 4 | """
Generate Best Possible Strategy
Created on Tue Apr 4 23:29:43 2017
@author: Xiaolu
"""
import csv
import pandas as pd
from indicators import get_prices
def test_run():
# Input data
dates_in_sample = pd.date_range('2008-01-01', '2009-12-31')
symbols = ['AAPL']
prices = get_prices(symbols, dates_in_sample)[0]
order_list = []
sym = 'AAPL'
for day, next_day in zip(prices.index[:-1], prices.index[1:]):
if prices.ix[day, sym] < prices.ix[next_day, sym]:
order_list.append([day.date(), sym, 'BUY', 200])
order_list.append([next_day.date(), sym, 'SELL', 200])
elif prices.ix[day, sym] > prices.ix[next_day, sym]:
order_list.append([day.date(), sym, 'SELL', 200])
order_list.append([next_day.date(), sym, 'BUY', 200])
# write orders to csv file
with open("orders-bestpossible.csv", "wb") as f:
writer = csv.writer(f)
writer.writerow(['Date', 'Symbol', 'Order', 'Shares'])
writer.writerows(order_list)
f.close()
if __name__ == "__main__":
test_run()
|
fba94e48ccba43f08b51964de83ff98337453902 | luckytiger1/data_structures_usd | /week1_basic_ds/check_brackets.py | 1,185 | 3.890625 | 4 | from collections import namedtuple
Bracket = namedtuple("Bracket", ["char", "position"])
def are_matching(left, right):
return (left + right) in ["()", "[]", "{}"]
def find_mismatch(text):
opening_brackets_stack = []
for i, nextElem in enumerate(text):
# print(f'{nextElem}, {i}')
if nextElem in "([{":
opening_brackets_stack.append([nextElem, i + 1])
if nextElem in ")]}":
if len(opening_brackets_stack) == 0:
return i + 1
top = opening_brackets_stack.pop()[0]
# print(f'top: {top}, nextElem: {nextElem}')
if (top == '[' and nextElem != ']') or (top == '{' and nextElem != '}') or (top == '(' and nextElem != ')'):
return i + 1
if len(opening_brackets_stack) != 0:
return opening_brackets_stack[0][1]
# for i, elem in enumerate(opening_brackets_stack):
# if elem in "([{)]}":
# return text.index(elem) + 1
def main():
text = input()
mismatch = find_mismatch(text)
if mismatch is not None:
print(mismatch)
else:
print("Success")
if __name__ == "__main__":
main()
|
1d8290932e03c3b43daef7911ea7f1c1741d75b5 | HEMALATHA310/python_basics | /tupleOPERATIONS.py | 244 | 3.828125 | 4 | print((1,2,3)+(4,5,6))
print(("7")*3)
tup=('h','e','m','a')
#del tup[1]#TypeError: 'tuple' object doesn't support item deletion
print(tup)
del tup
print(tup)#entire tuple can be deleted then we get [NameError: name 'tup' is not defined]
|
1fb6291ce47d04153c7e2436efc91a4ddcc0c981 | ABlued/PythonAlgorithmProblem | /programmers/hash/Phone_number_list.py | 552 | 3.625 | 4 | def solution(phone_book):
dic = {}
for i in range(len(phone_book)):
for j in range(len(phone_book[i])):
if phone_book[i][:j + 1] in dic: return False
dic[phone_book[i]] = 1
for i in range(len(phone_book)):
for j in range(len(phone_book[i])):
if phone_book[i][:j + 1] in dic and dic[phone_book[i][:j + 1]] == 2 : return False
elif phone_book[i][:j + 1] in dic : dic[phone_book[i]] = 2
return True
phone_book = ["12345","12","456","789","4123"]
print(solution(phone_book)) |
ab98bff47ccade473ac371b065bb76fccade6ff6 | ganeshuprety446/pythonexample | /quadraticifelese.py | 475 | 4.03125 | 4 | # Solve the quadratic equation
import math
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
d = (b*b) - (4*a*c)
print('value for drscriminant is',d)
if d < 0:
print ('This equation has no real solution')
elif d == 0:
sol1= (-b+math.sqrt(d))/2*a
print ('This equation has one solutions: ', sol1)
else:
sol2 = (-b+math.sqrt(d))/2*a
sol3 = (-b-math.sqrt(d))/2*a
print ('This equation has two solutions: ', sol2, 'and', sol3)
|
9b93d9af7773f5c435828a42f523ca3f6a11c038 | chenxu0602/LeetCode | /1018.binary-prefix-divisible-by-5.py | 1,479 | 3.640625 | 4 | #
# @lc app=leetcode id=1018 lang=python3
#
# [1018] Binary Prefix Divisible By 5
#
# https://leetcode.com/problems/binary-prefix-divisible-by-5/description/
#
# algorithms
# Easy (46.80%)
# Likes: 112
# Dislikes: 65
# Total Accepted: 14.3K
# Total Submissions: 30.5K
# Testcase Example: '[0,1,1]'
#
# Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to
# A[i] interpreted as a binary number (from most-significant-bit to
# least-significant-bit.)
#
# Return a list of booleans answer, where answer[i] is true if and only if N_i
# is divisible by 5.
#
# Example 1:
#
#
# Input: [0,1,1]
# Output: [true,false,false]
# Explanation:
# The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in
# base-10. Only the first number is divisible by 5, so answer[0] is true.
#
#
# Example 2:
#
#
# Input: [1,1,1]
# Output: [false,false,false]
#
#
# Example 3:
#
#
# Input: [0,1,1,1,1,1]
# Output: [true,false,false,false,true,false]
#
#
# Example 4:
#
#
# Input: [1,1,1,0,1]
# Output: [false,false,false,false,false]
#
#
#
#
# Note:
#
#
# 1 <= A.length <= 30000
# A[i] is 0 or 1
#
#
#
class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
n = 0
for i in range(len(A)):
A[i], n = (2 * n + A[i]) % 5 == 0, (2 * n + A[i]) % 5
return A
# for i in range(1, len(A)):
# A[i] += A[i - 1] * 2 % 5
# return [a % 5 == 0 for a in A]
|
c52e05d6bd83536bfcdad407984a23dcfe5f8f1e | apatti/csconcepts | /sorting/bubblesort/python/bubbleSort.py | 276 | 3.71875 | 4 | #bubble sort
def Sort(input: list) -> list:
for k in range(len(input)-1):
for i in range(len(input)-k-1):
if input[i]>input[i+1]:
temp = input[i+1]
input[i+1] = input[i]
input[i] = temp
return input
|
d84f18872421c1e8590ea6c52c4870e1e065e475 | toliveirac/Alura | /Python/Parte 03/playlist.py | 2,158 | 3.796875 | 4 | # Classe mãe, que contem os atributos comuns as classes Filmes e Séries
class Programa:
# Método init parâmetros
def __init__(self, nome, ano): ##Inicialização de valores, self = proprio object
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
@property
def nome(self):
return self._nome
@nome.setter
def nome(self, novo_nome):
self._nome = novo_nome.title()
def dar_like(self):
self._likes += 1
class Filme(Programa):
# Método init parâmetros
def __init__(self, nome, ano, duracao): ##Inicialização de valores, self = proprio object
super().__init__(nome, ano)
self.duracao = duracao
def imprime(self):
print(f'{self.nome} - {self.ano} - {self.duracao} min - {self.likes} likes')
class Serie(Programa):
# Método init parâmetros
def __init__(self, nome, ano, temporadas): ##Inicialização de valores
super().__init__(nome, ano) # chama parâmetros da classe mãe
self.temporadas = temporadas
def imprime(self):
print(f'{self.nome} - {self.ano} - {self.temporadas} temporadas - {self.likes} likes')
class programas_Playlist:
pass
class playlist:
def __init__(self, nome,programas):
self.nome = nome
self.programas = programas
def tamanho(self):
return len(self.programas)
## Criando objetos
vingadores = Filme('Vingadores - Guerra Infinita', 2018, 160)
B99 = Serie('Brookling 99', 2010, 9)
NovaOnda_Imperador = Filme('A nova onda do imperador', 2005, 80)
Anne = Serie('Anne with an E', 2018, 3)
vingadores.dar_like()
NovaOnda_Imperador.dar_like()
Anne.dar_like()
Anne.dar_like()
Anne.dar_like()
Anne.dar_like()
Anne.dar_like()
Anne.dar_like()
Anne.dar_like()
B99.dar_like()
B99.dar_like()
# Criando uma lista
list_Filmes_e_Series = [vingadores, B99, Anne, NovaOnda_Imperador]
play = playlist('Final de Semana', list_Filmes_e_Series)
for programa in play.programas:
programa.imprime()
|
5d775319065502ed26a147b620286113b8c72207 | Valinor13/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 843 | 4.21875 | 4 | #!/usr/bin/python3
"""
A module to store simple functions for testing
...
Functions
---------
add_integer(a, b=98)
Returns two integers or floats added together
Exceptions
----------
raise : TypeError
Raises a TypeError if a or b are not int or float
"""
def add_integer(a, b=98):
"""A function to safely add two integers
If the argument b isn't passed in, the default 98 is used
Parameters
----------
a : int, float
the first number to add
b : int, float
the second number to add (default is 98)
"""
if not isinstance(a, (int, float)):
raise TypeError("a must be an integer")
if not isinstance(b, (int, float)):
raise TypeError("b must be an integer")
if type(a) is float:
a = int(a)
if type(b) is float:
b = int(b)
return a + b
|
76c67e1df93f7887796581793be854046634537a | GriffinBabe/ARSWA | /tournament.py | 5,088 | 3.59375 | 4 | #Tournament Mode
if gamemode == 't':
#Loadings
players_number = 0
players_number_text_count = 1
players_list = []
players_classes = []
players_wins = []
eliminated = []
existing_tree_players_number = [2,4,8,16]
tree_plat
pools_best_of = 0
brackets_best_of = 0
pools_eliminations = 0
players_to_eliminate_number = 0
#Options
while True:
players_number = raw_input('How many players are there: ')
if type(players_number) == int:
if players_number <= max_players:
break
else:
print('Invalid or too big number of players (max 16)...')
while True:
pools_best_of = raw_input('Best of for pools (odd number): ')
if pools_best_of in existing_best_of:
break
else:
print('Invalid or too big number: ')
while True:
brackets_best_of = raw_input('Best of for brackets (odd number): ')
if pools_best_of in existing_best_of:
break
else:
print('Invalid or too big number: ')
#Choosing Names and Classes
for i in range(players_number):
pName = print('Player '+players_number_text_count+' name: ')
if pName in antoine_names:
print('\nGRIFFON PUTAIN !')
print('+ mention: casu\n')
if pName in simon_names:
print('\nJ\'ai essaye de mettre des caracteres en chinois mais Python les accepte pas et j\'ai la flemme de chercher')
print('+ mention: Robot\n')
if pName in igor_names:
print('\nO Igorus, deuxiemme createur du jeu')
print('+ mention: Ce dieux la est special, sur les 7 jours il n\'a travaille que dans 3 parce qu\'il est paresseux\n')
if pName in alexandre_names:
print('\nBeta testeur numero 1, attention les gars !')
print('+ mention: tchiiiip\n')
if pName in antoni_names:
print('\nSi il est numero 1 on dit que ca compte pas, ok les gars?')
print('+ mention: FAP FAP FAP FAP FAP\n')
if pName in darius_names:
print('\nO Darius, createur du jeu, qui se suce la bite langoureusement')
print('+ mention: GRIFFON PUTAIN !!\n')
while True:
pClass = raw_input('Player '+players_number_text_count+' class ?')
if pClass in existing_class:
break
else:
print('Class doesn\'t exists... ')
players_number_text_count += 1
players_list.append(pName)
players_classes.append(pClass)
players_class_dict = {}
#Creating a name:class dictionary
for i in range(len(players_list)):
players_class_dict[players_list[i]] = players_classes[i]
#Creating the wins list
for i in range(len(players_list)):
players_wins.append(0)
#Pool eliminations
while True:
for i in range(len(existing_tree_players_number)):
if players_number = existing_tree_players_number:
players_to_eliminate_number = 0
break
if players_number > existing_tree_players_number:
players_to_eliminate_number = players_number - existing_tree_players_number[i]
break
still_playing_players = players_list
while players_to_eliminate > 0:
still_playing_players_number = len(still_playing_players)
not_played_players = still_playing_player
print('Now we have to eliminate '+players_to_eliminate_number+' player(s)')
print('Crating match pairs...')
while len(not_played_players) > 0:
not_played_players_number = len(not_played_players)
p1Name = not_played_players[random.randint(0,not_played_players_number-1)]:
not_played_players.remove(p1Name)
p2Name = not_played_players[random.randint(0,not_played_players_number-1)]:
not_played_players.remove(p2Name)
rounds_to_win = int(math.ceil(pools_best_of/float(2)))
print('For this match we have '+p1Name+' against '+p2Name+'.')
while True:
localp1Wins = 0
localp2Wins = 0
winner = main(players_class_dict[p1Name],players_class_dict[p2Name],p1Name,p2Name,rounds_to_win,localp1Wins,localp2Wins)
if winner == p1Name:
players_wins[players_names.index(p1Name)] += 1
localp1Wins += 1
if winner == p2Name:
players_wins[players_names.index(p2Name)] += 1
localp2Wins += 1
if localp1Wins == rounds_to_win or localp2Wins == rounds_to_wins:
break
still_playing_players, players_wins = order_list(still_playing_players, players_wins)
print('--------------------Score Board----------------')
for i in len(still_playing_players):
print((i+1)+'. '+still_playing_players[i]+' score: 'players_wins[i])
for i in range(len(still_playing_players)-players_to_eliminate-1,len(still_playing_players)-2):
if players_wins[i] == players_wins[i+1]:
print('We have '+still_playing_players[i]+' and '+still_playing_players[i+1]+' having the same amount of wins, let\'s match them')
while True:
localp1Wins = 0
localp2Wins = 0
p1Name = still_playing_players[i]
p2Name = still_playing_players[i+1]
winner = main(players_class_dict[p1Name],players_class_dict[p2Name],p1Name,p2Name,rounds_to_win,localp1Wins,localp2Wins)
if winner == p1Name:
localp1Wins += 1
if winner == p2Name:
localp2Wins += 1
|
5b89a9c4fe809df926f13fd0b762c12b42c418ff | bakunobu/exercise | /1400_basic_tasks/chap_7/7_16.py | 982 | 4 | 4 | def give_num(text:str='Введите число: ') -> float:
while True:
try:
a = float(input(text))
return(a)
except ValueError:
print('Используйте только числа (разделитель - \'.\')')
def is_sum_bigger(n:int, lim:float) -> bool:
total = 0
for x in range(n):
i = give_num()
total += i
return(total <= lim)
def give_params() -> tuple:
while True:
try:
n = int(give_num('Укажите длину последоваельности'))
break
except ValueError:
print('Используйте только целые числа')
while True:
try:
lim = give_num('Укажите ограничение')
except ValueError:
print('Используйте только целые числа')
return(is_sum_bigger(n, lim))
print(give_params())
|
ec6a6541c3bdbe563b327eb9512f5b24cfabb373 | ursu1964/Libro2-python | /Cap1/Ejemplo 1_5.py | 3,240 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
@author: guardati
Ejemplo 1_5
Copia de listas: ejemplo de uso de funciones del módulo copy.
"""
import copy
# =============================================================================
# Ejemplos de copias superficiales y profundas de listas con datos inmutables.
# =============================================================================
dias_laborables = ["lunes", "martes", "miércoles", "jueves", "viernes"]
precios = [205.30, 107.18, 25, 450, 310.89]
dias = copy.copy(dias_laborables) # Copiado superficial.
print('\nListas luego de la copia superficial'.upper())
print('Lista original:', dias_laborables)
print('Copia:', dias)
# Se modifica la lista original y la copia.
dias_laborables.pop(0)
dias.remove('viernes')
tit1 = '''\nListas luego de hacer modificaciones en ambas:
cada una conserva sus cambios.'''.upper()
print(tit1)
print('Lista original:', dias_laborables)
print('Copia:', dias)
copia_precios = copy.deepcopy(precios) # Copiado profundo.
print('\nListas luego de la copia profunda'.upper())
print('Lista original:', precios)
print('Copia:', copia_precios)
# Se modifica la lista original y la copia.
precios.append(720.14)
copia_precios.pop(2)
print(tit1)
print('Lista original:', precios)
print('Copia:', copia_precios)
# =============================================================================
# Ejemplos de copias superficiales y profundas de listas con datos
# mutables (listas).
# =============================================================================
lista1 = [[2, 3], [9, 8]] # Lista formada por elementos mutables.
copial1= copy.copy(lista1) # Copiado superficial.
print('\nListas luego de la copia superficial'.upper())
print('Lista original:', lista1)
print('Copia:', copial1)
# Se modifica el primer elemento de la lista que es, a su vez,
# el primer elemento de lista1. El valor 2 se reemplaza por el valor 25.
lista1[0][0] = 25
tit2 = '''\nListas luego de la modificación de la lista original:
ambas listas reflejan el cambio'''.upper()
print(tit2)
print('Lista original:', lista1)
print('Copia:', copial1)
lista2 = [['verde', 'rojo'], ['blanco', 'azul']]
copial2= copy.deepcopy(lista2) # Copiado profundo.
print('\nListas luego de la copia profunda'.upper())
print('Lista original:', lista2)
print('Copia:', copial2)
# Se modifica el primer elemento de la lista que es, a su vez, el primer
# elemento de lista2: el valor verde se reemplaza por el valor amarillo.
lista2[0][0] = 'amarillo'
tit3 = '''\nListas luego de la modificación de la lista original:
solo la original se afectó'''.upper()
print(tit3)
print('Lista original:', lista2)
print('Copia:', copial2)
# =============================================================================
# Copiado de listas por medio de partir o dividir listas (slice).
# Igual efecto que el copiado superficial.
# =============================================================================
lis1 = lista1[:]
print('\nListas luego del slice'.upper())
print('Lista original:', lista1)
print('Copia:', lis1)
lista1[0][0] = 92
print(tit2)
print('Lista original:', lista1)
print('Copia:', lis1) |
891d46105b104c8f141eccdafe8269bd18fff080 | kumbharswativ/Core2Web | /Python/DailyFlash/19mar2020/MySolutions/program4.py | 345 | 3.734375 | 4 | '''
write a program to print the following pattern
1 2 3 4 5 6 7
7 6 5 4 3
3 4 5
5
'''
num=1
for i in range(4):
v=num
for j in range(7):
if(j-i<=-1 or i+j>=7):
print(" ",end=" ")
else:
if(i%2==0):
print(num ,end=" ")
num+=1
else:
num-=1
print(num,end=" ")
print(" ")
v=num-1
|
8f2c36c2eb3b0604313b31db0cb812de0f3d659b | willpiam/oldPythonCode | /PlayingWithFiles.py | 878 | 4.40625 | 4 | #William... Febuary 8th 2016
#program will show
#1. how to creat a .txt file
#2. How to write to a .txt file
#3. how to read from a text file
#1 and 2
f = open("test.txt","a") #opens file with name of "test.txt" if does file does not excist this line creates it
f.write("New End")
f.close()
#3
#this reads only first line
file = open('test.txt', 'r')
print file.readline();#number in () indicates number of charecters to read
#this seems to read all lines
file = open('test.txt', 'r')
print file.readlines()
#does it more clean
file = open('test.txt', 'r')
for line in file:
print line,
"""please note: this program doesn't really do anything usefull. It
was made as a demonstration. Parts of it are useful for other programs.
Also note that the file it creates or scans is always in the same directory as
the program itself
"""
|
f57c3ed7d91231623ed4ce8cb2ffc235f5c8f198 | NastyaZotkina/STP | /lab3.py | 178 | 3.765625 | 4 | a= int (input("Введите число 1 "))
b= int (input("Введите число 2 "))
print("a+b =", a+b)
print("a-b =", a-b)
print("a*b =", a*b)
print("a/b =", a/b) |
96fd4155c6fd3484a2721d323700e6017daed05a | Uriell77/PostulacionIsep | /hello_world.py | 643 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
# Jueves 12 de Noviembre de 2020
# Test de Conocimiento del lenguaje de Programacion Python
# Luis Hermoso
# 1. Escribe una funcion que devuelva la cadena "Hola, mundo!"; esta debera requerir 2 parametros tipo cadena, "Hola" y "Mundo", tambien deberas realizar un print de la cadena devuelta
def hola_mundo(Hola, Mundo):
#imprime una cadena conformada por dos parametros con el formato "Hola, mundo!"
Hola = Hola.capitalize()# el resultado debe tener el primer caracter mayuscula
Mundo = Mundo.lower() # la segunda entrada todo es minuscula
print('{}, {}!'.format(Hola, Mundo))
|
8bd558a82f6e6868b19968e107348dcc90f85fda | agermain/Kattis | /Python 3/Whatdoesthefoxsay.py | 268 | 3.59375 | 4 | for i in range(int(input())):
sounds = input().split()
while True:
s = input().split()
if s[0] == "what":
break
else:
sounds = list(filter((s[2]).__ne__, sounds))
print(' '.join(str(x) for x in list(sounds))) |
25f01f4be06fd277be72a3508505743284c7f573 | neo4reo/euler | /eulerlib.py | 3,021 | 3.84375 | 4 | '''
The purpose of this module is to collect functions that
are useful for solving project euler problems. For example,
many of the euler problems invole primes, hence many prime
functions are collected here.
Code aggregated and/or written by Justin Ethier
'''
#import itertools
import math
from functools import reduce
def primes(n):
'''
Find all primes less than n
Example of usage:
nums = primes(2000000)
sum = 0
for x in nums:
sum = sum + x
'''
if n==2: return [2]
elif n<2: return []
s=list(range(3,n+1,2))
mroot = n ** 0.5
half=(n+1)/2-1
i=0
m=3
while m <= mroot:
if s[i]:
j=(m*m-3)/2
#print(int(j))
if int(j) < len(s): s[int(j)]=0
while j<half:
#print(int(j))
if int(j) < len(s): s[int(j)]=0
j+=m
i=i+1
m=2*i+3
return [2]+[x for x in s if x]
# from stack overflow:
#Once you have the prime factorization, figuring out how many factors there are is straightforward. Suppose the prime factors are p1, p2, ..., pk and they are repeated m1, m2, ..., mk times. Then there are (1+m1)(1+m2)...(1+mk) factors
import operator
# A slightly efficient superset of primes.
def PrimesPlus():
yield 2
yield 3
i = 5
while True:
yield i
if i % 6 == 1:
i += 2
i += 2
# Returns a dict d with n = product p ^ d[p]
def GetPrimeDecomp(n):
d = {}
primes = PrimesPlus()
for p in primes:
while n % p == 0:
n /= p
d[p] = d.setdefault(p, 0) + 1
if n == 1:
return d
def NumberOfDivisors(n):
'''
Find the number of divisors of the given number
'''
d = GetPrimeDecomp(n)
powers_plus = map(lambda x: x+1, d.values())
return reduce(operator.mul, powers_plus, 1)
# end stack overflow
def GetPrimeFactors(n):
d = []
primes = PrimesPlus()
for p in primes:
while n % p == 0:
n /= p
d.append(p) #d[p] = d.setdefault(p, 0) + 1
if n == 1:
return d
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
def is_pandigital(n):
''' Determine if integer n is pandigital'''
l = list(str(n))
l.sort()
for i in range(0, len(l)):
if l[i] != str(i+1):
return False
return True
def nCr(n, r):
''' nCr (n choose r) probability function '''
return fac[n] / (fac[r] * fac[n - r])
|
9bdaab47c9a7ea8766ac2a1f3c864a76a08fe2de | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4005/codes/1635_2703.py | 110 | 3.578125 | 4 | idade= int(input("idade:"))
if (idade>=18):
mensagem="eleitor"
else:
mensagem="nao_eleitor"
print(mensagem) |
e8f80a07267065161cc2a7f744b38df2fbbfa78f | hieudtrinh/leetcode_python | /facebook_questions/arrays/group_by_caesar_cipher/GroupStringsByCaesarCipher.py | 1,166 | 3.96875 | 4 | from collections import defaultdict
alphabet = 'abcdefghijklmnopqrstuvwxyz'
# Idea
# 1) find the base 'anagram' for each string
# 2) put in dictionary[anagram] = string
# 3) return the values in the dictionary, where value is a list
def group_caesar(los):
dict = defaultdict(list)
# i is index base 0
# str is the value of string in 'los' list of string
for i, str in enumerate(los):
# for each char 'c' in 'str', find their index where char 'a' is 0
# and create a array index
# Example: str = "dac", then pos = [3, 0, 2]
# str = "ebd", then pos = [4, 1, 3]
pos = [alphabet.index(c) for c in str]
minPos = min(pos)
# pos = [3, 0, 2], minPos = 0
# pos = [4, 1, 3], minPos = 1
pos = [num - minPos for num in pos]
# pos = [3, 0, 2], minPos = 0, pos = [3, 0, 2]
# pos = [4, 1, 3], minPos = 1, pos = [3, 0, 2]
# there for "dac" and "ebd" have the same anagram
# and group them together
dict[tuple(pos)].append(str)
return dict.values()
print(group_caesar(["dac", "ebd", "abc", "bcd", "acd", "dfg", "ace", "bdf", "random"])) |
2463fe13482886c203bb7b93e01a3ce964ae8117 | TeamAIoT/python-tutorial | /5.Python_반복문/실습코드/pr05_06.py | 102 | 3.59375 | 4 | for i in range(2,10):
for j in range(1,10):
print(i,'x',j,'=',j*i,end='\t')
print() |
52ed31548e782714afcb5b6615138f3c4239be16 | melissaarliss/python-course | /hw/hw-5/problem2.py | 679 | 3.953125 | 4 | employees = [
{
"name": "Ron Swanson",
"age": 55,
"department": "Management",
"phone": "555-1234",
"salary": "100,000"
},
{
"name": "Leslie Knope",
"age": 45,
"department": "Middle Management",
"phone": "555-4321",
"salary": "90,000"
},
{
"name": "Andy Dwyer",
"age": 30,
"department": "Shoe Shining",
"phone": "555-1122",
"salary": "50,000"
},
{
"name": "April Ludgate",
"age": 25,
"department": "Administration",
"phone": "555-3345",
"salary": "60,000"
}
]
for i in range(len(employees)):
name = employees[i]["name"]
department = employees[i]["department"]
phone = employees[i]["phone"]
print(f"{name} in {department} can be reached at {phone}.")
|
8258d9f571f9f53b6eb20bf82754b4396f2ecede | wcwagner/Algorithms | /COP4531/missingval.py | 661 | 3.671875 | 4 | import math
def find_missing_val(A):
# case that n+1 is missing
if A[len(A) - 1] == len(A) - 1:
return len(A)
hi = len(A) - 1
lo = 0
mid = 0
while mid < hi:
mid = int(math.ceil((float(hi) + float(lo)) / 2))
print(lo, mid, hi)
if A[hi] - A[mid] > hi - mid:
lo = mid
elif A[mid] - A[lo] > mid - lo:
hi = mid
return hi + 1
if __name__ == "__main__":
# 7
print(find_missing_val([0, 1, 2, 3, 4, 5, 6]))
# 2
print(find_missing_val([0, 1, 3, 4, 5, 6, 7]))
# 5
print(find_missing_val([0, 1, 2, 3, 4, 6, 7]))
print(find_missing_val([0]))
|
c1325ad661df940716ce4b2fe13ae75d4b98d957 | janhavik/my_projects | /Course 3/Week 1/week1_prims.py | 3,176 | 3.890625 | 4 | from heappractice import Heap
from math import isinf
import os
import pprint
# filename = "F:\\Learning\\coursera\\Algorithms Exercises\\stanford-algs\\testCases\\course3\\assignment1SchedulingAndMST\\question3\\input_random_2_10.txt"
filename = "edges.txt"
def readGraph(filename):
with open(filename) as fp:
lines = fp.readlines()
num_nodes, num_edges = int(lines[0].split(
" ")[0]), int(lines[0].split(" ")[1])
graph = {everynode: [] for everynode in range(1, num_nodes + 1)}
for everyline in lines[1:]:
everyline = everyline.strip().split(" ")
graph[int(everyline[0])].append([int(everynum)
for everynum in everyline[1:]])
graph[int(everyline[1])].append(
[int(everyline[0]), int(everyline[-1])])
return (num_nodes, graph)
def MST_Prim(graph, num_nodes, source):
Q = Heap()
distance_mst = 0
visited_nodes = [False] * num_nodes
MST = []
i = 0
current_vertex = source
while i < num_nodes:
# process if vertex not visited by mst
if not visited_nodes[current_vertex - 1]:
# print "Unvisited", current_vertex
visited_nodes[current_vertex - 1] = True
# push this into the heap and extract min and set that as the current vertex
nodes_current_vertex = graph[current_vertex]
for everynode in nodes_current_vertex:
Q.insertKey((everynode[-1], everynode[-2], current_vertex))
# extract min
next_vertex = Q.extractMin()
# if vertex is new then add to the MST
if not visited_nodes[next_vertex[1] - 1]:
MST.append((next_vertex[1], next_vertex[0]))
current_vertex = next_vertex[1]
i = i + 1
else:
# if it is univisted, remove it from consideration next by extracting
# print "Visited", current_vertex
next_vertex = Q.extractMin()
if not visited_nodes[next_vertex[1] - 1]:
MST.append((next_vertex[1], next_vertex[0]))
current_vertex = next_vertex[1]
MST.insert(0, (source, 0))
return (MST, sum([w[-1] for w in MST]))
num_nodes, graph = readGraph(filename)
print MST_Prim(graph, num_nodes, 1)
# -3612829
# pathdir = "F:\\Learning\\coursera\\Algorithms Exercises\\stanford-algs\\testCases\\course3\\assignment1SchedulingAndMST\\question3"
# resultdir = open("Results.txt", "w")
# for everyele in os.listdir(pathdir):
# if "input" in everyele:
# num_nodes, graph = readGraph(os.path.join(pathdir, everyele))
# print everyele
# with open(os.path.join(pathdir, everyele.replace("input", "output"))) as fp1:
# result_required = int(fp1.read().strip())
# distances = MST_Prim(graph, num_nodes, 1)
# resultdir.write("Result=%s, Filename=%s, Required=%s, Obtained=%s \n" %
# (result_required == distances[-1], everyele, result_required, distances[-1]))
# # print everyele, result_required == comparisons
# resultdir.write("\n")
|
7b4a286b432372a602120a3cde98a8e8a47d9ad0 | khagendra1998/Coding-Problems | /Solution1.py | 263 | 3.734375 | 4 | #The Beginning of Everything
test_case = int(input())
for i in range(test_case):
s = str(input())
a = "ldrwolloeh"
#a = "".join(sorted(a))
if("".join(sorted(s)) == "".join(sorted(a))):
print("Yes\n")
else:
print("No\n")
|
d2bde4fd64582370ce8d147f5ec1640a724ddb5e | KonstantinKlepikov/all-python-ml-learning | /python_learning/oop_lutz.py | 1,381 | 4.34375 | 4 | class FirstClass:
"""Empty class
"""
def setdata(self, value):
"""Class method
Args:
value (any type): example of class attribute
"""
self.data= value
def display(self):
"""Print class attribute
"""
print(self.data)
class SecondClass(FirstClass):
"""Example of class inheritans
"""
def display(self):
"""Redifinition of method, that print class attribute
"""
print('Value of self.data is {0}'.format(self.data))
class ThirdClass(SecondClass):
"""Example of class inheritans
"""
def __init__(self, value):
"""Example of class constructor
Args:
value (any type): example
"""
self.data = value
def __add__(self, other):
"""Redifinition of operathor +
Args:
other (any type): example
Returns:
object: exemplar of ThirdClass
"""
return ThirdClass(self.data + other)
def __str__(self):
"""Difinition for print(seif)
Returns:
str: information about class attribute
"""
return 'ThirdClass: {0}'.format(self.data)
def mul(self, other):
"""Changes in place - example of named method
Args:
other (any type): example
"""
self.data *= other
|
0bd117bbc87a27386eb24d83568d7c3bc3fde02b | hellokathy/MarketSim | /testAgent.py | 3,337 | 3.546875 | 4 | from agent import *
import unittest
HUNGRY_UTIL = {"apple": 10, "orange": 9,
"water": 2, "land": 3, "clothes": 1, "money": 1}
THIRSTY_UTIL = {"apple": 1, "orange": 2,
"water": 8, "land": 2, "clothes": 1, "money": 1}
""" random_sample returns a random sample of an inventory set. avg_count is the number of items to expect on average"""
def random_sample(set, avg_count):
sample = inventory(dict())
for good in set.collection:
for item in xrange(set.collection[good]):
rand = random.random()
value = float(1) / self.count() * avg_count
if (rand < value):
sample.addItem(good)
return sample
""" generateRandomSet generates a set of random goods in random quantities """
def generateRandomSet():
randomSet = dict()
for good in ALL_GOODS:
randomSet[good] = int(random.random() * 100)
return randomSet
class TestAgent(unittest.TestCase):
def setUp(self):
self.exchange = Exchange()
self.a = Agent()
self.a.introduceExchange(self.exchange)
self.b = Agent()
self.b.introduceExchange(self.exchange)
self.a.utility.collection = HUNGRY_UTIL
self.b.utility.collection = THIRSTY_UTIL
def test_getWealthAndGetTotalWealth(self):
self.a.addInv("orange", 5)
self.a.addInv("orange", 5)
self.a.addInv("apple", 5)
self.assertTrue(self.a.getWealth() == 140)
self.b.addInv("money", 5)
self.assertTrue(self.b.getWealth() == 5)
self.assertTrue(Agent.getTotalWealth([self.a, self.b]) == 145)
def test_logCreated(self):
import os
filename = "/tmp/marketsim/agent/" + str(self.a.id) + ".log"
self.assertTrue(os.path.isfile(filename))
infile = open(filename, 'r')
firstLine = infile.readline()
self.assertTrue(firstLine == "Agent created\n")
def test_errorWhenRemovingTooMany(self):
self.a.addInv("orange", 5)
self.assertRaises(InventoryException, self.a.removeInv, "orange", 6)
def test_errorWhenAddingOrRemovingNegativeQuantities(self):
self.assertRaises(InventoryException, self.a.removeInv, "orange", -6)
self.assertRaises(InventoryException, self.a.addInv, "orange", -6)
def test_simpleAddAndRemove(self):
self.a.addInv("orange", 5)
self.a.addInv("orange", 5)
self.a.addInv("apple", 1)
self.assertTrue(self.a.getInv("orange") == 10)
self.assertTrue(self.a.getInv("apple") == 1)
self.a.removeInv("orange", 5)
self.a.removeInv("apple", 1)
self.assertTrue(self.a.getInv("orange") == 5)
self.assertTrue(self.a.getInv("apple") == 0)
self.a.removeInv("orange", 5)
self.assertTrue(self.a.getInv("orange") == 0)
def test_removeExchange(self):
self.a.addInv("orange", 5)
self.assertTrue(len(self.a.exchange.markets) == 7)
self.assertTrue(self.a.exchange.getMarket("orange").isEmpty() == False)
self.a.removeExchange(self.exchange)
self.assertTrue(self.a.exchange == None)
self.assertTrue(self.exchange.getMarket("orange").isEmpty() == True)
def test_addExchange(self):
self.a.removeExchange(self.exchange)
# Test needed for flushing agent from marketl
|
9491c24653c9333643b3d7b47491868cb3d150ea | JackRossProjects/Computer-Science | /u1m1.py | 11,664 | 4.15625 | 4 | from __future__ import print_function, division
import os
import sys
# CS31 U1M1
# Part 1
'''
1.) How many seconds are there in 21 minutes and 15 seconds?
2.) How many miles are there in 5 kilometers?
3.) If you run a 5 kilometer race in 21 minutes and 15 seconds,
what is your average pace (time per mile in minutes and seconds)?
4.) What is your average speed in miles per hour?
5.) Suppose the cover price of a book is $19.95, but bookstores get a
25% discount. Shipping costs $2.50 for the first copy and $1 for each additional copy.
What is the total wholesale cost for 75 copies?
'''
print("Part 1")
# 1
min = 21
sec = 15
print((min * 60) + sec)
# 2
km = 5
conversion = 0.62137119
miles = km * conversion
print(miles)
# 3
avg_sec = miles / ((min * 60) + sec)
avg = avg_sec / 60
print(avg)
# 4
mph = avg * .21
print(mph)
# 5
copies = 75
price = 19.95
discount = .75
shipping = (2.50 + (copies - 1))
total = ((price * discount) * copies) + shipping
print(total)
# Part 2
print("Part 2")
''' A function object is a value you can assign to a variable or pass as an argument.
For example, do_twice is a function that takes a function object as an argument
and calls it twice:
def do_twice(f):
"""
Takes a function and executes it twice.
"""
f()
f()
Here’s an example that uses do_twice to call a function named print_spam twice:
def print_spam():
print('spam')
do_twice(print_spam)
1.) Type this example into a script and test it.
2.) Change do_twice so it takes two arguments, a function object and a value, and calls the function
twice, passing the value as an argument.
3.) Define a function called print_twice that takes one argument and prints the value of that argument twice.
4.) Use the changed version of do_twice to call print_twice twice, passing 'spam' as an argument.
5.) Define a new function called do_four that takes a function object and a value and calls
the function four times, passing the value as a parameter. There should be only two
statements in the body of this function, not four.
'''
# 1-5
def do_twice(func, arg):
"""Runs a function twice.
func: function object
arg: argument passed to the function
"""
func(arg)
func(arg)
def print_twice(arg):
"""Prints the argument twice.
arg: anything printable
"""
print(arg)
print(arg)
def do_four(func, arg):
"""Runs a function four times.
func: function object
arg: argument passed to the function
"""
do_twice(func, arg)
do_twice(func, arg)
do_twice(print, 'spam')
print('')
do_four(print, 'spam')
# Part 3
'''
Fermat’s Last Theorem says that there are no positive integers a, b, and c such that:
a**n + b**n == c**n
for any values of n greater than 2.
1.)" Write a function named check_fermat that takes four parameters—a, b, c and n —and checks to see if
Fermats theorem holds. If n is greater than 2 and a**n + b**n = c**n the program should print,
"Holy smokes, Fermat was wrong!" Otherwise the program should print, "No, that doesn't work."
2.) Write a function that prompts the user to input values for a, b, c and n, converts them to integers,
and uses check_fermat to check whether they violate Fermat’s theorem.
'''
# SOLUTION:
# Other:
print("Hello, World!")
x = 2 ** 65536
print(x)
"""
Python is a strongly-typed language under the hood, which means
that the types of values matter, especially when we're trying
to perform operations on them.
Note that if you try running the following code without making any
changes, you'll get a TypeError saying you can't perform an operation
on a string and an integer.
"""
x = 5
y = "7"
# Write a print statement that combines x + y into the integer value 12
print(x + int(y))
# Write a print statement that combines x + y into the string value 57
print(str(x) + y)
"""
In this exercise, you'll be playing around with the sys module,
which allows you to access many system specific variables and
methods, and the os module, which gives you access to lower-
level operating system functionality.
"""
# See docs for the sys module: https://docs.python.org/3.7/library/sys.html
# Print out the command line arguments in sys.argv, one per line:
print(f'Arguments: {len(sys.argv)}')
print(f'Argument List: {str(sys.argv)}')
# Print out the OS platform you're using:
print(f'Windows Version: {sys.version}')
# Print out the version of Python you're using:
print(f'Python Version: {sys.version_info}')
# See the docs for the OS module: https://docs.python.org/3.7/library/os.html
# Print the current process ID
print(f'Current Process ID: {os.getpid()}')
# Print the current working directory (cwd):
print(f'PWD: {os.getcwd()}')
# Print out your machine's login name
print(f"Machine's login name: {os.getlogin()}")
"""
Python provides a number of ways to perform printing. Research
how to print using the printf operator, the `format` string
method, and by using f-strings.
"""
x = 10
y = 2.24552
z = "I like turtles!"
# Using the printf operator (%), print the following feeding in the values of x,
# y, and z:
# x is 10, y is 2.25, z is "I like turtles!"
print("x is %i, y is %f, z is \"%s\"" %(x , y, z))
# Use the 'format' string method to print the same thing
print("x is {}, y is {}, z is \"{}\"".format(x, y, z))
# Finally, print the same thing using an f-string
print(f"x is {x}, y is {y}, z is \"{z}\"")
"""
Python provides a number of ways to perform printing. Research
how to print using the printf operator, the `format` string
method, and by using f-strings.
"""
x = 10
y = 2.24552
z = "I like turtles!"
# Using the printf operator (%), print the following feeding in the values of x,
# y, and z:
# x is 10, y is 2.25, z is "I like turtles!"
print("x is %i, y is %f, z is \"%s\"" %(x , y, z))
# Use the 'format' string method to print the same thing
print("x is {}, y is {}, z is \"{}\"".format(x, y, z))
# Finally, print the same thing using an f-string
print(f"x is {x}, y is {y}, z is \"{z}\"")
# For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
x.extend(y)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
x.remove(8)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
x.insert(-1, 99)
print(x)
# Print the length of list x
print(len(x))
# Print all the values in x multiplied by 1000
for i in x:
print(i * 1000)
"""
Python tuples are sort of like lists, except they're immutable and
are usually used to hold heterogenous data, as opposed to lists
which are typically used to hold homogenous data. Tuples use
parens instead of square brackets.
More specifically, tuples are faster than lists. If you're looking
to just define a constant set of values and that set of values
never needs to be mutated, use a tuple instead of a list.
Additionally, your code will be safer if you opt to "write-protect"
data that does not need to be changed. Tuples enforce immutability
automatically.
"""
# Example:
import math
def dist(a, b):
"""Compute the distance between two x,y points."""
x0, y0 = a # Destructuring assignment
x1, y1 = b
return math.sqrt((x1 - x0)**2 + (y1 - y0)**2)
a = (2, 7) # <-- x,y coordinates stored in tuples
b = (-14, 72)
# Prints "Distance is 66.94"
print("Distance is: {:.2f}".format(dist(a, b)))
# Write a function `print_tuple` that prints all the values in a tuple
def print_tuple(tuple):
"""This function will print the each value in a tuple on a seperate line."""
for t in tuple:
print(t)
t = (1, 2, 5, 7, 99)
print_tuple(t) # Prints 1 2 5 7 99, one per line
# Declare a tuple of 1 element then print it
u = (1,) # What needs to be added to make this work? The ','.
print_tuple(u)
"""
Python exposes a terse and intuitive syntax for performing
slicing on lists and strings. This makes it easy to reference
only a portion of a list or string.
This Stack Overflow answer provides a brief but thorough
overview: https://stackoverflow.com/a/509295
Use Python's slice syntax to achieve the following:
"""
a = [2, 4, 1, 7, 9, 6]
# Output the second element: 4:
print(a[1])
# Output the second-to-last element: 9
print(a[-2])
# Output the last three elements in the array: [7, 9, 6]
print(a[-3:])
# Output the two middle elements in the array: [1, 7]
print(a[2:4])
# Output every element except the first one: [4, 1, 7, 9, 6]
print(a[1:])
# Output every element except the last one: [2, 4, 1, 7, 9]
print(a[:-1])
# For string s...
s = "Hello, world!"
# Output just the 8th-12th characters: "world"
print(s[7:12])
"""
List comprehensions are one cool and unique feature of Python.
They essentially act as a terse and concise way of initializing
and populating a list given some expression that specifies how
the list should be populated.
Take a look at https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
for more info regarding list comprehensions.
"""
# Write a list comprehension to produce the array [1, 2, 3, 4, 5]
y = [i for i in range(5)]
print (y)
# Write a list comprehension to produce the cubes of the numbers 0-9:
# [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
y = [i ** 3 for i in range(9)]
print(y)
# Write a list comprehension to produce the uppercase version of all the
# elements in array a. Hint: "foo".upper() is "FOO".
a = ["foo", "bar", "baz"]
y = [i.upper() for i in a]
print(y)
# Use a list comprehension to create a list containing only the _even_ elements
# the user entered into list x.
x = input("Enter comma-separated numbers: ").split(',')
# What do you need between the square brackets to make it work?
y = [i for i in x if int(i)%2 == 0]
print(y)
"""
Dictionaries are Python's implementation of associative arrays.
There's not much different with Python's version compared to what
you'll find in other languages (though you can also initialize and
populate dictionaries using comprehensions just like you can with
lists!).
The docs can be found here:
https://docs.python.org/3/tutorial/datastructures.html#dictionaries
For this exercise, you have a list of dictionaries. Each dictionary
has the following keys:
- lat: a signed integer representing a latitude value
- lon: a signed integer representing a longitude value
- name: a name string for this location
"""
waypoints = [
{
"lat": 43,
"lon": -121,
"name": "a place"
},
{
"lat": 41,
"lon": -123,
"name": "another place"
},
{
"lat": 43,
"lon": -122,
"name": "a third place"
}
]
# Add a new waypoint to the list
waypoints.append({
"lat": 22,
"lon": 42,
"name": 'no where'})
# Modify the dictionary with name "a place" such that its longitude
# value is -130 and change its name to "not a real place"
# Note: It's okay to access the dictionary using bracket notation on the
# waypoints list.
waypoints[0].update({
"lon": -130,
"name": "not a real place"
})
# Write a loop that prints out all the field values for all the waypoints
for x in waypoints:
for key in x:
print(key, '->', x[key])
# Write a function is_even that will return true if the passed-in number is even.
def is_even(num):
return num % 2 == 0
# Read a number from the keyboard
num = input("Enter a number: ")
num = int(num)
# Print out "Even!" if the number is even. Otherwise print "Odd"
if is_even(num) == True:
print('Even!')
else:
print('Odd') |
6a6d0907ffe8e48826f8b10855f5038044252dc3 | ljsuo/ProjectEulerProblems | /projeuler6.py | 412 | 3.796875 | 4 | #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
def diff(num):
sum_first = 0
sq_first = 0
index1 = 1
sum_first = index1 + num
sum_first *= num
sum_first = sum_first / 2
while index1 <= num:
sq_first += index1**2
index1 += 1
sum_first = sum_first**2
print(sum_first - sq_first)
diff(100)
|
be97a60c7318cc798057651c618e7c4818b07a86 | rallen0150/class_notes | /new_prac/nfl_draft.py | 839 | 3.59375 | 4 | from bs4 import BeautifulSoup
import time
import requests
round_num = input("What round would you like to see:\n>")
url = "http://www.espn.com/nfl/draft/rounds/_/round/{}".format(round_num)
x = requests.get(url)
soup = BeautifulSoup(x.text, "html.parser")
# print(soup)
num = 1
print("Round {} of 2017 NFL Draft".format(round_num))
## This is the first way, just the name and college!
# for draftTable__headline in soup.find_all(class_="draftTable__playerInfo"):
# print(num, draftTable__headline.text.replace("\n", " ").strip())
# num+=1
## This is for the name, college and position
for draftTable__headline in soup.find_all(class_="draftTable__headline"):
## Way to get the team's initials
a = str(draftTable__headline.img).upper()
a = a[79:82]
print(a, draftTable__headline.text.replace("\n", " ").strip())
|
b9c814045ac1a56f1362fa942e69da660ce72df2 | jcotillo/princeton_algorithms | /week_4/heap_sort.py | 872 | 3.8125 | 4 | def heap_sort(arr):
n = len(arr)
# set up binary heap
for k in range(n/2, 0, -1):
sink(arr, k, n)
# order it now
while n > 1:
_exch(arr, 1, n)
n -= 1
sink(arr, 1, n)
return arr
def sink(arr, k1, k2):
while 2*k1 <= k2:
j = 2*k1
if j < k2 and _less(arr, j, j+1):
# j needs to be BIGGEST child node for exchange
j += 1
# another check. break out before exchange if parent is greater...
if not _less(arr, k1, j):
break
_exch(arr, k1, j)
k1 = j
def _less(arr, i, j):
# make it behave like it's 0 index
return arr[i-1] < arr[j-1]
def _exch(arr, i, j):
# make it behave like it's 0 index
arr[i-1], arr[j-1] = arr[j-1], arr[i-1]
if __name__ == '__main__':
print heap_sort([9,8,31, 401, 23,1, 43,12, 32, 35, 39])
|
29b5fed013fc7e42fb1573938626f9f57284570c | lygtmxbtc/learning_notebook | /data_structure/linked_list.py | 890 | 3.671875 | 4 | class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def reverse(self, head):
prev = None
# head不断向后遍历,将head的前一个元素作为下一个元素
# prev不断赋值新的head
while head:
tmp = head.next
head.next = prev
prev = head
head = tmp
return prev
class DoubleListNode:
def __init__(self, val):
self.val = val
self.prev = self.next = None
def reverse(self, head):
curt = None
# head不断向后遍历,将head的前一个元素作为下一个元素,head的后一个元素作为前一个元素
# curt负责赋值新的head
while head:
curt = head
head = curt.next
curt.next = curt.prev
curt.prev = head
return curt
|
dbbff9c767dea8860844dd8ee8e179d715356df8 | MehediMehi/LearnPython3 | /3. Variables objects and values/variable-numbers.py | 737 | 4.21875 | 4 | #!C:\Users\Mehedi Hasan Akash\Anaconda3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 19:43:51 2019
@author: Mehedi Hasan Akash
"""
def main():
num = 42 # integer number
print(type(num), num)
num = 42.0 # float number
print(type(num), num)
num = 42 / 9 # divide and get float value
print(type(num), num)
num = 42 // 9 # divide but get integer value
print(type(num), num)
num = round(42 / 9) # divide and get rounded integer value
print(type(num), num)
num = 42 % 9 # find remainder
print(type(num), num)
num = int(42.9) # convert into integer
print(type(num), num)
num = float(42) # convert into float
print(type(num), num)
if __name__ == "__main__": main() |
45ac8371c86c82b65f933a85ed56edf28d7d19f8 | anubeig/python-material | /MyTraining_latest/MyTraining/18.sorting_and_searching/QuickSort.py | 2,198 | 4.15625 | 4 | #http://interactivepython.org/courselib/static/pythonds/SortSearch/TheQuickSort.html
def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
if first<last:
splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
pivotvalue = alist[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
alist = [54,26,93,17,77,31,44,55,20]
quickSort(alist)
print(alist)
#https://pythonschool.net/data-structures-algorithms/quicksort/
# quick sort
def partition(myList, start, end):
pivot = myList[start]
left = start+1
# Start outside the area to be partitioned
right = end
done = False
while not done:
while left <= right and myList[left] <= pivot:
left = left + 1
while myList[right] >= pivot and right >=left:
right = right -1
if right < left:
done= True
else:
# swap places
temp=myList[left]
myList[left]=myList[right]
myList[right]=temp
# swap start with myList[right]
temp=myList[start]
myList[start]=myList[right]
myList[right]=temp
return right
def quicksort(myList, start, end):
if start < end:
# partition the list
split = partition(myList, start, end)
# sort both halves
quicksort(myList, start, split-1)
quicksort(myList, split+1, end)
return myList
def main():
myList = [7,2,5,1,29,6,4,19,11]
sortedList = quicksort(myList,0,len(myList)-1)
print(sortedList) |
e47ae328a31f9ece2d9fbdcd540adc587b789747 | gabriellaec/desoft-analise-exercicios | /backup/user_020/ch20_2020_03_04_18_39_09_893530.py | 255 | 3.546875 | 4 | # Exercicio 4
def preco_da_passagem(km):
if km <= 200:
preco = km*(0.5)
return preco
elif km > 200:
preco = km*(0.45)
return preco
a = int(input('Insira a distância da viagem em km: '))
print(preco_da_passagem(a)) |
916c3858ab34ea4766f247a571a36593d60868cd | takecian/ProgrammingStudyLog | /AtCoder/ABC/106/b.py | 201 | 3.796875 | 4 | # https://atcoder.jp/contests/abc106/tasks/abc106_b
def count_div(n):
return sum([n % i == 0 for i in range(1, n+1)])
N = int(input())
print(sum(count_div(i) == 8 for i in range(1, N + 1, 2)))
|
63f4ab590a17108c41d6f7ce3dd7b939be5d0f40 | rodrigodub/Moby | /moby.py | 13,338 | 3.578125 | 4 | #################################################
# Moby
# Moby Dick is a sailing simulator
# intended to cross the seven seas.
#
# Usage:
# > python3 moby.py
#
# v0.034
# Issue #7
# 20180217-20180306
#################################################
__author__ = 'Rodrigo Nobrega'
# import
import os
import sys
import pygame
from pygame.locals import *
import random
# import math
# Global variables
# sizes and position
SCREENSIZE = (1024, 576)
HUDLEFT = 5
HUDMIDDLE = 250
HUDRIGHT = 500
# colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
LIGHTGREY = (230, 230, 230)
BACKGROUND = (0, 171, 214)
# load image function
def load_image(file):
path = os.path.join('images', file)
return pygame.image.load(path).convert_alpha()
# image resize function
def resize_image(img, factor):
return pygame.transform.scale(img, (img.get_rect().width // factor, img.get_rect().height // factor))
# write text
def writetext(font, text, colour):
# colour: tuple (r, g, b)
a = font.render(text, 0, colour)
return a
# find the opposite of an angle (in degrees)
def opposite(angle):
if angle < 180:
return 180 + angle
else:
return angle - 180
# screen
class Screen(object):
"""Starts a screen and displays background"""
def __init__(self, image_file=None):
# physical parameters
self.size = SCREENSIZE
self.bgcolour = BACKGROUND
# the canvas
self.display = pygame.display.set_mode(self.size)
self.title = pygame.display.set_caption('Moby Dick')
# background image and its enclosing rectangle
if image_file:
self.image = load_image(image_file)
self.rect = self.image.get_rect()
else:
self.image = ''
self.rect = Rect(0, 0, 0, 0)
# show image
self.show()
def show(self):
# fill screen with solid colour
self.display.fill(self.bgcolour)
# blit background image
if self.image != '':
self.display.blit(self.image, (0, 0))
# the Heads Up Display
class Hud(object):
"""
The HUD (Heads Up Display) will show on screen all relevant information
"""
def __init__(self, fnt, scr):
self.left = ['Wind Direction', 'Wind Speed', 'Beaufort']
self.middle = ['Absolute Sail', 'Relative Sail', 'Point of Sail']
self.right = ['Heading', 'Tiller', 'Rudder']
self.initial(fnt, scr)
def initial(self, fnt, scr):
# HUD text
scr.display.blit(writetext(fnt, self.left[0], LIGHTGREY), (HUDLEFT, 5))
scr.display.blit(writetext(fnt, self.left[1], LIGHTGREY), (HUDLEFT, 20))
scr.display.blit(writetext(fnt, self.left[2], LIGHTGREY), (HUDLEFT, 35))
scr.display.blit(writetext(fnt, self.middle[0], LIGHTGREY), (HUDMIDDLE, 5))
scr.display.blit(writetext(fnt, self.middle[1], LIGHTGREY), (HUDMIDDLE, 20))
scr.display.blit(writetext(fnt, self.middle[2], LIGHTGREY), (HUDMIDDLE, 35))
scr.display.blit(writetext(fnt, self.right[0], LIGHTGREY), (HUDRIGHT, 5))
scr.display.blit(writetext(fnt, self.right[1], LIGHTGREY), (HUDRIGHT, 20))
scr.display.blit(writetext(fnt, self.right[2], LIGHTGREY), (HUDRIGHT, 35))
def draw(self, fnt, scr, wind, boat):
# clean
pygame.draw.rect(scr.display, BACKGROUND, (HUDLEFT + 95, 5, 140, 15), 0)
pygame.draw.rect(scr.display, BACKGROUND, (HUDLEFT + 95, 20, 140, 15), 0)
pygame.draw.rect(scr.display, BACKGROUND, (HUDLEFT + 95, 35, 140, 15), 0)
pygame.draw.rect(scr.display, BACKGROUND, (HUDMIDDLE + 90, 5, 140, 15), 0)
pygame.draw.rect(scr.display, BACKGROUND, (HUDMIDDLE + 90, 20, 140, 15), 0)
pygame.draw.rect(scr.display, BACKGROUND, (HUDMIDDLE + 90, 35, 140, 15), 0)
pygame.draw.rect(scr.display, BACKGROUND, (HUDRIGHT + 55, 5, 140, 15), 0)
# pygame.draw.rect(scr.display, BACKGROUND, (HUDRIGHT + 55, 20, 140, 15), 0)
# pygame.draw.rect(scr.display, BACKGROUND, (HUDRIGHT + 55, 35, 140, 15), 0)
# HUD values
scr.display.blit(writetext(fnt, ': {} deg'.format(wind.direction), LIGHTGREY), (HUDLEFT + 95, 5))
scr.display.blit(writetext(fnt, ': {:.1f} m/s'.format(wind.speed), LIGHTGREY), (HUDLEFT + 95, 20))
scr.display.blit(writetext(fnt, ': {}'.format(wind.beaufort), LIGHTGREY), (HUDLEFT + 95, 35))
scr.display.blit(writetext(fnt, ': {} deg'.format(boat.sailabsolute), LIGHTGREY), (HUDMIDDLE + 90, 5))
scr.display.blit(writetext(fnt, ': {} deg'.format(boat.sailangle), LIGHTGREY), (HUDMIDDLE + 90, 20))
scr.display.blit(writetext(fnt, ': {}'.format(boat.pointofsail), LIGHTGREY), (HUDMIDDLE + 90, 35))
scr.display.blit(writetext(fnt, ': {} deg'.format(boat.heading), LIGHTGREY), (HUDRIGHT + 55, 5))
scr.display.blit(writetext(fnt, ': 0', LIGHTGREY), (HUDRIGHT + 55, 20))
scr.display.blit(writetext(fnt, ': 0', LIGHTGREY), (HUDRIGHT + 55, 35))
# the Wind
class Wind(object):
"""
Everything related to the Wind.
Wind Speed measured in Knots.
"""
def __init__(self):
self.direction = random.randint(0, 360)
# limit speed to some Beaufort scale
self.maxspeed = 25
self.speed = round(random.random() * self.maxspeed, 1)
# Beaufort scale
self.beaufort = ''
# representation
self.image = load_image('windarrow30.png')
self.pos = self.image.get_rect()
self.pos.center = (100, 150)
def changedirection(self):
# changes direction smootly
if random.randint(0, 200) == 1:
self.direction += 2 * (random.randint(0, 2) - 1)
# occasionally changes radically
if random.randint(0, 5000) == 1:
self.direction = random.randint(0, 360)
# resets if crosses limit
if self.direction >= 360:
self.direction = self.direction - 360
if self.direction < 0:
self.direction = 360 + self.direction
def changespeed(self):
if random.randint(0, 200) == 1:
self.speed += round(random.random() * 0.6 - 0.3, 1)
# limit to maximum speed
if self.speed < 0:
self.speed = 0
if self.speed > self.maxspeed:
self.speed = self.maxspeed
def beaufortscale(self):
beau = {'Calm': 0.3, 'Light air': 1.5, 'Light breeze': 3.3, 'Gentle breeze': 5.5
, 'Moderate breeze': 7.9, 'Fresh breeze': 10.7, 'Strong breeze': 13.8
, 'High wind': 17.1, 'Gale': 20.7, 'Strong gale': 24.4, 'Storm': 28.4
, 'Violent storm': 32.6, 'Hurricane': 100}
self.beaufort = list(beau.keys())[list(beau.values()).index(min([i for i in beau.values() if self.speed < i]))]
def arrowsize(self):
# define the size of wind representation depending on wind speed
if self.speed < 0:
return 20
elif self.speed > 35:
return 200
else:
return int(5.14 * self.speed + 20)
def draw(self, scr):
# rotate and scale image
rot = pygame.transform.rotate(
pygame.transform.scale(self.image, (self.arrowsize(), self.arrowsize()))
, 360-self.direction)
rotrect = rot.get_rect()
rotrect.center = self.pos.center
# delete and redraw
pygame.draw.rect(scr.display, BACKGROUND, (0, 50, 200, 200), 0)
scr.display.blit(rot, rotrect)
def update(self):
self.changedirection()
self.changespeed()
self.beaufortscale()
# the Boat
class Boat(object):
"""Everything related to the boat"""
def __init__(self):
# image and position
self.imagegroup = [resize_image(load_image('moby_cat_N.png'), 3), resize_image(load_image('moby_cat_L.png'), 3), resize_image(load_image('moby_cat_R.png'), 3)]
self.image = self.imagegroup[2]
self.pos = self.image.get_rect()
self.pos.center = (SCREENSIZE[0] / 2, SCREENSIZE[1] / 2)
# boat direction (heading)
self.heading = 0
self.pointofsail = ''
# sail image and position
self.sailgroup = [resize_image(load_image('moby_sail_open_L.png'), 3), resize_image(load_image('moby_sail_close.png'), 3), resize_image(load_image('moby_sail_open_R.png'), 3)]
self.sailimage = self.sailgroup[1]
self.sailpos = self.sailimage.get_rect()
self.sailpos.center = (SCREENSIZE[0] / 2, SCREENSIZE[1] / 2)
# sail relative angle and absolute angle
self.sailangle = 0
self.sailabsolute = 0
def steer(self):
# monitor keyboard
keys = pygame.key.get_pressed()
# move rudder
if keys[K_LEFT]:
self.image = self.imagegroup[1]
self.heading -= 1
elif keys[K_RIGHT]:
self.image = self.imagegroup[2]
self.heading += 1
else:
self.image = self.imagegroup[0]
# resets if crosses limit
if self.heading >= 360:
self.heading = self.heading - 360
if self.heading < 0:
self.heading = 360 + self.heading
def trim(self, wind):
# monitor keyboard
keys = pygame.key.get_pressed()
# move rudder
if keys[K_UP]:
self.sailangle += 1
elif keys[K_DOWN]:
self.sailangle -= 1
# set the limits
if self.sailangle > 90:
self.sailangle = 90
if self.sailangle < -90:
self.sailangle = -90
# calculate sail absolute angle
self.sailabsolute = self.heading + self.sailangle
if self.sailabsolute >= 360:
self.sailabsolute = self.sailabsolute - 360
if self.sailabsolute < 0:
self.sailabsolute = 360 + self.sailabsolute
# define the sail image - it's related to the wind direction
if 170 < abs(wind.direction - self.sailabsolute) < 190:
self.sailimage = self.sailgroup[1]
elif wind.direction < 180:
if wind.direction < self.sailabsolute < opposite(wind.direction):
self.sailimage = self.sailgroup[0]
else:
self.sailimage = self.sailgroup[2]
else:
if wind.direction < self.sailabsolute or self.sailabsolute < opposite(wind.direction):
self.sailimage = self.sailgroup[0]
else:
self.sailimage = self.sailgroup[2]
def calculatepointofsail(self, wind):
if 157.5 < abs(wind.direction - self.heading) <= 202.5:
self.pointofsail = 'In irons'
elif 112.5 < abs(wind.direction - self.heading) <= 157.5 \
or 202.5 < abs(wind.direction - self.heading) <= 247.5:
self.pointofsail = 'Close-hauled'
elif 67.5 < abs(wind.direction - self.heading) <= 112.5 \
or 247.5 < abs(wind.direction - self.heading) <= 292.5:
self.pointofsail = 'Beam reach'
elif 22.5 < abs(wind.direction - self.heading) <= 67.5 \
or 292.5 < abs(wind.direction - self.heading) <= 337.5:
self.pointofsail = 'Broad reach'
else:
self.pointofsail = 'Running'
def draw(self, scr):
# rotate boat image
rot = pygame.transform.rotate(self.image, 360-self.heading)
rotrect = rot.get_rect()
rotrect.center = self.pos.center
# rotate sail image
rotsail = pygame.transform.rotate(self.sailimage, 360-self.sailabsolute)
rotsailrect = rotsail.get_rect()
rotsailrect.center = self.sailpos.center
# delete and redraw
pygame.draw.rect(scr.display, BACKGROUND, (SCREENSIZE[0] / 2 - 100, SCREENSIZE[1] / 2 - 100, 200, 200), 0)
scr.display.blit(rot, rotrect)
scr.display.blit(rotsail, rotsailrect)
def update(self, wind):
self.steer()
self.trim(wind)
self.calculatepointofsail(wind)
# event loop
def eventloop(scr, fnt, clk, hud, wind, boat):
# arguments: scr=screen, fnt=font, clk=clock, hud=HUD, wind=wind, boat=boat
a = 1
while a == 1:
# quit gracefully
for event in pygame.event.get():
if event.type == pygame.QUIT or pygame.key.get_pressed()[K_q]:
sys.exit()
# measure time
clk.tick(60)
# write text
# scr.display.blit(scr.image, (120, 5, 50, 30), (120, 5, 50, 30))
hud.draw(fnt, scr, wind, boat)
# draw boat
boat.update(wind)
boat.draw(scr)
# change wind direction & speed
wind.update()
wind.draw(scr)
# refresh display
pygame.display.flip()
# main routine
def main():
print('\n ::: Moby :::\n\n Press [Q] to quit.\n')
# start Pygame
pygame.init()
pygame.mixer.init()
font1 = pygame.font.Font('fonts/Chicago Normal.ttf', 12)
clock = pygame.time.Clock()
# score = 0
# start the display
screen = Screen()
# screen = Screen('background green 640x480.png')
# initialize HUD
hud = Hud(font1, screen)
# create the Wind
wind = Wind()
# create the Boat
boat = Boat()
# start the event loop
eventloop(screen, font1, clock, hud, wind, boat)
# execute main
if __name__ == '__main__':
main()
|
5e7081cfa430965c735bdabb7fbeb83ed22b66a2 | Leeyp/DHS-work | /practical 2/q2_triangle.py | 588 | 4.15625 | 4 | x = 1
while x != 0:
valid = "no"
sides = []
for side in range(0,3):
print("Enter side", side+1)
sides.append(int(input(" ")))
a = sides[0] + sides[1]
b = sides[1] + sides[2]
c = sides[0] + sides[2]
if a > sides[2]:
if b > sides[0]:
if c > sides[1]:
valid = "yes"
else:
valid = "no"
if valid == "yes":
print("Perimeter =", sum(sides))
elif valid == "no":
print("Invalid Triangle!")
|
75f888845d9193a2a7bb8a4559244bd07efcfb76 | Madhu-Kumar-S/Python_Basics | /OOPS/Inheritance/i2.py | 597 | 3.734375 | 4 | # creating Student class and deriving attributes and methods from Teacher class to Student class
from i1 import Teacher
class Student(Teacher):
def set_marks(self, marks):
self.marks = marks
def get_marks(self):
return self.marks
si = int(input("Enter id:"))
sn = input("Enter name:")
sa = input("Enter address:")
sm = int(input("Enter marks:"))
s = Student()
s.set_data(si, sn, sa)
id, name, address = s.get_data()
s.set_marks(sm)
print("Student deatils are:")
print("ID = ", id)
print("Name = ", name)
print("Address = ", address)
print("Marks = ", s.get_marks())
|
cd8d6f48b99db5789127095034b0ecfc022d2a16 | aryasoni98/Face-X | /Snapchat_Filters/Festive-Filters/Rakshabandhan Festival Filter/Code.py | 931 | 4 | 4 | from PIL import Image
img_path=input("Enter your image path here:") #ex -> r'C:\Users\xyz\images\p1.jpg'
img = Image.open(img_path)
img = img.resize((900, 900), Image.ANTIALIAS)
img.save('resized_image.jpg')
#img.show()
filename1 = 'resized_image.jpg'
filename='rakshabandhan.png'
# Open Front Image
frontImage = Image.open(filename)
# Open Background Image
background = Image.open(filename1)
# Convert image to RGBA
frontImage = frontImage.convert("RGBA")
# Convert image to RGBA
background = background.convert("RGBA")
# Calculate width to be at the center
width = (background.width - frontImage.width) // 2
# Calculate height to be at the center
height = (background.height - frontImage.height) // 2
# Paste the frontImage at (width, height)
background.paste(frontImage, (width, height), frontImage)
# Save this image
background.save("Rakshabandhan Filter Image.png", format="png")
background.show()
|
6df041b8b5f76c8146ac90b6a5f87d7fddfaf74b | brumazzi/Python2.x-Exemples | /gerador_yield.py | 716 | 3.765625 | 4 | #!/usr/bin/python
# *-* coding:utf-8 *-*
gen1 = (x for x in range(10))
def gen_function():
yield 5
yield 3
yield 5
yield 1
yield 8
yield 7
gen2 = gen_function()
# gen1 e gen2, são ambos geradores, a diferença é que o gen1 por
# ser gerado pela estrutura, é um objeto do tipo genexpr.
# por gen2 ser criado pelo yield da função, seu tipo é o nome da
# função "gen_function"
print type(gen1),type(gen2)
print gen1
print gen2
# para remover as informações, basta coloca-los em um for ou r-
# emover através do método next
print "Valores do gen1:"
while(True):
try:
print gen1.next()
except:
break
print "Valores do gen2:"
for x in gen2:
print x
|
c334651eb4d65447ab697f3cf0b5630daf82ab68 | poipiii/app-dev-tutorial | /pratical-wk-2/Game.py | 2,824 | 3.578125 | 4 | #class Question:
# Questionbank = {}
# answerbank = {}
# def __init__(self):
# self.__question = []
# self.__answer = []
# def set_Question(self,question):
# for i in self.__class__.Questionbank.keys():
# if i == question:
# self.__question.append(self.__class__.Questionbank[i])
# else:
# pass
#
# def set_Answer(self,answer):
# for i in self.__class__.answerbank.keys():
# if i == answer:
# self.__answer.append(self.__class__.answerbank[i])
# else:
# pass
# def get_Question(self):
# return self.__question
#
# def get_Answer(self):
# return self.__answer
#
#
#class Quiz:
# def __init__(self):
# self.__playerans = []
# self.__playerscore = 0
# def Generate_num(self):
# import random
# return random.randint(1,11)
#
#
#
#testlist = []
#for i in range():
# rand = Quiz()
# testlist.append(rand.Generate_num())
#print(testlist)
# import random
# class question:
# def __init__(self,qus,ans):
# self.ans = ans
# self.qus = qus
#
# class quiz:
# questions = []
# def __init__(self):
# self.set_qus()
# self.points = 0
# def set_qus(self):
# q1 = question('can bird fly', 'N')
# self.__class__.questions.append(q1)
# q2 = question('python is easy','N')
# self.__class__.questions.append(q2)
# q3 = question('a cow can fly','N')
# self.__class__.questions.append(q3)
# q4 = question('a pig can fly','N')
# self.__class__.questions.append(q4)
# q5 = question('a chicken can fly','N')
# self.__class__.questions.append(q5)
# def set_points(self):
# self.points += 1
# def get_points(self):
# return self.points
# def get_question(self):
# num =random.randint(0,4)
# return self.__class__.questions[num]
# def check_ans(self,pans):
# gameans = self.get_question()
# if gameans.ans == pans:
# self.set_points()
# else:
# print('wrong ans the right ans is {}'.format(gameans.ans))
#
# p = quiz()
# while True:
# print(p.get_points())
# print(p.get_question().qus)
# a = input('your ans:')
# p.check_ans(a.upper())
# y_n = input('continue y/n')
# if y_n == 'y':
# continue
# else:
# break
# class quiz:
# questions = []
# def __init__(self):
# self.create_question()
# def create_question(self):
# q1 = question('can bird fly','N')
# q2 = question('python is easy','N')
# q3 = question('a cow can fly','N')
# q4 = question('a pig can fly','N')
# q5 = question('a chicken can fly','N') |
878968ea8334078dc49b73964dc6a6d8591345c1 | hemenez/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 319 | 4.09375 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
for first in range(len(matrix)):
for second in range(len(matrix[first])):
print('{:d}'.format(matrix[first][second]), end="")
if second < len(matrix[first]) - 1:
print("", end=" ")
print("\n", end="")
|
01fccb0e7c170b562a98f9a55f2cc102523cbf45 | wyaadarsh/LeetCode-Solutions | /Python3/0023-Merge-K-Sorted-Lists/soln.py | 889 | 3.953125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Pair:
def __init__(self, val, node):
self.val = val
self.node = node
def __lt__(self, other):
return self.val < other.val
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
queue = []
for node in lists:
if node:
heapq.heappush(queue, Pair(node.val, node))
head = cur = ListNode(0)
while queue:
pair = heapq.heappop(queue)
val, node = pair.val, pair.node
cur.next = ListNode(val)
cur = cur.next
if node.next:
heapq.heappush(queue, Pair(node.next.val, node.next))
return head.next |
96d7069a88d02f7934c5c11bf737522ec5a7d942 | ryansama/karan-Projects-Solutions | /Networking/ip-country-lookup.py | 779 | 4.0625 | 4 | #Country from IP Lookup - Enter an IP address and find the country that IP is registered in. Optional: Find the Ip automatically.
# Usage: python ip-country-lookup.py <country>
# Outputs user's current country by default
import urllib2
import json
import sys
if len(sys.argv) > 1:
response = urllib2.urlopen("http://ip-api.com/json/" + sys.argv[1]).read()
response_json = json.loads(response)
if response_json["status"] == "success":
print response_json["country"]
else:
print "Invalid input."
else:
response = urllib2.urlopen("http://ip-api.com/json/").read()
response_json = json.loads(response)
if response_json["status"] == "success":
print response_json["country"]
else:
print "Failed to obtain country."
|
1af1aba8f07392db0ad4426b9d2b8f2c201b6f81 | kgermeroth/tic_tac_toe | /tic_tac_toe.py | 3,757 | 4.15625 | 4 | def make_move (board, player, symbol):
print("Ok, {}, make your move!".format(player))
while True:
# asks user for a row
row_choice = int(input("Row 1, Row 2, or Row 3? > ")) - 1
print()
# asks user for a column
column_choice = int(input("Column 1, Column 2, or Column 3? > ")) - 1
print()
# check if board at row and column has been taken, else put x or o there depending on player
if tic_tac_toe_board[row_choice][column_choice] == "-":
tic_tac_toe_board[row_choice][column_choice] = symbol
break
else:
print("That spot is taken, try again!")
def make_rows_pretty(row):
pretty_line = ""
for place in row:
pretty_line = pretty_line + " " + place
return (pretty_line)
def print_board(board):
"""Prints board to show the players"""
print(make_rows_pretty(board[0]))
print(make_rows_pretty(board[1]))
print(make_rows_pretty(board[2]))
print()
def check_winning_line(value1, value2, value3):
game_finished = False
winner = None
if (value1 == value2) and (value2 == value3):
if value1 == "-":
game_finished = False
winner = None
else:
game_finished = True
winner = value1
return (game_finished, winner)
def check_win(board):
# check rows
for row in range(3):
game_finished, winner = check_winning_line(board[row][0], board[row][1], board[row][2])
if game_finished == True:
return (game_finished, winner)
# diagonals
game_finished, winner = check_winning_line(board[0][0], board[1][1], board[2][2])
if game_finished == True:
return (game_finished, winner)
game_finished, winner = check_winning_line(board[2][2], board[1][1], board[2][0])
if game_finished == True:
return (game_finished, winner)
# columns
for column in range (3):
game_finished, winner = check_winning_line(board[0][column], board[1][column], board[2][column])
return (game_finished, winner)
def check_tie(board):
"""Checks if board is full and there's a tie"""
game_finished = True
for row in range (3):
for column in range (3):
if board[row][column] == "-":
game_finished = False
return game_finished
def play(board):
"""Main REPL function to play the game"""
game_finished = False
winner = None
player_1 = input("Name of Player 1: ")
player_2 = input("Name of Player 2: ")
print()
print("{} you are X's, and {}, you are O's".format(player_1,player_2))
print()
# loop until win or tie conditions met
while game_finished == False:
for player, symbol in [(player_1, "X"), (player_2, "O")]:
# start by printing the board
print_board(tic_tac_toe_board)
# have player make a move
make_move(tic_tac_toe_board, player, symbol)
# check for win or tie
game_finished, winner = check_win(tic_tac_toe_board)
if game_finished:
break
game_finished = check_tie(tic_tac_toe_board)
if game_finished:
break
if winner == None:
print("It's a tie, there is no winner!")
else:
if winner == "X":
winning_player = player_1
else:
winning_player = player2
print("Congratulations, {}. You have won the game!".format(winning_player))
#################################################################################
tic_tac_toe_board = [["-","-","-"],["-","-","-"],["-","-","-"]]
play(tic_tac_toe_board) |
d9a33fcf4325cba2d1fc0048165120c9a4e4e152 | abiraaaaaaf/Digital-Image-Processing | /Homework1/ipl_utils/interpolate.py | 776 | 3.515625 | 4 | import numpy as np
class Interpolation:
@staticmethod
def avg_interpolate(img_array):
row, col, _ = img_array.shape
# Filling With Zeros The Out Array
new_img_array = np.zeros((row, col*2, 3))
# first assigning image pixels to the even cells in new array
for i in range(row):
for j in range(col):
new_img_array[i][2 * j][:] = img_array[i][j][:]
# then filling the odd pixels with average two nearest row pixels (it can be the other two column pixels or four or 8 pixels ^_^)
for i in range(row):
for j in range(col):
new_img_array[i][2 * j + 1][:] = (new_img_array[i][2 * j][:] + new_img_array[i][2 * j - 1])/2
return new_img_array
pass |
56f528060b59511279092dfb2b39ddeb1cc807d7 | AKDavis96/Data22python | /Advent of code/day3.py | 626 | 3.578125 | 4 | list = [str(x.strip()) for x in open("day3_details.txt", "r").readlines()]
def finding_trees(r, d):
trees = 0
a = 0
b = 0
row = len(list[0])
c = len(list) - 1
while a != c:
a += d
if b > row - (r + 1):
b -= row
b += r
elif b <= row - (r + 1):
b += r
if list[a][b] == "#":
trees += 1
return trees
finding_trees(1,1)
print(finding_trees(3,1))
finding_trees(5,1)
finding_trees(7,1)
finding_trees(1,2)
print(finding_trees(1, 1) * finding_trees(3, 1) * finding_trees(5, 1) * finding_trees(7, 1) * finding_trees(1, 2))
|
0ef79dcd906ad987077c74a160b46f9d7376aa39 | daniel-reich/ubiquitous-fiesta | /6BXmvwJ5SGjby3x9Z_5.py | 269 | 3.71875 | 4 |
def hours_passed(time1, time2):
a,b=','.join(i[:-6] if i[-2:]=='AM' else str(eval(i[:-6])+12) for i in (time1,time2)).split(',')
if time1=='12:00 AM':
return b+' hours'
elif a==b:
return "no time passed"
else:
return str(eval(b)-eval(a))+' hours'
|
36c0e611ed86721d32e8b388b2d5fea2d12fb849 | kcpedrosa/Python-exercises | /ex099.py | 508 | 3.890625 | 4 | #programa para mostrar o maior
def funcmaior(* num):
cont = 0
maior = 0
print('=-'*30)
print('Analisando números para retornar o MAIOR...')
from time import sleep
for c in num:
sleep(0.5)
print(f' {c} ', end=' ')
if cont == 0:
maior = c
elif c > maior:
maior = c
cont += 1
sleep(0.5)
print(f'\nO maior foi {maior}')
#programa principal
funcmaior(1,3,5)
funcmaior()
funcmaior(9,9,1,3)
funcmaior(10,14,-5,-20)
|
e17304a785c9208325182225b8cb48b40b3a7956 | Aasthaengg/IBMdataset | /Python_codes/p03854/s582347237.py | 151 | 3.640625 | 4 | s = input()[::-1]
words = ["eraser","erase","dreamer","dream"]
for i in words:
s = s.replace(i[::-1], "")
if s == "": print("YES")
else: print("NO") |
0491a31fb42b517b96f65655653b2fcb22f5cf89 | SheetanshKumar/smart-interviews-problems | /Contest/B/Check Subsequence.py | 861 | 3.90625 | 4 | '''
Check Subsequence
https://www.hackerrank.com/contests/smart-interviews-16b/challenges/si-check-subsequence/submissions/code/1324385337
Given 2 strings A and B, check if A is present as a subsequence in B.
Input Format
First line of input contains T - number of test cases. Its followed by T lines, each line contains 2 space separated strings - A and B.
Constraints
1 <= T <= 1000
1 <= len(A), len(B) <= 1000
'a' <= A[i],B[i] <= 'z'
Output Format
For each test case, print "Yes" if A is a subsequence of B, "No" otherwise, separated by new line.
Sample Input 0
2
data gojdaoncptdhzay
algo plabhagqogxt
Sample Output 0
Yes
No
'''
for _ in range(int(input())):
a, b = list(input().split())
x = 0
for i in b:
if x < len(a) and a[x] == i:
x+=1
if(x == len(a)):
print("Yes")
else:
print("No")
|
3e5b20c793131d9ed158841e0e6069cb0d0cf579 | rodrigolousada/LEIC-IST | /1st_Year/FP/1st_Project/1stProject_81115.py | 10,022 | 4.0625 | 4 | #81115 Rodrigo Lousada
#Algoritmo de Luhn
def last_digit(cc):
'''Recebe uma cadeia de caracteres que representa um numero e devolve o ultimo digito'''
last = eval(cc)%10
return last
def remove(cc):
'''Primeiro passo do Algoritmo de Luhn: Recebe como argumento uma cadeia de caracteres que representa um numero e devolve uma cadeia de caracteres que representa o mesmo numero sem o ultimo digito'''
cc = eval(cc)//10
return str(cc)
def inverte(cc):
'''Segundo passo do Algoritmo de Luhn: Recebe como argumento uma cadeia de caracteres e devolve a mesma com a ordem dos seus caracteres invertida'''
cc = cc[::-1]
return cc
def tupler(cc):
'''Recebe como argumento uma cadeia de caracteres e devolve um tuplo com cada um dos caracteres da cadeia como um elemento desse tuplo'''
tuplo_1=()
for caract in cc:
tuplo_1 = tuplo_1 + (int(caract),)
return tuplo_1
def duplicar_impares(cc):
'''Terceiro passo do Algoritmo de Luhn (1/2): Recebe como argumento um tuplo e multiplica por 2 os digitos em posicoes impares'''
num_indices = len(cc)
tuplo_2=()
for i in range(num_indices):
if i%2==0: #temos de considerar as posicoes impares pares, pois costumamos comecar a contar a primeira posicao como a posicao 1 (numero impar) e o tuplo comeca a contar como posicao 0 (numero par)
tuplo_2 = tuplo_2 + ((cc[i] * 2),)
else:
tuplo_2 = tuplo_2 + (cc[i],)
return tuplo_2
def subtrair_impares(cc):
'''Terceiro passo do Algoritmo de Luhn (2/2): Recebe como argumento um tuplo e subtrai 9 aos digitos em posicoes impares que sejam superiores a 9'''
num_indices = len(cc)
tuplo_3=()
for i in range(num_indices):
if i%2==0 and cc[i]>9: # mais uma vez temos de considerar como se fossem as posicoes pares
tuplo_3 = tuplo_3 + (cc[i]-9,)
else:
tuplo_3 = tuplo_3 + (cc[i],)
return tuplo_3
def calc_soma(cc):
'''Recebe como argumento uma cadeia de caracteres, representando um numero de cartao de credito sem o ultimo digito, e devolve a soma ponderada dos digitos de cc, calculada de acordo com o algoritmo de Luhn'''
cc = inverte(cc)
cc_tuplo = tupler(cc)
cc_tuplo = duplicar_impares(cc_tuplo)
cc_tuplo = subtrair_impares(cc_tuplo)
result = 0
for e in cc_tuplo:
result = e + result
return result
def luhn_verifica(cc):
'''Recebe como argumento uma cadeia de caracteres, representando um numero de cartao de credito, e devolve True, se o numero passar o algoritmo de Luhn'''
last = last_digit(cc)
cc = remove(cc)
cc = calc_soma(cc) + last #antes de verificar se e divisivel por 10, somamos ainda o digito que retiramos ao inicio
flag = False
if int(cc) % 10 == 0:
flag = True
return flag
# Prefixo do Numero
def comeca_por(cad1, cad2):
'''Recebe como argumentos duas cadeias de caracteres e devolve True apenas se a primeira comecar pela segunda'''
flag = True
cad1 = tupler(cad1)
cad2 = tupler(cad2)
if len(cad1)>=len(cad2):
num_elem = len(cad2)
for f in range(num_elem):
if cad1[f]!=cad2[f]:
flag = False
else:
flag = False
return flag
def comeca_por_um(cad, t_cads):
'''Recebe como argumentos uma cadeia de caracteres e um tuplo de cadeias de caracteres, e devolve True apenas se a cadeia de caracteres comecar por um dos elementos do tuplo'''
num_elementos = len(t_cads)
flag_1 = False
for g in range(num_elementos):
if comeca_por(cad, t_cads[g]) == True:
flag_1 = True
return flag_1
# Rede Emissora
tuplo_tabela = (('American Express', 'AE', ('34', '37'), ('15',)), ('Diners Club International', 'DCI', ('309', '36', '38', '39'), ('14',)), ('Discover Card', 'DC', ('65',), ('16',)), ('Maestro', 'M', ('5018', '5020', '5038'), ('13', '19')), ('Master Card', 'MC', ('50', '51', '52', '53', '54', '19'), ('16',)), ('Visa Electron', 'VE', ('4026', '426', '4405', '4508'), ('16',)), ('Visa', 'V', ('4024', '4532', '4556'), ('13', '16')))
#este tuplo representa todas as informacoes da tabela 1
def valida_iin(cc):
'''Recebe como argumento uma cadeia de caracteres, respresentando um numero de cartao de credito, e devolve uma cadeia correspondente a rede emissora do cartao'''
if comeca_por_um(cc, tuplo_tabela[0][2]) == True and len(tupler(cc))==15:
return tuplo_tabela[0][0]
elif comeca_por_um(cc, tuplo_tabela[1][2]) == True and len(tupler(cc))==14:
return tuplo_tabela[1][0]
elif comeca_por_um(cc, tuplo_tabela[2][2]) == True and len(tupler(cc))==16:
return tuplo_tabela[2][0]
elif comeca_por_um(cc, tuplo_tabela[3][2]) == True and (len(tupler(cc))==13 or len(tupler(cc))==19):
return tuplo_tabela[3][0]
elif comeca_por_um(cc, tuplo_tabela[4][2]) == True and len(tupler(cc))==16:
return tuplo_tabela[4][0]
elif comeca_por_um(cc, tuplo_tabela[5][2]) == True and len(tupler(cc))==16:
return tuplo_tabela[5][0]
elif comeca_por_um(cc, tuplo_tabela[6][2]) == True and (len(tupler(cc))==13 or len(tupler(cc))==16):
return tuplo_tabela[6][0]
else:
return ''
# MII
def categoria(cc):
'''Recebe como argumento uma cadeia de caracteres, respresentando um numero de cartao de credito, e devolve uma cadeia correspondente a categoria da entidade correspondente ao primeiro caracter da cadeia'''
cc_tuplo = tupler(cc)
first_digit = cc_tuplo[0]
if first_digit == 1:
return 'Companhias aereas'
elif first_digit == 2:
return 'Companhias aereas e outras tarefas futuras da industria'
elif first_digit == 3:
return 'Viagens e entretenimento e bancario / financeiro'
elif first_digit == 4 or first_digit == 5:
return 'Servicos bancarios e financeiros'
elif first_digit == 6:
return 'Merchandising e bancario / financeiro'
elif first_digit == 7:
return 'Petroleo e outras atribuicoes futuras da industria'
elif first_digit == 8:
return 'Saude, telecomunicacoes e outras atribuicoes futuras da industria'
elif first_digit == 9:
return 'Atribuicao nacional'
else:
return 'Por favor, confirme se o primeiro digito e mesmo 0'
# Vamos entao criar a funcao verifica_cc
def verifica_cc(cc):
'''Recebe como argumento um inteiro correspondente a um possivel numero de um cartao de credito e devolve, se este for valido, um tuplo contendo a categoria e a rede do cartao, ou, se este for invalido, a cadeia de caracteres 'cartao invalido' '''
cc = str(cc)
if luhn_verifica(cc) == True and valida_iin(cc)!='':
tuplo_4 = (categoria(cc), valida_iin(cc))
return tuplo_4
else:
return 'cartao invalido'
#Geracao do numero de um cartao de credito
from random import random
def possiveis_prefixos(abreviatura):
'''Recebe como argumento uma cadeia de caracteres correspondente a abreviatura de uma rede emissora e devolve um tuplo de cadeias de caracteres composto pelos possiveis prefixos para gerar um numero emitido por essa entidade'''
num_indices = len(tuplo_tabela)
for i in range(num_indices):
if abreviatura == tuplo_tabela [i] [1]:
return tuplo_tabela [i] [2]
def prefixo(abreviatura):
'''Recebe como argumento uma cadeia de caracteres correspondente a abreviatura de uma rede emissora e devolve aleatoriamente um dos possiveis prefixos para gerar um numero emitido por essa entidade'''
tuplo_prefixos = possiveis_prefixos(abreviatura)
indice_max = len(tuplo_prefixos)
indice_escolhido = int(indice_max * random())
prefixo = tuplo_prefixos[indice_escolhido]
return prefixo
def possiveis_comprimentos(abreviatura):
'''Recebe como argumento uma cadeia de caracteres correspondente a abreviatura de uma rede emissora e devolve um tuplo de cadeias de caracteres composto pelos possiveis comprimentos para gerar um numero emitido por essa entidade'''
num_indices = len(tuplo_tabela)
for i in range(num_indices):
if abreviatura == tuplo_tabela [i] [1]:
return tuplo_tabela [i] [3]
def comprimento(abreviatura):
'''Recebe como argumento uma cadeia de caracteres correspondente a abreviatura de uma rede emissora e devolve aleatoriamente um dos possiveis comprimentos para gerar um numero emitido por essa entidade'''
tuplo_comprimentos = possiveis_comprimentos(abreviatura)
indice_max = len(tuplo_comprimentos)
indice_escolhido = int(indice_max * random())
comprimento = tuplo_comprimentos[indice_escolhido]
return int(comprimento)
def gerador(abreviatura):
'''Recebe como argumento uma cadeia de caracteres correspondente a abreviatura de uma rede emissora e gera um numero aleatorio de cartao de credito sem o ultimo digito emitido por essa entidade'''
prefixo_cc = prefixo(abreviatura)
comprimento_cc = comprimento(abreviatura) - len(tupler(prefixo_cc)) -1
result = int(prefixo_cc)
while comprimento_cc>0:
result = result*10 + int(random()*10)
comprimento_cc = comprimento_cc -1
return result
def digito_verificacao(cc):
'''Recebe como argumento uma cadeia de caracteres, representando um numero de cartao de credito, sem o ultimo digito, e devolve o ultimo digito, de verificacao, que lhe devera ser acrescentado, de forma a obter um numero de cartao valido'''
soma = calc_soma(cc)
resto = soma % 10
if resto == 0:
complemento = 0
else:
complemento = 10 - resto
return str(complemento)
def gera_num_cc(abreviatura):
'''Recebe como argumento uma cadeia de caracteres correspondente a abreviatura de uma rede emissora e gera um numero de cartao de credito valido emitido por essa entidade'''
gerado = gerador(abreviatura)
last_digit = digito_verificacao(str(gerado))
final = gerado*10 + eval(last_digit)
return final
|
d501f1e26e093cba6719af9a632ff576c63d6d83 | jtquisenberry/PythonExamples | /Interview_Cake/combinatorics/two_egg_drop_formula_working.py | 3,278 | 4.15625 | 4 | import unittest
import math
#######################
# Problem
#######################
# A building has 100 floors. One of the floors is the highest floor an egg can be
# dropped from without breaking.
# If an egg is dropped from above that floor, it will break. If it is dropped from
# that floor or below, it will be completely undamaged and you can drop the egg again.
# Given two eggs, find the highest floor an egg can be dropped from without breaking,
# with as few drops as possible.
# Gotchas
# We can do better than a binary approach, which would have a worst case of 50 drops.
# We can even do better than 19 drops!
# We can always find the highest floor an egg can be dropped from with a worst case
# of 14 total drops.
#######################
# Discussion
#######################
# Binary is out of the question because we have only two eggs. We could drop on floor 50 and
# then on floor 25. If the egg breaks both times, we do not have a solution.
# Can do a part divide and conquer and part linear. Within each chunk, say, 10 floors, we must
# test every floor from lowest to highest. Otherwise, we risk breaking an egg without narrowing
# down which floor is the highest safe floor.
# If we divide 100 into chunks of 10 and assume the worst case (floor 99), we drop at
# Round 1: egg1 at floor 10, survives
# Round 2: egg1 at floor 20, survives
# ...
# Round 10: egg1 at floor 100, breaks; egg2 at 91..99
# = 19 drops.
# However, if the highest safe floor = 9, we only drop at
# Round 1: egg1 at floor 10, breaks; egg2 at 1..9
# That is only 10 drops.
# To minimize the number of drops in the worst case we want to make the number of drops constant
# for all cases.
# Instead of fixed-size chunks, reduce the size of the chunk each round to reflect the fact that
# testing the previous chunk took up one drop.
# x + (x-1) + (x-2) + x-3 + ... + 1 >= 100
# Simplifies to x(x+1) / 2
def get_egg_drops_given_floors(floors=0):
# Reduce the number of floors skipped with the first egg by one each time the first egg does
# not break. This is because we want the number of drops of both eggs to remain constant.
# Round 1: egg1 = 1st drop at floor 14. egg2 13 drops (1 - 13) = 14 drops
# Round 2: egg1 = 2nd drop at floor 27, egg2 12 drops (15 - 26) = 14 drops
# Round 3: egg1 = 3rd drop at floor 39, egg2 11 drops (28 - 38) = 14 drops
# ...
# Round 11: egg31415921 = 11th drop at floor 99, egg2 3 drops (96 - 98) = 14 drops
# Round 12: egg1 = 1
# Using the quadratic formula
answer1 = (-1 + math.sqrt(1 ** 2 - 4 * 1 * (-2 * floors))) / (2 * 1)
answer1 = int(answer1) if answer1 % 1 == 0 else int(answer1) + 1
answer2 = (-1 - math.sqrt(1 ** 2 - 4 * 1 * (-2 * floors))) / (2 * 1)
answer2 = int(answer2) if answer2 % 1 == 0 else int(answer2) + 1
return max(answer1, answer2)
class Test(unittest.TestCase):
def test_floor_100(self):
# expected = 13.650971698084906
expected = 14
actual = get_egg_drops_given_floors(100)
self.assertEqual(expected, actual)
def test_floor_753(self):
expected = 39
actual = get_egg_drops_given_floors(753)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
|
52b3e6364c0b17223ec86ea66b389fb3f44bcaa9 | Aasthaengg/IBMdataset | /Python_codes/p03109/s586538202.py | 123 | 3.578125 | 4 | S=input()
month=int(S[5:7])
day=int(S[8:10])
if (month==4 and day<=30) or month<4 :
print("Heisei")
else :
print("TBD") |
a4851aeede04161d4e98645eef86f23120e80523 | YBrady/dataRepresentation | /Labs/week09/selectAllRows.py | 676 | 3.859375 | 4 | # Import mySQL connector python package
import mysql.connector
# Set up the connection to the database
db = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="datarepresentation"
)
# Create the cursor
cursor = db.cursor()
# The mySQL select - take away the where id bit if you want to return all rows
sql = "select * from student"# where id = %s"
# This is needed for where the id =
# Comma needed as it is a tuple
values = (1,)
# Do the select statement
cursor.execute(sql)#, values)
# Save the result into the result variable
result = cursor.fetchall()
# For all the results found
for x in result:
# Print out
print(x)
|
5850fe3192dcc3841144d585cf6f7cc200c59eef | coci/camo | /common/date.py | 2,125 | 3.796875 | 4 | """
converting date
"""
import datetime
def gregorian_to_jalali(date):
if date.find("-"):
new_date = date.split("-")
gy = int(new_date[0])
gm = int(new_date[1])
gd = int(new_date[2])
elif date.find("/"):
new_date = date.split("/")
gy = int(new_date[0])
gm = int(new_date[1])
gd = int(new_date[2])
else:
return None
g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
if gy > 1600:
jy = 979
gy -= 1600
else:
jy = 0
gy -= 621
if gm > 2:
gy2 = gy + 1
else:
gy2 = gy
days = (365 * gy) + (int((gy2 + 3) / 4)) - (int((gy2 + 99) / 100)) + (int((gy2 + 399) / 400)) - 80 + gd + g_d_m[
gm - 1]
jy += 33 * (int(days / 12053))
days %= 12053
jy += 4 * (int(days / 1461))
days %= 1461
if days > 365:
jy += int((days - 1) / 365)
days = (days - 1) % 365
if days < 186:
jm = 1 + int(days / 31)
jd = 1 + (days % 31)
else:
jm = 7 + int((days - 186) / 30)
jd = 1 + ((days - 186) % 30)
form_date = [str(jy), str(jm), str(jd)]
date = "-".join(form_date)
return date
def jalali_to_gregorian(date):
if date.find("-"):
new_date = date.split("-")
jy = int(new_date[0])
jm = int(new_date[1])
jd = int(new_date[2])
elif date.find("/"):
new_date = date.split("/")
jy = int(new_date[0])
jm = int(new_date[1])
jd = int(new_date[2])
else:
return None
if jy > 979:
gy = 1600
jy -= 979
else:
gy = 621
if jm < 7:
days = (jm - 1) * 31
else:
days = ((jm - 7) * 30) + 186
days += (365 * jy) + ((int(jy / 33)) * 8) + (int(((jy % 33) + 3) / 4)) + 78 + jd
gy += 400 * (int(days / 146097))
days %= 146097
if days > 36524:
gy += 100 * (int(--days / 36524))
days %= 36524
if days >= 365:
days += 1
gy += 4 * (int(days / 1461))
days %= 1461
if days > 365:
gy += int((days - 1) / 365)
days = (days - 1) % 365
gd = days + 1
if (gy % 4 == 0 and gy % 100 != 0) or (gy % 400 == 0):
kab = 29
else:
kab = 28
sal_a = [0, 31, kab, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
gm = 0
while gm < 13:
v = sal_a[gm]
if gd <= v:
break
gd -= v
gm += 1
form_date = [str(gy), str(gm), str(gd)]
date = "-".join(form_date)
return date
|
f90248384d99936a1829fbcf2beb8b749ae881cc | miguelmartinez0/MISCourseWork | /MIS 304/iteminfo.py | 3,687 | 4.15625 | 4 | #Author: Miguel Martinez Cano
#Homeowkr Number & Name: Homework #8: The COOP
#Due Date: Monday, November 7, 2016 at 5:00 P.M.
#Item Info
#Class Name: Item Info
#List of Attributes: Item Number, Quantity, Price, Name, Mode
#List of Methods:__init__(), get_item_num(), set_item_num(new_item_num), get_qty(),
#update_qty(new_qty), get_price(), set_price(new_price), get_item_name()
#set_item_name(new_name), get_mode(), update_mode(new_mode), calculate_total()
#__str__()
#Establish item numbers
SHORTS = 32
SHIRT = 83
SOCKS = 39
SHORTS_PRICE = 18.97
SHIRT_PRICE = 29.95
SOCKS_PRICE = 2.99
#Define class
class ItemInfo:
#Initializer method
def __init__(self):
#Define attributes
self.__item_num = 1
self.__quantity = 1
self.__price = 1
self.__name = "Name"
self.__mode = "Buy"
#Retrieve the item number
def get_item_num(self):
return self.__item_num
#Retrieve the item quantity
def get_qty(self):
return self.__quantity
#Retrieve the item price
def get_price(self):
return self.__price
#Retrieve the item name
def get_item_name(self):
return self.__name
#Retrieve the mode to either make a purchase or return
def get_mode(self):
return self.__mode
#Mutators to allow code outside of ItemInfo to update the values
#of the hidden attributes
#Update the item's number
def set_item_num(self, new_item_num):
#Make sure item number is valid
if new_item_num == SHORTS or new_item_num == SHIRT or new_item_num == SOCKS:
#Change the number of the item
self.__item_num = new_item_num
else:
#Print a message that the item number was not changed.
print ("Invalid item number. Item number not changed.")
#Update the item's quantity
def update_qty(self, new_qty):
#Make sure the item quantity is positive
if new_qty > 0:
#Change the quantity of the item
self.__quantity = new_qty
return True
else:
#Print a message that the item quantity was not changed.
print ("Invalid item quanaity. Item quantity not changed.")
return False
#Update the item's price
def set_price(self, new_price):
#Determine if the price of the item will be positive or negative
if self.__mode == "Buy":
#Positive price
self.__price = float (new_price)
elif self.__mode == "Return":
#Negative price
self.__price = -1 * float (new_price)
#Update the item's name
def set_item_name(self, new_name):
self.__name = new_name
#Updat the item's mode
def update_mode(self, new_mode):
#Make sure item mode entered is valid
if new_mode == "Buy" or new_mode == "Return":
self.__mode = new_mode
return True
else:
#Print a message saying that the item mode was not changed
print ("Invalid item mode. Item mode not changed.")
return False
#Calculate the item total
def calculate_total(self):
item_total = self.__price * self.__quantity
item_total = format (item_total, '.2f')
return item_total
#Create a string with the values of the object's attributes
def __str__(self):
item_info_print = "The " + self.__name + " has an item number of " + str(self.__item_num) + \
". You chose to " + self.__mode + " " + str(self.__quantity) + " at a cost of " + \
str(self.__price) + " per item."
return item_info_print
|
bcfb930c58785072b5e2fb2f530f9fd65d0c5b57 | sheikhiu/Easy-URL-Shortener | /urlshortener.py | 1,039 | 3.765625 | 4 | import pyshorteners
import tkinter as tk
from tkinter import messagebox
import webbrowser
shortener = pyshorteners.Shortener()
#This method shortens the URL using pyshorteners
def URLshort():
x=pyshorteners.Shortener()
a=x.tinyurl.short(entry.get())
shortened.insert(0, a)
#start of the GUI window
window=tk.Tk()
#label of the GUI
window.title("Easy URL Shortener")
window.geometry("450x450")
label = tk.Label(text="What's the URL you want to shorten: ")
entry = tk.Entry()
shortened = tk.Entry()
bottomlabel = tk.Label(text = "This is the shortened URL: ")
label.pack(padx=10, pady=10)
entry.pack(padx=10, pady=10)
bottom=tk.Button(text="Click to shorten the Url",command=URLshort, padx=10, pady=10).pack()
bottomlabel.pack(padx=10, pady=10)
shortened.pack(padx=20,pady=20)
image = tk.PhotoImage(file="linkz.png")
imageput= tk.Label(image=image,padx=50,pady=50)
imageput.place(x=0,y=0,relwidth=1,relheight=1)
imageput.pack()
#end of the window GUI
window.mainloop()
|
143d33f24290569b3d381e009be5fc92b9bfd08f | jameslehoux/a-test | /mysoftware/functions.py | 1,961 | 4.34375 | 4 |
import numpy as np
def square(x):
"""
Takes a number x and squares it.
Parameters:
-----------
x, float or int:
Number which is to be squared.
Returns:
--------
float:
Square of x
Examples:
---------
>>> square(2)
4
>>> square(-1)
1
"""
return x*x
def coulomb(r):
return 1.0/r
def CentralDifference(f, x, h):
# f(x + h) - f(x - h)
# ------------------ \approx f'(x)
# 2*h
return (f(x + h) - f(x - h))/(2*h)
def myfunc(x):
return (x**2 + (x - 2)**3 - 5)
def mysinfunc(x):
return (np.sin(x**2) - x + 5)
def mysquaredfunc(x):
return (x - 2)**2
def mytanfunc(x):
return np.tan(x)
def myrugbyfunc(theta, yend, ystart, x, v):
return ystart - yend + x * np.tan(theta) - (0.5 * (x**2 * 9.81)/(v**2)) * (1 + np.tan(theta)**2)
def myrealrugbyfunc(theta):
return 1.85 - 1.96 + 20 * np.tan(theta) - (0.5 * (20**2 * 9.81)/(15**2)) * (1 + np.tan(theta)**2)
def mybisection(func, a, b, eps):
fa = func(a)
fb = func(b)
if fa * fb > 0:
print('No root between these bounds')
return None
while abs(b - a) > eps:
x = 0.5 * (a + b)
fx = func(x)
if fa * fx < 0:
b = x
else:
a = x
return x
def mytrapz(func,a,b,n):
integral=0.5*(func(a)+func(b))
h=(b-a)/n
x=a
for i in range(1,n):
x=x+h
integral=integral+func(x)
integral=integral*h
return integral
def myintegral(x):
return -(x-2)**2+4
def myfindiff(Ta,Tb,x,tend,T0,alpha,dx,dt):
nodes = int(x/dx)+1
Tdist = np.ones(nodes)*T0
Tdist[0]=Ta
Tdist[nodes-1]=Tb
steps = int(tend/dt) + 1
Tnew = np.zeros(nodes)
Tnew[0] = Ta
Tnew[nodes-1] = Tb
for p in range(1,steps):
for i in range (1,nodes - 1):
Tnew[i] = ((alpha * dt) / dx**2) * (Tdist[i+1] + Tdist[i-1])\
+ (1 - ((2*alpha*dt)/(dx**2)))*Tdist[i]
print(Tdist)
Tdist = Tnew[:]
print(Tdist)
return Tdist
|
cf67580e31a2916c5f763f431ec0f3d78a3e4677 | Mai-pharuj/lab03-two-character | /lab03.py | 1,121 | 4.03125 | 4 | # lab03.py for Shulin Li and Pharuj Rajborirug
# CS20, Spring 2016, Instructor: Phill Conrad
# Draw some initials using turtle graphics
import turtle
def drawS(s,w,h):
# draw a letter S using s-Turtle, with some width and height
# set up initial position
s.penup()
s.setx(-100)
s.sety(-100)
# start drawing
s.pendown()
s.circle(h,-90)
s.circle(h,270)
s.circle(-h,270)
s.goto(-100+h,-100+3*h+w)
s.circle(-h-w,-90)
s.circle(-h-w,-180)
s.circle(h+w,-270)
s.goto(-100-h, -100+h)
s.hideturtle()
def drawL(l,w,h):
# draw a letter L using l-Turtle, with some width and height
# set up initial position
l=turtle.Turtle()
l.penup()
l.setx(100)
l.sety(90)
# start drawing
l.pendown()
l.right(90)
l.forward(2*h)
l.left(90)
l.forward(h)
l.left(90)
l.forward(w)
l.left(90)
l.forward(h-w)
l.right(90)
l.forward(2*h-w)
l.left(90)
l.forward(w)
l.hideturtle()
#test
def go():
shulin=turtle.Turtle()
drawS(shulin,4,50)
drawL(shulin,4,100)
|
147254cf2f4016a7c51f8152580a16aa0119a566 | kabirsrivastava3/python-practice | /BOOK/PRACTICAL-BOOK/chapter-2/01-remove-element-0-index.py | 373 | 4.09375 | 4 | # A program that accepts a list and removes the value at index 0 from the list.
def removeElementArray():
numList = []
size = int(input("Enter the size of the array: "))
numValue = 0
for index in range(size):
numValue = int(input("Enter the number: "))
numList.append(numValue)
numList.pop(0)
print(numList)
removeElementArray() |
d1cdee75de845f523400072d8d2edb3db7e8abe0 | Err0rdmg/python-programs | /3.py | 135 | 4.21875 | 4 | text = input("Enter the string:")
count = 0
for i in text:
count += 1
print("The numbers of letters in your string is :", count)
|
531e3830c10cfc2e280197b213cf2ae725dc4f66 | DilyanTsenkov/SoftUni-Software-Engineering | /Python Fundamentals/Mid exams/03_school_library.py | 995 | 3.96875 | 4 | book_names = input().split("&")
while True:
command = input().split(" | ")
if command[0] == "Done":
break
if command[0] == "Add Book":
if command[1] not in book_names:
book_names.insert(0, command[1])
elif command[0] == "Take Book":
if command[1] in book_names:
book_names = [book for book in book_names if book != command[1]]
elif command[0] == "Swap Books":
if command[1] in book_names and command[2] in book_names:
book1_index = book_names.index(command[1])
book2_index = book_names.index(command[2])
book_names[book1_index], book_names[book2_index] = book_names[book2_index], book_names[book1_index]
elif command[0] == "Insert Book":
book_names.append(command[1])
elif command[0] == "Check Book":
if int(command[1]) in range(len(book_names)):
print(book_names[int(command[1])])
print(", ".join(book_names))
|
c78702647213bd077603733c360b40b56be87ca0 | braca51e/CS231A_3DCV | /E1/ps1_code/p2.py | 3,782 | 3.765625 | 4 | # CS231A Homework 1, Problem 2
import numpy as np
'''
DATA FORMAT
In this problem, we provide and load the data for you. Recall that in the original
problem statement, there exists a grid of black squares on a white background. We
know how these black squares are setup, and thus can determine the locations of
specific points on the grid (namely the corners). We also have images taken of the
grid at a front image (where Z = 0) and a back image (where Z = 150). The data we
load for you consists of three parts: real_XY, front_image, and back_image. For a
corner (0,0), we may see it at the (137, 44) pixel in the front image and the
(148, 22) pixel in the back image. Thus, one row of real_XY will contain the numpy
array [0, 0], corresponding to the real XY location (0, 0). The matching row in
front_image will contain [137, 44] and the matching row in back_image will contain
[148, 22]
'''
'''
COMPUTE_CAMERA_MATRIX
Arguments:
real_XY - Each row corresponds to an actual point on the 2D plane
front_image - Each row is the pixel location in the front image where Z=0
back_image - Each row is the pixel location in the back image where Z=150
Returns:
camera_matrix - The calibrated camera matrix (3x4 matrix)
'''
def compute_camera_matrix(real_XY, front_image, back_image):
# TODO: Fill in this code
real_XY = np.append(np.array(real_XY), np.ones((len(real_XY), 1)), axis=1)
front_image = np.append(np.array(front_image), np.zeros((len(front_image), 1)), axis=1)
front_image = np.append(np.array(front_image), np.ones((len(front_image), 1)), axis=1)
back_image = np.append(np.array(back_image), 150*np.ones((len(back_image), 1)), axis=1)
back_image = np.append(np.array(back_image), np.ones((len(back_image), 1)), axis=1)
A_ = np.vstack((front_image, back_image))
b = np.vstack((real_XY, real_XY))
b = b.flatten()
A = np.zeros((3*len(A_), 12))
for i in range(0, len(A), 3):
A[i, :4] = A_[int(i/3), :]
A[i+1, 4:8] = A_[int(i/3), :]
A[i+2, 8:] = A_[int(i/3), :]
#Solve Linear Systems
m = np.dot(np.dot(np.linalg.inv(np.dot(A.T, A)), A.T), b)
return m.reshape(3, 4)
'''
RMS_ERROR
Arguments:
camera_matrix - The camera matrix of the calibrated camera
real_XY - Each row corresponds to an actual point on the 2D plane
front_image - Each row is the pixel location in the front image where Z=0
back_image - Each row is the pixel location in the back image where Z=150
Returns:
rms_error - The root mean square error of reprojecting the points back
into the images
'''
def rms_error(camera_matrix, real_XY, front_image, back_image):
#TODO: Fill in this code
real_XY = np.append(np.array(real_XY), np.ones((len(real_XY), 1)), axis=1)
front_image = np.append(np.array(front_image), np.zeros((len(front_image), 1)), axis=1)
front_image = np.append(np.array(front_image), np.ones((len(front_image), 1)), axis=1)
back_image = np.append(np.array(back_image), 150*np.ones((len(back_image), 1)), axis=1)
back_image = np.append(np.array(back_image), np.ones((len(back_image), 1)), axis=1)
points_a = np.vstack((front_image, back_image))
points_a = np.dot(camera_matrix, points_a.T).T
points_b =np.vstack((real_XY, real_XY))
return np.sqrt(np.sum((points_a - points_b)/len(points_a)))
if __name__ == '__main__':
# Loading the example coordinates setup
real_XY = np.load('real_XY.npy')
front_image = np.load('front_image.npy')
back_image = np.load('back_image.npy')
camera_matrix = compute_camera_matrix(real_XY, front_image, back_image)
print("Camera Matrix:\n", camera_matrix)
print()
print("RMS Error: ", rms_error(camera_matrix, real_XY, front_image, back_image))
|
7ca6f72797c6eb1b5cbbb7ffcdff67c2fd073f2f | raghuxpert/Array7Boom | /Comprehension.py | 1,440 | 3.859375 | 4 | # list = [i for i in range(5)]
# print(list) #[0, 1, 2, 3, 4]
#
# list = [i for i in range(1,5)]
# print(list) #[1, 2, 3, 4]
#
# list = [i for i in range(1,5,2)]
# print(list) #[1, 3]
#
# list = [i for i in range(5,1,-1)]
# print(list) #[5, 4, 3, 2]
#
# list = [i for i in range(5,1,-2)]
# print(list) #[5, 3]
# #
# # ##################################################
# list = [1,2,3,4,5]
#
# l = [i for i in list]
# print(l) #[1, 2, 3, 4, 5]
#
# l = [i*2 for i in list]
# print(l) #[2, 4, 6, 8, 10]
#
# l = [i for i in list if i%2 == 0]
# print(l) #[2, 4]
#
# l = [i*i for i in list if i%2 == 0]
# print(l) #[4, 16]
#
# l = [i*i for i in list if i%2 != 0]
# print(l) #[1, 9, 25]
##################################################
#
# list = [1,2,3,4,5]
#
# l = (i for i in list)
# print(next(l)) #[1, 2, 3, 4, 5]
#
# l = (i*2 for i in list)
# print(next(l)) #[2, 4, 6, 8, 10]
#
# l = (i for i in list if i%2 == 0)
# print(next(l))
#
# l = (i*i for i in list if i%2 == 0)
# print(next(l)) #[4, 16]
#
# l = (i*i for i in list if i%2 != 0)
# print(next(l)) #[1, 9, 25]
###########################################
list = (i for i in range(5))
print(next(list)) #[0, 1, 2, 3, 4]
list = (i for i in range(1,5) if i%2 == 0)
for i in list:
print(i)
list = (i for i in range(1,5,2))
for i in list:
print(i)
list = (i for i in range(5,1,-1))
for i in list:
print(i)
list = (i for i in range(5,1,-2))
for i in list:
print(i)
|
569af16cef42e215594ab26fa5c7ab734514ca95 | frankpiva/leetcode | /problemset/20.py | 1,466 | 3.953125 | 4 | """
20. Valid Parentheses
Easy
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.
"""
# approach: iterate with a stack
# memory: O(n)
# runtime: O(n)
class Solution:
def isValid(self, s: str) -> bool:
complements = { ')': '(', ']': '[', '}': '{' }
stack = []
# iterate through every character
for c in s:
if c == '(' or c == '{' or c =='[':
stack.append(c)
else:
# check if there is a value to pop
if len(stack) > 0:
# check if the value lines up
if stack[-1] == complements[c]:
stack.pop(-1)
else:
return False
else:
return False
# check for leftover values
if len(stack) > 0:
return False
return True
|
2b41318b51bb4b1a11909edb66509fdc742f0f84 | maddiegabriel/python-tutoring | /moreLoops.py | 236 | 4.21875 | 4 | #!/usr/bin/python
# while loop that prints the numbers from 1 to 5
count = 1
fruit = "BANANA"
while count <= 5:
print fruit
count += 1
while count < 6:
print count
count += 1
for letter in "BANANA":
print letter |
d364b61b2eae7f736cf4416d93812df7e7aa89bc | gamingrobot/WotMiniMapMaker | /manualconverter.py | 939 | 3.515625 | 4 |
def main():
import Image
themap = raw_input("Map: ")
background = Image.open("mapsRaw/" + themap + "/mmap.png")
gametype = raw_input("Gametype: ")
thescale = int(raw_input("Scale: "))
done = False
while(done != True):
foreground = Image.open("icon/" + raw_input("Marker Filename: ") + ".png")
inx = int(raw_input("X:"))
iny = int(raw_input("Y:"))
#0-1000 instead of -500-500
inx += thescale
iny += thescale
#scale to 500x500
doublescale = thescale * 2
divscale = doublescale / 500.0
inx /= divscale
iny /= divscale
#fix icon size
inx -= 24
iny += 24
background.paste(foreground, (int(inx), int(500 - iny)), foreground)
if raw_input("Done?") == "y":
done = True
background.save("maps/" + themap + "_" + gametype + ".png")
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.