blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ad59ed5a6d1efa47e2e9025420dafb4aa327304e | VovoRVA/Invader_hunter | /run.py | 3,453 | 3.578125 | 4 | from sys import argv
class InvaderRecognizer:
def __init__(self, accuracy: float):
self.accuracy = accuracy
@staticmethod
def read_file(filename: str) -> list:
try:
with open(filename, 'r') as file:
return [list(line.strip()) for line in file]
except FileNotFoundError:
print('File not found')
exit()
@staticmethod
def calc_matches(invader, radar, i_r, j_r, inv_r, inv_c, radar_r, radar_c) -> int:
matches = 0 # invader's symbol that matches the radar's one
for i in range(inv_r): # iterate invader's string
# checking if we are not out of list's boundary and skipping negative edge coordinates
if i_r + i >= radar_r or i_r + i < 0:
continue
for j in range(inv_c): # iterate invader's column
if j_r + j < 0: # skipping negative edge coordinates
continue
# checking if we are not out of boundary and symbols are matching
if j_r + j < radar_c and invader[i][j] == radar[i + i_r][j + j_r]:
matches += 1
return matches
def get_matches(self, invader: list, radar: list) -> list:
invader_coord = []
inv_r = len(invader) # invader number of rows (length)
inv_c = len(invader[0]) # invader number of columns (width)
radar_r = len(radar) # radar number of rows (length)
radar_c = len(radar[0]) # radar number of columns (width)
upper_edge = 1 - inv_r
left_edge = 1 - inv_c
for i_r in range(upper_edge, radar_r): # iterate radar's string
for j_r in range(left_edge, radar_c): # iterate radar's column
# calculating matches and checking matches' rate of success
match_rate = self.calc_matches(invader, radar, i_r, j_r, inv_r, inv_c, radar_r, radar_c) / (
inv_r * inv_c)
if match_rate >= self.accuracy:
invader_coord.append(([i_r, j_r], match_rate))
return invader_coord
@staticmethod
def print_nicely(result: list, invader_file: str = ''):
print(invader_file)
for i, j in result:
print("invader's initial coordinates: ", i, '\t', 'match_rate: ', round(j, 4))
try:
accuracy = argv[1]
except IndexError:
accuracy = 0.8
try:
invader_file = argv[2]
except IndexError:
invader_file = 'invader_1.txt'
try:
radar_file = argv[2]
except IndexError:
radar_file = 'radar_sample.txt'
if __name__ == '__main__':
"""
accuracy arg can be number from 0 to 1 inclusive (e.g. 0.8 means 80% matches of invader)
radar_file arg should be file's name that contains radar's ASCII sample
invader_file arg should be file's name that contains invader's ASCII pattern
"""
# create object
inv_rec = InvaderRecognizer(accuracy)
# create radar
radar = InvaderRecognizer.read_file(radar_file)
# get first invader's matches
invader_first = InvaderRecognizer.read_file(invader_file)
# get second invader's matches
invader_second = InvaderRecognizer.read_file('invader_2.txt')
# print nicely matches
InvaderRecognizer.print_nicely(inv_rec.get_matches(invader_first, radar), invader_file)
InvaderRecognizer.print_nicely(inv_rec.get_matches(invader_second, radar), 'invader_2.txt')
|
ba83571eb0bab91de4032508ff1f0810da656ea2 | chomimi101/system-design | /tiny-url/tiny-url.py | 1,025 | 3.578125 | 4 | class TinyUrl:
def __init__(self):
self.long_short = {}
self.short_long = {}
self.char_dict = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
self.tot = 0
# @param {string} url a long url
# @return {string} a short url starts with http://tiny.url/
def longToShort(self, url):
# Write your code here
if url not in self.long_short:
tiny = ""
tmp = self.tot
for i in xrange(6):
tiny += str(self.char_dict[tmp % 62])
tmp /= 62
self.tot += 1
self.long_short[url] = tiny
self.short_long[tiny] = url
return "http://tiny.url/" + self.long_short[url]
# @param {string} url a short url starts with http://tiny.url/
# @return {string} a long url
def shortToLong(self, url):
# Write your code here
if url[-6:] in self.short_long:
return self.short_long[url[-6:]]
else:
return None
|
d668e648293f44ab766f2126349c3bb9a422f19f | Nish76ant/Multiple-Inheritence-in-Python-Code | /MultipleInheritence.py | 1,386 | 3.6875 | 4 | class Employee:
noOfLeaves = 8
var = 8
def __init__(self,name,role,salary):
self.name = name
self.role = role
self.salary = salary
def printDetailsofEmp(self):
return f'Hey your name is {self.name} and your role is {self.role} and your salary is {self.salary}'
@classmethod
def changeOfleaves(cls,newleaves):
cls.noOfLeaves = newleaves
@classmethod
def from_str(cls,string):
params = string.split("-")
#print(params)
return cls(params[0],params[1],params[2])
@staticmethod
def printgood(string):
print('This is good'+string)
return 'Hii'
class Player:
noOfGames = 4
var = 9
def __init__(self,name,game):
self.name = name
self.game = game
def printdetails(self):
return f' the name is {self.name} and game is {self.game}'
class coolprogrammer(Employee,Player):
language = "C++"
var = 10
def printlange(self):
return f'{self.language}'
Rajan = Employee('Rajan','Developer',25000)
rohan = Employee('Rohan','Computer Science Engineer',25000)
shubham = Player('Shubham',['Cricket'])
karan = coolprogrammer('Karan',34000,'Cool Programmer')
print(karan.printlange())
print(karan.var)
#det = karan.printDetailsofEmp()
#print(karan.language)
#print(karan.noOfGames)
#print(det)
|
60f24bde8f1acd6637010627b439584eb8d08f32 | mosesobeng/Lab_Python_04 | /Lab04_2_3.py | 1,048 | 4.3125 | 4 | print 'Question 2'
##2a. They will use the dictionary Data Structure cause they will need a key and value
## where stock is the key and price is the value
shopStock ={'Apples ' : '7.3' , 'Bananas ' : '5.5' , 'Bread ' : '1.0' , 'Carrots ':'10.0','Champagne ':'20.90','Strawberries':'32.6'}
print 'The Initial Items in the store'
for i in shopStock:
print i +' '+ shopStock[i]
print''
##Changing the value of straberries
shopStock['Strawberries']='63.43'
##Adding another item to dictionary
shopStock['Chicken ']='6.5'
print 'The Final Items in the store'
for i in shopStock:
print i +' '+ shopStock[i]
print''
print''
print''
print 'Question 3'
##3a. The list should be used
##
##3b.
print 'The List for advertisement'
in_stock = shopStock.keys()
##3c.
always_in_stock=()
##convertion from list to tuple
always_in_stock+=tuple(in_stock)
##3d.
print ''
print 'Come to shoprite! We always sell:'
for i in always_in_stock :
print i
|
8e6b5ddf4a8e8199af33626c2d5f96513002fab1 | apatten001/Car_repair | /car_repair.py | 678 | 3.703125 | 4 | from parts import part
class CarRepair:
def __init__(self):
self.part = input("What part do you need?: ")
self.part = self.part.capitalize()
self.cost = part.get(self.part)
self.labor = 1.75
# this gets the part and cost from dictionary
def parts_cost(self):
if self.part in part:
print(f"The {self.part} will cost ${self.cost} to order.")
else:
print("We don't have that item in stock")
def estimate(self):
print("Your estimate for the repair of the %s will be $%.2f." % (self.part, float(self.cost * self.labor)))
Acura = CarRepair()
Acura.parts_cost()
Acura.estimate()
|
681b30c132deb92cdb9188bfee4ab8f683f85a9e | HammadAhmedSherazi/Python-Assignment-2-3 | /python assignment 3/DictionaryAdd.py | 177 | 3.609375 | 4 | personal_info={"Name": "Hammad Ahmed","Contact No.": "0304-********", "Email":"abc@gmail.com"}
print (personal_info)
personal_info["age"]=int(input("Enter your age:"))
print (personal_info) |
cbec5a76e403c55dacae345a07bbd42a941befd8 | anahm/4word-game | /wordmatch.py | 3,036 | 3.78125 | 4 |
import re
def main():
# want to randomly print out a word.
print "Insert random word here.\n"
while True:
user_word = raw_input("Your turn: ").upper()
if (not check(user_word)):
print "Try again? Word is: " + next_word + "\n"
else:
# add the word to known words..
said_words.append(user_word)
next_word = find_next(user_word)
if (len(next_word) < 4):
print "No more words can be found. You're da wordmaster!\n"
break
# otherwise, good! print that thing
print "\n" + next_word + "\n"
said_words.append(next_word)
def check_said(new):
# If it's already been said, then that's bad too!
for word in said_words:
if (new == word):
return False
return True
def check_dict(new):
f = open('4words.txt', 'r')
# I guess just linear search through for the word in the total list..
for line in f:
if (new == line[:-1]):
f.close()
return True
f.close()
return False
def check_related(new):
if (len(said_words) == 0):
return True
# can only be one character off from the previously added word.
# use simple hamming distance? - Saagar
diffs = 0
for ch1, ch2 in zip(new, said_words):
if ch1 != ch2:
diffs += 1
if diffs == 1:
return True
return False
# regex = '[A-Z]'
# patterns = []
# patterns.append(new.replace(new[0], regex))
# patterns.append(new.replace(new[1], regex))
# patterns.append(new.replace(new[2], regex))
# patterns.append(new.replace(new[3], regex))
# for p in patterns:
# m = re.search(p, said_words[-1])
# if (m):
# return True
# return False
def check(new):
if (len(new) != 4):
return False
if (not check_dict(new)):
print "Not a valid word! "
return False
if (not check_said(new)):
print "Already been said! "
return False
# already know hasn't been said, just check character off
if (not check_related(new)):
print "Too many characters off! "
return False
return True
def find_next(new):
# painfully stupid...just switch out each possible letter and then call
# check?
regex = '[A-Z]'
patterns = []
patterns.append(new.replace(new[0], regex))
patterns.append(new.replace(new[1], regex))
patterns.append(new.replace(new[2], regex))
patterns.append(new.replace(new[3], regex))
f = open('4words.txt', 'r')
for p in patterns:
for line in f:
m = re.search(p, line)
if (m):
next_word = line[m.start():m.end()]
if (check_said(next_word)):
f.close()
return next_word
f.close()
return "no"
# create a list of the words that have been said.
# TODO - use a set here? O(1) lookup - Saagar
said_words = []
main()
|
e6b31f6dc70f44c41294c46fc3b262a876a8f133 | CRTejaswi/Python3 | /Text Processing/ROT13/rot13v1.py | 1,352 | 3.890625 | 4 | """rot13v1 = Convert command-line input to ROT13 format"""
######################## IMPORT LIBRARIES #######################
import sys
import string
########################## DICTIONARIES #########################
CHAR_MAP = dict(list(zip(string.ascii_lowercase, string.ascii_lowercase[13:36]+string.ascii_lowercase[0:13])))
##################### FUNCTION DECLARATIONS #####################
# Return 13-shifted character notation of a letter
def rot13_letter(letter):
do_upper = False
if letter.isupper():
do_upper = True
letter = letter.lower()
if letter not in CHAR_MAP:
return letter
else:
letter = CHAR_MAP[letter]
if do_upper:
letter = letter.upper()
return letter
########################## MAIN PROGRAM #########################
if __name__ == '__main__':
for char in sys.argv[1]:
sys.stdout.write(char)
sys.stdout.write('\n')
for char in sys.argv[1]:
sys.stdout.write(rot13_letter(char))
sys.stdout.write('\n')
#################################################################
"""
NOTE: From Windows Command Line, change to directory where the script
is stored, then type:
python rot13v1.py "Hi, My Name is ... Slim Shady"
Replace the text in quotes with something you like.
"""
|
eb7a489b667d475b5808ccb20cc03604e022dba7 | CRTejaswi/Python3 | /Text Processing/PyPDF2/7.py | 1,409 | 3.5 | 4 | """ Python3: Extract text from pdf file and copy into txt file """
import PyPDF2
pdf_pages = [] # Page object container
pdf_text = [] # Page text container
pages = [int(i) for i in input('Enter page numbers to split text for: ').split(',')]
# Initialize input pdf file
in_pdf = open(r'path/to/input.pdf', 'rb')
pdf_reader = PyPDF2.PdfFileReader(in_pdf) # Reader element
for page in pages:
pdf_pages.append(pdf_reader.getPage(page-1))
for i in range(len(pdf_pages)):
try:
pdf_text.append(pdf_pages[i].extractText())
except:
pdf_text.append('<NO_TEXT_EXTRACTED>')
pass
in_pdf.close()
# Initialize output txt file using 'with' context-manager
with open(r'path/to/output.txt','w') as txt_file:
for page,page_txt in zip(pages,pdf_text):
txt_file.write('\n=={}==\n'.format(page)+page_txt) # Insert page-numbers alongwith text
"""
Note
1. pdf_pages = [] # Every element is a single-page object
pdf_text = [] # Every element is a single-page text-string
2. It'd be really helpful if you could suggest a better way to insert page number (without using multiprocessing).
3. The efficiency is no-way close to 'pdftotext'. This one's just for fun!
An easier alternative (especially for pages in range) would be to use:
>>> import os
>>> os.system('pdftotext -f 1 -l 10 -layout /path/to/input.pdf /path/to/output.txt')
"""
|
52f3c8c96b86ac7d6eace0b3102b31dbec0bd750 | CRTejaswi/Python3 | /Basics/SimpleCalc.py | 1,426 | 3.734375 | 4 | """ SimpleCalc: Four-Function Calculator """
#################### FUNCTION INITIALIZATIONS ###################
def Add(x,y):
print('Sum = ',x+y)
def Sub(x,y):
print('Difference = ',x-y)
def Mul(x,y):
print('Product ',x*y)
def Div(x,y):
print('Quotient = ',x/y)
#################################################################
########################## MAIN PROGRAM #########################
legalTup = (1,2,3,4)
flag = 0
restart = 1
print('This Is A Simple Calculator')
while restart:
print('==== Choose Functionality ====')
print('Add (1)\nSubstract (2)\nMultiply (3)\nDivide (4)')
usrInput = int(input('Choose Option (1-4): '))
print('==============================')
for i in range(0,4):
if (usrInput == legalTup[i]):
flag = 1
break
if flag == 0:
print('Incorrect Response, Try Again!')
else:
print('Enter Values of (x,y): ')
x = float(input())
y = float(input())
if usrInput == 1:
Add(x,y)
elif usrInput == 2:
Sub(x,y)
elif usrInput == 3:
Mul(x,y)
else:
Div(x,y)
rst = input('Restart? (y|n)')
if (rst == 'y' or rst == 'Y'):
restart = 1
elif (rst == 'n' or rst == 'N'):
restart = 0
else:
print('Invalid Choice!')
break
#################################################################
|
59372d406d16df1fb4db37440ceee32b0f466345 | byunseob/python-study | /파이썬 코딩의 기술/chapter-04-mataclss & attribute/29.Use generic attributes instead of getters and setter methods/main.py | 1,972 | 3.546875 | 4 | # 파이썬에서는 명시적인 게터와 세터를 구현할 일이 거의 없다.
class Resistor(object):
def __init__(self, ohms):
self.ohms = ohms
self.voltage = 0
self.current = 0
r1 = Resistor(50e3)
r1.ohms = 10e3
r1.ohms += 5e3
class VoltageResistance(Resistor):
def __init__(self, ohms):
super().__init__(ohms)
self._voltage = 0
@property
def voltage(self):
return self._voltage
@voltage.setter
def voltage(self, voltage):
self._voltage = voltage
self.current = self._voltage / self.ohms
r2 = VoltageResistance(1e3)
print(r2.current)
r2.voltage = 10
print(r2.current)
# 프로퍼티에 setter 를 설정하면 클래스에 전달된 값들의 타입을 체크하고 값을 검증할 수도 있다.
class BoundedResistance(Resistor):
def __init__(self, ohms):
super().__init__(ohms)
@property
def ohms(self):
return self._ohms
@ohms.setter
def ohms(self, ohms):
if ohms <= 0:
raise ValueError(f"{ohms} ohms muse be > 0")
self._ohms = ohms
r3 = BoundedResistance(1e3)
# r3.ohms = 0 #ValueError: 0 ohms muse be > 0
# 부모 클래스의 __init__함수 때문에 세터 메소드가 호출되기 때문
# 객체 생성이 완료되기도 전에 곧장 검증 코드가 실행
# BoundedResistance(-5) #ValueError: -5 ohms muse be > 0
class FixedResistance(Resistor):
def __init__(self, ohms):
super().__init__(ohms)
@property
def ohms(self):
return self._ohms
@ohms.setter
def ohms(self, ohms):
if hasattr(self, '_ohms'):
raise AttributeError("Can't set attribute")
self._ohms = ohms
# @property 의 가장 큰 단점은 속성에 대응하는 메서드를 서브클래스에서만 공유할 수 있다는 점
# @property 메서드로 세터와 게터를 구현할 때 예상과 다르게 동작하지 않게 해야한다.
|
6ef55cc4ae921f109d089d680e7af4d2bf040574 | byunseob/python-study | /파이썬 코딩의 기술/chapter-01-pythonic/08.simple comprehension/main.py | 349 | 4.0625 | 4 | # 리스트 컴프리헨션은 다중 루프와 루프 레벨별 다중 조건을 지원한다.
# 표현식이 두 개가 넘게 들어 있는 리스트 컴프리 헨션은 가독성상 좋지 않아 지양해야한다.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
1d9273f5c011deea21d1f9c16a6a8c4f5f40181c | byunseob/python-study | /파이썬 코딩의 기술/chapter-01-pythonic/07.comprehension/main.py | 830 | 3.640625 | 4 | # comprehesion 이란 iterable 한 오브젝트를 생성하기 위한 방법중 하나로 파이썬에서 사용할 수 있는 유용한 기능중 하나이다.
# List Comprehension (LC)
# Set Comprehension (SC)
# Dict Comprehension (DC)
# Generator Expression (GE)
# Generator 의 경우 comprehension 과 형태는 동일하지만 특별히 expression이라고 부른다.
# 한 리스트에서 다른 리스트를 만들어내는 간결한 문법
# 이 문법을 사용한 표션힉을 리스트 컴프리헨션 이라고 함.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [x ** 2 for x in a if x % 2 == 0]
print(squares)
# [4, 16, 36, 64, 100]
# 리스트 컴프리헨션을 사용하면 조건식으로 아이템을 간편하게 걸러 낼 수 있음
# 출처 https://mingrammer.com/introduce-comprehension-of-python/
|
03ec68ab4d4d9173202c346d34313a29dbd63340 | byunseob/python-study | /파이썬 코딩의 기술/chapter-06-Built-in module /47. Use decimal when precision is important/main.py | 633 | 3.609375 | 4 | from decimal import Decimal, ROUND_UP
rate = Decimal('1.45')
seconds = Decimal('222')
cost = rate * seconds / Decimal('60')
print(cost)
rounded = cost.quantize(Decimal('0.01'), rounding=ROUND_UP)
print(rounded)
rate = Decimal('0.05')
seconds = Decimal('5')
cost = rate * seconds / Decimal('60')
print(cost)
rounded = cost.quantize(Decimal('0.01'), rounding=ROUND_UP)
print(rounded)
# 데시몰이 고정 소수점 수에도 잘 동작하지만 아직도 정확도 면에서는 제약이 있다
# 정확도에 제한이 없는 유리수를 표현하려면 내장 모듈 fractions 의 Fraction 클래스를 사용해야 한다.
|
87aa6b093cf79a2d013ca7a8d2538c5af2933e54 | priyansh210/Airline_Reservation_and_Management_System-python | /admin/cancel_a_flight.py | 1,088 | 3.78125 | 4 |
import pandas as pd
import menu.adminmenu as adminmenu
import sql
mycursor=sql.mycursor
mydb=sql.mydb
def cancel_flight():
df=pd.read_sql("SELECT CODE ,AIRLINE, F AS FROM_ , T AS TO_ ,DOF FROM FLIGHT",mydb)
print(df)
code = int(input("ENTER THE CODE OF FLIGHT YOU WANT TO DELETE : "))
code_list=list(df.loc[:,'CODE'])
if code not in code_list:
print("ENTER A VALID CODE ! ")
return adminmenu.admin_menu()
print("YOU WANT TO DELETE FLIGHT CODE :",code)
print(pd.read_sql("SELECT CODE ,AIRLINE, F AS FROM_ , T AS TO_ ,DOF FROM FLIGHT WHERE CODE = {} ".format(code),mydb))
x=input("\n Proceed ? >")
if x in ['No','no','N','n']:
return cancel_flight()
else:
mycursor.execute("DELETE FROM FLIGHT WHERE CODE = '{}' ".format(code))
mycursor.execute("DELETE FROM SEATS WHERE CODE = '{}' ".format(code))
mycursor.execute("DELETE FROM BOOKING WHERE CODE = '{}' ".format(code))
mydb.commit()
print("\n FLIGHT CANCELLED !")
return adminmenu.admin_menu()
|
f1006fb3f36057afe070ac8faf9f6a09de74905e | annaVR/solutions | /src/ww_coding_exercise_1.py | 914 | 3.859375 | 4 | #!/usr/bin/env python3
import sys
def does_file_exists(path):
try:
f = open(path, "r")
f.close()
return True
except Exception as e:
print(e)
def read_from_file(path):
f = open(path, "r")
text = f.read()
f.close()
return text
def get_dictionary(text):
lines = text.splitlines()
dictionary = {}
for line in lines:
split_line = line.split(" – ")
dictionary[split_line[0]] = split_line[1].split(",")
return dictionary
def print_dictionary(dictionary):
for k, v in dictionary.items():
print(k)
for item in v:
print(item.strip())
def main(path):
if does_file_exists(path):
text = read_from_file(path)
dictionary = get_dictionary(text)
print_dictionary(dictionary)
if __name__ == "__main__":
main(str(sys.argv[1]))
# main("../tst/resources/input.txt")
|
d8b247312829600f153881f92a1bba5c36b54466 | D4DeepakJain/Python | /12.py | 200 | 3.984375 | 4 | def fact(num):
if num > 1:
return num * fact(num - 1)
else:
return num
print('enter number')
a=int(input())
if(a==0):
print('Not Possible')
else:
print(fact(a))
|
b09ebfb2af075572e6650fa153f8314a80db71ab | D4DeepakJain/Python | /29.py | 239 | 3.609375 | 4 | def check(str):
a = 0
strv = 'aeiou'
vowels = set(strv)
for i in vowels:
if i in set(str.lower()):
a= a +1
if a==5:
print('Accept')
else:
print('Not Accept')
check(input()) |
8b49f8a95c096964da16109997761bddcaf6487b | danidassler/CloudBigData | /HOMEWORK/DanielSanzMayo-HomeworkA/P5-MeteoriteLanding/P5_reducer.py | 469 | 3.515625 | 4 | #!/usr/bin/python
import sys
previous = None
sum = 0
average = 0
count = 0
for line in sys.stdin:
key, value = line.split( '\t' )
if key != previous:
if previous is not None:
average = sum / count
print (previous + '\t' + str(average))
previous = key
sum = 0
count = 0
count = count + 1
sum = sum + float(value)
average=sum/count
print (previous + '\t' + str(average))
#Daniel Sanz Mayo
|
f63bd219bb89d94f41d8aecea52d6b87ab0ab3a7 | rafaelfneves/ULS-WEB-III | /aula03/aula3.py | 2,116 | 4.34375 | 4 | # -*- coding: utf-8 -*-
print('==============================[INICIO]==============================')
#String
frase=('Aula Online')
#upper() - para colocar em letra maiuscula
print(frase.upper())
print(frase.upper().count('O'))
#lower() - para colocar em letra minúscula
print(frase.lower())
#capitalize()
print(frase.capitalize())
#title() - vai analisar quantas palavras tem essa string, e transformar todas as primeiras letras de cada palavra
print(frase.title())
#swapcase() - inverte a caixa da string, o que é maiusculo vira minusculo e vice versa
print(frase.swapcase())
#strip() - remove os espaços
print(frase.strip())
#rstrip() - Remove espaço do lado direito
print(frase.rstrip())
#rstrip() - Remove espaço do lado esquerda
print(frase.lstrip())
#split() - dividir em sub strings, uma função que retorna uma lista
print(frase.split())
#join() - para definir o separador da palavra
print('-'.join(frase))
#===formatação de string===
#center() - centralizar
print(frase.center(100))
print(frase.center(100,'*'))
#ljust() - para alinhar a esquerda
print(frase.ljust(100))
print(frase.ljust(100,'-'))
#rjust() - para alinhar a direita
print(frase.rjust(100))
print(frase.rjust(100,'&'))
#Estruturas Condicionais - simples(if); composta(else); aninhada(elif)
a=7
b=9
if a>b:
print('A variavel A é maior: {}'.format(a))
if a<b:
print('A variavel B é maior: {}'.format(b))
#tipo um scanf
nome=input("\nQual o seu nome?")
if nome=='Rafael':
print('Esse nome é maravilhoso')
print('Bom dia!!{}'.format(nome))
#Exemplo de condicional composta
ano=int(input('\nQuantos anos tem o seu carro?'))
if ano <= 5:
print('Carro Novo')
else :
print('Carro Velho')
n1= float(input('Digite a nota 1: '))
n2= float(input('Digite a nota 2: '))
media = n1+n2/2
if media >= 7:
print('Passou!')
else:
print('Reprovou!')
#Indicar se o numero digitado é par ou impar
print('================================[FIM]================================') |
863c76edceb3d1e98acd52d7b45b114153532a1f | PreetiChandrakar/Letsupgrade_Assignment | /Day1.py | 634 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
num=int(input("Enter Number to check prime or not:"))
m=0
i=0
flag=0
m=int(num/2)
for i in range(2,m+1):
if(num%i==0) :
print("Number is not prime")
flag=1
break
if(flag==0) :
print("Number is prime")
# In[3]:
num=int(input("Enter Number to get Factotial:"))
i=0
fact = 1
for i in range(2,num+1) :
fact = fact * i
print("Factorial of",num, "is:",fact)
# In[8]:
num=int(input("Enter Number till you need to find sum from 1 to:"))
i=1
sum =0
while(i<=num):
sum = sum + i
i=i+1
print(sum)
# In[ ]:
|
348f13f98d6764633d8d2b49b2e3eb9b20d280b7 | Manuel-condori/mastermind-hack-day | /codeBreaker.py | 1,607 | 3.84375 | 4 | #!usr/bin/python3
""" CodeBreaker class """
from constants import *
class CodeBreaker:
def __init__(self):
""" initializes an instance """
pass
def makeGuess(self, guessCount):
""" returns a validated guess """
guessesLeft = MAX_NUMBER_OF_GUESSES - guessCount
print('\nNumber of guesses left: {}'.format(guessesLeft))
guess = input(GUESS_PROMPT).split()
inputValidationResult = self._validateUserInput(guess)
self._printUserFriendlyErrorMessage(inputValidationResult)
while inputValidationResult is not None:
guess = input(GUESS_PROMPT).split()
inputValidationResult = self._validateUserInput(guess)
self._printUserFriendlyErrorMessage(inputValidationResult)
return guess
def _validateUserInput(self, guess):
""" validates user input """
if 'exit' in guess:
print('Goodbye...')
quit()
if len(guess) != GUESS_LENGTH:
return MISSING_INPUT_ERROR_CODE
for color in guess:
if color not in PEG_COLORS:
return UNKNOWN_COLOR_ERROR_CODE
return None
def _printUserFriendlyErrorMessage(self, errCode):
""" prints error messages based on user input """
if errCode == MISSING_INPUT_ERROR_CODE:
print('Please enter 4 colors.')
print(USER_INPUT_ERROR_MSG)
elif errCode == UNKNOWN_COLOR_ERROR_CODE:
print('Wrong color provided.')
print(USER_INPUT_ERROR_MSG)
else: # assume None
return
|
b72c0c78beeda2947dd05fee51dbdbb47ef0d5fa | BryceBeagle/IntelligentLanguage | /tokenizer.py | 3,959 | 3.6875 | 4 | def getWords():
# Position of token [line, first character (inclusive), last character (exclusive)]
lineNumber = 1
for line in tester.readlines():
startChar = 1
endChar = 1
tempToken = ""
# Iterate through each character
for char in line:
endChar += 1
# Actions
# ------------------------
# Whitespace: Tokenize previous word if existent. Ignore whitespace
# Parens : Tokenize previous word if existent. Tokenize paren
# Operators : Tokenize previous word if existent. Tokenize operator
# Semicolon : Tokenize previous word if existent. Tokenize semicolon
# New line : Tokenize previous word if existent. Tokenize new line
# Other : Add character to token string
# Whitespace (not including new line)
if char in " \t":
# Only add new token if there is one to add
if tempToken != "":
words.append([tempToken, [lineNumber, startChar, endChar - 1]])
tempToken = ""
# Move start position to current position last token
startChar = endChar
#
elif char in "(){}+-*/=;\n":
# Add previous token if there is one.
# This is for situations where there is no space before the current character
if tempToken != "":
words.append([tempToken, [lineNumber, startChar, endChar - 1]])
tempToken = ""
# Set token start position to end position of last token
startChar = endChar
# Also add token for character
words.append([char, [lineNumber, startChar, endChar]])
startChar = endChar
else:
# Add character to tempToken string
tempToken += char
lineNumber += 1
def getTokens():
for word in words:
# tokenLocation = None
tokenType = None
tokenValue = None
if isNumber(word[0]):
tokenType = 'NUMBER'
tokenValue = float(word[0])
elif isString(word[0]):
tokenType = 'STRING'
tokenValue = word[0]
else:
tokenTypeTemp = tokenTypes.get(word[0])
if not tokenTypeTemp:
tokenType = 'NAME'
tokenValue = word[0]
else:
tokenType = tokenTypeTemp
tokenValue = word[0]
tokens.append([tokenType, tokenValue, word[1][0], word[1][1], word[1][2]])
def isNumber(test):
try:
float(test)
return True, test
except ValueError:
return False
def isString(test):
return '"' in test
tester = open('tester.java')
# Others are NUMBER, NAME, STRING
tokenTypes = {'for' : 'FOR',
'while' : 'WHILE',
'public' : 'ACCESS_MODIFIER',
'private': 'ACCESS_MODIFIER',
'(' : 'PAREN',
')' : 'PAREN',
'{' : 'CURLY',
'}' : 'CURLY',
'void' : 'TYPE',
'int' : 'TYPE',
'double' : 'TYPE',
'String' : 'TYPE',
'class' : 'TYPE',
'+' : 'OPERATOR',
'-' : 'OPERATOR',
'*' : 'OPERATOR',
'/' : 'OPERATOR',
'=' : 'EQUAL',
';' : 'SEMICOLON',
'\n' : 'NEWLINE'
}
words = []
tokens = []
getWords()
getTokens()
print(words)
print(tokens)
file = open('testerOut.tkn', 'w')
for token in tokens:
# Write tokens to file. Make sure \n's are formatted correctly
file.write(", ".join(map(str, token[:])).replace("\n", "\\n") + "\n")
file.close()
|
ca042ea9f14a92d57b1af6db4494e139c99a3423 | nm4archana/parking-lot-design | /park_unpark.py | 8,990 | 3.5 | 4 | # Lastline parking challenge. Please see task description in accompanying PDF for details.
import threading
from datetime import datetime
import math
# define the 15 minute minimum parking interval
MINIMUM_PARKING_INTERVAL_SECONDS = 15*60
# define the minimum number of spaces for each row
MAXIMUM_NO_OF_SPACES_PER_ROW = 10
GOT_SPACE = True
LOST_SPACE = False
NO_SPACE = None
CHARGE_HANDICAPPED = 5
CHARGE_COMPACT = 5
CHARGE_LARGE = 7.50
class InvalidInputError(Exception):
"""
Raised if the provided API input is invalid.
"""
def park(size, has_handicapped_placard):
"""
Return the most appropriate available parking space for this vehicle. Refer to
challenge description for explanation of how to determine the most appropriate space
:param size: vehicle size. For now this is 'compact_car' or 'large_car'
:type size: `str`
:param has_handicapped_placard: if True, provide handicapped space (if available)
:type has_handicapped_placard: `bool`
:returns: parking location. tuple of (level, row, space), or None if no spaces available.
Level, row and space numbers start at 1.
:rtype: tuple(`int`,`int`,`int`)
:raises InvalidInputError: if size invalid
"""
if size not in ['compact_car','large_car']:
raise InvalidInputError('Wrong input!!')
# Flag set to True if allocated a space in row corresponding to 'large_car'
charge_high = False
if has_handicapped_placard is True:
# t_space is a tuple - (space,boolean) returned from findspace method
t_space = findspace(code['handicapped'])
# Restart search if space lost to different thread
space = t_space[0] if t_space[1] is GOT_SPACE else park(size, has_handicapped_placard)
# If no 'handicapped' space available, continue search in 'compact_car' & 'large_car'
if space is NO_SPACE:
if size is 'compact_car':
t_space = findspace(code['compact_car'])
space = t_space[0] if t_space[1] is GOT_SPACE else park(size, has_handicapped_placard)
if space is NO_SPACE or size in 'large_car':
t_space = findspace(code['large_car'])
space = t_space[0] if t_space[1] is GOT_SPACE else park(size, has_handicapped_placard)
else:
if size is "compact_car":
t_space = findspace(code['compact_car'])
space = t_space[0] if t_space[1] is GOT_SPACE else park(size, has_handicapped_placard)
if space is NO_SPACE:
charge_high = True
t_space = findspace(code['large_car'])
space = t_space[0] if t_space[1] is GOT_SPACE else park(size, has_handicapped_placard)
else: # size is "large_car"
t_space = findspace(code['large_car'])
space = t_space[0] if t_space[1] is GOT_SPACE else park(size, has_handicapped_placard)
if space is NO_SPACE:
print "The parking is full!!"
return -1, -1, -1
# update the park_details dictionary which is used for calculating the time and cost
if has_handicapped_placard is True:
park_details[space] = (CHARGE_HANDICAPPED, datetime.now())
elif size is "compact_car" and charge_high is False:
park_details[space] = (CHARGE_COMPACT, datetime.now())
else:
park_details[space] = (CHARGE_LARGE, datetime.now())
return space
def findspace(code_v):
"""
Return the space (if available) for parking
:param code_v: code for 'compact_car' or 'large_car' or 'handicapped'
:type code_v: int
:returns: Space allocated
:rtype: tuple
"""
# Iterate through every level
for i in range(len(parking_structure)):
size_space_tuples = parking_structure[i]
# Iterate through every row
for j in range(len(size_space_tuples)):
# Check if the row belongs to the code (compact_car or large_car or hadicapped) and if space is available
if parking_structure[i][j][0] is code_v and parking_structure[i][j][1] < MAXIMUM_NO_OF_SPACES_PER_ROW:
spot = getspot(i, j, parking_structure[i][j][1])
space = ()
# If the thread gets the space , then space is allocated and returned
if spot[0] is GOT_SPACE:
space = (i + 1, j + 1, spot[1])
return space, GOT_SPACE
else:
# Returned if the thread dis not acquire the lock i.e No space is allocated yet
return space, LOST_SPACE
# Returned if parking is full
return NO_SPACE, True
def unpark(location):
"""
Return the charge for parking at this location based on location type and time spent.
Refer to challenge description for details on how to calculate parking rates.
:param location: parking space the vecicle was parked at as tuple (level, row, space)
:type location: tuple(`int`,`int`,`int`)
:returns: The total amount that the parker should be charged (eg: 7.5)
:rtype: float
:raises InvalidInputError: if location invalid or empty
"""
if location not in park_details:
raise InvalidInputError('Wrong input!!')
# Calculate the time difference in seconds
time_diff = (datetime.now() - park_details[location][1]).total_seconds()
# Calculate the total amount
if time_diff <= MINIMUM_PARKING_INTERVAL_SECONDS:
total_amount = park_details[location][0]
else:
total_amount = park_details[location][0] * math.ceil(time_diff/MINIMUM_PARKING_INTERVAL_SECONDS)
i = location[0]-1
j = location[1]-1
#Call function to release spot after unpark
releasespot(i, j, location[2]-1)
park_details.pop(location, None)
# Return the total amount
return total_amount
def getspot(level, row, space_count):
"""
Allocates a space for parking
:param level: Level in which the space has to be allocated
:param row: Row in which the space has to be allocated
:param space_count: Space allocated
:return: Returns tuple of flag(space allocated or not allocated) and the space
"""
# Acquire the lock before making changes to level
lock.acquire()
set_flag = False
k = -1
if space_count is parking_structure[level][row][1]:
spot = parking_structure[level][row][2]
for k in range(len(spot)):
if spot[k] is 0:
# Allocating a space
spot[k] = spot[k] + 1
break
parking_structure[level][row][2] = spot
# Incrementing the count in the level
parking_structure[level][row][1] = parking_structure[level][row][1] + 1
set_flag = True
# Release the lock
lock.release()
return set_flag, k+1
def releasespot(level,row,s):
"""
Releases the spot allocated.
:param level: Level in which the space is allocated
:param row: Row in which the space is allocated
:param s: Space allocated
"""
# Acquire the lock before making changes to level
lock.acquire()
# Decrementing the count in the level
parking_structure[level][row][1] = parking_structure[level][row][1] - 1
spot = parking_structure[level][row][2]
for k in range(len(spot)):
if k is s:
# De-allocating a space
spot[k] = spot[k]-1
parking_structure[level][row][2] = spot
break
# Release the lock
lock.release()
def printlevel():
"""
Prints the parking levels
"""
print "\n************PARKING STRUCTURE********************"
for i in range(len(parking_structure)):
list_a = []
for j in range(len(parking_structure[i])):
list_a.append(parking_structure[i][j][1])
print "Level:",i+1,list_a
print "**************************************************\n"
def init():
"""
Called on system initialization before any park/unpark function is called.
"""
global code, parking_structure, lock, park_details
# Dictionary to store the codes for type of car and 'handicapped'
code = {'compact_car': 1, 'large_car': 2, 'handicapped': 3}
"""
List to store the rows in each level, type of row(compact_car or handicapped or large_car),space count & spaces.
parking_structure[l][r] = {[type-code, count, space]..}, where space = [0]*10
"""
parking_structure = [[[3, 0, [0] * 10], [3, 0, [0] * 10], [1, 0, [0] * 10], [1, 0, [0] * 10], [1, 0, [0] * 10], [1, 0, [0] * 10]],
[[1, 0, [0] * 10], [1, 0, [0] * 10], [1, 0, [0] * 10], [1, 0, [0] * 10], [2, 0, [0] * 10], [2, 0, [0] * 10], [2, 0, [0] * 10], [2, 0, [0] * 10]],
[[1, 0, [0] * 10], [1, 0, [0] * 10], [1, 0, [0] * 10], [1, 0,[0] * 10], [2, 0, [0] * 10], [2, 0, [0] * 10], [2, 0, [0] * 10], [2, 0, [0] * 10]]]
# Dictionary to store the allocated space , time and cost
park_details = dict()
# Thread object
lock = threading.Lock()
|
218f8f5bc6dc213366ac36c7ae4ca39a34a0f66d | rajivsarvepalli/Python-Projects | /gmuwork/graphs_and_visuals/stack_plotter.py | 2,701 | 3.53125 | 4 | def bar_stack_grapher(values,bar_labels,colors,barwidth=1,legend_values=None,x_label=None,y_label=None,title=None,x_lim=None,y_lim=None,plt_show=True):#modify latetr make eay interface
'''
input: values in a array that follow the format that each bar is one row\n
bar_labels label what the bars and determine the number of bars\n
colors is the colors to use for each stack len(colors) must = len(values[0])
barwidth is the width of the bars\n
legned_values is what each color of the bar represents\n
x_label,y_label are labels for x, and y axis\n
title is title of the plot\n
x_lim,y_lim are limits of x-axis and y-axis\n
plt_show determines whether the plot is hown at the end
output: a stacked bar graph plotted in matplotlib
'''
import matplotlib.pyplot as plt
import numpy as np
values= np.array(values)
try:
t,v = np.shape(values)
except ValueError:
values = np.array([values])
if len(colors)!=len(values[0]):
raise ValueError("Length of colors must equal len of times")
if len(values)!=len(bar_labels):
raise ValueError("the number of value's rows must equal length of bar_labels")
x_values_of_bars =[]
barw =round(barwidth)
for i in range((barw)+1,((int)(barw)+1)*(len(bar_labels))+barw+1,int(barw)+1):
x_values_of_bars+=[i]
f, ax1 = plt.subplots(1)
bars=[]
for z in range(0,len(bar_labels)):
for i in range(0,len(values[0])):
bars.append(ax1.bar(x_values_of_bars[z], values[z,i],width=barwidth, color = colors[i],bottom=np.sum(values[z,0:i])+0)[0])
bars = bars[0:len(values[0])]
plt.xticks(x_values_of_bars, bar_labels)
if x_label !=None:
ax1.set_xlabel(x_label)
if y_label !=None:
ax1.set_ylabel(y_label)
if title != None:
plt.title(title)
if x_lim !=None:
plt.xlim(x_lim)
else:
plt.xlim([min(x_values_of_bars)-barwidth, max(x_values_of_bars)+barwidth])
if y_lim !=None:
plt.ylim(y_lim)
if legend_values ==None:
raise ValueError("legend_values set to none while show_legend is true")
elif len(bars)!=len(legend_values):
raise ValueError("length of bars(columns of values) not equl to lentgh of legend_values")
else:
plt.legend(tuple(bars),tuple(legend_values))
if plt_show:
plt.show()
if __name__ =="__main__":
#testing here
bar_stack_grapher([10,20,30,40],['Times for Ensemble Testing(all parts) using clasifiers: (GaussianNB, GaussianProcess, RandomForestClassifier) '],['b','g','y','r'],legend_values=['Load Data','Oversampling Method(cluster)','Fitting Ensemble','Predicting with Ensemble']) |
a8ffbaa72ba79b8f6ca2e90742a12814f510393d | muonictonic/poker | /Hand.py | 5,546 | 3.609375 | 4 | from Deck import *
class Hand(object):
def __init__(self, hand):
self.hand = hand
self.sortHand()
#Sorts the hand by rank and suit
def sortHand(self):
self.hand.sort()
#Creates a histogram of the frequencies of each rank for use
#in determining the hand's type
def rankHistogram(self):
h = dict()
for card in self.hand:
if card.rank not in h:
h[card.rank] = 1
else:
h[card.rank] += 1
return h
#Returns a list of the ranks of each card in the hand
def getRankList(self):
ranks = []
for card in self.hand:
ranks.append(card.rank)
return ranks
#Returns a list of the suits of each card in the hand
def getSuitList(self):
suits = []
for card in self.hand:
suits.append(card.suit)
return suits
#Returns true if there is a pair in the hand, and the value of those cards
def pair(self):
onePair = False
for rank, freq in self.rankHistogram().items():
if freq == 2:
return True, rank
return False, None
#Returns true if there are twp pairs in the hand,
#and the value of those cards
def twoPair(self):
havePair = False
for rank, freq in self.rankHistogram().items():
if freq == 2 and not havePair:
rank1 = rank
havePair = True
elif freq == 2 and havePair:
return True, rank1, rank
return False, None, None
#Returns true if there is a three of a kind in the hand,
#and the value of those cards
def threeOfaKind(self):
for rank, freq in self.rankHistogram().items():
if freq == 3:
return True, rank
return False, None
#Returns true if there is a four of a kind in the hand,
#and the value of those cards
def fourOfaKind(self):
for rank, freq in self.rankHistogram().items():
if freq == 4:
return True, rank
return False, None
#Returns true of the hand is a straight
def straight(self):
ranks = self.sortRank(self.getRankList())
for i in range(len(ranks) - 1):
if ranks[i + 1] != ranks[i] + 1:
return False
return True
#Returns true is the hand is a straight flush
def straightFlush(self):
if not self.straight():
return False
for i in range(len(self.hand) - 1):
if self.hand[i].suit != self.hand[i].suit:
return False
return True
#Returns true if the hand is a full house,
#and the value of the high card
def fullHouse(self):
pair, temp1 = self.pair()
triple, temp2 = self.threeOfaKind()
if not (triple and pair):
return False, None, None
high, low, = None, None
for rank, freq in self.rankHistogram().items():
if freq == 3:
high = rank
else:
low = rank
return True, high, low
#Returns true if the hand is a flush
def flush(self):
suits = self.getSuitList()
for i in range(len(suits) - 1):
if self.hand[i + 1].suit != self.hand[i].suit:
return False
return True
#Returns true if the hand is a Royal Flush
def royalFlush(self):
if not self.flush():
return False
royals = ['Ten','Jack', 'Queen', 'King', 'Ace']
ranks = self.getRankList()
i = 0
for rank in ranks:
if rank in royals:
i += 1
if i == 5:
return True
return False
#Returns a list of numbers that correspond
#to the ranks of each card in the hand
def sortRank(self, ranks):
ref = dict()
i = 1
for rank in Deck.ranks:
ref[rank] = i
i += 1
num_hand = []
for card in self.hand:
num_hand.append(ref[card.rank])
return num_hand
#Prints the values of each card in the hand,
#as <rank> of <suit>
def __str__(self):
for card in self.hand:
print "%s of %s" % (
card.getRank(), card.getSuit())
#Determines which is the best possible type of the hand.
#And returns the name of the hand to be used in the dictionary
#in the Engine class
def determineScore(self):
pair, high = self.pair()
if pair:
return 'Pair'
twoPair, high, low = self.twoPair()
if twoPair:
return 'Two Pair'
triple, high = self.threeOfaKind()
if triple:
return 'Three of a Kind'
if self.straight():
return 'Straight'
if self.flush():
return 'Flush'
full, high, low = self.fullHouse()
if full:
return 'Full House'
quad, high = self.fourOfaKind()
if quad:
return 'Four of a Kind'
if self.straightFlush():
return 'Straight Flush'
if self.royalFlush():
return 'Royal Flush'
else:
return 'High Card'
|
4cb46d874d4f473b7275fc75e433b2e3868ecbf3 | rabahbedirina/Cisco-Python | /hasattr.py | 1,537 | 3.96875 | 4 | """Checking an attribute's existence"""
class ExampleClass:
def __init__(self, val):
if val % 2 != 0:
self.a = 1
else:
self.b = 1
example_object = ExampleClass(2)
print(example_object.a)
try:
print(example_object.b)
except AttributeError:
pass
class ExampleClass:
def __init__(self, val):
if val % 2 != 0:
self.a = 1
else:
self.b = 1
example_object = ExampleClass(1)
if hasattr(example_object,'a'):
print(example_object.a)
if hasattr(example_object, 'b'):
print(example_object.b)
"""hasattr() function can operate on classes, too.
You can use it to find out if a class variable is available"""
class ExampleClass:
a = 1
def __init__(self):
self.b = 2
example_object = ExampleClass()
print(hasattr(example_object, 'b'))
print(hasattr(example_object, 'a'))
print(hasattr(ExampleClass, 'b'))
print(hasattr(ExampleClass, 'a'))
class Sample:
gamma = 0 # Class variable.
def __init__(self):
self.alpha = 1 # Instance variable.
self.__delta = 3 # Private instance variable.
# Sample.gamma=5
obj = Sample()
obj.beta = 2 # Another instance variable (existing only inside the "obj" instance.)
print(obj.__dict__,obj.gamma)
class Python:
population = 1 #class variable
__victims = 0 #private class variable
def __init__(self):
self.length_ft = 3 #instance variable
self.__venomous = False #private insrance variable |
ba934740e3a009ec713f7c3630b71ec56d9bb699 | killo21/poker-starting-hand | /cards.py | 2,285 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 25 17:30:27 2020
@author: dshlyapnikov
"""
import random
class Card:
def __init__(self, suit, val):
"""Create card of suit suit [str] and value val [int] 1-13
1 - Ace, 2 - 2, 3 - 3,..., 11 - Jack, 12 - Queen, 13 - King
suit can be "clubs", "diamonds", "hearts", "spades"."""
assert type(suit) is str
assert suit == "clubs" or suit == "diamonds" or suit == "hearts" or suit == "spades"
assert type(val) is int
assert val > 0 and val < 14
self.suit = suit
self.val = val
def getSuit(self):
"""A card's suit. Can be "clubs", "diamonds", "hearts", "spades"."""
return self.suit
def getVal(self):
"""A card's value. [int] 1-13.
1 - Ace, 2 - 2, 3 - 3,..., 11 - Jack, 12 - Queen, 13 - King"""
return self.val
def getShortHand(self):
"""Short hand [str] notation to represent a card. The first character
is the chard's value 1-13, J, Q, K, or A. The second char is the
card's suit C - clubs, D - diamonds, H - hearts, S - spades."""
result = ""
if self.val == 1:
result = "A"
elif self.val == 11:
result = "J"
elif self.val == 12:
result = "Q"
elif self.val == 13:
result = "K"
else:
result = str(self.val)
result = result + self.suit[0].capitalize()
return result
class Deck:
def __init__(self):
"""Creates a shuffled deck of 52 [card] objects."""
self.cardCount = 52
suits = ["clubs", "diamonds", "hearts", "spades"]
self.cards = []
for suit in suits:
for val in range(1, 14):
c = Card(suit, val)
self.cards.append(c)
random.shuffle(self.cards)
def getCount(self):
"""The [int] number of cards in the deck. Between 0-52 inclusive."""
return self.cardCount
def draw(self):
"""The first [card] in the deck. Removed from the deck without replacement."""
card = self.cards[0]
self.cards = self.cards[1:]
self.cardCount -= 1
return card
|
0c0b9dd0631d424a7d653a38c9e6584d725240cb | sivaneshl/python_ps | /breakcont.py | 220 | 4.0625 | 4 | # break and continue
for index in range(10):
if index == 5:
print("Hello")
break
print(index)
for index in range(10):
if index == 5:
continue
print("Hello")
print(index)
|
87afa5b77ae77a307a71769f6b4b40cd089fcb18 | sivaneshl/python_ps | /dict_compr.py | 348 | 3.890625 | 4 | country_to_capital = {'United Kingdom': 'London', 'France': 'Paris', 'India': 'New Delhi', 'Sri Lanka': 'Colombo'}
captital_to_country = {capital: country for country, capital in country_to_capital.items()}
print(captital_to_country)
# duplicate keys are overwritten
words = ['hi', 'hello', 'welcome', 'hey']
d = {x[0]: x for x in words}
print(d) |
141b6d72a3890b96f51838d1b4806763f0c60684 | sivaneshl/python_ps | /tuple.py | 801 | 4.25 | 4 | t = ('Norway', 4.953, 4) # similar to list, but use ( )
print(t[1]) # access the elements of a tuple using []
print(len(t)) # length of a tuple
for item in t: # items in a tuple can be accessed using a for
print(item)
print(t + (747, 'Bench')) # can be concatenated using + operator
print(t) # immutable
print(t * 3) # can be used with multiply operator
# nested tuples
a = ((120, 567), (747, 950), (474, 748), (747,738)) # nested tuples
print(a[3])
print(a[3][1])
# single element tuple
h = (849)
print(h, type(h)) # this is treated as a int as a math exp
h = (858,) # single element tuple with trailing comma
print(h, type(h))
e = () # empty tuple
print(e, type(e))
# parenthesis of literal tuples may be omitted
p = 1, 1, 3, 5, 6, 9
print(p, type(p))
|
a29a778e801e3ca3e9a5904fafca8310de0b0b43 | sivaneshl/python_ps | /range.py | 541 | 4.28125 | 4 | # range is a collection
# arithmetic progression of integers
print(range(5)) # supply the stop value
for i in range(5):
print(i)
range(5, 10) # starting value 5; stop value 10
print(list(range(5, 10))) # wrapping this call to the list
print(list(range(0, 10, 2))) # 2 is the step argument
# enumerate - to count
t = [6, 44, 532, 2232, 534536, 36443643]
for i in enumerate(t): # enumerate returns a tuple
print(i)
# tuple unpacking of enumerate
for i, v in enumerate(t):
print("i={} v={}".format(i,v))
|
b1460f656250aecfb1dc62d391618a46bcb93667 | Wilgy/SLIScripts | /zipunzipper.py | 6,014 | 3.8125 | 4 | #!/usr/bin/env python
"""
zipunzipper.py - Given a zip directory of student submissions pulled in
bulk from myCourses, unzips them and puts them in directories with the
students' user names.
Author: T. Wilgenbusch
"""
import sys
import os.path
from subprocess import call, check_output
from os import listdir
#place to write all output we don't want to see
devnull = open(os.devnull, 'w')
def get_student_dict(student_name_file, file_list, temp_zip_directory_name):
"""
get_student_dict - given a file containing student usernames and full names,
will return a dictionary that maps student user names to file names in
list of files
Final dictionary: (key, value) -> (username, {file1, file2})
@param student_name_file the file with the student names
@param file_list the list of zip file names in the temp directory
"""
# Line format in student_name_file:
# username firstName lastName
# (key, value) -> (firstNamelastName, username)
username_dict = {}
# (key, value) -> ([file1, file2])
student_name_dict = {}
for line in open(student_name_file):
items = line.split(" ")
username_dict[items[1].strip()+items[2].strip()] = items[0].strip()
student_name_dict[items[0]] = []
# File format for files in file_list:
# DDDDD-DDDDDDD - lastName, firstName - fileName
for current_file_name in file_list:
file = temp_zip_directory_name + "/" + current_file_name
full_name = (file.split(" - ")[1].strip()).split(", ")
first_name, last_name = full_name[1].strip(), full_name[0].strip()
# Grab the original name of the file and rename the current one
file_name = file.split(" - ")[2].strip()
user_name = username_dict[first_name+last_name]
call(["mkdir", file, temp_zip_directory_name + "/" + user_name ], stdout=devnull, stderr=devnull)
call(["mv", file, temp_zip_directory_name + "/" + user_name + "/" + file_name], stdout=devnull, stderr=devnull)
student_name_dict[user_name] += [user_name + "/" + file_name]
return student_name_dict
def move_labs(student_dict, dir_name, temp_zip_directory_name):
"""
move_labs - moves all of the files from in the temporary directory to the
provided directory, creating any student directories if they do
not already exist
@param student_dict the dictionary of students
@param dir_name the directory to unzip all of the labs into
@param temp_zip_directory_name name of directory with temp labs
"""
for user_name in student_dict.keys():
# Make the student directory
if not os.path.exists(dir_name + "/" + user_name):
call(["mkdir", dir_name + "/" + user_name ],
stdout=devnull, stderr=devnull)
# Directory to put the submision into to avoid mixing with
# try submissions directories that are already there
call(["mkdir", dir_name + "/" + user_name + "/Submission"],
stdout=devnull, stderr=devnull)
# NOTE: There may be no files to move
for file in student_dict[user_name]:
call(["mv", temp_zip_directory_name + "/" + file,
dir_name + "/" + user_name + "/Submission"],
stdout=devnull, stderr=devnull)
def usage():
"""
prints the usage statement for the script
"""
print('usage: zipunzipper.py zipfile students dirname')
print(' zipfile - The zip file downloaded from myCourses that contains all the labs')
print(' students - file containing all the students full names and usernames (new line delimited).')
print(' dirname - the name of the directory to drop all of the labs (i.e ./course/labs/lab01/')
def main():
"""
unzips a zip file that contains all the from dropbox and puts them
in the correct student directory
first argument is the zip file
second argument is a list of the students (directories) names
third argument is the Lab directory
"""
# Check for valid number of parameters
if(len(sys.argv) != 4):
usage()
exit(1)
zip_file_name = sys.argv[1]
student_name_file = sys.argv[2]
dir_name = sys.argv[3]
# Check that all arguments passed in are vallid
if( not os.path.isfile(zip_file_name) or
not zip_file_name.endswith('.zip') ):
print('Zip file does not exist or is not a zip file')
return
if( not os.path.isfile(student_name_file) ):
print('Student file does not exist')
return
if( not os.path.exists(dir_name) ):
print('Lab directory does not exist')
return
# Create a temp directory to store the unzipped myCourses zip files
temp_zip_directory_name = "temp_zip_directory"
if(dir_name.endswith('/')):
temp_zip_directory_name = dir_name + temp_zip_directory_name
else:
temp_zip_directory_name = dir_name + '/' + temp_zip_directory_name
dir_name = dir_name + '/'
call(["mkdir", temp_zip_directory_name], stdout=devnull, stderr=devnull)
call(["unzip", "-d", temp_zip_directory_name, zip_file_name],
stdout=devnull, stderr=devnull)
# New file format:
# DDDDD-DDDDDDD - lastName, firstName - fileName
# Grab all of the zip files that were unzipped from dropbox super zip
file_list = listdir(temp_zip_directory_name)
# Remove the "index.html" file from the file_list
file_list.remove("index.html")
#create the student dictionary
student_dict = get_student_dict(student_name_file, file_list, temp_zip_directory_name)
sorted_keys = sorted(student_dict.keys())
# Print out all files and usernames
for username in sorted_keys:
print username,
print(student_dict[username])
move_labs(student_dict, dir_name, temp_zip_directory_name)
# Remove the temp directory
call(["rm", "-r", temp_zip_directory_name], stdout=devnull, stderr=devnull)
main()
|
f23cc417d38bd75d21ff607bd109011b7eda2703 | katahiromz/SphereDist | /__main__.py | 1,887 | 3.625 | 4 | #!/usr/bin/env python3
import __init__ as SphereDist
def show_version():
print("SphereDist version 0.8.3 by katahiromz")
def show_help():
print(
"SphereDist --- Equal distance distribution of vertexes on a sphere or a hemisphere.\n" +
"Usage: SphereDist [options] [output.tsv]\n" +
"Options:\n" +
" output.tsv Specify the output file (default: output.tsv)\n" +
" --number XXX Specify the value of N (default: 100)\n" +
" --hemisphere Use a half of sphere\n" +
" --no-relocate Don't relocate\n" +
" --help Show this message\n" +
" --version Show version info\n" +
"\n" +
"E-mail: katayama.hirofumi.mz@gmail.com\n")
def main():
import sys
hemisphere = False
no_relocate = False
N = 100
filename = ""
skip = False
for i in range(1, len(sys.argv)):
if skip:
skip = False
continue
arg = sys.argv[i]
if arg == "--help":
show_help()
return 0
if arg == "--version":
show_version()
return 0
if arg == "--hemisphere":
hemisphere = True
continue
if arg == "--no-relocate":
no_relocate = True
continue
if arg == "--number":
N = int(sys.argv[i + 1])
skip = True
continue
if arg[0] == "-":
print("SphereDist: Invalid argument '", arg, "'.")
return -1
if len(filename) == 0:
filename = arg
else:
printf("SphereDist: Too many arguments.")
return -2
if len(filename) == 0:
filename = "output.tsv"
sd = SphereDist.dist(N, hemisphere, not no_relocate)
sd.save(filename)
return 0
main()
|
cd8f008e8959b50487c0c732cf0b5286116df7c9 | IDDeltaQDelta/crpyt | /creator.py | 1,146 | 3.734375 | 4 | """ This module will be used for creating image """
from PIL import Image
from randcolor import randomColor
def imageCreator():
a = randomColor()
b = randomColor()
c = randomColor()
d = randomColor()
e = randomColor()
img = Image.open("image/SZE3.png") # img contain image. should contain path to image
pixels = img.load() # create the pixel map
for i in range(img.size[0]): # for every pixel:
# Если добавить цвета в эту строчку то будет радужная картинка для каждой вертикальной линии
for j in range(img.size[1]):
if pixels[i,j] == (0,0,0): # black #000000
pixels[i,j] = a
if pixels[i,j] == (255, 255, 255): # white
pixels[i, j] = b
if pixels[i,j] == (0, 36, 255): # red #ff0000
pixels[i, j] = c
if pixels[i,j] == (246, 0, 255): # green
pixels[i, j] = d
if pixels[i,j] == (255, 234, 0): # green
pixels[i, j] = e
return img.show()
for i in range(0,2):
imageCreator() |
9c4cd21023e4cd188ede34775b9cf9dce033ec19 | imimali/rieud | /version3/game/util.py | 258 | 3.96875 | 4 | '''
created on 06 April 2019
@author: Gergely
'''
import math
def distance(point_1=(0, 0), point_2=(0, 0)):
"""Returns the distance between two points"""
return math.sqrt((point_1[0] - point_2[0]) ** 2 + (point_1[1] - point_2[1]) ** 2) |
149e32d2ea991a06c3d6a7dd1c18c4cc85c3d378 | CcccFz/practice | /python/design_pattern/bigtalk/Behavioral/11_visitor.py | 1,326 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# 模式特点:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
# 程序实例:对于男人和女人(接受访问者的元素,ObjectStructure用于穷举这些元素),不同的遭遇(具体的访问者)引发两种对象的不同行为。
class Action(object):
def get_man_conclusion(self):
pass
def get_woman_conclusion(self):
pass
class Success(Action):
def get_man_conclusion(self):
print '男人成功时,背后有个伟大的女人'
def get_woman_conclusion(self):
print '女人成功时,背后有个不成功的男人'
class Failure(Action):
def get_man_conclusion(self):
print '男人失败时,闷头喝酒,谁也不用劝'
def get_woman_conclusion(self):
print '女人失败时,眼泪汪汪,谁也劝不了'
class Person(object):
def accept(self, visitor):
pass
class Man(Person):
def accept(self, visitor):
visitor.get_man_conclusion()
class Woman(Person):
def accept(self, visitor):
visitor.get_woman_conclusion()
if __name__ == '__main__':
man, woman = Man(), Woman()
woman.accept(Success())
man.accept(Failure())
|
e4892689a5d2ee4fabd2fb2cc9e0940e5f64d67c | CcccFz/practice | /python/structure_and_algorithm/04_tree.py | 2,255 | 3.734375 | 4 | class Node(object):
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
tree = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4)))
tree_bak = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4)))
# 层次遍历
def lookup(root):
row = [root]
while row:
print([x.data for x in row])
row = [kid for item in row for kid in (item.left, item.right) if kid]
# 深度遍历
def deep(root):
if not root:
return
print(root.data)
deep(root.left)
deep(root.right)
# 中序遍历
def mid(root):
if not root:
return False
if root.left:
mid(root.left)
print(root.data)
if root.right:
mid(root.right)
# 前序遍历
def pre(root):
if not root:
return False
print(root.data)
if root.left:
pre(root.left)
if root.right:
pre(root.right)
# 后续遍历
def last(root):
if not root:
return False
if root.left:
last(root.left)
if root.right:
last(root.right)
print(root.data)
# 最大深度
def max_depth(root):
if not root:
return 0
return max(max_depth(root.left), max_depth(root.right)) + 1
# 两树是否相同
def is_same(p, q):
if not p and not q:
return True
elif p and q:
return p.data == q.data and is_same(p.left, q.left) and is_same(p.right, q.right)
else:
return False
# 已知前序中序求后序
def rebuild(pre, center):
root = Node(pre[0])
idx = center.index(pre[0]) # 有了idx,即能得到左子树的中序遍历,同时得到左子树的节点个数,进而结合pre推出左子树的前序遍历
left_tree_pre = pre[1:idx+1]
left_tree_center = center[:idx]
root.left = rebuild(left_tree_pre, left_tree_center)
right_tree_pre = pre[idx+1:]
right_tree_center = center[idx+1:]
root.right = rebuild(right_tree_pre, right_tree_center)
return root
if __name__ == '__main__':
lookup(tree)
# deep(tree)
# mid(tree)
# pre(tree)
# last(tree)
# print(max_depth(tree))
# print('两树相等' if is_same(tree, tree_bak) else '两树不等')
|
aee0198cb560125d50e9fdfa09543b9b092bed42 | FarimaM/python-class | /EX4.py | 336 | 3.734375 | 4 | "chandomin rooze separi shode az saal"
d = int(input('rooz: '))
m = int(input('mah: '))
y = int(input('sal: '))
days=[31,28,31,30,31,30,31,31,31,30,31,30]
days_passed = 0
if y%400 == 0 or (y%4 == 0 and y%100 != 0):
days[1] = 29
for months in days[:m-1]:
days_passed += months
days_passed += d
print(days_passed)
|
c5b55c5da804cc7c5094b67509407820b4907656 | poofcefnunsj/Unidad2POO | /claseFecha.py | 907 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 19:30:52 2020
@author: morte
"""
class Fecha:
__dia=0
__mes=0
__anio=0
def __init__(self, d=1,m=1,a=1900):
self.__dia=d
self.__mes=m
self.__anio=a
def formato(self, tipo='es'):
'''por defecto genera la fecha en formato español, dd/mm/aaaa,
si se pasa el parámetro tipo con el valor ‘en’, lo hará en formato
inglés, aaaa/mm/dd'''
formato = None
if tipo=='en':
formato = '{}/{}/{}'.format(self.__anio, self.__mes, self.__dia)
else:
formato = '{}/{}/{}'.format(self.__dia, self.__mes, self.__anio)
return formato
if __name__=='__main__':
fecha = Fecha()
print('Fecha en formato español {}'.format(fecha.formato()))
print('Fecha en formato inglés {}'.format(fecha.formato('en'))) |
a6f8ed7c9dfc5d35047e5ab30b4347cd45811f46 | poofcefnunsj/Unidad2POO | /destructorCicloDeVida.py | 873 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 07:35:11 2020
@author: morte
"""
class A:
__b=None
def __init__(self, unObjetoB):
self.__b=unObjetoB
def __del__(self):
print('Chau objeto A')
class B:
__a=None
def __init__(self):
self.__a=A(self)
def __del__(self):
print('Chau Objeto B')
def funcionCreaB():
b = B()
del b
class CicloDeVida:
__nombre=None
def __init__(self, nombre):
print('Hola: ',nombre)
self.__nombre = nombre
def vida(self):
print(self.__nombre)
def __del__(self):
print('Chau... ',self.nombre)
def funcion():
o = CicloDeVida('Violeta')
o.vida()
if __name__=='__main__':
objeto = CicloDeVida('Carlos')
objeto.vida()
del objeto
funcion()
funcionCreaB()
|
400cca5cff7b1b6d01f6f0bb413918b8e9a39540 | jasonminsookim/multimedia_test | /classic_corners_test.py | 5,144 | 3.859375 | 4 | # libraries
import pygame
import random
class Circle:
"""
This is our simple Circle class
"""
# color and radius globals
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
RADIUS = 50
def __init__(self, circle_number, x, y):
self.color = self.WHITE
self.radius = self.RADIUS
self.circle_number = circle_number
self.x = x
self.y = y
self.previous_color = self.WHITE
# randomly assigns a color to a circle
def change_color(self, num_yellow):
self.previous_color = self.color
if num_yellow == 0 and self.previous_color != self.YELLOW:
color_int = random.randint(1, 3)
else: # if there is already a yellow circle, then do not change to a yellow circle
color_int = random.randint(1, 2)
if color_int == 1:
self.color = self.WHITE
elif color_int == 2:
self.color = self.RED
else:
self.color = self.YELLOW
class ClassicCornersTest:
FPS = 30
RECT_COLOR = (255, 255, 255)
TOTAL_CIRCLES = 4
PIXELS_BETWEEN_CIRCLES = 100
SCREEN = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
WIDTH = SCREEN.get_width()
HEIGHT = SCREEN.get_height()
TIME_INTERVAL = 1 # seconds
MAX_ITER = 60 * 15 # 15 minute test
def __init__(self):
pygame.init()
# Set up screen
self.screen = self.SCREEN
self.central_line = pygame.Rect(self.WIDTH/2, 0, 1, self.HEIGHT)
# Create list of circles
self.circles = []
self.total_iter = -1 # starts at -1 to account for all white circles for first iterations
# Initialize scores
self.total_yellows = 0
self.yellows_correctly_clicked = 0
self.incorrectly_clicked = 0
self.click_in_interval = False
# Creates 4 circles
circle_num = 1
while circle_num <= self.TOTAL_CIRCLES:
if circle_num == 1:
self.circles.append(Circle(circle_num, self.WIDTH / 4 - self.PIXELS_BETWEEN_CIRCLES,
self.HEIGHT / 2 - self.PIXELS_BETWEEN_CIRCLES))
elif circle_num == 2:
self.circles.append(Circle(circle_num, self.WIDTH / 4 + self.PIXELS_BETWEEN_CIRCLES,
self.HEIGHT / 2 - self.PIXELS_BETWEEN_CIRCLES))
elif circle_num == 3:
self.circles.append(Circle(circle_num, self.WIDTH / 4 - self.PIXELS_BETWEEN_CIRCLES,
self.HEIGHT / 2 + self.PIXELS_BETWEEN_CIRCLES))
else:
self.circles.append(Circle(circle_num, self.WIDTH / 4 + self.PIXELS_BETWEEN_CIRCLES,
self.HEIGHT / 2 + self.PIXELS_BETWEEN_CIRCLES))
circle_num += 1
self.clock = pygame.time.Clock()
self.int_elapsed_time = 0 # ms
def change_circle_colors(self):
num_yellow_circles = 0
random.shuffle(self.circles) # shuffles the order in which the colors are changed
for circle in self.circles:
circle.change_color(num_yellow_circles)
if circle.color == (255, 255, 0):
num_yellow_circles += 1
self.total_yellows += 1 # adds to the total yellow scores
# Main loop
def game_loop(self):
while True:
if self.total_iter == self.MAX_ITER and self.int_elapsed_time >= self.TIME_INTERVAL*1000:
return
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
if event.type == pygame.MOUSEBUTTONDOWN and self.click_in_interval is False:
if self.screen.get_at(pygame.mouse.get_pos()) == (255, 255, 0):
self.yellows_correctly_clicked += 1
else:
self.incorrectly_clicked += 1
self.click_in_interval = True
if self.int_elapsed_time >= self.TIME_INTERVAL*1000:
self.total_iter += 1
self.change_circle_colors()
for circle in self.circles:
pygame.draw.circle(self.screen, circle.color, (circle.x, circle.y), circle.radius)
self.int_elapsed_time = 0
self.click_in_interval = False
self.screen.fill((0, 0, 0))
pygame.draw.rect(self.screen, self.RECT_COLOR, self.central_line)
for circle in self.circles:
pygame.draw.circle(self.screen, circle.color, (circle.x, circle.y), circle.radius)
pygame.display.update()
dt = self.clock.tick(self.FPS)
self.int_elapsed_time += dt
cct = ClassicCornersTest()
cct.game_loop()
print("Total Iterations: %d " % cct.total_iter)
print("Total Yellow Circles: %d" % cct.total_yellows)
print("Total Correctly Clicked Circles: %d" % cct.yellows_correctly_clicked)
print("Total Incorrectly Clicked Circles: %d" % cct.incorrectly_clicked)
|
a46fd0382038742dc0b3df9f70b93cb22294c2e7 | wboler05/AdventOfCode2020 | /day09/part2.py | 888 | 3.703125 | 4 | #!/usr/bin/env python3
import argparse, os, sys
import numpy as np
from part1 import find_invalid_number, load_data
def find_encryption_weakness(input_filename, preamble_size):
fail_number = find_invalid_number(input_filename, preamble_size)
if fail_number is not None:
data = load_data(input_filename)
for i in range(len(data)):
for j in range(i+1, len(data)+1):
snip = data[i:j]
if np.sum(snip) == fail_number:
return np.min(snip) + np.max(snip)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("input_filename", type=str)
parser.add_argument("--preamble", "-p", type=int, default=25)
args = parser.parse_args()
encryption_weakness = find_encryption_weakness(args.input_filename, args.preamble)
print("Encryption Weakness: {}".format(encryption_weakness))
if __name__ == '__main__':
main()
|
d3febd6b9c2199638fa4b0c25b8f928a766aaacf | sajalrustagi/Wiki_Of_Words_Using_Pdf_Wiki_Parser | /WordCountProcessor.py | 490 | 3.875 | 4 | # Takes a fileName, parses the file whether pdf/wiki, convert it to keywords and return
# the count of words
import FileContentParser
import TextProcessorAndTokenizer
from collections import Counter
def get_word_count(filename):
# get the text content present in file
text = FileContentParser.parse(filename)
# get the keywords from the text
keywords = TextProcessorAndTokenizer.get_keywords(text)
# return the count of words in the file
return Counter(keywords)
|
048b4f0751d17ca9930ce5c5309d5351527769b6 | DaniSestan/testing-algorithms-in-python | /exercises/01_basic_algorithms.py | 5,103 | 4.125 | 4 | # Testing the following:
# - binary search
# - basic performance timing
# - measure performance of (deterministic) brute force algorithm versus pure random algorithm
import time
import random
import os
# common number guessing game, with the typical roles reversed
# -- rather than prompting the user to guess the number, the user will
# choose a number and evaluate the program's guesses as lower/higher/correct.
def guessing_game():
num = 0
response = ''
i = 0
low_num = 1
high_num = 1000
while num < 1 or num > 1000:
# try-catch to validate the data as an int
try:
num = int(input("Enter a number between 1 and 1000:"))
except ValueError:
print("Invalid data. Try again.")
while response != 'c':
i += 1
guess_num = (low_num + high_num) // 2
print("Computer guesses: ", guess_num)
while True:
response = input("Type 'l' if your number is larger than the guessed number, "
"'s' if smaller, 'c' if correct: ")
if response == 'l':
low_num = guess_num + 1
break
elif response == 's':
high_num = guess_num
break
elif response == 'c':
break
else:
print("Invalid data. Try again.")
print("Done! Your number is %d. Guessed in %d time(s)" % (num, i))
# The following decorator is to be used for passing functions w/their own parameters as argumentss
# in another function. Test with the time_efficiency function.
def wrap_function(func, *args, **kwargs):
def wrap():
return func(*args, **kwargs)
return wrap
# def time_efficiency(func, *args, **kwargs):
def time_efficiency(func):
start = time.perf_counter_ns() / 10**9
# func(*args, **kwargs)
func()
end = time.perf_counter_ns() / 10**9
duration = end - start
print("Starts at: ", start)
print("Ends at: ", end)
print("Time taken to execute the function: %f seconds" % duration)
return duration
def sum_up():
num = 0
sum_num = 0
while num <= 0:
try:
num = int(input("Enter your_num for 0 .. your_num: "))
except ValueError:
print("Invalid data. Try again")
while num >= 0:
sum_num += num
num -= 1
return sum_num
# function for testing decorator
def foo(n):
print("printing from function to test decorator")
def another_guessing_game(guess_method):
highest_tries = 0
lowest_tries = 0
correct_tries = 0
total_tries = 0
reached_upperbound_occurrences = 0
for number_of_tries in range(0, 10000):
random_nums = random.sample(range(0, 10), 3)
result = guess_method(random_nums)
if result[0] == random_nums:
correct_tries += 1
if highest_tries < result[1]:
highest_tries = result[1]
if lowest_tries > result[1] or lowest_tries == 0:
lowest_tries = result[1]
if result[1] > 10000:
reached_upperbound_occurrences += 1
total_tries += result[1]
print("Number of tries: ", correct_tries)
print("Highest number of guesses in a try: ", highest_tries)
print("Lowest tries: ", lowest_tries)
print("Number of correct tries: ", correct_tries)
print("Average number of tries: ", total_tries / number_of_tries)
if reached_upperbound_occurrences > 0:
print("Reached upper-bound limit %d times" % reached_upperbound_occurrences)
def deterministic_brute_force_guessing(nums):
random_nums = int(''.join(map(str, nums)))
guess = 0
while guess != random_nums and guess < 10000:
guess += 1
result = list(map(int, str(guess)))
while len(result) < 3:
result.insert(0, 0)
return [result, guess]
def pure_random_guessing(nums):
guess = 0
i = 0
for i in range(0, 10000):
if guess != nums:
guess = random.sample(range(0, 10), 3)
else:
break
return [guess, i]
def top_word_occurrences():
file = os.getcwd() + '/../data/kennedy.txt'
use_sample = ''
while use_sample.lower() != 'n' and use_sample.lower() != 'y':
use_sample = input("Use sample text file? Y/N")
if use_sample.lower() == 'n':
file = input("Enter full file path: ")
n = int(input("Enter the number of most frequent words to display: "))
word_dict = {}
with open(file) as f:
word_list = [word for line in f for word in line.split()]
for word in word_list:
word_dict[word] = word_dict.get(word, 0) + 1
for i in range(n):
print('%s : %d' % (sorted(word_dict.items(), key=lambda x: x[1], reverse=True)[i][0], sorted(word_dict.items(), key=lambda x: x[1], reverse=True)[i][1]))
top_word_occurrences()
guessing_game()
time_efficiency(sum_up)
# testing decorator
wrapped_func = wrap_function(foo, 'bar')
time_efficiency(wrapped_func)
another_guessing_game(deterministic_brute_force_guessing)
another_guessing_game(pure_random_guessing)
|
5f843ed9fa8dc5a986db693c63056bdd9f2950d4 | priyankapanda78/dataScienceProjects | /letter_count.py | 657 | 3.71875 | 4 | # def letter_counter(filename,to_count):
# newFile=open(filename,'r')
# inpFile=newFile.read()
# word={}
# for i in inpFile:
# i=i.lower()
# if i in to_count and i not in word:
# word[i]=1
# elif i in to_count and i in word:
# word[i]=word[i]+1
# return word
# print(letter_counter("sample.txt",'aeiou'))
def remove_item(list_item,to_remove):
new=[]
for i in list_item:
if to_remove not in list_item:
return "This item is not in list"
elif i != to_remove:
new.append(i)
return new
print(remove_item([1,2,34,7,5],7)) #remove item program
|
3052ee9cd3eebd578dcc6e90f155c25e6c9d8360 | VishnuGopireddy/Data-Structures-and-Algorithms | /Bit Magic/Find first set bit.py | 422 | 3.765625 | 4 | # author : vishnugopireddy
# find first set bit from right
def findfirstSetbit(num):
pos = 1
# counting the position of first set bit
for i in range(32):
if not (num & (1 << i)):
pos += 1
else:
break
if pos > 32:
return 0
else:
return pos
kases = int(input())
for kase in range(kases):
num = int(input())
print(findfirstSetbit(num))
|
3c4fd3ce7601761a8d0e1acd9c73c8f8b7db71ad | Ryanless/CodeWars | /kyu5678/kyu6.py | 5,800 | 3.671875 | 4 |
def queue_time(customers, n):
if n == 0:
return "invalid n!"
queues = [[] for i in range(n)]
for c in customers:
queues[shortest_queue_index(queues)].append(c)
return max(sum(q) for q in queues)
def shortest_queue_index(queues):
minSum = sum(queues[0])
index = 0
for q in range(0, len(queues)):
if sum(queues[q]) < minSum:
minSum = sum(queues[q])
index = q
return index
#CH6: IQ Test
def iq_test(numbers):
numbers = numbers.split(' ')
numbers = [int(i) for i in numbers]
odd, even = -1, -1
flagOdd = False
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
if even != -1:
flagOdd = True
even = i + 1
else:
odd = i + 1
if flagOdd:
return odd
else:
return even
#CH6: Tribonacci Sequence
def tribonacci(signature, n):
seq = []
for i in range(min(n, 3)):
seq.append(signature[i])
for i in range(3,n):
seq.append(seq[i-1] + seq[i-2] + seq[i-3])
return seq
#CH6: Counting Duplicates
# sooooooo many possible solutions o.o
def duplicate_count(text):
dicto = {}
copies = 0
for i in text.lower():
if i in dicto:
dicto[i] += 1
else:
dicto[i] = 1
for j in dicto:
if dicto[j] > 1:
copies += 1
return copies
#CH6: Unique In Order
def unique_in_order(iterable):
if len(iterable) == 0:
return []
result = [iterable[0]]
for i in range(1, len(iterable)):
if iterable[i] != result[-1]:
result.append(iterable[i])
return result
#CH6: Stop gninnipS My sdroW!
def spin_words(sentence):
words = sentence.split(' ')
new_words = []
for word in words:
if len(word)> 4:
new_words.append(word[::-1])
else:
new_words.append(word)
return (' ').join(new_words)
#CH6: Find the missing letter
def find_missing_letter(chars):
alpha = 'abcdefghijklmnopqrstuvwxyz'
offset = alpha.find(chars[0].lower())
for i in range(len(chars)):
if not chars[i].lower() == alpha[i + offset]:
return alpha[i + offset] if chars[0].islower() else alpha[i + offset].upper()
#CH6: Vector Operations and Functionals
def vector_op(func, *vs):
# for just the first element: func([element[0] for element in vs])
return [func([element[index] for element in vs]) for index in range(len(vs[0]))]
def iter_mult(xs):
res = 1
for ele in xs:
res *= ele
return res
def iter_eq(xs):
if len(xs) == 1: return xs[0]
value = xs[0]
for ele in xs:
if ele != value:
return False
return True
#CH6: Build a pile of Cubes
def find_nb(m):
root = int(m**(1/4) * 1.4)
naeherung = calculate_nb(root)
while not naeherung > m:
if naeherung == m:
return root
root += 1
naeherung = calculate_nb(root)
return -1
# print("m: {0} root: {1} nb(root): {2} nb(root+1): {3}".format(m, root, calculate_nb(root), calculate_nb(root+1)))
#somehow it gives a wrong value
def calculate_nb(n):
return int((n**4 + 2*n**3 + n**2)/4)
def check_calc_nb(n):
summeSimple = 0
for i in range(n+1):
summeSimple += i**3
summeCalc = calculate_nb(n)
print ("simple: {} calc: {}".format(summeSimple, summeCalc))
if summeCalc != summeSimple:
print("diff is %d" % (summeSimple - summeCalc))
return summeSimple == summeCalc
#CH6: Street Fighter 2 - Character Selection
def street_fighter_selection(fighters, initial_position, moves):
selected = []
pos = [i for i in initial_position]
for move in moves:
pos = do_move(pos, move, fighters)
selected.append(fighters[pos[1]][pos[0]])
return selected
def do_move(pos, move, array):
x, y = len(array[0]), len(array) -1
if move == 'right':
pos[0] = (pos[0] + 1) % x
elif move == 'left':
pos[0] = (pos[0] - 1) % x
elif move == 'up':
pos[1] = max(0, pos[1] - 1)
elif move == 'down':
pos[1] = min(y, pos[1] + 1)
return pos
fighters = [
["Ryu", "E.Honda", "Blanka", "Guile", "Balrog", "Vega"],
["Ken", "Chun Li", "Zangief", "Dhalsim", "Sagat", "M.Bison"]
]
start_pos = (0,0)
#CH6: Decode the Morse code
#in code_wars MORSE_CODE is preloaded
MORSE_CODE = {'.-...': '&', '--..--': ',', '....-': '4', '.....': '5', '...---...': 'SOS', '-...': 'B', '-..-': 'X',
'.-.': 'R', '.--': 'W', '..---': '2', '.-': 'A', '..': 'I', '..-.': 'F', '.': 'E', '.-..': 'L', '...': 'S',
'..-': 'U', '..--..': '?', '.----': '1', '-.-': 'K', '-..': 'D', '-....': '6', '-...-': '=', '---': 'O',
'.--.': 'P', '.-.-.-': '.', '--': 'M', '-.': 'N', '....': 'H', '.----.': "'", '...-': 'V', '--...': '7',
'-.-.-.': ';', '-....-': '-', '..--.-': '_', '-.--.-': ')', '-.-.--': '!', '--.': 'G', '--.-': 'Q',
'--..': 'Z', '-..-.': '/', '.-.-.': '+', '-.-.': 'C', '---...': ':', '-.--': 'Y', '-': 'T', '.--.-.': '@',
'...-..-': '$', '.---': 'J', '-----': '0', '----.': '9', '.-..-.': '"', '-.--.': '(', '---..': '8', '...--': '3'}
def decodeMorse(morse_code):
words = morse_code.strip().split(' ')
readables = []
for word in words:
t, letter = '', word.split(' ')
for l in letter:
t += MORSE_CODE[l]
readables.append(t)
return ' '.join(readables)
#CH6: Give me a Diamond
def diamond(n):
# Make some diamonds!
if n < 0 or n % 2 == 0: return
result = ""
for i in range(1, n + 1, 2):
result += " "*int((n-i)/2) + "*"*i + "\n"
for j in range(n - 2, 0, -2):
result += " "*int((n-j)/2) + "*"*j + "\n"
return result |
aeb75cc44055faf3222ec8ba6aba504ce2602456 | git-ysz/python | /day12-递归,高阶函数/00-递归.py | 262 | 4.03125 | 4 | """
递归特点
1、函数自调用
2、必须有出口
"""
# 应用:3以内数字累加和 3 + 2 + 1
def sum_numbers(n):
if n == 1:
# 必须存在出口,否则报错
return 1
return n + sum_numbers(n - 1)
print(sum_numbers(3))
|
9f467500632ad90051263cb2282edacfe1258b1b | git-ysz/python | /day5-字符串/05-字符串的查找方法.py | 934 | 4.46875 | 4 | """
1、字符串序列.find(子串, 查找开始位置下标, 查找结束位置下标)
返回子串出现的初始下标
1.1、rfind()函数查找方向和find()相反
2、字符串序列.index(子串, 查找开始位置下标, 查找结束位置下标)
返回子串出现的初始下标
2.1、rindex()函数查找方向和find()相反
3、字符串序列.count(子串, 查找开始位置下标, 查找结束位置下标)
返回子串出现的次数
......
"""
myStr = 'hello world and itcast and itheima and Python'
# find() 函数
print(myStr.find('and')) # 12
print(myStr.find('and', 15, 30)) # 23
print(myStr.find('ands')) # 找不到返回-1
# index()函数
print(myStr.index('and')) # 12
print(myStr.index('and', 15, 30)) # 23
# print(myStr.index('ands')) # 找不到报错 substring not found
# count() 函数
print(myStr.count('and', 15, 30)) # 1
print(myStr.count('ands')) # 0
|
fe00e79bf104bc4cb8dae4d4d5ba652e89780e28 | git-ysz/python | /day19-学员管理系统/StudentManagerSystem/student.py | 475 | 3.984375 | 4 | class Student(object):
"""
学员角色类
name:学员姓名; gender:学员性别; tel:学员联系方式
"""
def __init__(self, name, gender, tel):
self.name, self.gender, self.tel = name, gender, tel
def __str__(self):
return f'该学员姓名为:{self.name},性别:{self.gender},联系方式:{self.tel}'
if __name__ == '__main__':
_XM = Student('小明', '男', 111)
print(Student.__doc__)
print(_XM)
|
5c8e53bc40566dfe596ecf26e8425f65dae57a6a | git-ysz/python | /day15-继承/04-子类调用父类的同名方法和属性.py | 1,549 | 4.3125 | 4 | """
故事演变:
很多顾客都希望既能够吃到古法又能吃到学校技术的煎饼果子
"""
# 师傅类
class Master(object):
def __init__(self):
self.kongfu = '古法煎饼果子配方'
def make_cake(self):
print(f'运用{self.kongfu}制作煎饼果子 -- 师父')
# 学校类
class School(object):
def __init__(self):
self.kongfu = '学校煎饼果子配方'
def make_cake(self):
print(f'运用{self.kongfu}制作煎饼果子 -- 学校')
# 徒弟类 - 继承师傅类 《第一种方法》 (第二种方法见06文件super)
class Prentice(Master, School):
"""注意:当一个类有多个父类的时候,默认使用第一个父类的同名属性和方法"""
def __init__(self):
self.kongfu = '独创煎饼果子配方'
def make_cake(self):
# 注意:如果先调用了父类的属性和方法,父类属性就会覆盖子类属性
# 故在方法一中,在调用自己类的方法时需要初始化自身类的属性
self.__init__()
print(f'运用{self.kongfu}制作煎饼果子 -- 自己')
# 注意:调用父类方法,但是为保证调用到的也是父类的属性,必须在调用方法钱调用父类的初始化
def make_master_cake(self):
Master.__init__(self)
Master.make_cake(self)
def make_school_cake(self):
School.__init__(self)
School.make_cake(self)
tudi = Prentice()
tudi.make_cake()
tudi.make_master_cake()
tudi.make_school_cake()
tudi.make_cake()
|
d06e4c4c9cda208bba4ea94437e71d3a25157616 | git-ysz/python | /day6-列表、元组/08-综合应用-随机分配办公室.py | 398 | 3.890625 | 4 | """
需求:
1、有8位老师
2、有三个办公室
3、将八位老师随机分配到三个办公室
4、验证结果
"""
import random
# 1. 准备数据
teachers = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
offices = [[], [], []]
# 2.分配老师到办公室 -- 取每个老师放到offices中
for name in teachers:
num = random.randint(0, 2)
offices[num].append(name)
print(offices)
|
a469aa835b15c7f5e419df7d083b83d2500f2787 | git-ysz/python | /day13-文件操作/02-文件的读取函数.py | 919 | 3.8125 | 4 |
# 1、文件对象.read(num)
"""
num表示要从文件中读取的数据的长度(字节),如果没有传入num,表示读取文件中所有的数据
"""
f1 = open('02-test.txt', 'r')
# print(f1.read())
print(f1.read(10)) # 文件内容如果换行,程序底层是需要\n才能完成换行,所以\n(换行)占一个字节
f1.close()
# 2、文件对象.readlines()
"""
按照行的方式去读取文件所有内容,返回列表,列表的每一项为内容的一行
"""
f2 = open('02-test.txt', 'r')
print(f2.readlines()) # 返回结果中换行的会有\n(换行)字符
f2.close()
# 3、文件对象.readline()
"""
一次性读取一行内容,多次调用,读取多行
"""
f3 = open('02-test.txt', 'r')
print(f3.readline() + '-end')
print(f3.readline() + '-end')
print(f3.readline() + '-end')
print(f3.readline() + '-end') # 始终会读取,读不到内容则返回空字符
f3.close()
|
eadb9454aeedd0dff94404ac92f9e6e43f4089c8 | git-ysz/python | /day7-字典/04-字典的循环遍历.py | 335 | 4.25 | 4 | dict1 = {
'name': 'Tom',
'age': 20,
'gender': '男'
}
# 遍历keys
for key in dict1.keys():
print(key)
# 遍历values
for val in dict1.values():
print(val)
# 遍历键值对
for item in dict1.items():
print(item, item[0], item[1])
# 键值对拆包
for key, value in dict1.items():
print(f'{key}:{value}')
|
b5bdd6a7b80e23823c3a97def9717da822c0b3b7 | git-ysz/python | /day18-模块包/00-导入模块的方法.py | 565 | 4.1875 | 4 | """
模块:
Python模块(module),是一个python文件,以.py结尾,包含了python对象定义和python语句。
模块能定义函数,类和变量,模块里面也能包含可执行的代码
"""
import math # 导入指定模块
# from math import sqrt # 导入指定模块内的指定功能
from math import * # 导入指定模块内的所有功能
print(math.sqrt(9)) # 开平方 -- 3.0
print(sqrt(9)) # 开平方 -- 3.0 导入指定模块内的所有功能
print(pi, e) # 3.141592653589793... 导入指定模块内的所有功能
|
511f5e71a988213812fe04a44b1d08bc2fb10ecf | git-ysz/python | /day17-异常处理/01-捕获异常.py | 1,261 | 4.25 | 4 | """
语法:
try:
可能发生错误的代码
except 异常类型:
如果捕获到该异常类型执行的代码
注意:
1、如果尝试执行的代码的异常类型和要捕获的类型不一致,则无法捕获异常
2、一般try下发只放一行尝试执行的代码
"""
# 捕获指定异常类型
try:
# 找不到num变量
print(num)
except NameError:
print('NameError:', NameError.__dict__)
try:
print(1 / 0)
except ZeroDivisionError:
print('0不能做被除数')
# 捕获多个指定异常
try:
# print(arr)
print(1 / 0)
except (NameError, ZeroDivisionError):
print('捕获多个指定异常')
# 获取异常信息 {ErrorType} as result
try:
# print(arr)
print(1 / 0)
except (NameError, ZeroDivisionError) as res:
print('捕获多个指定异常(有异常信息):', res)
# 捕获所有异常 --- Exception
try:
print(arr)
print(1 / 0)
except Exception as res:
print('捕获所有异常(有异常信息):', res)
# 异常之else --- 没有异常时执行的代码
# 异常之finally --- 有无异常都执行的代码
try:
print(111)
# print(aaa)
except Exception as res:
print(res)
else:
print('else')
finally:
print('finally')
|
8c10fa45abe684d15408e9f6fcd32d3d39106ed2 | git-ysz/python | /day10-函数/05-函数的参数-关键字参数.py | 500 | 3.71875 | 4 | # 2、关键字参数 键=值 的方式传参
# **kw 代表多余的传入的参数,类型为字典
def user_info(name, age, gender, **kw):
print(f'您的姓名是{name},年龄为{age},性别为{gender}')
print(kw)
dict1 = {
'age': 21,
'name': 'Yao',
'gender': '男'
}
list1 = ['小明', 25, '男']
user_info('Tom', age=18, gender='男')
user_info('Rose', gender='女', age=20)
user_info(**dict1)
user_info(*list1)
# 注意:位置参数必须在关键字参数前面
|
a5eac9492d089bbf1658cc44bd066f662af8ce0d | git-ysz/python | /day17-异常处理/00-了解异常.py | 532 | 3.921875 | 4 | """
当检测到一个错误时,解释器就无法继续执行了,反而出现了一些错误的提示,这就是所谓的"异常"。
例如:以r方式打开一个不存在的文件
语法
try:
可能发生错误的代码
except:
发生错误的时候执行的代码
注意:
1、如果尝试执行的代码的异常类型不一致,则无法捕获异常。
2、一般try下方只放一行尝试执行的代码
"""
try:
f1 = open('test.txt', 'r')
f1.close()
except:
print('except')
print(123)
|
b5f859c64a9b05aa5188a2f8b831298fd870ec7b | git-ysz/python | /day6-列表、元组/01-列表体验案例in.py | 412 | 3.953125 | 4 | name_list = ['Tom', 'Lily', 'Rose']
# 需求:注册邮箱,用户输入一个账户名,判断这个账户名是否存在,如果存在,提示用户,否则提示可以注册
"""
1、用户输入账号
2、判断if...else...
"""
name = input('请输入您的邮箱账号名:')
if name in name_list:
print(f'您输入的名字为{name},该用户名已经存在')
else:
print('可以注册')
|
e07b9d4a1f29f73ee0288a637eecfbf60f3d0f9b | git-ysz/python | /day6-列表、元组/11-元组数据的修改.py | 324 | 3.828125 | 4 | """
元组数据不支持修改,只支持查找
"""
t1 = ('aa', 'bb', 'cc', 'dd')
# 出错:'tuple' object does not support item assignment
# t1[0] = 'aaa'
# 特例 -- 元组内部的可更改数据类型不会因为元组的特性而不可变
t2 = ('aa', ['bb', 'cc', 'dd'])
t2[1][0] = 'bbb' # 更改成功
print(t2)
|
026950e2888b6502ea595395cdfafa80fdfd1b05 | git-ysz/python | /day10-函数/04-函数的参数-位置参数.py | 227 | 3.765625 | 4 | # 1、位置参数 -- 传参个数和顺序必须一致
def user_info(name, age, gender):
print(f'您的姓名是{name},年龄为{age},性别为{gender}')
user_info('Tom', 18, '男')
# user_info('Tom', 18) # 报错
|
4faed1f02855f8954b31445b7827c0f4a70e7842 | lanzam/ISM-4402 | /Line Plot.py | 1,219 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Line Plot
# Dataset used in an example from the book. Then, we'll add an annotation to Bob's 76 that will says "Wow!".
# In[1]:
import pandas as pd
names = ['Bob','Jessica','Mary','John','Mel']
grades = [76,83,77,78,95]
GradeList = zip(names,grades)
df = pd.DataFrame(data = GradeList, columns=['Names', 'Grades'])
get_ipython().run_line_magic('matplotlib', 'inline')
df.plot()
# In[6]:
# Graph "y" location to be 76 that Bob got on the previous dataset. Then, move text 'Wow!!!' up and center.
import matplotlib.pyplot as plt
df.plot()
displayText = "Wow!!!"
xloc = 0
yloc = 76
xtext = 180
ytext = 100
plt.annotate(displayText,
xy=(xloc, yloc),
xytext=(xtext,ytext),
xycoords=('axes fraction', 'data'),
textcoords='offset points')
# In[8]:
# Add an arrow to the graph to point "Wow!!!"
df.plot()
displayText = "Wow!!!"
xloc = 0
yloc = 76
xtext = 180
ytext = 100
plt.annotate(displayText,
xy=(xloc, yloc),
arrowprops=dict(facecolor='black', shrink=0.05),
xytext=(xtext,ytext),
xycoords=('axes fraction', 'data'),
textcoords='offset points')
|
701391a6956c3c9dad884792eeb11f9074cb8657 | pasalu/TicTacToe | /AI.py | 464 | 3.609375 | 4 | import random
class AI:
RANDOM = "RANDOM"
def __init__(self, strategy):
self.strategy = strategy
def random(self, actions):
"""
Randomly select an action.
:param actions: A list of valid actions a player can make.
:return: A single action.
"""
return random.choice(actions)
def take_action(self, actions):
if self.strategy == self.RANDOM:
return self.random(actions)
|
1f0e2612abcb9d4e537074be265f9fca0c059c30 | magnethus/Test-AL | /src/com/jalasoft/ShoppingCart/model/billing.py | 1,059 | 3.75 | 4 |
class Billing:
"""metodo que devuelve el billing id de la tabla purchase"""
def getBillId(self):
return self.__billId
def setBillId(self, billId):
self.__billId = billId
"""metodo usado para obtener el nombre de un producto para ser mostrado en el billing detail"""
def getProdName(self):
return self.__prodName
"""metodo que setea el nombre de un producto"""
def setProdName(self, prodName):
self.__prodName = prodName
"""metodo que obtiene la cantidad del item en la orden"""
def getProdQuantity(self):
return self.__prodQuantity
"""metodo que setea la cantidad de un producto"""
def setProdQuantity(self, prodQuantity):
self.__prodQuantity = prodQuantity
"""metodo que obtiene el precio unitario de un producto que puede ser de la tabla purchase"""
def getProdPrice(self):
return self.__prodPrice
"""metodo que setea el precio unitario de un producto"""
def setProdPrice(self, prodPrice):
self.__prodPrice = prodPrice
|
c3d92fcc7f25bd9097d9a1c08a51121b84978a51 | athul-santhosh/Leetcode | /274. H-Index.py | 473 | 3.53125 | 4 | class Solution:
def hIndex(self, citations: List[int]) -> int:
if not citations: return 0
index = len(citations)
count = 0
citations.sort()
while index > 0:
if index <= citations[count]:
return index
else:
count += 1
index -= 1
return 0
|
c085827df602a90b1d9c2e55ba2c8437260f7979 | athul-santhosh/Leetcode | /Integer Palindrome.py | 386 | 3.5 | 4 | class Solution:
def isPalindrome(self, x: int) -> bool:
temp = x
p = 0
if x<0:
return False
while x != 0:
p =p*10 + x%10
x=x//10
if p == temp:
return True
else:
return False
#return(x==int(str(x)[::-1]))
|
2f1decfec222a93f69fed1106f2f7f7b6e2ba1de | athul-santhosh/Leetcode | /83 remove duplicates .py | 935 | 3.65625 | 4 | def deleteDuplicates(self, head: ListNode) -> ListNode:
#this solution works even if the list is sorted or unsorted but uses an
#additional memory space for dictionary
cur = head
map = {}
prev = head
while cur:
if cur.val in map:
prev.next = cur.next
cur = None
else:
map[cur.val] = 1
prev = cur
cur = prev.next
return head
def deleteDuplicates(self, head: ListNode) -> ListNode:
# this solution only works for sorted list i.e the duplicate elements should
# adjacnent to each other , it does not uses any auxillary memory
cur = head
if cur is None:
return None
while cur.next:
if cur.next.val == cur.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
|
b9d1034e19ba3741afde74c462cac25f58061961 | lauraikoeva/cheap_airtickets_bot | /validation.py | 454 | 3.828125 | 4 | def validate_date(date):
try:
day = int(date.split(".")[0])
month = int(date.split(".")[1])
year = int(date.split(".")[2])
except:
return False
if day>31:
return False
if month>12:
return False
if month == 2 and year % 4 !=0 and day>28:
return False
if month == 2 and day>29:
return False
if month in [4,6,9,11] and day>30:
return False
return True |
461c94991055250ad2b48ba7ef00c46d6d3eb68a | nancy-cai/Data-Structure-and-Algorithm-in-Python | /linked-list.py | 2,097 | 4.09375 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def print_list(self):
cur = self.head
while cur:
print(cur.value)
cur=cur.next
def print_helper(self, node, name):
if node is None:
print(name + ": None")
else:
print(name + ": "+ node.value)
# A -> B -> C -> D -> 0
# A <- B <- C <- D <- 0
def reverse_iterative(self): # https://www.youtube.com/watch?v=xFuJI29BiDY
prev = None
cur = self.head
while cur:
nxt = cur.next # Save it to a temp var
cur.next = prev # Flip the arrow to point to the prev node
prev = cur # Move along the list still from left to right
cur = nxt # Move along the list still from left to right
self.print_helper(prev, "prev")
self.print_helper(cur, "cur")
self.head = prev # when cur is D, we flip the arrow, set prev to D and move to the next node which is None, exit loop. then set head to prev which is D
def reverse_recursive(self):
def _reverse_recursive(cur, prev):
if not cur: # if cur reached end of the list(None), return prev. Otherwise keep going through the list and reverse it by calling this fun itself
return prev
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return _reverse_recursive(cur, prev)
self.head = _reverse_recursive(cur=self.head, prev=None)
llist=LinkedList()
llist.append("A")
llist.append("B")
llist.append("C")
llist.append("D")
llist.reverse_iterative()
llist.print_list()
|
26a9c9a4c99c424e9732fa1788c495f58140fc2e | giselemanuel/programa-Ifood-backend | /modulo-1/exercicios/dicionario_jogo.py | 433 | 3.796875 | 4 | print('\n')
fases_jogo = {'Fase1': 'Intrudução de Conceitos', 'Fase2': 'Diversidade no mundo dos negócios', 'Fase3': 'O Grande Desafio'}
print(fases_jogo)
print('-' * 40)
print('\n')
personagens = {'personagem1': 'Denise', 'personagem2': 'Paulo', 'personagem3': 'Gabriela'}
print(personagens)
print('-' * 40)
print('\n')
print(fases_jogo['Fase1'],personagens['personagem1']) # exibe o item da chave informada dentro do print
|
9605013db14a55234a8f79a0f50833ce6f9af675 | giselemanuel/programa-Ifood-backend | /modulo-1/exercicios/animal.py | 1,227 | 4.34375 | 4 | """
Programa VamoAI:
Aluna: Gisele Rodrigues Manuel
Desafio : Animal
Descrição do Exercício 3:
Criar um programa que:
1. Pergunte ao usuário qual aninal ele gostaria de ser e armazene em uma variável.
2. Exiba na tela o texto: "Num primeiro momento , eu gostaria de ser o <animal>
3. Pergunte ao usuário qual animal ele gostaria de ser no lugar desse e armazene esse novo animal na mesma variável.
4. Exibe na tela o seguinte texto: " Pensando melhor , eu gostaria mesmo de ser um <animal>
"""
# Cores
cores = { 'limpa': '\033[m',
'vermelho': '\033[31m',
'verde': '\033[32m',
}
# Cabeçalho do programa
print('\n')
print('-' * 60)
print(f'{"PROGRAMA ANIMAL - QUAL ANIMAL VOCÊ SERIA?":^60}')
print('-' * 60)
# Variável e entradas de valores
animal = str(input('{}1. Se você pudesse ser um animal, qual animal seria? {}'.format(cores['verde'], cores['limpa'])))
print('Num primeiro momento, eu gostaria de ser um(a) {}{}{}.\n'.format(cores['vermelho'], animal, cores['limpa']))
animal = str(input('{}2. Qual outro animal você gostaria de ser? {}'.format(cores['verde'], cores['limpa'])))
print('Pensando melhor, eu gostaria mesmo de ser um(a) {}{}{}\n'.format(cores['vermelho'], animal, cores['limpa']))
|
f288d7e1e1eeef42d3a8effadcf20585cd253a4a | giselemanuel/programa-Ifood-backend | /modulo-2/exercicios/ex_class.py | 1,177 | 3.921875 | 4 | """
Descrição do Exercício:
Escrever as classes gato, caneta e relogio, atribuindo suas características
e métodos, e colocar o print no Discord.
Aluno: Gisele Manuel
"""
# classe gato
class Gato:
def __init__(self, cor, sexo, raca, idade): # construtor com os atributos
self.cor = cor
self.sexo = sexo
self.raca = raca
self.idade = idade
def dormir(self, local_dormir):
self.local_dormir = local_dormir
def comer(self, racao):
self.racao = racao
def miar(self, situacao):
self.situacao = situacao
def vacinar(self, situacao_vacina):
self.situacao_vacina = situacao_vacina
# classe caneta
class Caneta:
def __init__(self, cor, marca, tipo):
self.cor = cor
self.marca = marca
self.tipo = tipo
def escrever(self, local):
self.local = local
# classe Relógio
class Relogio:
def __init__(self, tipo, marca, tamanho):
self.tipo = tipo
self.marca = marca
self.tamanho = tamanho
def exibir_hora(self, hora, minuto, segundo):
self.hora = hora
self.minuto = minuto
self.segundo = segundo
|
abf1cd991eb9acb1b94912929eefeb84b471c448 | giselemanuel/programa-Ifood-backend | /qualified/sem10_qualified_4.py | 4,682 | 3.640625 | 4 | """
Descrição
Utilizando a classe Pessoa criada na atividade Parentesco entre Pessoas, crie a função encontre_os_irmaos(lista_pessoas) que recebe uma lista de objetos do tipo Pessoa e retorna uma lista apenas com o nome das pessoas que são irmãos.
Se não houver irmãos na lista, a lista retornada deve ser vazia ([]).
Lembre-se que a mesma pessoa não pode aparecer mais de uma vez na lista final.
Exemplos
p1 = Pessoa("Sasuke", "222222")
p2 = Pessoa("Itachi", "202020")
p3 = Pessoa("Mikoto", "444444")
p4 = Pessoa("Fugaku", "333333")
# Adiciona pai e mãe de p1
p1.adiciona_mae(p3)
p1.adiciona_pai(p4)
# Adiciona pai e mãe de p2
p2.adiciona_mae(p3)
p2.adiciona_pai(p4)
lista_pessoas = [p1, p2]
# Exemplo e chamada da função
encontre_os_irmaos(lista_pessoas)
# Exemplo da saída esperada: ["Sasuke", "Itachi"]
p1 = Pessoa("Pessoa 1", "222222")
p2 = Pessoa("Pessoa 2", "202020")
p3 = Pessoa("Pessoa 3", "444444")
p4 = Pessoa("Pessoa 4", "333333")
p5 = Pessoa("Pessoa 5", "555555")
# Adiciona pai e mãe de p1
p1.adiciona_mae(p3)
p1.adiciona_pai(p4)
# Adiciona pai e mãe de p5
p5.adiciona_mae(p3)
p5.adiciona_pai(p4)
lista_pessoas = [p1, p2, p5]
# Exemplo e chamada da função
encontre_os_irmaos(lista_pessoas)
# Exemplo da saída esperada: ["Pessoa 1", "Pessoa 5"]
p1 = Pessoa("Pessoa 1", "222222")
p2 = Pessoa("Pessoa 2", "202020")
p3 = Pessoa("Pessoa 3", "444444")
p4 = Pessoa("Pessoa 4", "333333")
p5 = Pessoa("Pessoa 5", "555555")
lista_pessoas = [p1, p2, p3, p4, p5]
# Exemplo e chamada da função
encontre_os_irmaos(lista_pessoas)
"""
# classe da entidade pessoa ------------------------------------------------------------
class Pessoa:
def __init__(self, nome, rg):
self.nome = nome
self.rg = rg
self.pai = None
self.mae = None
# método adiciona pai -------------------------------------------------------------------
def adiciona_pai(self, pai):
self.pai = pai
# método adiciona mãe -------------------------------------------------------------------
def adiciona_mae(self, mae):
self.mae = mae
# método eh_mesma_pessoa ----------------------------------------------------------------
def eh_mesma_pessoa(self, Pessoa):
if self.nome == Pessoa.nome and self.mae == Pessoa.mae and self.rg == Pessoa.rg:
return True
elif self.nome == Pessoa.nome and self.rg == Pessoa.rg and self.mae is None:
return True
else:
return False
# método eh_antecessor_direto -----------------------------------------------------------
def eh_antecessor_direto(self, Pessoa):
if self.mae == Pessoa or self.pai == Pessoa:
return True
else:
return False
# método eh_irmao -----------------------------------------------------------------------
def eh_irmao(self, Pessoa):
if self.mae == Pessoa.mae and self.pai == Pessoa.pai:
return True
elif self.mae is None and self.pai is None:
return False
else:
return False
# método encontre_os_irmaos -------------------------------------------------------------------------------
def encontre_os_irmaos(lista_pessoas):
lista_irmao = [] # lista que receberá o atributo nome dos objetos da classe pessoa se forem irmão
# iteração na lista_pessoas para verificar se os objetos da classe pessoa são irmão
for p in range(0, len(lista_pessoas)):
if lista_pessoas[p].eh_irmao(lista_pessoas[p + 1]):
lista_irmao.append(lista_pessoas[p].nome) # adiciona o nome da lista_pessoa a lista_irmao
lista_irmao.append(lista_pessoas[p + 1].nome) # adiciona o nome da lista_pessoa a lista_irmao
return lista_irmao
else:
lista_irmao = []
return lista_irmao
# instancia objetos na classe pessoa ----------------------------------------------------------------------
p1 = Pessoa("Sasuke", "222222")
p2 = Pessoa("Itachi", "202020")
p3 = Pessoa("Mikoto", "444444")
p4 = Pessoa("Fugaku", "333333")
# Adiciona pai e mãe de p1 --------------------------------------------------------------------------------
p1.adiciona_mae(p3)
p1.adiciona_pai(p4)
# Adiciona pai e mãe de p2 --------------------------------------------------------------------------------
p2.adiciona_mae(p3)
p2.adiciona_pai(p4)
# cria lista variável do tipo lista -----------------------------------------------------------------------
lista_pessoas = [p1, p2]
# Exemplo e chamada da função -----------------------------------------------------------------------------
encontre_os_irmaos(lista_pessoas)
|
fdc4109862d6acdaaf3b28b259407310172e9973 | giselemanuel/programa-Ifood-backend | /qualified/sem7_qualified_3.py | 2,466 | 4.21875 | 4 | """
Descrição
Utilizando as mesmas 4 funções da atividade Pilha - Funções Básicas:
cria_pilha()
tamanho(pilha)
adiciona(pilha, valor)
remove(pilha):
Implemente a função insere_par_remove_impar(lista) que recebe uma lista de números inteiros como parâmetro e retorna uma pilha de acordo com a seguinte regra: para cada elemento da lista, se o número for par, deve ser inserido na pilha. Caso contrário, deve ser removido.
0 deve ser considerado par.
Utilize o funcionamento da pilha para que isso aconteça.
Lembre-se:
A pilha funciona seguindo a sequência LIFO(Last In First Out) - Último a entrar, primeiro a sair.
Em python, a pilha é implementada utilizando a estrutura de uma lista.
IMPORTANTE
É OBRIGATÓRIO utilizar pelo menos as funções cria_pilha, adiciona e remove da atividade Pilha - Funções Básicas para implementar a função insere_par_remove_impar. Seu código não passará nos testes se elas não forem utilizadas.
Exemplos
Chamada da função insere_par_remove_impar(lista)
Entrada: [1, 2, 3]
Saída: []
Entrada: [1, 2, 3, 4]
Saída: [4]
Entrada: []
Saída: []
Entrada: [1]
Saída: []
Entrada: [2, 2, 2, 2, 1, 1, 1]
Saída: [2]
Entrada: [1, 2, 3, 4, 6, 8]
Saída: [4, 6, 8]
"""
# função cria_pilha -------------------------------
def cria_pilha():
stack = []
# função tamanho ----------------------------------
def tamanho(pilha):
return len(pilha)
# função cria_pilha -------------------------------
def adiciona(pilha, elemento):
if len(pilha) != 0:
pilha.append(elemento)
else:
pilha = None
return pilha
# função remove -----------------------------------
def remove(pilha):
if len(pilha) != 0:
remove = pilha.pop()
return remove
else:
pilha = None
return pilha
# função insere_par_remove_impar -----------------
def insere_par_remove_impar(lista):
nova_pilha = []
cria_pilha()
# se num da lista par , adicionar na pilha LIFO
for num in range(0, len(lista)):
if num % 2 == 0:
adiciona(nova_pilha, num)
elif num % 2 != 0: # se num da lista impar
remove(nova_pilha)
# retorna None se lista estiver vazia
if len(lista) == 0:
lista = None
return lista
# define variáveis ------------------------------
minha_lista = (1, 2, 30)
cria_pilha()
# chama funções ---------------------------------
insere_par_remove_impar(minha_lista)
|
3b831b55e3fc2796d52d1a3298b690cfbe41fdf7 | giselemanuel/programa-Ifood-backend | /qualified/sem5_qualified_2.py | 1,078 | 4.4375 | 4 | # função para somar as duas listas
"""
Descrição
Eu sou novo na programação e gostaria da sua ajuda para somar 2 arrays. Na verdade, eu queria somar todos os elementos desses arrays.
P.S. Cada array tem somente numeros inteiros e a saída da função é um numero também.
Crie uma função chamada array_plus_array que recebe dois arrays(listas) de números e some os valores de todos os elementos dos dois arrays.
O resultado deverá ser um número que representa a soma de tudo.
Exemplos
Entrada: [1, 1, 1], [1, 1, 1]
Saída: 6
Entrada: [1, 2, 3], [4, 5, 6]
Saída: 21
"""
# função que soma os valores das duas listas
def array_plus_array(arr1,arr2):
soma_l1 = 0
soma_l2 = 0
total = 0
# soma os elemento da lista 1
for l1 in list1:
soma_l1 += l1
# soma os elementos da lista 2
for l2 in list2:
soma_l2 += l2
# total da soma das duas listas
total = soma_l1 + soma_l2
print(total)
# difinição das listas
list1 = [-1, -2, -3]
list2 = [-4, -5, -6]
# chama a função e passa a lista
array_plus_array(list1,list2) |
c39d37c177f12f17b10ff8618d40b2d9bcc00b55 | giselemanuel/programa-Ifood-backend | /modulo-2/exercicios/classe_pilha2.py | 704 | 3.75 | 4 |
class Pilha:
def __init__(self):
self.lista_filmes = []
def tamanho(self):
return len(self.lista_filmes)
def pop(self):
return self.lista_filmes.pop()
def push(self, item):
return self.lista_filmes.append(item)
# instancia o objeto na classe
gisele = Pilha()
# adiciona elemento na lista
gisele.push("A lagoa Azul")
gisele.push('As Panteras')
gisele.push('Velozos e Furiosos')
# exibe a lista com os elementos
print(gisele.lista_filmes)
# exibe o tamanho da lista
print(f'Tamanho: {gisele.tamanho()}')
# remove o ultimo elemento da lista
gisele.pop()
# exibe os elementos da lista
print(gisele.lista_filmes)
print(f'Tamanho: {gisele.tamanho()}') |
e07cd5a1719c796c980b06b003c83df9d57457f3 | giselemanuel/programa-Ifood-backend | /qualified/sem7_qualified_1.py | 1,757 | 4.65625 | 5 | """
Descrição
Crie quatro funções básicas para simular uma Pilha:
cria_pilha(): Retorna uma pilha vazia.
tamanho(pilha): Recebe uma pilha como parâmetro e retorna o seu tamanho.
adiciona(pilha, valor): Recebe uma pilha e um valor como parâmetro, adiciona esse valor na pilha e a retorna.
remove(pilha): Recebe uma pilha como parâmetro e retorna o valor no topo da pilha. Se a pilha estiver vazia, deve retornar None.
Lembre-se:
A pilha funciona seguindo a sequência LIFO(Last In First Out) - Último a entrar, primeiro a sair.
Em python, a pilha é implementada utilizando a estrutura de uma lista.
Exemplos
Função cria_pilha()
Saída: []
Função tamanho(pilha)
# minha_pilha = [9, 1, 2, 3, 100]
Entrada: minha_pilha
Saída: 5
Função adiciona(pilha, valor)
# minha_pilha = [1, 2, 3]
Entrada: minha_pilha, 100
Saída: [1, 2, 3, 100]
Função remove(pilha)
# minha_pilha = [1, 2, 3]
Entrada: minha_pilha
Saída: [1, 2]
# minha_pilha = []
Entrada: minha_pilha
Saída: None
"""
# Função cria_pilha ----------------------------------
def cria_pilha():
pilha = []
return pilha
# Função tamanho -------------------------------------
def tamanho(pilha):
return len(pilha)
# Função adiciona ------------------------------------
def adiciona(pilha, elemento):
pilha.append(elemento)
return pilha
# Função remove --------------------------------------
def remove(pilha):
if len(pilha) != 0:
removido = pilha.pop()
return removido
else:
pilha = None
return pilha
# Define variável -----------------------------------
minha_pilha = [1, 2, 3]
# Chama Funções -------------------------------------
tamanho(minha_pilha)
remove(minha_pilha)
adiciona(minha_pilha, 100)
|
003112e87a05bb6da91942b2c5b3db98d082193a | joshua-hampton/my-isc-work | /python_work/functions.py | 370 | 4.1875 | 4 | #!/usr/bin/python
def double_it(number):
return 2*number
def calc_hypo(a,b):
if (type(a)==float or type(a)==int) and (type(b)==float or type(b)==int):
hypo=((a**2)+(b**2))**0.5
else:
print 'Error, wrong value type'
hypo=False
return hypo
if __name__ == '__main__':
print double_it(3)
print double_it(3.5)
print calc_hypo(3,4)
print calc_hypo('2',3)
|
a748f2008bc9aed1eccb121f2a909bd24ea61e4b | 1raviprakash/P342-Assignment-4 | /F_B_SUB.PY | 747 | 3.515625 | 4 | # Function for finding F&B Substitution
def func(a, b):
n = len(a)
m = len(b[0])
# Doing forward substitution first
# For getting [[0,0,0,m times],for getting this n times]
y = [[0 for y in range(m)] for x in range(n)]
for i in range(n):
for j in range(m):
s = 0
for k in range(i):
s = s + a[i][k] * y[k][j]
y[i][j] = b[i][j] - s
# Doing backward substitution then
x = [[0 for y in range(m)] for x in range(n)]
for i in range(n-1, -1, -1):
for j in range(m):
s = 0
for k in range(i + 1, n):
s = s + a[i][k] * x[k][j]
x[i][j] = (y[i][j] - s) / a[i][i]
return x
|
37e3f89dcc79e475518d57428281a62d859ee40c | ixinit/architecture_pc | /sistem_schisl.py | 688 | 4 | 4 | # -*- coding: utf-8 -*-
a = input("Введите число: ")
b = int(input("Из какой системы счисления конверировать? "))
c = int(input("В какую систему счисления? "))
def convert_base(num, to_base=10, from_base=10):
# first convert to decimal number
if isinstance(num, str):
n = int(num, from_base)
else:
n = int(num)
# now convert decimal to 'to_base' base
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n < to_base:
return alphabet[n]
else:
return convert_base(n // to_base, to_base) + alphabet[n % to_base]
print(convert_base(a, from_base=b, to_base=c))
|
7ec3bd5424a62f25ab1c973a6d90a1b1fb65d9d5 | felipegust/canal | /exerciciosLogica/logica2.py | 271 | 3.734375 | 4 | # dizer se um número é primo ou não
def ehPrimo(numero):
for n in range(2, numero):
if numero % n == 0:
print(numero, "não é primo")
return
print(numero, "é primo")
ehPrimo(10)
ehPrimo(7)
ehPrimo(23)
ehPrimo(30)
ehPrimo(29) |
e2018cb94d6973716664d60f1dd10a528ee6bc24 | picopicogame/Practice_Cipher | /src/Caesar_cipher.py | 1,506 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class CaesarCipher:
"""シーザー暗号"""
def __init__(self, plain_text, key=3):
self.plain_text = plain_text
self.key = key
self._check_input()
def _check_input(self):
if len(self.plain_text) == 0:
print("入力エラー。英字小文字a-zを入力してください")
exit()
for s in self.plain_text:
if 'a' <= s <= 'z':
pass
else:
print("入力エラー。英字小文字a-zを入力してください")
exit()
def encrypt(self):
crypted_str = ""
for s in self.plain_text:
shift_key = self.key % 26
shift_s = ord(s) + shift_key
if shift_s > ord('z'):
shift_s = (shift_s - ord('z') + (ord('a')-1))
crypted_str += chr(shift_s)
return crypted_str
def decrypt(self, crypted):
plain_txt = ""
for s in crypted:
shift_key = self.key % 26
shift_s = ord(s) - shift_key
if shift_s < ord('a'):
# aよりもいくつ前にあるか計算する
sub_a_s = ord('a') - shift_s
# zから差を引く
shift_s = ord('z') - sub_a_s + 1
plain_txt += chr(shift_s)
return plain_txt
if __name__ == '__main__':
cci = CaesarCipher("abcmnxyz", 4)
print(cci.decrypt(cci.encrypt()))
|
a7fa93eefd7c705fda3a6cd793a74afb3c902264 | JacksonEckersley/cp1404practicals | /prac_02/randoms.py | 275 | 3.71875 | 4 | """
Line 1 produced random integers between and including 5 and 20.
Line 2 produced random odd integers between 3 and 10. It would not produce a 4.
Line 3 produced a random number of 15 decimal places between 2.5 and 5.5.
"""
import random
print(random.randrange(1, 101))
|
5aae18dd6addca502355ec33019eaafb40f95dfb | DaniilStepanov2000/test_tasks_data_engineer | /main.py | 5,626 | 4.0625 | 4 | import math
import os
import argparse
def create_parser() -> argparse.ArgumentParser:
"""Create parser to get arguments from console
Args:
None.
Returns:
Parser object.
"""
parser = argparse.ArgumentParser()
parser.add_argument('name')
parser.add_argument('--em_sue_name', default=None)
parser.add_argument('--em_salary', default=None)
return parser
def write_to_file(user_name: str, user_salary: str, file_name: str) -> None:
"""Add new data to file.
Args:
user_name: Name of user that to add to file.
user_salary: User's salary that to add to file.
file_name: Name of file that should open.
Returns:
None.
"""
if (user_name is None) or (user_salary is None):
return
with open(f'data/{file_name}', 'a+') as file:
file.write(f'{user_name} {user_salary}\n')
def check_name(name: str) -> None:
"""Check does file with this name exist.
Args:
name: Name of file to open.
Returns:
None.
"""
if not os.path.isfile(f'data/{name}'):
print('Sorry! The file with this name does not exist! Try again!')
exit()
def get_line_from_file(file_name: str) -> str:
"""Get line from file.
Args:
file_name: Name of file to open.
Returns:
Line from file.
"""
with open(f'data/{file_name}', 'r') as file:
for line in file:
yield line
def get_bigger_mean(all_slries: list, mean: float) -> int:
"""Finds the number of employees whose salary is higher than the mean salary.
Args:
all_slries: List of all employees salaries.
mean: Mean salary.
Returns:
Number of employees whose salary is higher than mean salary.
"""
count = 0
for salary in all_slries:
if salary > mean:
count += 1
return count
def get_min_max_median(all_slries: list) -> (int, int, int):
"""Find the smallest, the biggest and median salary.
Args:
all_slries: List of all employees salaries.
Returns:
Tuple that contains the smallest, the biggest and median salary.
"""
all_slries.sort()
if len(all_slries) % 2 == 0:
return all_slries[len(all_slries) % 2 - 1] + all_slries[len(all_slries) % 2], min(all_slries), max(all_slries)
return all_slries[math.ceil(len(all_slries) / 2)], min(all_slries), max(all_slries)
def get_user_slry_mean(file_name: str) -> (int, int, float, int, int):
"""Count: number of employees that in file, total employees salary, number of employees that has first letter 'K'.
Create list of all salaries.
Args:
file_name: Name of file to open.
Returns:
Tuple that contains number of employees that in file, total employees salary, mean salary, list of all salaries,
number of employees that has first letter 'K'.
"""
user_count = 0
total_slry_count = 0
count_of_k = 0
all_salary = []
for line in get_line_from_file(file_name):
data_line = line.split()
all_salary.append(int(data_line[1]))
if data_line[0][0] == 'k' or data_line[0][0] == 'K':
count_of_k += 1
total_slry_count += int(data_line[1])
user_count += 1
return user_count, total_slry_count, total_slry_count / user_count, all_salary, count_of_k
def print_results(number_user: int, total_salary: int,
mean_salary: float, median: int,
minimum: int, maximum: int,
bg_mean: int, start_k: int
) -> None:
"""Print final result.
Args:
number_user: Number of employees in file.
total_salary: Total salary of employees.
mean_salary: Mean salary.
median: Median salary.
minimum: Minimum salary.
maximum: Maximum salary.
bg_mean: Number of employees whose salary is higher than mean salary.
start_k: Number of employees that has first letter 'K'.
Returns:
None.
"""
print(f'Number of users: {number_user}')
print(f'Total salary: {total_salary}')
print(f'Mean salary: {mean_salary}')
print(f'Median salary: {median}')
print(f'Minimum salary: {minimum}')
print(f'Maximum salary: {maximum}')
print(f'Value of users with salary bigger than mean salary: {bg_mean}')
print(f'Number of users that name start with k: {start_k}')
def start_params(name: str) -> None:
"""Start procedure to find parameters.
Args:
name: name of file to read.
Returns:
None.
"""
number_user, total_salary, mean_salary, salaries, start_k = get_user_slry_mean(name)
median, minimum, maximum = get_min_max_median(salaries)
bg_mean = get_bigger_mean(salaries, mean_salary)
print_results(number_user, total_salary, mean_salary, median, minimum, maximum, bg_mean, start_k)
def get_arg_from_pars() -> (str, str, str):
"""Get parameters from console.
Args:
None.
Returns:
Tuple that contains name of file, employee's name, employee's salary.
"""
parser = create_parser()
namespace = parser.parse_args()
name = namespace.name
emp_name = namespace.em_sue_name
emp_salary = namespace.em_salary
return name, emp_name, emp_salary
def main() -> None:
"""Start procedure.
Args:
None.
Returns:
None.
"""
name, emp_name, emp_salary = get_arg_from_pars()
check_name(name)
write_to_file(emp_name, emp_salary, name)
print('')
start_params(name)
if __name__ == '__main__':
main()
|
eda28e4cdf9e141b4cf1f4c05dd5cbc9bd8d7e40 | MarjoHysaj/betaPlan | /users_bankaccount/userstobankaccount.py | 1,128 | 3.78125 | 4 | class BankAccount:
def __init__(self, int_rate=0, balance=0):
self.int_rate=int_rate
self.balance=balance
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance += amount
return self
def display_account_info(self):
print(self.balance)
def yield_interest(self):
self.balance += self.int_rate * self.balance
print(self.balance)
return self
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account = BankAccount(int_rate=0.02 , balance=0)
print(self.account.balance)
def make_deposit(self, amount):
self.account.deposit(100)
print(self.account.balance)
def make_withdrawl(self,amount):
self.account.withdraw(20)
print(self.account.balance)
def transfer_money(self,other_user,amount):
self.account.withdraw(30)
other_user.account.deposit(30)
user1=User("Mario" , "mariohysaj@gmail.com")
print(23)
print(user1.account.balance) |
33527a98f48b44c0711a97a7545965786d4d64d3 | RobotGyal/Captian-Rainbow-Checklist | /checklist.py | 4,266 | 3.640625 | 4 | class colors:
purple = '\033[30m'
green = '\033[32m'
yellow = '\033[93m'
grey = '\033[37m'
red='\033[31m'
checklist = list()
# CREATE
def create(item):
checklist.append(item)
# READ
def read(index):
if in_scope(index):
print(checklist[index])
return checklist[index]
else:
print ("Index out of scope")
# UPDATE
def update(index, item):
if in_scope(index):
checklist[index] = item
else:
print("Index out of sccope")
# DESTROY
def destroy(index):
if in_scope(index):
checklist.pop(index)
else:
print("Index out of scope")
# LIST ALL ITEMS
def list_all_items():
index = 0
for list_item in checklist:
print("{} {}".format(index, list_item))
index += 1
# MARK COMPLETED
def mark_completed(index):
if in_scope(index):
update(index, ' √ ' + checklist[index])
else:
print("\nIndex out of scope")
def in_scope(index):
try:
checklist[int(index)]
return True
except:
return False
# SELECT
def select(function_code):
# Create item
if function_code == "C" or function_code == "c":
input_item = user_input("Input item: ")
create(input_item)
# Read item
elif function_code == "R" or function_code == "r":
item_index = int(user_input("Index Number? "))
# Remember that item_index must actually exist or our program will crash.
read(item_index)
# Update
elif function_code == "U" or function_code == "u":
list_all_items()
update_index = input('What list item (by assosciated index) would you like to update? : ')
new_item = input("Input new value: ")
update(int(update_index), new_item)
print('\nHere is the updated list: \n')
list_all_items()
#Destroy
elif function_code == "D" or function_code == "d":
list_all_items()
destroy_index = input('What list item (by assosciated index) would you like to destroy? : ')
destroy(int(destroy_index))
list_all_items()
# Print all items
elif function_code == "P" or function_code == "p":
list_all_items()
elif function_code == "M" or function_code == "m":
completed_index = input("Which item would you like to mark completed (enter index): ")
mark_completed(int(completed_index))
print("Updated List:\n")
list_all_items()
#Quit
elif function_code == "Q" or function_code == "q":
#Where the loop stops
return False
# Catch all
else:
print("Unknown Option")
return True
# USER INPUT
def user_input(prompt):
# the input function will display a message in the terminal
# and wait for user input.
user_input = input(prompt)
return user_input
# TEST
def test():
create("purple sox")
create("red cloak")
print(colors.green, read(0))
print(colors.green, read(1))
update(0, "purple socks")
destroy(1)
print(colors.yellow, read(0))
print("\nCreate Tests: \n")
select("C") #create test
select("C")
select("C")
in_scope(0) #should pass
print("in bounds")
in_scope(5) #should fail (print out of bounds)
print("\nRead Test: \n")
select("R") #read test
print("\nUpdate Test: \n")
select("U") #update test
print("\nDestroy Test: \n")
select("D") #destroy test
print("\nPrint All Test: \n")
select("P") #print all test
print("\nMark Complete Test\n")
select("M")
print("\nQuit Test: \n")
select("Q") #quit test
def run():
running = True
print(colors.grey)
while running:
selection = user_input(
"\nPress C to create list, R to read, U to update item, D to destroy, M to mark completed, P to print list, and Q to quit ")
running = select(selection)
print(colors.yellow, "Welcome to the Captian Rainbow Checklist!")
start_option = input("Would you like to run the TEST or the full APPLICATION? Enter t/a: ")
if start_option == "t" or start_option == 'T':
print(colors.green)
test()
elif start_option == 'a' or start_option == "A":
print(colors.grey)
run()
else:
print("\nInvalid response\nExiting software\n")
|
763cf249bb354d13bc6f271456a26e56d68e2a9a | shadkaiser/demos_n_stuff | /mac_address_changer | 3,066 | 4.3125 | 4 | #!/usr/bin/python
# The subprocess call method allows us to executed the commands in the shell
# Python3 would use input instead of raw_input
import subprocess
import optparse
import re
def get_arguments():
# creates an object called parser in the OptionParser class
# This will parse the arguments that are passed into the command line
parser = optparse.OptionParser()
# In the parser object, we create instances - the first 2 arguments will give the user the appropriate flags
# it will pass those arguments from the command line and save them to the dest
parser.add_option("-i", "--interface", dest="interface", help="Interface to change its MAC Address")
parser.add_option("-m", "--mac", dest="mac_address", help="New Mac Address that the person wants to use")
# This will parse the arguments its receives from the user
# This will save the options and arguments into a tuple
# To access the options, just do options.[name of the option dest]
# This will save the options and arguments into a tuple
# To access the options, just do options.[name of the option dest]
(options, arguments) = parser.parse_args()
# This condition checks to see if both arguments were entered
if not options.interface:
parser.error("[-] Please specify and interface, use --help for more info")
elif not options.mac_address:
parser.error("Please specify a MAC, use --help for more info")
return options
def change_mac(inter, mac):
# subprocess.call("ifconfig "+ inter + " down", shell=True)
# subprocess.call("ifconfig " + inter + " hw ether " + mac, shell=True)
# subprocess.call("ifconfig " + inter + " up", shell=True)
# more secure version of above code
# Prevents command chaining
print("[+] Changing MAC address for {} to {}".format(inter, mac))
subprocess.call(["ifconfig", inter, "down"])
subprocess.call(["ifconfig", inter, "hw", "ether", mac])
subprocess.call(["ifconfig", inter, "up"])
def get_current_mac(interface):
# The subprocess check output method will display the output of the command passed in
ifconfig_result = subprocess.check_output(["ifconfig", interface])
# The first parameter in re.search is the regex pattern to look for
# The second argument is where to look for the regex pattern
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
# The re.search matches are saved in a group, so we only want to pull the first item from it
if mac_address_search_result:
return mac_address_search_result.group(0)
else:
print("[-] Could not read MAC address")
options = get_arguments()
current_mac = get_current_mac(options.interface)
print("Current MAC = " + str(current_mac))
change_mac(options.interface, options.mac_address)
current_mac = get_current_mac(options.interface)
if current_mac == options.mac_address:
print("[+] MAC address was successfully changed to " + current_mac)
else:
print("[-] MAC address did not get changed.")
|
1b816c2a4c68ddadd488de7ea758018d61e4a43e | briennehayes/ClickbaitSummarizer | /sumbasic.py | 1,497 | 3.578125 | 4 | import spacy
import operator
from collections import Counter
def sumbasic(doc, sum_length = 1):
""" Implementation of sumbasic text summarization algorithm. Picks representative sentences based on high word frequencies.
Args:
doc (spacy.tokens.doc.Doc): spacy document to summarize
sum_length (int): number of sentences for the summary
Returns:
string: document summary
"""
tokens = [tok.norm_ for tok in doc if not tok.is_punct and not tok.is_stop]
freqdist = Counter(tokens)
probs = [freqdist[key] / len(tokens) for key in freqdist]
probdict = dict(zip(freqdist.keys(), probs))
sents = list(doc.sents)
most_frequent_word = max(probdict.items(), key = operator.itemgetter(1))[0]
sum_count = 0
summary = []
while sum_count < sum_length:
best_sent = None
best_weight = 0
for sent in sents:
weight = 0
for tok in sent:
if not tok.is_punct and not tok.is_stop:
weight += probdict[tok.norm_]
weight = weight / len(sent)
if weight > best_weight and most_frequent_word in sent.text.lower():
best_sent = sent
best_weight = weight
summary.append(best_sent.text)
sum_count += 1
for tok in best_sent:
if not tok.is_punct and not tok.is_stop:
probdict[tok.norm_] = probdict[tok.norm_] ** 2
return " ".join(summary) |
6102ef9f156e84f8fdea6bf7016802a5e415e103 | KubaWasik/object-oriented-programming-python | /student.py | 4,962 | 3.953125 | 4 | class Pupil:
"""Klasa Pupil zawierająca dane o uczniu oraz jego ocenach i wagach"""
grades = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0]
def __init__(self, name="Nieznane", surname="Nieznane"):
self.name = name
self.surname = surname
self.marks = {}
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
if len(new_name) >= 3 and new_name.isalpha():
self._name = new_name
else:
print('Imię musi składać się z co najmniej 3 liter i ' +
'zawierać tylko litery\nUstawiono "Nieznane"')
self._name = "Nieznane"
@property
def surname(self):
return self._surname
@surname.setter
def surname(self, new_surname):
if len(new_surname) >= 3 and new_surname.isalpha():
self._surname = new_surname
else:
print('Nazwisko musi składać się z co najmniej 3 liter i ' +
'zawierać tylko litery\nUstawiono "Nieznane"')
self._surname = "Nieznane"
@property
def marks(self):
return self._marks
@marks.setter
def marks(self, new_marks):
tmp = {}
for mark in new_marks:
if new_marks[mark] in Pupil.grades:
tmp[mark] = new_marks[mark]
else:
print("Dla przedmiotu", mark,
"ocena była niepoprawna, nie dodano do dziennika!")
self._marks = tmp
@marks.deleter
def marks(self):
self._marks = {}
def complete_marks(self, new_marks):
tmp = {}
for mark in new_marks:
if new_marks[mark] in Pupil.grades:
tmp[mark] = new_marks[mark]
else:
print("Dla przedmiotu", mark,
"ocena była niepoprawna, nie dodano do dziennika!")
self._marks = tmp
def print_marks(self):
print("Oceny:\n")
for mark in self.marks:
print(str(mark) + ": " + str(self.marks[mark]))
def mean(self):
if self.marks:
return sum(self.marks.values()) / len(self.marks.values())
else:
return "Dziennik jest pusty!"
def __repr__(self):
values = ', '.join(('{} = {!r}'.format(k.lstrip('_'), v)
for k, v in self.__dict__.items()))
return '{}({})'.format(self.__class__.__name__, values)
def __str__(self):
description = "Imię:\t\t{0.name}\nNazwisko:\t{0.surname}\n".format(self)
description += "Średnia ocen:\t{}".format(self.mean())
return description
class Student(Pupil):
def __init__(self, name="Nieznane", surname="Nieznane", weights=None):
super().__init__(name, surname)
if weights is None:
weights = {}
self.weights = weights
@property
def weights(self):
return self._weights
@weights.setter
def weights(self, new_weights):
tmp = {}
for mark in new_weights:
if isinstance(new_weights[mark], float) and (0 < float(new_weights[mark]) <= 1):
tmp[mark] = new_weights[mark]
else:
print("Dla przedmiotu ", mark, " waga była niepoprawna, nie dodano do dziennika!")
self._weights = tmp
@weights.deleter
def weights(self):
self._weights = {}
def complete_weights(self, new_weights):
for mark in new_weights:
if 0 < new_weights[mark] <= 1:
self._weights[mark] = new_weights[mark]
else:
print("Dla przedmiotu ", mark, " waga była niepoprawna, nie dodano do dziennika!")
def mean(self):
if self.marks:
avg_sum = 0.0
avg_wei = 0.0
for mark in self.marks:
if mark in self.weights and self.weights[mark]:
avg_sum += self.marks[mark] * self.weights[mark]
avg_wei += self.weights[mark]
else:
print("Brak wagi dla przedmiotu ", mark, "\nDodaję z wagą 0.5")
avg_sum += self.marks[mark] * 0.5
avg_wei += 0.5
return avg_sum / avg_wei
else:
return "Dziennik jest pusty!"
def main():
jozef = Pupil("Jozef", "Kowalski")
jozef.marks = {
"Chemia": 4.0,
"Biologia": 3.5,
"Matematyka": 5.5,
"Informatyka": 6.0,
"WF": 5.0
}
print(jozef)
print()
frank = Student("Franciszek", "Nowak")
frank.marks = {
"Chemia": 4.0,
"Biologia": 3.5,
"Matematyka": 5.5,
"Informatyka": 6.0,
"WF": 5.0
}
frank.weights = {
"Chemia": 0.3,
"Biologia": 0.673684,
"Matematyka": 1.0,
"Informatyka": 0.987654321,
"WF": 0.4
}
print(frank)
if __name__ == "__main__":
main()
|
5340a4aab74a71aec9cf30b6f0a3487e5e9ae22e | anahitha/c-106 | /graphs.py | 762 | 3.859375 | 4 | import plotly.express as px
import csv
import numpy as np
import pandas as pd
def data():
temp = []
sales = []
with open("icecreamdata.csv") as data:
df = csv.DictReader(data)
for row in df:
temp.append(float(row['Temperature']))
sales.append(float(row['Ice-cream Sales']))
return {'x': temp, 'y': sales}
def correlate():
datasrc = data()
correlation = np.corrcoef(datasrc['x'], datasrc['y'])
print(correlation[0, 1])
def plot():
f = pd.read_csv('icecreamdata.csv')
graph = px.scatter(f, x="Temperature", y = "Ice-cream Sales", size = "Ice-cream Sales")
graph.show()
correlate()
input("Do you want to see a graph? ")
if input == "yes":
plot() |
a15f72482720e16f831f6e44bece611910eec4d5 | Katakhan/TrabalhosPython2 | /Aula 5/aula5.2.py | 505 | 4.125 | 4 | #2- Mercado tech...
#Solicitar Nome do funcionario
#solicitar idade
#informar se o funcionario pode adquirir produtos alcoolicos
#3-
#cadastrar produtos mercado tech
#solicitar nome do produto
#Solicitar a categoria do produto(alcoolicos e não alcoolicos)
#exibir o produto cadastrado
nomef = input('informe o nome do funcionário: ')
idade = int(input('informe a idade :' ))
if idade >=18:
print(f'pode dale na cachaça,{nomef}')
else:
print(f'Vai chapar de energético só se for{nomef}')
|
aaca340072fbd4a1893ab6c49546aa10f5d7457c | Katakhan/TrabalhosPython2 | /Aula 27/exercicios/exercicio1.py | 2,616 | 3.953125 | 4 | # Aula 21 - 16-12-2019
#Funções para listas
from geradorlista import lista_simples_int
from random import randint
lista1 = lista_simples_int(randint(5,100))
lista2 = lista_simples_int(randint(5,75))
lista3 = lista_simples_int(randint(5,70))
# 1) Com as listas aleatórias (lista1,lista2,lista3) e usando as funções para listas,
# f-string, responda as seguintes questões:
# 1.1) Qual é o tamanho da lista1?
print(f"Tamanho da lista1 : {len(lista1)}")
# 1.2) Qual é o maior valor da lista2?
print(f"Maior valor da lista2 : {max(lista2)}")
# 1.3) Qual seria a soma do maior valor com o menor valor da lista2?
print(f"A soma entre o maior valor da Lista2: {max(lista2)} e o menor valor da lista2: {min(lista2)} é de : {max(lista2)+min(lista2)}")
# 1.4) Qual é a média aritmética da lista1?
print(f"A media aproximada da lista1 é {round(sum(lista1)/len(lista1),2)} ")
# 1.5) Qual o valor da soma de todas as listas e a soma total delas?
# quero que mostre a soma individual (por lista) e a soma total de todas elas (soma das somas das listas)
print(f'A soma da lista1: {sum(lista1)}. A soma da lista2: {sum(lista2)}. A soma da lista3: {sum(lista3)}. Valor total: {sum(lista1)+sum(lista2)+sum(lista3)}')
# 1.6) Usando o f-string, imprima todos os valores da lista1 um de baixo do outro.
for elemento in lista1:
print(f'Elementos da lista1: {elemento}')
# 1.7) Com a indexação e f-string, mostre o valor das posições 5, 9, 10 e 25 de cada lista.
# trate para evitar o erro: IndexError
try:
print(f'Posições da lista1: {lista1[5]}, {lista1[9]}, {lista1[10]} e {lista1[25]} ')
print(f'Posições da lista2: {lista2[5]}, {lista2[9]}, {lista2[10]} e {lista2[25]} ')
print(f'Posições da lista3: {lista3[5]}, {lista3[9]}, {lista3[10]} e {lista3[25]} ')
except IndexError:
print('erro de índice')
# 1.8) Mostre qual das listas tem mais itens (lembre-se, as listas são randômicas, não há como prever o
# tamanho delas).
if len(lista1) > len(lista2):
print(f'A lista1 é a com maior itens')
elif len(lista1) < len(lista2) and len(lista2) > len(lista3):
print(f'A lista2 é a com maior itens')
else:
print('a lista3 é a maior')
# 1.9) Some os maiores números de todas as listas e subtraia pelo menor número dos menores valores das listas.
# Para obter o menor valor, pegue o menor valor das listas e veja qual deles é o menor e use ele.
# 1.10) Pegue o maior valor de todas as listas e some com o menor valor de todas as listas
print(f'{max(lista1)+min(lista1)}')
print(f'{max(lista2)+min(lista2)}')
print(f'{max(lista3)+min(lista3)}')
|
637a4a941cd877a8a0283d65b1bf4c779960b3fe | Katakhan/TrabalhosPython2 | /exercicios/exercicio2.py | 3,434 | 3.796875 | 4 | #--- Exercicio 2 - Input, Estrutura de decisão e operações matemáticas
#--- Crie um programa que leia os dados de um cliente
#--- Cliente: Nome, Sobrenome, ano de nascimento
#--- Exiba uma mensagem de boas vindas para o cliente
#--- Exiba um menu: Produtos alcoolicos e Produtos não alcoolicos, Sair
#--- Caso o cliente seja menor de idade o item 'produtos alcoolicos' não deve ser exibido
#--- Leia a opção digitada e crie uma tela para cada opção
nome = input('Informe seu nome\n')
sobrenome = input('Informe seu sobrenome\n')
nomecomp = nome +' '+ sobrenome
anodenasc = int(input('Informe seu ano de nascimento\n'))
idade = 2019 - anodenasc
if (idade >= 18):
print('-'*30)
print(f'Seja bem-vindo(a), {nomecomp}!\n\n1 - Produtos Alcoólicos.\n2 - Produtos Não-Alcoólicos.\n3 - Encerrar Programa.\n ')
print('-'*30)
op = int(input('\nEscolha uma opção:\n'))
if(op == 1):
print('-'*50)
print('\tMarcas de Bebidas Alcoólicas AB InBev')
print('1 - Antarctica.\n2 - Brahma.\n3 - Budweiser.\n4 - Corona.\n5 - Encerrar Programa.')
print('-'*50)
opma = int(input('\nEscolha uma opção:\n'))
if(opma == 1):
print('Nome da Marca: Antarctica.\nTeor Alcoólico: 4,6% vol.\nMédia de Preço: R$3.50 unid.')
elif(opma == 2):
print('Nome da Marca: Brahma.\nTeor Alcoólico: 5% vol.\nMédia de Preço: R$3.10 unid.')
elif(opma == 3):
print('Nome da Marca: Budweiser.\nTeor Alcoólico: 5% vol.\nMédia de Preço: R$2.10 unid.')
elif(opma == 4):
print('Nome da Marca: Corona.\nTeor Alcoólico: 4,5% vol.\nMédia de Preço: R$3.20 unid.')
elif(opma == 5):
SystemExit
if(op == 2):
print('-'*50)
print('\tMarcas de Bebidas Não-Alcoólicas AB InBev')
print('1 - Fusion.\n2 - Guaraná Antartica.\n3 - Pepsi.\n4 - Encerrar Programa.')
print('-'*50)
opmna = int(input('\nEscolha uma opção:\n'))
if(opmna == 1):
print('Nome da Marca: Fusion.\nTipo de Bebida: Energético.\nMédia de Preço: R$7.50 unid.')
elif(opmna == 2):
print('Nome da Marca: Guaraná Antartica.\nTipo de Bebida: Refrigerante.\nMédia de Preço: R$5.00 unid.')
elif(opmna == 3):
print('Nome da Marca: Pepsi.\nTipo de Bebida: Refrigerante.\nMédia de Preço: R$6.00 unid.')
elif(opmna == 4):
SystemExit
elif(idade < 18):
print('-'*30)
print(f'Seja bem-vindo(a), {nomecomp}!\n\n1 - Produtos Não-Alcoólicos.\n2 - Encerrar Programa.\n ')
print('-'*30)
op = int(input('\nEscolha uma opção:\n'))
if(op == 1):
print('-'*50)
print('\tMarcas de Bebidas Não-Alcoólicas AB InBev')
print('1 - Fusion.\n2 - Guaraná Antartica.\n3 - Pepsi.\n4 - Encerrar Programa.')
print('-'*50)
opmna = int(input('\nEscolha uma opção:\n'))
if(opmna == 1):
print('Nome da Marca: Fusion.\nTipo de Bebida: Energético.\nMédia de Preço: R$7.50 unid.')
elif(opmna == 2):
print('Nome da Marca: Guaraná Antartica.\nTipo de Bebida: Refrigerante.\nMédia de Preço: R$5.00 unid.')
elif(opmna == 3):
print('Nome da Marca: Pepsi.\nTipo de Bebida: Refrigerante.\nMédia de Preço: R$6.00 unid.')
elif(opmna == 4):
SystemExit
elif(op == 2):
SystemExit |
e1602fcc8c1c145b7a8cdc495c0f26ff657f42d8 | Katakhan/TrabalhosPython2 | /Exercicios Modulo 16/Exercicio 2.py | 517 | 3.90625 | 4 | #--- Exercício 2 - Funções - 1
#--- Escreva uma função que leia dois números do console
#--- Armazene cada número em uma variável
#--- Realize a soma entre os dois números e armazene o resultado em uma terceira variável
#--- Imprima o resultado e uma mensagem usando f-string (módulo 3)
n1 = ''
n2 = ''
r = ''
def ler (n1,n2,r):
n1 = float(input('Informe o 1 número'))
n2 = float(input('Informe o 2 número'))
r = (n1 + n2)
return print(f'A soma entre {n1} e {n2} é : {r}')
ler(n1,n2,r) |
34fb94928b4521a02ee32683fcc1369b36a03697 | Katakhan/TrabalhosPython2 | /Aula59/A59C1.py | 1,478 | 4.3125 | 4 | # ---- Rev Classe
# ---- Métodos de Classe
# ---- Método __init__
# ---- Variáveis de classe
# ---- Variáveis privadas
# ---- Metodos Getters e Setters
class Calc:
def __init__(self, numero1, numero2):
# Variável de classe
self.__n1 = numero1
self.__n2 = numero2
self.__resultado = 0
def set_n1(self, valor):
self.__n1 = valor
def get_n1(self):
return self.__n1
def set_n2(self, valor):
self.__n2 = valor
def get_n2(self):
return self.__n2
def get_resultado(self):
return self.__resultado
def soma(self):
a = self.__resultado = self.__n1 + self.__n2
return a
def multiplicacao(self):
a = self.__resultado = self.__n1 * self.__n2
return a
def subtracao(self):
self.__resultado = self.__n1 - self.__n2
return self.__resultado
c = Calc(10, 20)
assert isinstance(c, Calc)
for i in range(1000):
c.set_n1(i)
assert c.get_n1() == i
c.set_n2(i)
assert c.get_n2() == i
c.set_n1(50)
c.set_n2(20)
assert c.soma() == 70
assert c.subtracao() == 30
assert c.multiplicacao() == 1000
assert c.soma() == c.get_resultado()
assert c.subtracao() == c.get_resultado()
assert c.multiplicacao() == c.get_resultado()
# Instanciando um objeto da classe Calc
# c = Calc(10,20)
# print(c.get_n1())
# print(c.get_n2())
# c.set_n1(50)
# c.set_n2(100)
# print(c.get_n1())
# print(c.get_n2())
# print(c.get_resultado())
|
60f6598ba438e4ebb1d8210d5ebf7a0a9557a2f5 | Katakhan/TrabalhosPython2 | /Aula 15/Ex 1 .py | 1,081 | 3.8125 | 4 | marca = input('Informe a marca da cerveja')
teor = float(input('informe o teor alcoolico da cerveja'))
tipo = input('Informe o tipo da cervaja(Alcoolico(1) e não alcoolico (0))')
cerva_dicionario = {'marca':marca, 'teor':teor, 'tipo':tipo}
def salvar_cerva(cerva_dicionario):
arquivo = open ('Banco de cerva.txt','a')
arquivo.write(f"{cerva_dicionario['marca']};{cerva_dicionario['teor']};{cerva_dicionario['tipo']}\n")
arquivo.close()
def ler():
lista = []
arquivo = open ('Banco de cerva.txt', 'r')
for linha in arquivo:
linha = linha.strip()
lista_linha = linha.split(';')
cerva = {'marca':lista_linha[0] , 'teor':lista_linha[1], 'tipo':lista_linha[2]}
lista.append(cerva)
arquivo.close()
return lista
def salvar(cerva):
arquivo = open ('Banco de cerva.txt', 'r')
for cerva in arquivo:
print('linha')
arquivo.close()
cerva = {'marca':marca , 'teor':teor, 'tipo':tipo}
salvar_cerva(cerva_dicionario)
lista = ler()
for p in lista:
print(f"{p['marca']} - {p['teor']} - {p['tipo']}") |
bbadb83a9436c4fb543e3a703638449549af44e6 | Katakhan/TrabalhosPython2 | /Aula59/Classe.py | 501 | 4.15625 | 4 | #---- Métodos
#---- Argumentos Ordenados
#---- Argumentos Nomeados
def soma(n1,n2):
resultado = n1+n2
return resultado
res = soma(10,20)
print(res)
def multiplicacao(n1,n2,n3):
resultado = n1 * n2 * n3
return resultado
res = multiplicacao(10,20,30)
print(res)
def subtracao(n1,n2,n3):
resultado = n1-n2-n3
return resultado
res2 - subtracao(n1=10,n2=20,n3=10)
print(res2)
def multiplicacao(n1,n2=1,n3=1):
return n1*n2*n3
res3 = multiplicacao(n1,n2,n3)
print(res3) |
ac8a36d86281a5bcec872f04ce37a10a9600bea5 | Katakhan/TrabalhosPython2 | /Aula 16/Aula 16.py | 431 | 3.640625 | 4 | ## 29/11/2019 - Aula 16
##
## Cadastro de playlist
## Lendo Musica, Artista E album
from Faixa import faixa,salvar,ler
musica = input('Informe o nome da Musica \n')
artista = input('Informe o nome do Artista \n')
album = input('Informe o nome do Album \n')
faixa = faixa(musica,album,artista)
salvar(faixa)
lista_ler = ler()
for faixa in lista_ler:
print(f"{faixa['musica']} | {faixa['artista']} | {faixa['album']}") |
bbb99b2724b90a7bdf25c8a63d2d073a653089f5 | pjy08062/Winterschool2018 | /자동다각형2.py | 157 | 3.546875 | 4 | import turtle
t=turtle.Turtle()
t.shape('turtle')
n=int(input('몇각형을 그리시겠어요?(3-6):'))
for i in range(n):
t.fd(100)
t.lt(360/n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.