blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1e398537391f40744603c8b337fef71f7ae3eed8 | Reisande/ProjectEuler | /Project Euler 12.py | 615 | 3.671875 | 4 | import time
start_time = time.time()
def divisors(divisors_check):
root = int(divisors_check**.5) + 1
divisors_list = [(number, divisors_check/number) for number in range(1, root) if divisors_check % number == 0]
return len(divisors_list)*2
def triangle():
triangle_number = 0
triangle_number_list = [0, 1, 3]
while divisors(triangle_number_list[-1]) < 500:
triangle_number = 2*triangle_number_list[-1] - triangle_number_list[-2] + 1
triangle_number_list.append(triangle_number)
print(triangle_number)
triangle()
end_time = time.time()
print(end_time - start_time) |
6676596d813d6120804057454a271acbca5c0ca5 | tuguin/calculadora | /calculadora.py | 782 | 4.0625 | 4 | class calculator:
continuar=0
while(continuar==0):
a=int(input("valor de a "))
b=int(input("valor de b "))
soma=a+b
sub=a-b
multi=a*b
div=a/b
potencia=1
while (a!=0):
potencia=potencia*b
a=a-1
escolha=int(input("soma 1 sub 2 div 3 multi 4 potencia 5 "))
print("resultado " )
if (escolha==1):
print(soma)
if(escolha==2):
print(sub)
if(escolha==3):
print(div)
if(escolha==4):
print(multi)
if(escolha==5):
print(potencia)
print("------------")
continuar=int (input("sim 0 não 1 "))
|
36ff08887b4826ef0e11a3f7b419ecbac69aef11 | jahonjumanov/python_darslari_2 | /python fayllari/09.07.Funksiyalar va proseduralar/6-misol.py | 178 | 3.765625 | 4 | # ikkita sonni kattasini topuvchi funksiya
a=int(input("1-son="))
b=int(input("2-son="))
def katta(a,b):
if a>b:
return a
else:
return b
print(katta(a,b)) |
6e37e5d5eba5c3c4cbff337ca348b719a0f20bea | kurtrm/linear_algebra_pure | /src/matrix_mismatch_detector.py | 551 | 3.640625 | 4 | """
Function that takes in a bunch of numbers and determines if matrix
multiplication can occur.
1223344663322232
011111111
1, 2
1, 3
1, 4
1, 6
1, 3
1, 2
"""
from itertools import zip_longest
def can_multiply_matrices(*args):
"""
Takes in a series of tuples and detects
whether they can all be multiplied.
Meant to take in a series of numpy array shapes.
"""
rows, columns = zip(*args)
for row, column in zip_longest(rows[1:], columns):
if row != column:
return row is None
|
5b21b7a26649761899f1270dfe1d0f25ce5df4f0 | MinjeongSuh88/python_workspace | /20200724/test8.py | 989 | 3.78125 | 4 | def make2(fn):
def test2():
return '곤니찌와' + fn()
return test2
# return lambda: '곤니찌와' + fn() # 위의 2줄을 매개변수 없는 람다 함수 한 줄로 표현
def make1(fn): # 함수를 매개변수로 받음
# def test():
# return '니하오' +fn()
# return test
return lambda: '니하오' + fn() # fn() :매개변수 함수를 실행하기 때문에 함수 f1의 매개변수 fn에 그냥 변수가 대입되면 에러
def hello():
return '한라봉'
print(make2(make1(hello)))
hi = make2(make1(hello)) # hi는 람다함수
print(hi()) # print(make2(make1(hello))()) 와 같음
# 데코레이터(decorator), 다른언어에서는 annotator라고 함
@make2 # 함수 make2에 함수 hello2를 매개변수로 넣은 함수 make1을 매개변수로 넣음
@make1 # 함수 make1에 함수 hello2를 매개변수로 넣음
def hello2():
return '소망이'
hi = hello2
print(hi()) # print(make2(make1(hello2))())와 같음
|
d2a562966ea84a22a0d02a0a69b53c113cf00c49 | Prithamprince/Python-programming | /string60.py | 204 | 3.59375 | 4 | c=list(input())
d=""
e=""
for i in c:
if(i=="A" or i=="E" or i=="I" or i=="0" or i=="U" or i=="a" or i=="e" or i=="i" or i=="o" or i=="u"):
d+=i
else:
e+=i
d+=e
print(d)
|
66e090e9a7e5ee7f12344908b351e003de38ed03 | hernamesbarbara/Amortizer | /Loan.py | 2,893 | 4.15625 | 4 | import Amortizer
from pprint import pprint as pp
class Loan(object):
"""
Loan class for creating and amortizing loans.
"""
def __init__(self, amount, interest_rate, term, nper=12):
"""
Create a new Loan.
Args:
amount: loan amount
interest_rate: nominal interest rate as 'stated' without full effect of compounding (e.g. 10% would be 0.1)
term: term in years
nper: compounding frequency will default to 12 (i.e. compounding once per month)
"""
self.periods = nper
self.amount = self.present_value = self.outstanding = amount
self.term = term
self.interest_rate = interest_rate
self.rate = Amortizer.rate(interest_rate, self.periods)
self.pmt()
def pmt(self):
"""
Calculate the loan payment for the loan. Called from the __init__().
Args:
self.rate: periodic interest rate (i.e. interest rate / period)
self.periods*(self.term+1): total number of compounding periods
self.present_value: the loan amount
Returns:
self.payment: amount of each payment (float)
"""
self.payment = Amortizer.pmt(self.rate, self.periods*(self.term+1), self.present_value)
def makePayment(self):
"""
Make a payment: reduces the outstanding balance of a loan by 1 payment
Args:
self
Returns:
self.outstanding -= self.payment
"""
print 'Total Payment: ', self.payment
print 'Interest Part: %s\nPrincipal Part: %s' %\
Amortizer.breakdown(self.outstanding,self.payment, self.rate)
self.outstanding -= self.payment
print 'Principal Outstanding: ', self.outstanding, '\n'
def amortize(self):
"""
Amortizes the loan from start to finish. It will stop every 10 payments
and wait for you to hit 'enter'. After each payment is made, the nth_pmt
counter will be incremented and balance details will be printed.
"""
nth_pmt = 1
while int(self.outstanding) > 0:
print "_"*80+'\n'
print 'Payment Number: ', nth_pmt, '\n'
self.makePayment()
nth_pmt += 1
if nth_pmt % 10 == 0:
try:
selection = raw_input("Hit 'enter' to continue\nHit 'q' to quit\n")
if selection.lower()=='q': break
continue
except (KeyboardInterrupt,ValueError):
continue
def Print(self):
"""
Uses pprint to print the loan's attributes.
"""
pp(vars(self))
print '\n'
l = Loan(150000, 0.06, 5) #create a loan for $150k over 5 years at a 6% interest rate
l.amortize() #amortize the loan
|
0558be126544b48654f350b2ee573a9b9e03853a | ekmahama/Mircosoft | /backtracking/wordSearchII.py | 1,349 | 3.734375 | 4 | class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
def backtrack(board, i, j, word):
if len(word) == 0:
return True
if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):
return False
if board[i][j] != word[0]:
return False
board[i][j] = '#'
ret = False
for x, y in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
ret = backtrack(board, x+i, y+j, word[1:])
if ret:
break
board[i][j] = word[0]
return ret
result = []
for word in words:
found = False
for i in range(len(board)):
for j in range(len(board[0])):
if not backtrack(board, i, j, word):
continue
result.append(word)
found = True
break
if found:
break
return result
board = [["o", "a", "a", "n"], ["e", "t", "a", "e"],
["i", "h", "k", "r"], ["i", "f", "l", "v"]]
words = ["oath", "pea", "eat", "rain"]
r = Solution().findWords(board, words)
print()
|
a80eae95d240f2b3684c3e816f58794129a4898e | elYaro/Codewars-Katas-Python | /8 kyu/Surface_Area_and_Volume_of_a_Box.py | 173 | 3.578125 | 4 | '''
Write a function that returns the total surface area and volume of a box as an array: [area, volume].
'''
def get_size(w,h,d):
return[((w*h)+(w*d)+(h*d))*2,(w*h*d)] |
732ec77c8672210cc43a66d76d014f0ca1254750 | bilalkhan225/pythonpractice | /marksheet.py | 652 | 4.09375 | 4 | english = int(input("enter the marks of english: "))
maths = int(input("enter the marks of maths: "))
urdu = int(input("enter the marks of urdu: "))
sindhi = int(input("enter the marks of sindhi: "))
pakstudies = int(input("enter the marks of pak studies: "))
sum = (english+maths+urdu+sindhi+pakstudies)
per = (sum / 500) * 100
if per >= 90 :
print(per)
print("your grade is A")
elif per >= 80 and per < 90 :
print(per)
print("your grade is B")
elif per >= 70 and per < 80:
print(per)
print("your grade is C")
elif per >= 60 and per < 70:
print(per)
print("your grade is D")
else:
print("you are fail in exams")
|
7d33827cc05d4e11d4e23d41076245a4a7eaa08b | gnyoung19/flask_mortgage_calculator | /affordable_mortgage_function.py | 689 | 3.953125 | 4 | def mortgage_afford(income, down_payment, interest_rate):
monthly_income = income/12
mortgage_monthly = monthly_income * 0.25
cost_to_borrow_ten_grand = interest_rate*1000
max_affordable_mortgage = ((mortgage_monthly/cost_to_borrow_ten_grand) * 10000) + down_payment
print "Your maximum affordable mortgage is {}.".format(max_affordable_mortgage)
print "Welcome to the Mortgage affordability calculator!"
user_income = int(raw_input("What is your annual income? "))
user_down_payment = int(raw_input("What will be your down payment? "))
user_interest_rate = float(raw_input("What is the current interest rate? "))
mortgage_afford(user_income, user_down_payment, user_interest_rate) |
594839d495432d84ddd3dd1e0fe83cb92224971c | TomCallR/py_recursive | /tests/test_gift.py | 3,870 | 3.734375 | 4 | import unittest
from decimal import Decimal as D
from lib.gift import Book, ChocolateType, Chocolate, WithACard, WrappedGift, WrappingPaperStyle, BoxedGift
def build_data():
wolfHall = Book(title="Wolf Hall", price=2000)
yummyChoc = Chocolate(
type=ChocolateType.SeventyPercent,
price = 500)
birthdayPresent = WithACard(
gift = WrappedGift(gift = wolfHall, paper = WrappingPaperStyle.HappyBirthday),
message = "Happy Birthday")
christmasPresent = WrappedGift(
gift = BoxedGift(gift = yummyChoc),
paper = WrappingPaperStyle.HappyHolidays)
return wolfHall, yummyChoc, birthdayPresent, christmasPresent
class TestGiftDeclaration(unittest.TestCase):
#
def test_print_description(self):
wolfHall, yummyChoc, birthdayPresent, christmasPresent = build_data()
self.assertEqual(wolfHall.__str__(), "\"Wolf Hall\"")
self.assertEqual(yummyChoc.__str__(), "SeventyPercent chocolate")
self.assertEqual(
birthdayPresent.__str__(),
"\"Wolf Hall\" wrapped in HappyBirthday paper with a card saying \"Happy Birthday\""
)
self.assertEqual(
christmasPresent.__str__(),
"SeventyPercent chocolate in a box wrapped in HappyHolidays paper"
)
# Fails on purpose : fold mixes the order of elements
# def test_description_fold(self):
# wolfHall, yummyChoc, birthdayPresent, christmasPresent = build_data()
# self.assertEqual(wolfHall.description_fold(), "\"Wolf Hall\"")
# self.assertEqual(yummyChoc.description_fold(), "SeventyPercent chocolate")
# self.assertEqual(
# birthdayPresent.description_fold(),
# "\"Wolf Hall\" wrapped in HappyBirthday paper with a card saying \"Happy Birthday\""
# )
# self.assertEqual(
# christmasPresent.description_fold(),
# "SeventyPercent chocolate in a box wrapped in HappyHolidays paper"
# )
#
def test_print_description_fold_back(self):
wolfHall, yummyChoc, birthdayPresent, christmasPresent = build_data()
self.assertEqual(wolfHall.description_fold_back(), "\"Wolf Hall\"")
self.assertEqual(yummyChoc.description_fold_back(), "SeventyPercent chocolate")
self.assertEqual(
birthdayPresent.description_fold_back(),
"\"Wolf Hall\" wrapped in HappyBirthday paper with a card saying \"Happy Birthday\""
)
self.assertEqual(
christmasPresent.description_fold_back(),
"SeventyPercent chocolate in a box wrapped in HappyHolidays paper"
)
#
def test_print_description_foldback(self):
wolfHall, yummyChoc, birthdayPresent, christmasPresent = build_data()
self.assertEqual(wolfHall.description_foldback(), "\"Wolf Hall\"")
self.assertEqual(yummyChoc.description_foldback(), "SeventyPercent chocolate")
self.assertEqual(
birthdayPresent.description_foldback(),
"\"Wolf Hall\" wrapped in HappyBirthday paper with a card saying \"Happy Birthday\""
)
self.assertEqual(
christmasPresent.description_foldback(),
"SeventyPercent chocolate in a box wrapped in HappyHolidays paper"
)
#
def test_total_cost(self):
wolfHall, yummyChoc, birthdayPresent, christmasPresent = build_data()
self.assertEqual(birthdayPresent.total_cost(), D("22.5"))
self.assertEqual(christmasPresent.total_cost(), D("6.5"))
#
def test_total_cost_fold(self):
wolfHall, yummyChoc, birthdayPresent, christmasPresent = build_data()
self.assertEqual(birthdayPresent.total_cost_fold(), D("22.5"))
self.assertEqual(christmasPresent.total_cost_fold(), D("6.5"))
if __name__ == "__main__":
unittest.main() |
3b91282a27d3d254c221654e54a85fa6e9d13ccb | mehul-prajapati/Programs | /Python_Scripts/1 | 197 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def foo(n):
count = 1
if n > 0:
count += foo(n - 1) + foo(n - 1)
print '1'
return count
print foo(1)
print r"hello ew\"
|
219b68334d8af105c440066a788269d4917b354b | FeminaAnsar/luminarpython | /RegularExpressions/gmail_validation.py | 205 | 3.65625 | 4 | #validate gmail
from re import *
mail=input("Enter gmail id:")
rule="[a-zA-Z0-9.]*@gmail.com"
matcher=fullmatch(rule,mail)
if matcher ==None:
print("invalid gmail id")
else:
print("Valid gmail id") |
cae67c23a375d0154bc4e12db2743a8a8ab9ca77 | kaushik-mac/py-wiki | /pywiki/pywiki.py | 3,529 | 3.609375 | 4 |
'''01001011 01000001 01010101 01010011 01001000 01001001 01001011 00100000 01000111 01010101 01010000 01010100 01000001'''
# '''import all modules needed'''
from tkinter import Button, Label, Listbox, PhotoImage, Tk ,Text
from tkinter.constants import ACTIVE, END, SINGLE
import wikipedia
from py_module import search
# '''set up basic configuration for main app'''
root=Tk()
root.geometry('500x500')
root.resizable(False,False)
root.title('Pywiki Search')
# '''icon photo on title bar which is saved in same directory named `wikipedia.png`'''
photo_icon=PhotoImage(file='wikipedia.png')
root.iconphoto(False,photo_icon)
root.configure(bg='#34393b')
# '''main function in whhich all things are there'''
def main_function():
# '''command function to search on wikipedia api if entered text by user in match in wikipedia api if true then show a list of all possible title in wikipedia'''
def result():
global result_list
# label to show how to do summary search
search_topic_label=Label(root,text='Select topic from above list and press submit button below',bg='#34393b',fg='#fffffc',font=('bold italic',12))
search_topic_label.place(x=20,y=300,height=20,width=460)
# btn for summary search label
search_topic_btn=Button(root,text='Submit',bg='#6be387',fg='#c72222',font=('bold italic',11),command=lambda:result_selected())
search_topic_btn.place(x=200,y=330,height=20,width=100)
# get text entered by user
search_object=str(search_input.get('1.0','end'))
search_object_number=int(number_input.get('1.0','end'))
# search the result from custom library named `pywiki`
y=list(search(search_object,search_object_number))
# create list box and insert elements here the result of user inputed text
result_list=Listbox(root,selectmode=SINGLE,font=('bold',12),bg='#e8e26f')
result_list.place(x=25,y=50,height=230,width=445)
result_list.insert(END)
for items in y:
result_list.insert(END,items)
# function to show what topic user what to read from wikipedia based on what he/she search
def result_selected():
# get selected item
selected_item=(result_list.get(ACTIVE))
summary=(wikipedia.summary(selected_item,sentences=3))
# resize the geometry
root.geometry('500x700')
# output the summary
summary_label=Label(root,text=summary,wraplength=440,font=('small',9))
summary_label.place(x=20,y=370,height=300,width=460)
# label to show search text
search_label=Label(root,text='Search',bg='#6be387',fg='#000000',font=("bold italic", 11))
search_label.place(x=20,y=20,height=20,width=60)
# to get user input
search_input=Text(root,bg='#b3afaf')
search_input.place(x=90,y=20,height=20,width=130)
# search result by pressing this button
search_btn=Button(root,text='Submit',command=result,bg='#6be387',fg='#c72222',font=('bold italic',11))
search_btn.place(x=400,y=20,height=20,width=70)
# how many result user want
number_label=Label(root,text='No. of result',bg='#a6cede',fg='#000000',font=("bold italic", 11))
number_label.place(x=250,y=20,height=20,width=85)
# get entry of number of result
number_input=Text(root,bg='#b3afaf')
number_input.place(x=350,y=20,height=20,width=40)
# call function
main_function()
# show the app
root.mainloop()
|
0f03d4320e610115a1f5c88b05b06609429a8d32 | budaLi/leetcode-python- | /最常见的单词.py | 1,239 | 3.8125 | 4 | # @Time : 2019/9/20 11:12
# @Author : Libuda
# @FileName: 最常见的单词.py
# @Software: PyCharm
class Solution(object):
def mostCommonWord(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
dic = {}
paragraph = self.splitParagraph(paragraph)
print(paragraph)
for one in paragraph:
if one in banned:
pass
elif one not in dic:
dic[one] = 1
else:
dic[one] += 1
# dic= sorted(dic.items(),key = lambda key:key[1],reverse=True)
tem = max(dic.values())
for key, value in dic.items():
if value == tem:
return key
def splitParagraph(self, paragraph):
s = ['!', '?', "'", ",", ";", "."]
for one in s:
paragraph = paragraph.replace(one, " ")
paragraph = paragraph.lower().split()
return paragraph
if __name__ == "__main__":
S = Solution()
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
res = S.mostCommonWord(paragraph, banned)
# res= S.splitParagraph(paragraph)
print(res)
|
a4ac7132f6ae6f4a2595b5745ec61d9b299438a7 | Htrams/Leetcode | /string_to_integer.py | 2,734 | 3.984375 | 4 | # My Rating = 2
# Same logic can be used in a 32 bit language
# https://leetcode.com/problems/string-to-integer-atoi/
# The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
# The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
# If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
# If no valid conversion could be performed, a zero value is returned.
# Only the space character ' ' is considered as whitespace character.
# Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
class Solution:
def myAtoi(self, str: str) -> int:
INT32_MAX = 2**31-1
INT32_MIN = -2**31
numbers={'0','1','2','3','4','5','6','7','8','9'}
start=0
neg=1
num=0
for i in str:
if i == ' ':
if start==1:
start=2
break
continue
elif (i == '-' or i == '+') and start==0:
start=1
if i=='-':
neg=-1
elif i in numbers:
start=1
print(num)
if INT32_MAX//10 > num*neg and (-1)*((INT32_MIN*-1)//10) < num*neg:
num=num*10+int(i)
elif INT32_MAX//10 < num * neg:
return INT32_MAX
elif INT32_MIN//10 > num * neg:
return INT32_MIN
elif INT32_MAX//10 == num * neg:
if INT32_MAX%10 > int(i):
num=num*10+int(i)
else:
return INT32_MAX
else:
print((-1*INT32_MIN)%10)
if (-1*INT32_MIN)%10 > int(i):
num=num*10+int(i)
else:
return INT32_MIN
else:
if start==1:
start = 2
break
else:
# Did not start and is not a number
return 0
return num*neg |
80e303ddbf0ef1c6aeda14572a4aa9d44ca310af | harerakalex/code-wars-kata | /python/RomanNumerals.py | 1,835 | 4.09375 | 4 | '''
Create a RomanNumerals class that can convert a roman numeral to and from an integer value. It should follow the API demonstrated in the examples below. Multiple roman numeral values will be tested for each helper method.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Input range : 1 <= n < 4000
In this kata 4 should be represented as IV, NOT as IIII (the "watchmaker's four").
Examples
RomanNumerals.to_roman(1000) # should return 'M'
RomanNumerals.from_roman('M') # should return 1000
Help
Symbol Value
I 1
IV 4
V 5
X 10
L 50
C 100
D 500
M 1000
'''
class RomanNumerals:
sym = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
num = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
def to_roman(number):
result = ''
pointer = 0
while number:
div = number // RomanNumerals.num[pointer]
number %= RomanNumerals.num[pointer]
while div:
result += RomanNumerals.sym[pointer]
div -= 1
pointer += 1
return result
def from_roman(roman_numeral):
result = 0
for idx, val in enumerate(roman_numeral):
first_num = RomanNumerals.num[RomanNumerals.sym.index(val)]
second_num = RomanNumerals.num[RomanNumerals.sym.index(roman_numeral[idx + 1])] if idx + 1 != len(
roman_numeral) else -1
if first_num >= second_num:
result += first_num
else:
result -= first_num
return result |
9f1a99d9e1a4fd26172773e98b6bf07f710d8a7d | loayyehia9/SMTP | /SMTP.py | 2,780 | 3.53125 | 4 | #import abilities
from socket import *
msg = "\r\n I love Computer Networks" #body meesage
endmsg = "\r\n.\r\n" #character returns and line returns end message
#choosing a mail server smtp.gmail.com, 587
#mailserver = ("mail.smtp2go.com", 2525) #Fill in start #Fill in end
mailserver = ("smtp.gmail.com", 587) #Fill in start #Fill in end
# Create socket called clientSocket and establish a TCP connection with mailserver
clientSocket = socket(AF_INET, SOCK_STREAM) #internet and socket protocols
clientSocket.connect(mailserver)
recv = clientSocket.recv(1024) #client socket will recieve amount of data equals 1024
print("Message after connection request:", recv)
if recv[:3] != '220': #if the msg not recieved
print('220 reply not received from server.')
# Send HELO command and print server response.
heloCommand = 'Helo Alice\r\n' #server reply
clientSocket.send(heloCommand.encode()) #send the reply msg
recv1 = clientSocket.recv(1024) #receive the msg
print(recv1)
if recv1[:3] != '250': #if the msg not recieved
print('250 reply not received from server.')
# Send MAIL FROM command and print server response.
mailFrom = "MAIL FROM: <anyemailid@gmail.com> \r\n"
clientSocket.send(mailFrom.encode())
recv2 = clientSocket.recv(1024) #amount of data recieved
print("After MAIL FROM command: ", recv2)
if recv1[:3] != '250': #if the data not recieved
print('250 reply not received from server.')
# Send RCPT TO command and print server response.
rcptTo = "RCPT TO: <destination@gmail.com> \r\n" #reciepent
clientSocket.send(rcptTo.encode())
recv3 = clientSocket.recv(1024) #amount of data recieved
print("After RCPT TO command: ",recv3)
if recv1[:3] != '250': #if the data not recieved
print('250 reply not received from server.')
# Send DATA command and print server response.
data = "DATA\r\n"
clientSocket.send(data.encode()) #send the data
recv4 = clientSocket.recv(1024) #total size of the msg
print("After DATA command: ", recv4)
if recv1[:3] != '250': #if the msg not recieved
print('250 reply not received from server.')
# Send message data.
subject = "Subject: SMTP mail client testing \r\n\r\n"
clientSocket.send(subject.encode())
message = input("Enter your message: ") #input the message
#fill in end #msg ends with a single period
clientSocket.send(message.encode())
clientSocket.send(endmsg.encode())
recv_msg = clientSocket.recv(1024) #amountof data to be send
print("Response after sending message body:", recv_msg.decode())
if recv1[:3] != '250': #if the msg doesn't print properly
print('250 reply not received from server.')
# Send QUIT command and get server response.
clientSocket.send("QUIT\r\n".encode()) #tells the server the interaction should be terminated
message=clientSocket.recv(1024)
print (message)
clientSocket.close() #close the socket |
0199888989e1bb069636d9bcaaea379105482362 | batatay/dio-desafio-github | /desafios/aula14___57-65/desafio062.py | 567 | 4.03125 | 4 | #Melhore o DESAFIO 061, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerra quando ele disse que quer mostrar 0 termos.
termo = int(input('Digite o Primeiro termo: '))
razao = int(input('Digite a Razão: '))
primeiro = termo
contador = 1
total = 0
mais = 10
while mais != 0:
total = total + mais
while contador <= total:
print(f'{primeiro}/', end='')
primeiro += razao
contador += 1
print('...')
print('=*=' * 10)
mais = int(input('Deseja mostrar mais quantos termos? '))
print('FIM..!')
|
6735e08551253f76ea579b0dd6ca131db4a22b31 | marcos-s1/Problemas-Basicos | /Ordenação/ordenador.py | 1,186 | 3.796875 | 4 | class Ordenador:
def selecao_direta(self, lista):
fim = len(lista)
for i in range (fim-1):
#Inicialmete o menor elemento ja visto é o i-esimo
pos_minimo=i
for j in range(i+1, fim):
if lista[j]<lista[pos_minimo]:
pos_minimo=j
#Coloca o menor elemento achado no inicio da sub-lista
#Para isso, troca de lugar os elementos da posicao i e pos_minimo
lista[i], lista[pos_minimo] = lista[pos_minimo], lista[i]
def bubble_sort(self, lista):
fim = len(lista)
for i in range(fim-1,0,-1):
for j in range(i):
if lista[j] > lista[j+1]:
lista[j], lista[j+1] = lista[j+1], lista[j]
print(lista)
def bolha_curta(self, lista):
fim = len(lista)
for i in range(fim-1, 0, -1):
trocou = False
for j in range(i):
if lista[j] > lista[j+1]:
lista[j], lista[j+1] = lista[j+1], lista[j]
trocou =True
if not trocou:
return
|
d8576813f1bccddb24247fe87de4de49145aea33 | magicpieh28/nlp100 | /chapter1/05.py | 422 | 3.84375 | 4 | # n-gram
def make_word_bi_gram(text: str):
word_bi_gram = text.split(' ')
return [word_bi_gram[i:i+2] for i in range(len(word_bi_gram) - 1)]
def make_char_bi_gram(text: str):
char_bi_gram = text.replace(' ', '')
return [char_bi_gram[i:i+2]for i in range(len(char_bi_gram) - 1)]
if __name__ == '__main__':
text = "I am an NLPer"
print(make_word_bi_gram(text))
print(make_char_bi_gram(text))
|
b107aabc614a2f7e592c0ffca57e9931cc3e896f | MadisonStevens98/Koch-Curve-and-Snowflake-Python | /KochCurveDraw.py | 560 | 4.21875 | 4 | # Write your program below:
import turtle
import math
shape = turtle.Turtle()
def drawFractalLine(level, distance):
if level == 0:
shape.pendown()
shape.forward(distance)
else:
drawFractalLine(level-1, distance/3)
shape.left(60)
drawFractalLine(level-1, distance/3)
shape.right(120)
drawFractalLine(level-1, distance/3)
shape.left(60)
drawFractalLine(level-1, distance/3)
for i in range(6):
drawFractalLine(3, 55)
shape.left(60)
|
a5d9ed6d6d5ebac0e8d620918f92413b08a8620d | Nordevor/hi | /UTEC/Python/promedio.py | 97 | 3.71875 | 4 | a=0
x=0
z=0
while (a<5):
x=int(input("ingresar notas: "))
z=z+x
a+=1
print (z/5)
|
56dfe75099b6fce4e640d5dba505c3714de29cca | chichuyun/LeetCode | /0102/main.py | 748 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None: return []
temp = [root]
res = list()
while(temp):
res.append([])
temp_r = temp.copy()
temp = list()
for r in temp_r:
res[-1].append(r.val)
if r.left:
temp.append(r.left)
if r.right:
temp.append(r.right)
if not res[-1]: del res[-1]
return res
|
3ac84fa9f1cc787cdcd9c189648c973326072355 | Sorbus/artichoke | /authorize.py | 1,106 | 3.890625 | 4 | #!/usr/bin/python
#-----------------------------------------------------------------------
# twitter-authorize:
# - step through the process of creating and authorization a
# Twitter application.
#-----------------------------------------------------------------------
import twitter
import time
print("1. Create a new Twitter application here: https://apps.twitter.com")
print("When you have created the application, enter:")
print(" your application name: ")
app_name = input()
print(" your consumer key: ")
consumer_key = input()
print(" your consumer secret: ")
consumer_secret = input()
print("2. Now, authorize this application.")
print("You'll be forwarded to a web browser in two seconds.")
print()
time.sleep(2)
access_key, access_secret = twitter.oauth_dance(app_name, consumer_key, consumer_secret)
print("Done.")
print()
print("Now, replace the credentials in config.py with the below:")
print()
print("consumer_key = '%s'" % consumer_key)
print("consumer_secret = '%s'" % consumer_secret)
print("access_key = '%s'" % access_key)
print("access_secret = '%s'" % access_secret) |
3d21c7ca9a43508349c852c73e7a76c4669f919e | ashvinipadekar/my-django-app | /pythonfull/while program.py | 318 | 4.25 | 4 | """
**** To print the numbers upto 5
count=0
while count<6:
print(count)
count+=1
*** To print the numbers using break
num=1
while num<6:
print(num)
if num==3:
break
num+=1
**** To print the no using continew stmt
i = 0
while i < 6:
i+=1
if i == 3:
continue
print(i)
""" |
167e5176e5f65d74be1ef800017f5d05f28412fb | Cattleman/python_for_everybody_coursera | /conditional_practice.py | 507 | 4.0625 | 4 | x = raw_input('what is x?')
#if statement asks a variable
if x < 10:
print 'Smaller'
if x > 20:
print ' Bigger'
print 'Finis'
if x < 6 : print 'x <6'
#two nested ifs
y = 101
if y > 1 :
print 'More than one'
if y < 100:
print 'Less than 100'
print 'all done'
#two-way using else
z = 4
if z > 2:
print 'Bigger'
else :
print 'smaller'
print 'All done'
# < Less than
# <= less than or equal
# == Equal to
# >= Greater than or equal
# > Greater than
# != not equal |
fe1d61e28865415d529345742478c2340470f824 | PraiseTheDotNet/Python | /lab5/task2.py | 478 | 3.703125 | 4 | import numpy as np
if __name__ == '__main__':
n = np.array([0])
max_index = -1
for x in range(len(n)):
if n[x] == 0 and x + 1 < len(n):
if max_index == -1:
max_index = x + 1
else:
if n[max_index] < n[x + 1]:
max_index = x + 1
print('Максимальный элемент находится в индексе:', max_index)
if max_index != -1:
print(n[max_index]) |
b4b8a1cd3160372d759b43922b3ba9c40878d09c | jonfisik/ScriptsPython | /Scripts10/testLista2.py | 1,454 | 3.96875 | 4 | print('--'*30)
nomeIdade = list()
nomeIdade.append('Jonatan')
nomeIdade.append(39)
galera = list()
galera.append(nomeIdade[:])
nomeIdade[0] = 'Amanda'
nomeIdade[1] = 36
galera.append(nomeIdade[:])
print(galera)
print('--'*30)
#-----------------------------------------------------
galera2 = [['Jonatan',17],['Gabriel',16],['Isaac',10]]
print(f'1 - {galera2}')
print(f'2 - {galera2[0][0]}')
print(f'3 - {galera2[1][0]}')
print(f'4 - {galera2[2][1]}')
print(f'5 - {galera2[2]}')
print('--'*30)
#-----------------------------------------------------
for pessoa in galera2:
print(pessoa)
print('--'*30)
for pessoa in galera2:
print(pessoa[0])
print('--'*30)
for pessoa in galera:
print(f'{pessoa[0]} tem {pessoa[1]} anos de idade.')
for pessoa in galera:
print(f'{pessoa[0]} tem {pessoa[1]} anos de idade.')
print('--'*30)
#-----------------------------------------------------
# receber elementos na lista
galera3 = list()
dado = list()
for c in range(0,3):
dado.append(str(input('Nome: ')))
dado.append(int(input('Idade: ')))
galera3.append(dado[:])
dado.clear() #apaga dados a cada volta(loop)
print(galera3)
totmaior = totmenor = 0
for pessoa in galera3:
if pessoa[1] >= 21:
print(f'{pessoa[0]} é maior de idade.')
totmaior += 1
else:
print(f'{pessoa[0]} é menor de idade.')
totmenor += 1
print(f'Temos {totmaior} maiores de idade e {totmenor} menores de idade.')
print('--'*30)
|
dca7a3c967574e8e6931bfb2372665a1eb036064 | Eustaceyi/Leetcode | /289. Game of Life.py | 1,168 | 3.65625 | 4 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
self.row = len(board)
self.col = len(board[0])
pos = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]
for i in range(self.row):
for j in range(self.col):
count = 0
for x,y in pos:
count += self.checkaround(board, i+x, j+y)
if board[i][j] == 0:
if count == 3:
board[i][j] = 2
else:
if count < 2 or count > 3:
board[i][j] = -1
for i in range(self.row):
for j in range(self.col):
if board[i][j] > 0:
board[i][j] = 1
else:
board[i][j] = 0
def checkaround(self, board, i, j):
if i < 0 or i >= self.row or j < 0 or j >= self.col:
return 0
elif board[i][j] == 1 or board[i][j] == -1:
return 1
else:
return 0 |
f4b1266ce69343825ce2dc449a70ddac3ef7df21 | SnipGhost/Python-Lab2 | /lab_python_oop/Circle.py | 956 | 3.546875 | 4 | from lab_python_oop.Figure import Figure
from lab_python_oop.Color import Color
class Circle(Figure):
# Add math package to requirements only for PI value? No, thanks!
PI_VALUE = 3.14159265359
def __init__(self, radius, color):
self.__radius = 0
self.__area = 0
self.radius = radius
self.radius_set(radius)
self.color = Color(color)
super(Circle, self).__init__('Круг')
@property
def area(self):
return self.__area
def radius_set(self, r):
self.__radius = r
self.__area = self.PI_VALUE * r * r
def radius_get(self):
return self.__radius
def radius_del(self):
del self.__radius
def __repr__(self):
tpl = '{}:\n\tЦвет: {}\n\tРадиус: {}\n\tПлощадь: {}\n'
return tpl.format(self.name, self.color, self.radius, self.area)
radius = property(radius_get, radius_set, radius_del, 'Radius')
|
20e0b5d9fbcf575f3406556b88068b98ef821c44 | sseering/AdventOfCode | /2017/aoc16.py | 4,060 | 4.09375 | 4 | #!/usr/bin/env python3
# -- Day 16: Permutation Promenade ---
#
# You come upon a very unusual sight; a group of programs here appear to be dancing.
#
# There are sixteen programs in total, named a through p. They start by standing in a line: a stands in position 0, b stands in position 1, and so on until p, which stands in position 15.
#
# The programs' dance consists of a sequence of dance moves:
#
# Spin, written sX, makes X programs move from the end to the front, but maintain their order otherwise. (For example, s3 on abcde produces cdeab).
# Exchange, written xA/B, makes the programs at positions A and B swap places.
# Partner, written pA/B, makes the programs named A and B swap places.
#
# For example, with only five programs standing in a line (abcde), they could do the following dance:
#
# s1, a spin of size 1: eabcd.
# x3/4, swapping the last two programs: eabdc.
# pe/b, swapping programs e and b: baedc.
#
# After finishing their dance, the programs end up in order baedc.
#
# You watch the dance for a while and record their dance moves (your puzzle input). In what order are the programs standing after their dance?
#
# --- Part Two ---
#
# Now that you're starting to get a feel for the dance moves, you turn your attention to the dance as a whole.
#
# Keeping the positions they ended up in from their previous dance, the programs perform it again and again: including the first dance, a total of one billion (1000000000) times.
#
# In the example above, their second dance would begin with the order baedc, and use the same dance moves:
#
# s1, a spin of size 1: cbaed.
# x3/4, swapping the last two programs: cbade.
# pe/b, swapping programs e and b: ceadb.
#
# In what order are the programs standing after their billion dances?
import fileinput
from typing import List, Optional
def part1(startline: Optional[str] = None) -> None:
if startline is None:
danceline = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
else:
danceline = [_ for _ in startline]
def do_op(op_str: str):
nonlocal danceline
if op_str[0] == 's':
i = int(op_str[1:]) * -1
danceline = danceline[i:] + danceline[:i]
elif op_str[0] == 'x':
(a_str, b_str) = op_str[1:].split('/')
a = int(a_str)
b = int(b_str)
(danceline[a], danceline[b]) = (danceline[b], danceline[a])
elif op_str[0] == 'p':
(a_str, b_str) = op_str[1:].split('/')
a = danceline.index(a_str)
b = danceline.index(b_str)
(danceline[a], danceline[b]) = (danceline[b], danceline[a])
else:
raise Exception
for line in fileinput.input('input16.txt'):
for op in line.split(','):
do_op(op)
return ''.join(danceline)
def part2() -> None:
idx_helpers = "kbednhopmfcjilag"
danceline = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
map_indices = [danceline.index(_) for _ in idx_helpers]
for _ in range(1000000000):
newline = list([danceline[i] for i in map_indices])
danceline = newline
print(''.join(danceline))
def better_part_2() -> None:
danceline_begin = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
danceline_end = ['k', 'b', 'e', 'd', 'n', 'h', 'o', 'p', 'm', 'f', 'c', 'j', 'i', 'l', 'a', 'g']
mapping = [danceline_begin.index(_) for _ in danceline_end]
danceline = danceline_begin
def do_map():
nonlocal danceline
newline = [danceline[i] for i in mapping]
danceline = newline
print(''.join(danceline))
do_map()
print(''.join(danceline))
do_map()
print(''.join(danceline))
def main() -> None:
print("1")
print(part1())
print("2")
print(part1(part1()))
print("3")
print(part1(part1(part1())))
print('---')
better_part_2()
print('done')
if __name__ == '__main__':
main()
|
557fb0c440d7835e524bc35562b2bc276539524f | JakobJBauer/CompMath2021 | /UE7/Aufgabe6.py | 2,191 | 3.765625 | 4 | # copy from Task 2
from typing import Tuple
class Complex:
"""This class allows to add, multiply and divide two complex numbers"""
def __init__(self, z1: Tuple[float, float], z2: Tuple[float, float]) -> None:
self.z1 = z1
self.z2 = z2
def add(self) -> Tuple[float, float]:
return self.z1[0] + self.z2[0], self.z1[1] + self.z2[1]
def multiply(self) -> Tuple[float, float]:
erg = complex(self.z1[0], self.z1[1]) * complex(self.z2[0], self.z2[1])
return erg.real, erg.imag
def divide(self) -> Tuple[float, float]:
erg = complex(self.z1[0], self.z1[1]) / complex(self.z2[0], self.z2[1])
return erg.real, erg.imag
# end copy
# copy from Task 3
class Vector:
"""This class contains two basic Vectorfunctions, which can be statically accessed
Function add takes two Vectors and returns the sum of them
Function scalar takes a float number and a Vector and multiplies every Dimension of the Vector with the scalar. The
product is returned"""
@staticmethod
def add(z1: list, z2: list):
if len(z1) != len(z2):
raise ValueError("z1 and z2 need to have the same dimension")
return [z1[i] + z2[i] for i in range(len(z1))]
@staticmethod
def scalar(a: float, z1: list):
return [a * z_dim for z_dim in z1]
class VectorPlus(Vector): # BillaPlus
"""This class contains two extendes Vectorfunctions, which can be statically accessed.
Function vector_prod takes two Vectors and returns the crossproduct of them
Function tensor takes two Vectors and returns the tensor product of them"""
@staticmethod
def vector_prod(z1: list, z2: list):
if len(z1) != len(z2):
raise ValueError("z1 and z2 need to have the same dimension")
return [z1[(i + 1) % len(z1)] * z2[(i + 2) % len(z2)] - z2[(i + 1) % len(z2)] * z1[(i + 2) % len(z1)] for i in range(len(z1))]
@staticmethod
def tensor(z1: list, z2: list):
return [[z1_el * z2_el for z2_el in z2] for z1_el in z1]
# end copy
print('Problem A')
print('\n\n\n', Complex.__doc__)
print('\n\n\n', Vector.__doc__)
print('\n\n\n', VectorPlus.__doc__)
|
25bacea962d9ae6a05e2e336a0729f598f20c4b8 | StudyGroupPKU/TESTs | /junho/python/chapter01/n2_format.py | 350 | 3.625 | 4 | principal = 1000
rate = 0.05
numyears = 5
year = 1
'''
while year <= numyears:
principal = principal * (1 + rate)
print(year, principal)
year += 1
'''
while year <= numyears:
principal = principal * (1 + rate)
# print(format(year,"3d"),format(principal,"0.2f"))
print("{0:3d} {1:0.2f}".format(year,principal))
year += 1
|
b82ee4b347952f2f5c55aa70025e7fe1639008cb | u3aftab/Project-Euler | /Euler48.py | 124 | 3.5 | 4 | ## Find the last ten digits of 1**1 + 2**2 + ... + 1000**1000.
a=0
for i in xrange(1,1001):
a+=i**i
print str(a)[-10:]
|
9a989933ebfbf402eae8deb7b43087b465f11c09 | horacet0728/control_system_examples | /vexvr/proportional_derivative_algorithm_solution_for_template_1.py | 3,394 | 3.5625 | 4 | from math import *
from random import randint
def proportionalDerivativeControlX(setpoint,duration):
maxSpeed = 250
k = 3
kD = 1.5
oldError = 0
# reset the timer
brain.timer_reset()
# loop while the timer is less than the duration input of the function.
while(brain.timer_time(SECONDS)<duration):
currentXLocation = location.position(X,MM)
error = setpoint - currentXLocation
changeError = error - oldError
output = k*error - kD*changeError
oldError = error
# Ensure the output is not more than the maximum speed
if(output > maxSpeed):
output = maxSpeed
elif(output < -maxSpeed):
output = -maxSpeed
brain.print(output)
brain.new_line()
drivetrain.drive(FORWARD)
drivetrain.set_drive_velocity(output,PERCENT)
# Set the direction of movement
#VEXCode VR requires that we have a small pause in any loop we run.
wait(1,MSEC)
drivetrain.stop()
def proportionalDerivativeControlY(setpoint,duration):
maxSpeed = 250
k = 3
kD = 1.5
oldError = 0
# reset the timer
brain.timer_reset()
# loop while the timer is less than the duration input of the function.
while(brain.timer_time(SECONDS)<duration):
currentYLocation = location.position(Y,MM)
error = setpoint - currentYLocation
changeError = error - oldError
output = k*error - kD*changeError
oldError = error
# Ensure the output is not more than the maximum speed
if(output > maxSpeed):
output = maxSpeed
elif(output < -maxSpeed):
output = -maxSpeed
brain.print(output)
brain.new_line()
drivetrain.drive(FORWARD)
drivetrain.set_drive_velocity(output,PERCENT)
# Set the direction of movement
#VEXCode VR requires that we have a small pause in any loop we run.
wait(1,MSEC)
drivetrain.stop()
def proportionalDerivativeControlDiagonal(setpoint,duration):
maxSpeed = 250
k = 3
kD = 1.5
oldError = 0
# reset the timer
brain.timer_reset()
# loop while the timer is less than the duration input of the function.
while(brain.timer_time(SECONDS)<duration):
currentXLocation = location.position(X,MM)
error = setpoint - currentXLocation
changeError = error - oldError
output = k*error - kD*changeError
oldError = error
# Ensure the output is not more than the maximum speed
if(output > maxSpeed):
output = maxSpeed
elif(output < -maxSpeed):
output = -maxSpeed
brain.print(output)
brain.new_line()
drivetrain.drive(FORWARD)
drivetrain.set_drive_velocity(output,PERCENT)
# Set the direction of movement
#VEXCode VR requires that we have a small pause in any loop we run.
wait(1,MSEC)
drivetrain.stop()
# Add project code in "main"
def main():
pen.move(DOWN)
drivetrain.turn_to_heading(90,DEGREES,wait=True)
proportionalDerivativeControlX(0,3)
drivetrain.turn_to_heading(0,DEGREES,wait=True)
proportionalDerivativeControlY(0,3)
drivetrain.turn_to_heading(45,DEGREES,wait=True)
proportionalDerivativeControlDiagonal(400,3)
# VR threads — Do not delete
vr_thread(main())
|
41df82fe7cc8340d0f8896504ec6bfe98afdea00 | dikoko/practice | /2 Sequences/2-47_calculator.py | 1,415 | 4.09375 | 4 | # You have a string of numbers, i.e. 123.
# You can insert a + or - sign in front of every number, or you can leave it empty.
# Find all of the different possibilities, make the calculation and return the sum.
# e.g.
# +1+2+3 = 6
# +12+3 = 15
# +123 = 123
# +1+23 = 24
# ...
# -1-2-3 = 6
# ...
# Return the sum of all the results.
def calculator(N):
nlist = str(N)
len_n = len(nlist)
# 1,2,3 / 1,23 / 12,3 / 123
def _terms(i):
if i == len_n:
return [[]]
out_list = []
for k in range(i, len_n):
picked = nlist[i:k+1]
picked_results = _terms(k+1)
plus_results = []
for item in picked_results:
new_item = item[:] # bacause of side effects!
new_item.append('+'+picked)
plus_results.append(new_item)
minus_results = []
for item in picked_results:
new_item = item[:]
new_item.append('-'+picked)
minus_results.append(new_item)
out_list += plus_results
out_list += minus_results
return out_list
results = _terms(0)
results = [list(reversed(item)) for item in results]
results = [sum(map(int, item)) for item in results]
return results
if __name__ == '__main__':
N = 123
print(calculator(N))
|
919494c7dc4506a65d7b8c6fda245554993474a3 | algorithm003/algorithm | /Week_03/id_27/LeetCode_547_27.py | 939 | 3.515625 | 4 | class Solution:
def findCircleNum(self, A):
N = len(A)
seen = set()
def dfs(node):
for nei, adj in enumerate(A[node]):
if adj and nei not in seen:
seen.add(nei)
dfs(nei)
ans = 0
for i in range(N):
if i not in seen:
dfs(i)
ans += 1
return ans
def findCircleNum2(self, M):
def dfs(M, i, visited):
visited[i] = True
for j in range(len(M[i])):
if M[i][j] == 1 and not visited[j]:
dfs(M, j, visited)
visited = [False] * len(M)
circle = 0
for i in range(len(M)):
if not visited[i]:
dfs(M, i, visited)
circle += 1
return circle
if __name__ == "__main__":
a = Solution()
print(a.findCircleNum([[1,1,0],[1,1,0],[0,0,1]])) |
74433e017e582f18061c30ad762bdfbb3a04611b | EmilyOng/cp2019 | /testing/unit_testing/test_age.py | 531 | 3.59375 | 4 | import unittest
from age_validation import validate_age
class AgeTest (unittest.TestCase):
def test_length (self):
self.assertEqual(validate_age(""), "Expected an input.")
def test_data_type (self):
self.assertEqual(validate_age("hlelo"), "Expected a number.")
def test_range (self):
self.assertEqual(validate_age(100), "Expected an age from 1 to 90.")
def test_valid (self):
self.assertEqual(validate_age(9), True)
if __name__ == "__main__":
unittest.main(exit=False)
|
e4af0ef75e5a02532ee2442fca7f6c6e3947e167 | tunealog/python-study | /ex/ex_030_Quiz_Class.py | 965 | 4.21875 | 4 | # Basic of Python
# Title : Quiz(Class)
# Date : 2020-07-04
# Creator : tunealog
# Quiz) Create the real estate program
# Example (Result):
# Total : 3
# Korea Apartment Buy 10M 2010Y
# Japan Office Rental 1M 2007Y
# America Gym Monthly 100/10 2000Y
class House:
def __init__(self, location, house_type, deal_type, price, completion_year):
self.location = location
self.house_type = house_type
self.deal_type = deal_type
self.price = price
self.completion_year = completion_year
def show_detail(self):
print(
f"{self.location} {self.house_type} {self.deal_type} {self.price} {self.completion_year}")
re = []
re0 = House("Korea", "Apartment", "Buy", "10M", "2010Y")
re1 = House("Japan", "Office", "Rental", "1M", "2007Y")
re2 = House("America", "Gym", "Monthly", "100/10", "2000Y")
re.append(re0)
re.append(re1)
re.append(re2)
print(f"Total : {len(re)}")
for i in re:
i.show_detail()
|
bab553b86398c1a95198ef2179a5a82fc04ce324 | AnnaCilona/PythonExercises | /EjHoja1/3.py | 456 | 4.40625 | 4 | '''Ejercicio 3. Escriba un programa que lea dos números desde teclado
y si el primero es mayor que el segundo intercambie sus valores
y los muestre ordenados por pantalla
(después de haber intercambiado el valor de las variables correspondientes).'''
num1=int(input("Escribe un número"))
num2=int(input("Escribe un número"))
if num1>num2:
num1,num2=num2,num1
orden=[num1,num2]
print(sorted(orden))
else:
print(num1, "es menor que", num2)
|
0f31826fb791c1da3adc2bbfcbbfc3d6688fd6c0 | dicksoy/python-learn | /pythonProject/pythonLearn/PythonFunctionTest.py | 2,057 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# 位置参数
def power(x, n) :
s = 1
while n > 0 :
n = n - 1
s = s * x
return s
print(power(5, 2))
print(power(15, 3))
# 默认参数
def power2(x, n=2) :
s = 1
while n > 0 :
n = n - 1
s = s * x
return s
print(power2(5))
print(power2(5, 3))
# 这样会出现错误,默认参数必须指向不变对象
def add_end(L=[]) :
L.append('end')
return L
print(add_end())
print(add_end())
print(add_end())
# 修改后的add_end
def add_end2(L=None) :
if L is None :
L = []
L.append('end')
return L;
print(add_end2())
print(add_end2())
print(add_end2())
# 可变参数
def calc(number) :
sum = 0
for n in number :
sum = sum + n * n
return sum
print(calc([1, 2, 3]))
print(calc((1, 3, 5, 7)))
def calc2(*numbers) :
sum = 0
for n in numbers :
sum = sum + n * n
return sum
print(calc2(1, 2, 3))
print(calc2(1, 3, 5, 7))
nums = [1, 2, 3]
print(calc2(*nums))
# 关键字参数
def person(name, age, **kw) :
print("name :", name, " age :", age, " other :", kw)
person('Michael', 30)
person('Bob', 35, city="BeiJing", address="东城区")
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, city=extra['city'], job=extra['job'])
# 简化写法
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, **extra)
# 命名关键字参数
def person2(name, age, *, city="北京", job) :
print(name, age, city, job)
# 传入参数名,调用将报错
person2("diu", 25, city="beijing", job="colck")
person2("diu", 25, job="colck")
# 参数组合
def f1(a, b, c=0, *args, **kw) :
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw) :
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
f1(1, 2)
f1(1, 2, 3)
f1(1, 2, 3, 'a', 'b')
f1(1, 2, 3, 'a', 'b', x=99)
f2(1, 2, d=99, ext=None)
args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args, **kw)
args = (1, 2, 3)
kw = {'d': 88, 'x': '#'}
f2(*args, **kw)
|
82e9e29b4f74fc9c36fce86693bc3bd065e9628e | pjlorenz/myappsample | /wordloop.py | 1,260 | 4.0625 | 4 | def word_loop():
# 0 to 9 . how many in the list 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
#
word = "absolutely"
for i in range(len(word)):
# we don't want to hardcode 9... we want it to work with any string word
# len(word) is 10 <-- that's a clue
print(word[len(word) - 1 - i])
# i what character do you want to print? 9 - i
# 0 y 9 9
# 1 l 8 8
# 2 e 7
#...
# 9
index = 1
while index <= len(word):
letter = word[-index]
print(letter)
index = index + 1
index = 0
while index < len(word):
newIndex = len(word) - index - 1
print(word[newIndex])
index += 1
# index -index word[-index]
# 1 -1 y
# 2 -2 l
# ...
# 9 -9 b
# 10 -10 a
# index len(word) - index - 1
# 0 9
# 1 8
# 2 7
# ...
# 9 0
# 10 stop
# someList = [1, 2, 3, 4]
# someList[-2]
def func2():
word = "fabulous"
for i in range(len(word) - 1, -1, -1):
print(word[i])
func2() |
ae95cb9f7fa91ae2f2eff0e05358a8d1f5caf0cc | akozubek/python-exercises | /advent-of-code/2017/4-passphrase.py | 1,240 | 3.53125 | 4 | import unittest
def isvalid(passphrase):
words = passphrase.split()
return len(set(words)) == len(words)
def isvalid2(passphrase):
words = passphrase.split()
canonic_words = [''.join(sorted(w)) for w in words]
return len(set(canonic_words)) == len(canonic_words)
def countvalid(filename, valid_function):
with open(filename) as file:
return sum([1 for line in file if valid_function(line) ])
class Test(unittest.TestCase):
def test1(self):
self.assertEqual(isvalid('aa bb cc dd ee'), True)
def test2(self):
self.assertEqual(isvalid('aa bb cc dd aa'), False)
def test3(self):
self.assertEqual(isvalid('aa bb cc dd aaa'), True)
def test21(self):
self.assertEqual(isvalid2('abcde fghij'), True)
def test22(self):
self.assertEqual(isvalid2('abcde xyz ecdab'), False)
def test23(self):
self.assertEqual(isvalid2('a ab abc abd abf abj'), True)
def test24(self):
self.assertEqual(isvalid2('iiii oiii ooii oooi'), True)
def test25(self):
self.assertEqual(isvalid2('oiii ioii iioi iiio'), False)
print('Result:', countvalid('day4.txt', isvalid))
print('Result:', countvalid('day4.txt', isvalid2))
unittest.main()
|
574db40351dff33a3b4d9139d868635a84953557 | arslanislam845/DevNation-Python-assignments | /6.May28/q2.py | 662 | 4.125 | 4 | def values(no):
students=[]
for i in range(data):
print()
print("Enter Student",i+1,"name : ")
names=input()
print("Enter Student",i+1,"age : ")
age=int(input())
print("Enter Student",i+1,"phone no : ")
phone_no=int(input())
print("Enter Student",i+1,"address : ")
address=input()
dict = {i+1:{"name":names,"age": age,"phone no":phone_no,"address": address}}
students.insert(i,dict)
return students
data=int(input("enter the number of students you wanted to enter data : "))
List_Of_All_Students=values(data)
print("List Of All Students: ",List_Of_All_Students)
|
065d13f0c32aaabcedd286d10c2d7521b23594ed | ZiHaoYa/1808 | /06day/09-异常.py | 521 | 3.515625 | 4 | #coding=utf-8
try:
#print(b)
#open("1.txt","r")
1/0
#print("老王")
except (NameError,FileNotFoundError):#指定异常捕获
print("捕获指定异常")
except Exception as ret:#捕获任何异常 ret具体异常信息
print("捕获任何异常")
print(ret)
else:
print("没有任何异常走的逻辑")
finally:
print("不管有没有异常都会走")
'''
不是所有的代码都需要加上异常
可能会出现一次才加上捕获
'''
number = int(input("请选择功能"))
|
15945ecad76a96ffa9dcebbb7b55c31d419da394 | mbharanya/Advent-of-code-2020 | /day5/day5.py | 1,445 | 3.5625 | 4 | filename = "/home/xmbomb/dev/aoc2020/day5/input.txt"
def get_lower_half(list):
length = len(list)
return list[0:int(length / 2)]
def get_upper_half(list):
length = len(list)
return list[int(length / 2):length]
def get_row_col(line):
row_numbers = list(range(0, 127 + 1))
col_numbers = list(range(0, 7 + 1))
for char in line:
if char == 'F':
row_numbers = get_lower_half(row_numbers)
elif char == 'B':
row_numbers = get_upper_half(row_numbers)
elif char == 'L':
col_numbers = get_lower_half(col_numbers)
elif char == 'R':
col_numbers = get_upper_half(col_numbers)
# print(f'Keeping row numbers {row_numbers[0]} .. {row_numbers[len(row_numbers) - 1]}')
# print(f'Keeping col numbers {col_numbers[0]} .. {col_numbers[len(col_numbers) - 1]}')
return (row_numbers[0], col_numbers[0])
def calc(row, col):
return row * 8 + col
def test(line):
(row, col) = get_row_col(line)
print(calc(row, col))
def part2(l):
l.sort()
full_range = list(range(l[0], l[len(l)-1] + 1))
return [x for x in full_range if x not in l]
test("FBFBBFFRLR")
test("BFFFBBFRRR")
test("BBFFBBFRLL")
with open(filename, 'r') as file:
lines = file.read().strip().split('\n')
results = [calc(*get_row_col(line)) for line in lines]
print(f'max is {max(results)}')
print(f'my seat is {part2(results)[0]}')
|
3a7362a62649e7553d9302d4fa415baf8d257190 | vadalikasi/python-exercises | /courseware-gen/labs/py3/gen_squares.py | 355 | 3.953125 | 4 | def res_generators(max_value):
value = 0
while value < max_value:
yield value * value
value += 1
def squares(max_value):
res = []
for i in range(max_value):
res.append(i ** 2)
return res
if __name__ == '__main__':
gen = res_generators(10)
for res in gen:
print("Square is : {}".format(res))
|
8821d761cffc73739155aff5da7bbc96937d9eac | tianyolanda/leetcoding | /leet23-2.py | 431 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
vals = []
for i in lists:
while i:
vals += [i.val]
i = i.next
vals.sort()
return vals |
a401166f223c115b76388a9ef012a6da04fb0673 | ygtfrdes/Program | /Empirical/python/Python-Machine-Learning-Cookbook/Chapter12/pie_chart.py | 729 | 3.78125 | 4 | #!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
# Labels and corresponding values in counter clockwise direction
data = {'Apple' : 26,
'Mango' : 17,
'Pineapple' : 21,
'Banana' : 29,
'Banana2' : 79,
'Strawberry': 11}
# List of corresponding colors
colors = ['orange', 'lightgreen', 'lightblue', 'gold', 'cyan', 'red']
# Needed if we want to highlight a section
explode = (0, 0, 0, 0, 0, 0)
# Plot the pie chart
plt.pie(data.values(), explode=explode, labels=data.keys(), colors=colors, autopct='%1.1f%%', shadow=False, startangle=90)
# Aspect ratio of the pie chart, 'equal' indicates tht we want it to be a circle
plt.axis('equal')
plt.show()
|
8b4da12b88cd47e870130cfd40df71cf3bce28c7 | wickyou23/python_learning | /python3_learning/main.py | 617 | 4.09375 | 4 | #Learning python
#####Hello word
# print("hello word")
#####Assigning Values to Variables
# x = 100
# pi = 3.14
# empname = "python is great"
# a = b = c = 100
# print(x)
# print(pi)
# print(empname)
# print(a, b, c)
#####Simultaneous Assignment
# d, e = 101, 102
# print(d, e)
# e, d = d, e #swap using simultaneous assignment
# print(d, e)
#####Receiving input from Console
# name = input("Enter your name: ")
# print("Hello:", name)
# age = int(input("Enter your age: "))
# print("Age: ", age)
# print(type(age))
#####Importing modules
# import math, os
# print(math.pi, math.e)
# print(os.getcwd())
|
ad2cb20b2e7a95bcccc82cc6eff40d2479015a75 | littlelove2013/lab_python_workspace | /general/webbigdata/pagerank/graph.py | 691 | 3.84375 | 4 | # -- coding: utf-8 --
#
# PageRank工程的Graph创建程序
#
from collections import deque
class Graph():
def __init__(self):
self.node_n={}
def add_nodes(self,nodelist):
for i in nodelist:
self.add_node(i)
#对每一个节点,建一个链表(数组),链表(数组)保存的是其指向的节点
def add_node(self,node):
if not node in self.nodes():
self.node_n[node]=[]
def add_edge(self,edge):
u,v=edge
if (v not in self.node_n[u]):# and (u not in self.node_n[v]):#为什么要求u not in v呢?
self.node_n[u].append(v)#u->v
#if u !=v:
# self.node_n[v].append(u)
#获取dict的关键字集合,即节点name
def nodes(self):
return self.node_n.keys()
|
af42a48c0eb66dfcf3137f714f5fe802c435a03a | raiyanshadow/BasicPart1-py | /ex50.py | 114 | 4 | 4 | # Write a Python program to print without newline or space.
print("Hello,", sep = "", end="")
print(" world") |
821234c899f01cf6ba92174c4879c600fcd4bb5b | NejcPivec/FizzBuzz | /fizzBuzz.py | 375 | 3.765625 | 4 |
# narediš zanko čez 100 elementov 1- 100
for x in range(1, 101):
if x % 3 == 0 and x % 5 == 0: # najprej morš definerat ta pogoj, ker python začčne iz vrha in ga drugače spregleda
print("FizzBuzz")
elif x % 5 == 0:
print("Fuzz")
elif x % 3 == 0:
print("Fizz")
else:
print (x) # če ni 3, 5 ali 15 samo zapiše število |
f9bd1a6072637651da4fb3436a6eb56160d0b84c | AlexTargon1/esercizi-informatica- | /03.py | 620 | 3.765625 | 4 | tappa1 = input("inserisci distanza percorsa in km = ")
tappa2 = input("inserisci distanza percorsa in km = ")
tappa3 = input("inserisci distanza percorsa in km = ")
tappa1miglia = int(tappa1)/1.609
tappa1iarde = int(tappa1miglia)*1760
print ("tappa 1 in miglia=",tappa1miglia)
print ("tappa 1 in iarde=",tappa1iarde)
tappa2miglia = int(tappa2)/1.609
tappa2iarde = int(tappa2miglia)*1760
print ("tappa 2 in miglia=",tappa2miglia)
print ("tappa 2 in iarde=",tappa2iarde)
tappa3miglia = int(tappa3)/1.609
tappa3iarde = int(tappa3miglia)*1760
print ("tappa 3 in miglia=",tappa3miglia)
print ("tappa 3 in iarde=",tappa3iarde) |
ed8f2949054ff42bdc689bd3b481e17a2731e6a8 | VincentGFL/python_challenge | /programs/timestable.py | 187 | 3.828125 | 4 | number1 = 1
while number1 <= 10:
number2 = 0
while number2 <= 10:
number2 += 1
print(number1 * number2, end='\t')
print('')
number1 += 1
|
49c82f21838638e507a3a8f7da590b30788a314f | wondershow/CodingTraining | /Python/LC739_DailyTemperatures.py | 598 | 3.703125 | 4 | class Solution:
"""
Use a monotonic stack to keep all increasing temps indexes.
Iterate from last to first
REMEMBER to reverse the res
"""
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack, N, res = [], len(temperatures), []
for i in range(N - 1, -1, -1):
while stack and temperatures[stack[-1]] <= temperatures[i]:
stack.pop()
if stack:
res.append(stack[-1] - i)
else:
res.append(0)
stack.append(i)
return res[::-1]
|
6159ff567e63acdc5199e416c7bde758c07aee12 | MatthewRoberts1/Big-code | /Term 1 Week 4 Challenge 1.py | 426 | 3.71875 | 4 | print("Hello, pleace input what you want to do: R for Read or W for Write")
word = input("Input here: ")
if word == "R":
large = open("D:\Computing stuff\Challenges\BigBoi212.txt", "r")
print(large.read())
large.close()
elif word == "W":
newWords = input("Input the new text: ")
small = open("D:\Computing stuff\Challenges\BigBoi212.txt", "wt")
small.write(newWords)
small.close()
|
079b576bb2429b0ac136ea2772d7ab95b648ef6f | Lei-Tin/OnlineCourses | /edX/MIT 6.00.1x Materials/pset2/Paying Debt off in a Year 1.py | 690 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 5 15:03:11 2021
@author: ray-h
"""
# Givens
# Outstanding balance on the card
balance = 484
# Annual interest rate as decimal
annualInterestRate = 0.2
# Minimum monthly payment as decimal
monthlyPaymentRate = 0.04
# To be solved
monthlyInterestRate = annualInterestRate / 12
months = 12
while months > 0:
minimumMonthlyPayment = balance * monthlyPaymentRate
monthlyUnpaidBalance = balance - minimumMonthlyPayment
balanceUpdated = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance)
balance = balanceUpdated
months -= 1
print(round(balance, 2)) |
faa47569a0feccf599c3f8ea7cc5e54bf02cff11 | Shubhampy-code/Let_us_C_book_solution_5th-Edition | /Chapter 5-Functions & Pointers/let_us_c_5_(F_A).py | 476 | 4.125 | 4 | """Write a function which receives a float and an int from main( ),
finds the product of these two and returns the product which is printed through main( )."""
def Product(FirstNumber,SecNumber):
product = FirstNumber * SecNumber
return product
firstNum,secNum = input("Enter the first and second number : ").split()
firstNum = float(firstNum)
secNum = float(secNum)
multiply = Product(firstNum,secNum)
print("Product of first and second number : "+ str(multiply)) |
87af6670ec80ac78bb842b3fec2dc767cdf58446 | aaronfox/CECS-622-Simulation-and-Modeling | /Homework 03/critical_path_simulation.py | 5,745 | 3.703125 | 4 | # Aaron Fox
# CECS 622-01
# Dr. Elmaghraby
# Assignment 3 Problem 4
import random # for uniform random distributions of length of process between nodes
# Node class is used to contain all info abotu the nodes and their connections and connection lengths
class Node:
def __init__(self, name):
self.node_connections = []
self.name = name
print("Creating Node...")
# For printing purposes
def __repr__(self):
return self.name
def __str__(self):
return str(self.name + ". Connections: " + str(self.node_connections))
def add_connection(self, connecting_node, length):
self.node_connections.append([connecting_node, length])
def get_connecting_nodes(self):
return self.node_connections
def get_connection_length(self, other_node):
for node, length in self.node_connections:
if node == other_node:
return length
# list_results stores all connections globally for use in main function
list_results = []
# analyze_performance recursively iterates through every node connection
# and attaches every completed path to global variable list_results
def analyze_performance(start_node, end_node, curr_list):
if start_node == end_node:
curr_list.append(start_node)
list_results.append(curr_list)
return
for node, node_length in start_node.get_connecting_nodes():
# Ensure duplicates aren't added to list
if start_node not in curr_list:
curr_list.append(start_node)
copy_list = curr_list.copy()
analyze_performance(node, end_node, copy_list)
# get_length_of_connections returns the length of all the connections of the path
# INPUT: node_list (list): list of all nodes and their connections, e.g. [Node 1, Node 2, Node 3, Node 4, Node 7]
# OUTPUT: length_sum (float): float sum of all the lengths
def get_length_of_connections(node_list):
length_sum = 0
for i in range(len(node_list) - 1):
length = node_list[i].get_connection_length(node_list[i + 1])
length_sum = length_sum + length
# print(node_list)
return length_sum
if __name__ == "__main__":
print("Running critical path simulation...")
node_1 = Node("Node 1")
node_2 = Node("Node 2")
node_3 = Node("Node 3")
node_4 = Node("Node 4")
node_5 = Node("Node 5")
node_6 = Node("Node 6")
node_7 = Node("Node 7")
# Add respective deterministic/uniformly distributed connections per prompt
## Node 1 ##
node_1.add_connection(node_2, random.uniform(4, 6)) # (1, 2): U (4,6)
node_1.add_connection(node_5, 6) # (1, 5): 6
## Node 2 ##
node_2.add_connection(node_3, 6) # (2, 3): 6
node_2.add_connection(node_4, random.uniform(6, 8)) # (2, 4): U (6,8)
## Node 3 ##
node_3.add_connection(node_4, random.uniform(4, 8)) # (3, 4): U (4,8)
## Node 4 ##
node_4.add_connection(node_7, 4) # (4, 7): 4
## Node 5 ##
node_5.add_connection(node_3, 8) # (5, 3): 8
node_5.add_connection(node_4, 11) # (5, 4): 11
node_5.add_connection(node_6, random.uniform(8, 10)) # (5, 6): U (8,10)
## Node 6 ##
node_6.add_connection(node_7, random.uniform(9, 10)) # (6, 7): U (9, 10)
# Run over each path to get average values for each path
path_12347_values = []
path_1247_values = []
path_15347_values = []
path_1547_values = []
path_1567_values = []
iterations_to_run = 5000
for i in range(iterations_to_run):
list_results = []
analyze_performance(start_node=node_1, end_node=node_7, curr_list=[])
max_value = 0
min_value = float('inf')
max_connection = []
min_connection = []
for connection_list in list_results:
length = get_length_of_connections(connection_list)
print(connection_list, end='')
print(": ", end=' ')
print(length)
# Assign length values to each path to get average values
if str(connection_list) == "[Node 1, Node 2, Node 3, Node 4, Node 7]":
path_12347_values.append(length)
elif str(connection_list) == "[Node 1, Node 2, Node 4, Node 7]":
path_1247_values.append(length)
elif str(connection_list) == "[Node 1, Node 5, Node 3, Node 4, Node 7]":
path_15347_values.append(length)
elif str(connection_list) == "[Node 1, Node 5, Node 4, Node 7]":
path_1547_values.append(length)
elif str(connection_list) == "[Node 1, Node 5, Node 6, Node 7]":
path_1567_values.append(length)
if max_value < length:
max_value = length
max_connection = connection_list
if min_value > length:
min_value = length
min_connection = connection_list
print("Max Value list: ", end='')
print(max_connection, end=', Length of ')
print(max_value, end='\n')
print("Min Value list: ", end='')
print(min_connection, end=', Length of ')
print(min_value, end='\n')
print("Finished iteration " + str(i + 1), end='\n\n')
print("Average values for each path over " + str(iterations_to_run) + " samples: ")
print("Average path_12347_values: " + str(sum(path_12347_values)/len(path_12347_values)))
print("Average path_1247_values: " + str(sum(path_1247_values)/len(path_1247_values)))
print("Average path_15347_values: " + str(sum(path_15347_values)/len(path_15347_values)))
print("Average path_1547_values: " + str(sum(path_1547_values)/len(path_1547_values)))
print("Average path_1567_values: " + str(sum(path_1567_values)/len(path_1567_values)))
|
732b79b79d35b4d9a26ab5c1228b9e3c1f9eac81 | hugo-valle/intro-python | /my_dictionaries.py | 1,791 | 4.1875 | 4 | """
Learn about dictionaries
"""
from pprint import pprint as pp
def main():
"""
Test function
:return:
"""
urls = {
"google": "www.google.com",
"yahoo": "www.yahoo.com",
"twitter": "www.twitter",
"wsu": "weber.edu"
}
print(urls, type(urls))
# Access by key: [key]
print(urls["wsu"])
# Build dict with dict() constructor
names_age = [('Alice', 32), ('Mario', 23), ('Hugo', 21)]
d = dict(names_age)
print(d)
# Another method
phonetic = dict(a='alpha', b='bravo', c='charlie', d='delta')
print(phonetic)
# make a copy
e = phonetic.copy()
print(e)
# Updating a dictionary: update() method
stocks = {'GOOG':891, 'AAPL':416, 'IBM':194}
print(stocks)
stocks.update({'GOOG':999, 'YHOO':2})
print(stocks)
# Iteration default is by key value
for key in stocks:
print("{k} => {v}".format(k=key, v=stocks[key]))
# Iterate by values
for val in stocks.values():
print("val = ", val)
# Iterate by both key and value with: items()
for items in stocks.items():
print(items)
for key, val in stocks.items():
print(key, val)
# test for membership via key
print('GOOG' in stocks)
print('WINDOWS' not in stocks)
# Deleting: del keyword
print(stocks)
del stocks['YHOO']
print(stocks)
# Mutability of dictionaries
isotopes = {
'H': [1, 2, 3],
'He': [3, 4],
'Li': [6, 7],
'Be': [7, 9, 10],
'B': [10, 11],
'C': [11, 12, 13, 14]
}
print("\n\n\n") # 3 empty lines
pp(isotopes)
isotopes['H'] += [4, 5, 6, 7]
pp(isotopes)
isotopes['N'] = [13, 14, 15]
pp(isotopes)
if __name__ == '__main__':
main()
exit(0) |
915f4f7c413609e99f4ed93f5db117997ccb5562 | BansiddhaBirajdar/python | /assignment05/ass5Q1.py | 583 | 4.125 | 4 | '''2.Write a program which accept number from user and display its factors in decreasing order.
Input : 12
Output : 6 4 3 2 1
Input : 13
Output : 1
Input : 10
Output : 5 2 1'''
def factDec(ino):
imult=1
print("Output::",end="")
if(ino<0):
ino=-ino
if(ino==0):
print("Enter a +ve number")
return
i=ino//2;
while(i>0):
if(ino%i==0):
print( i,end=" ")
i-=1
def main():
print("+++++++++++++FACTORS +++++++++++++++++")
ino=int(input("Enter the no::"))
factDec(ino)
if __name__=='__main__':
main() |
e8110ecb397330ddeb2d99100930118296923c5f | MLMatheus/banco | /gerente/telas/listar.py | 283 | 3.515625 | 4 | from gerente.telas import imprimir
def listar(dicionario, chave, numerada):
contador = 0
for l in dicionario:
if numerada:
print("{} - {}".format(contador, dicionario[l][chave]))
else:
print(dicionario[l][chave])
contador += 1 |
516c0d7475877db91aca34335516695f4a6c08ee | DevAbdullah7/Mine-Univaresity | /main.py | 816 | 3.625 | 4 | import methods
def main():
print('\n\t{} {}/{}/{}\n'.format(methods.time_now.strftime('%A'),
methods.time_now.day, methods.time_now.month, methods.time_now.year))
print('For Courses: 1')
print('For Requireds: 2')
print('For Reports: 3')
user = int(input('\n( choice ): \t ( To Exit prees 0 ): '))
try:
if user == 1:
methods.courses()
main()
elif user == 2:
methods.Requireds()
main()
elif user == 3:
methods.Reports()
elif user == 4:
methods.Subjects()
elif user == 0:
pass
else:
raise Exception('Error: Your choice is incorrect !')
except Exception as Error:
print(Error)
main()
main()
|
3ee0d95c4e729cb5833ecbfe572c17ccc39aa157 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2542/60635/260915.py | 242 | 3.53125 | 4 | src=eval(input())
num_set=set(src)
longest=0
for num in num_set:
curr = 0
if num-1 not in num_set:
curr+=1
while num+1 in num_set:
num=num+1
curr+=1
longest=max(longest,curr)
print(longest) |
08c09e9b95ef5e11305b918e273f42093a0e34f4 | MiroVatov/Python-SoftUni | /Python Advanced 2021/MULTIDIMESNIONAL_LISTS/Exercise 08.py | 3,888 | 3.671875 | 4 | def find_starting_position(field, size):
pos = []
for row in field:
for col in row:
if col == 's':
pos.append(field.index(row))
pos.append(row.index(col))
return pos
def valid_position(pos, size):
row, col = pos[0], pos[1]
if 0 <= row < size and 0 <= col < size:
return True
return False
n = int(input())
commands = [e for e in input().split()]
field = [[e for e in input().split()] for _ in range(n)]
starting_position = find_starting_position(field, n)
current_position = starting_position
coals_left = len([e for m in field for e in m if e == 'c'])
game_over = False
position = []
for i in range(len(commands)):
command = commands[i]
row = current_position[0]
col = current_position[1]
if command == 'up':
up_move = [-1, 0]
position = [row + up_move[0], col + up_move[1]]
if valid_position(position, n):
current_position = [row + up_move[0], col + up_move[1]]
row, col = current_position[0], current_position[1]
if field[row][col] == 'e':
print(f"Game over! ({row}, {col})")
game_over = True
break
elif field[row][col] == 'c':
field[row][col] = '*'
coals_left -= 1
if coals_left == 0:
game_over = True
print(f"You collected all coals! ({row}, {col})")
break
elif command == 'down':
down_move = [1, 0]
position = [row + down_move[0], col + down_move[1]]
if valid_position(position, n):
current_position = [row + down_move[0], col + down_move[1]]
row, col = current_position[0], current_position[1]
if field[row][col] == 'e':
print(f"Game over! ({row}, {col})")
game_over = True
break
elif field[row][col] == 'c':
field[row][col] = '*'
coals_left -= 1
if coals_left == 0:
print(f"You collected all coals! ({row}, {col})")
game_over = True
break
elif command == 'left':
left_move = [0, -1]
position = [row + left_move[0], col + left_move[1]]
if valid_position(position, n):
current_position = [row + left_move[0], col + left_move[1]]
row, col = current_position[0], current_position[1]
if field[row][col] == 'e':
print(f"Game over! ({row}, {col})")
game_over = True
break
elif field[row][col] == 'c':
field[row][col] = '*'
coals_left -= 1
if coals_left == 0:
print(f"You collected all coals! ({row}, {col})")
game_over = True
break
elif command == 'right':
right_move = [0, 1]
position = [row + right_move[0], col + right_move[1]]
if valid_position(position, n):
current_position = [row + right_move[0], col + right_move[1]]
row, col = current_position[0], current_position[1]
if field[row][col] == 'e':
print(f"Game over! ({row}, {col})")
game_over = True
break
elif field[row][col] == 'c':
field[row][col] = '*'
coals_left -= 1
if coals_left == 0:
print(f"You collected all coals! ({row}, {col})")
game_over = True
break
if not game_over:
print(f"{coals_left} coals left. ({current_position[0]}, {current_position[1]})") |
754e4cf87805acc755afe9ff9c895f1243f52c05 | YertAlan/Yert_Python | /MiscroProject/random_game.py | 1,544 | 3.9375 | 4 | #-*- coding:utf-8 -*-
#创建一个摇色子的游戏
import random
#生成一个色子的随机数
def ran_num():
list = [1,2,3,4,5,6]
n = random.choice(list)
return n
#将三个色子的随机数进行总和
def ran_sum():
s = 0
list = []
for i in range(3):
n = ran_num()
list.append(n)
s = sum(list)
print(list," = ",s)
return s
#判断摇色子后的输赢
def ran_win(c):
s = ran_sum()
if s >= 11:
if c == "Big":
return True
else:
return False
else:
if c == "Small":
return True
else:
return False
#获取选择,并根据选择和结果对比输赢
def choice():
choi = ["Big","Small","Stop"]
score = 1000
while True:
your_choice = str(input("Please input your choice: Big or Small or Stop\n"))
if your_choice not in choi:
print("Your choice is error")
else:
if your_choice == "Stop":
break
else:
n = ran_win(your_choice)
if n == True:
score += 100
print("You're win,your score is ",score)
else:
score -= 200
print("You're loose,your score is ",score)
if score <= -1000:
print("Your score is low -1000,game over.")
break
def main():
choice()
if __name__ == '__main__':
main() |
8ff7ae389b4a3ee40c2f2f9194f2500d4ec7af22 | cavandervoort/Project-Euler-001-to-100 | /Euler_099.py | 1,479 | 3.640625 | 4 | # Problem 99
# Largest exponential
def get_pairs(file_name, permissions): # gets coordinates from file and formats them
f = open(file_name, permissions)
pairs = []
line_str = ' '
while line_str != '':
line_temp = f.readline()
line_str = [char for char in line_temp]
line_str = ''.join(line_str)
if len(line_str) < 10:
break
line_list = line_str[0:].split(',')
output = []
for pos in range(len(line_list)):
output.append(int(line_list[pos]))
pairs.append(output)
return pairs
def bigger_big(x,y,a,b):
x_temp = x
y_temp = y
a_temp = a
b_temp = b
while True:
if x_temp >= y_temp and a_temp >= b_temp:
return (x,a)
elif y_temp >= x_temp and b_temp >= a_temp:
return (y,b)
elif x_temp >= y_temp and b_temp >= a_temp:
x_temp /= y_temp
b_temp -= a_temp
else:
y_temp /= x_temp
a_temp -= b_temp
pairs = get_pairs("p099_base_exp.txt", "r")
max_line = 1
x = pairs[0][0]
a = pairs[0][1]
for pair_num in range(1,len(pairs)):
y = pairs[pair_num][0]
b = pairs[pair_num][1]
x,a = bigger_big(x,y,a,b)
if x == y and a == b: # if the new pair became x and y
max_line = pair_num + 1
print(f'The max value is line {max_line}, in which the base is {x} and the exponent {a}.')
|
4cb3527fd6ff9db5402c124664f91def8c68b326 | Mirgul12/python12 | /chapter1.1.py | 3,354 | 4 | 4 | # 1.напишите код ввода двух чисел.Вычислите их разницу
# a = int(input('Введите число:'))
# b = int(input('Введите число:'))
# s = (a - b)
# print(s)
# 2.вычислите остаток деления 36 на 5
# number1 = 36
# number2 = 5
# print(number1 % number2)
# 3.Напишите проверку на то, является ли строка палиндромом.
# Палиндром — это слово или фраза, которые одинаково читаются
# слева направо и справа налево.
# text = ('заказ')
# print(text[::-1])
# 4. Дана строка “I love Java”. Выведите первые два слова I love Java”.
# Выведите первые два слова и добавьте к ним Python.
# text = 'I love java'
# print(text.replace('Java','Python')
# 5.Напишите код для ввода текста. Введите свое имя и выведите его в терминал 10 раз.
# name = input('Введите имя:')
#
# print(name)
# print(name*10)
# 6. Напишите код для ввода текста. Выведите все буквы в обратном порядке.
# text = input('Введите текст:')
# print(text[::-1])
# 7. Напишите код для ввода числа. Выведите его 10 цифру по порядку (Учтите, что число может быть коротким,
# в таком случае начинайте отсчет с первой цифры).
# 8. Напишите программу для получения первых 2 и последних 2 символов в строке.
# Если строка содержит 2 символа, выведите их 2 раза. Если в строке 2 символа, выведите саму строку.
# Если строка содержит меньше 2 символов, то выведите сообщение «Error».Error».
# Строка: 'You know nothing, John Snow'
# Результат: 'Yoow'
# Строка : 'hi'
# Результат : 'hi'
# Строка : ''
# Результат : Error
# 9. Напишите код для ввода числа. Выведите его предыдущее и следующее числа.
# (Например пользователь ввел 5. Вывод должен быть: 4, 6)
# 10. Пользователь вводит два числа. Сравните эти числа и выведите результат.
# Пример:
# First number: 10
# Second number: 5
# Результат: 10 > 5
# number1 = int(input('Введите число :'))
# number2 = int(input('Введите число :'))
# if number1 > number2:
# print(number1)
# else:
# print(number2)
#11. Пользователь вводит число. Проверьте отрицательное оно или положительное
# и выведите результаты (0 не является ни положительным, ни отрицательным)
# num = int(input('Введите число:'))
# if num > 0:
# print('Это число положительное')
# else: print('Это число отрицательное')
|
8358af3584bc3fe740962bb4893eb4ad63b9b573 | emilianot04/Exercise_Python | /The-Python-Workbook/1-Introduction-to-Programming/exercise2.py | 238 | 4.625 | 5 | #Write a program that asks the user to enter his or her name. The program should respond with a message that says hello to the user, using his or her name.
name= input('Hello! Insert your name:\n')
print('Hello ' + name + '! Welcome')
|
6249d6087984f287fe34ffe0b9dec7cea34a44a8 | nonasi/AI_P2 | /multiAgents.py | 24,966 | 3.75 | 4 | # multiAgents.py
# --------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
from util import manhattanDistance
from game import Directions
import random, util
from game import Agent
class ReflexAgent(Agent):
"""
A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change
it in any way you see fit, so long as you don't touch our method
headers.
"""
def getAction(self, gameState):
"""
You do not need to change this method, but you're welcome to.
getAction chooses among the best options according to the evaluation function.
Just like in the previous project, getAction takes a GameState and returns
some Directions.X for some X in the set {North, South, West, East, Stop}
"""
# Collect legal moves and successor states
legalMoves = gameState.getLegalActions()
# Choose one of the best actions
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestIndices) # Pick randomly among the best
"Add more of your code here if you want to"
return legalMoves[chosenIndex]
def findManhattanDistance(self, p1, p2):
x1 = p1[0]
y1 = p1[1]
x2 = p2[0]
y2 = p2[1]
dist = abs(x1 - x2) + abs(y1 - y2)
return dist
#scores how the agent is doing in respect to food
def getFoodScore(self, newPos, oldPos, oldFood):
from decimal import Decimal
numOldFood = len(oldFood)
numNewFood = len(oldFood)
foodPoints = 0
#if we ate a food, add a point,
if newPos in oldFood:
#print "can capture food!"
numNewFood = numNewFood - 1
foodPoints += 1
#find food distances
else:
foodDistances = [0]* len(oldFood)
i = 0
for curFood in oldFood:
oldD = self.findManhattanDistance(curFood, oldPos)
newD = self.findManhattanDistance(curFood, newPos)
foodDistances[i] = newD
i = i+1
#print "fd: ",foodDistances
#print "min: ", Decimal(1/Decimal(min(foodDistances)))
foodPoints = Decimal(1/Decimal(min(foodDistances)))
#print "food points: ", foodPoints
return Decimal(foodPoints)
def evaluationFunction(self, currentGameState, action):
from decimal import Decimal
"""
Design a better evaluation function here.
The evaluation function takes in the current GameState and proposed successor
GameStates (pacman.py) and returns a number, where higher numbers are better.
The code below extracts some useful information from the state:
oldFood = remaining food
newPos = Pacman position after moving.
newScaredTimes = holds the number of moves that each ghost will remain
scared because of Pacman having eaten a power pellet.
Print out these variables to see what you're getting, then combine them
to create a masterful evaluation function.
"""
# Useful information you can extract from a GameState (pacman.py)
successorGameState = currentGameState.generatePacmanSuccessor(action)
newPos = successorGameState.getPacmanPosition()
oldPos = currentGameState.getPacmanPosition()
oldFood = currentGameState.getFood().asList()
newGhostStates = successorGameState.getGhostStates()
newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]
"*** YOUR CODE HERE ***"
"print highest number for best performance."
"Base performance measure on getting closer to food and farther from ghost"
""
#print "food: ", oldFood
#print "num food: ", len(oldFood)
#print "current score: ", currentGameState.getScore()
#print "successor score ", successorGameState.getScore()
#print "ghost states: ", newGhostStates[0].getPosition()
# get food points
foodPoints = self.getFoodScore(newPos, oldPos, oldFood)
score = Decimal(foodPoints)
#get staying away from ghost points:
for curGhost in newGhostStates:
gp = curGhost.getPosition()
gd = curGhost.getDirection()
if gp[0]!= newPos[0] and gp[1]!=newPos[1] :
score +=2
elif gp[0]== newPos[0] and gp[1]==newPos[1]:
score = abs(score) - abs(score)#score - 2*(len(newGhostStates) + 1)
#print "score: ", score
return Decimal(score)
def scoreEvaluationFunction(currentGameState):
"""
This default evaluation function just returns the score of the state.
The score is the same one displayed in the Pacman GUI.
This evaluation function is meant for use with adversarial search agents
(not reflex agents).
"""
return currentGameState.getScore()
class MultiAgentSearchAgent(Agent):
"""
This class provides some common elements to all of your
multi-agent searchers. Any methods defined here will be available
to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.
You *do not* need to make any changes here, but you can if you want to
add functionality to all your adversarial search agents. Please do not
remove anything, however.
Note: this is an abstract class: one that should not be instantiated. It's
only partially specified, and designed to be extended. Agent (game.py)
is another abstract class.
"""
def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):
self.index = 0 # Pacman is always agent index 0
self.evaluationFunction = util.lookup(evalFn, globals())
self.depth = int(depth)
class MinimaxAgent(MultiAgentSearchAgent):
"""
Your minimax agent (question 2)
"""
def getAction(self, gameState):
"""
Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
Directions.STOP:
The stop direction, which is always legal
gameState.generateSuccessor(agentIndex, action):
Returns the successor game state after an agent takes an action
gameState.getNumAgents():
Returns the total number of agents in the game
"""
"*** YOUR CODE HERE ***"
numAgents = gameState.getNumAgents()
ai = self.index #index of current agent
legalActions = gameState.getLegalActions(ai)
legalActions.remove(Directions.STOP)
numAgents = gameState.getNumAgents()
direction = self.Minimax_Decision(gameState, legalActions, numAgents, ai)
return direction
#returns the best action to take
def Minimax_Decision(self, currentGameState, legalActions, numGhosts, ai):
curUtility = -1
bestUtility = -1
bestAction = legalActions[0]
nSet = True;
for action in legalActions:
successorGameState = currentGameState.generatePacmanSuccessor(action)
#does the argmax part of the code:
curUtility = self.MinValue(successorGameState, numGhosts, ai, 0)
if curUtility >= bestUtility or nSet:
bestAction = action
bestUtility = curUtility
nSet = False
return bestAction
#returns a utility value
def MaxValue(self, state, numGhosts, ai, depth):
if self.terminalTest(state, depth):
valToReturn = self.evaluationFunction(state)
#print "terminating with value", valToReturn
return valToReturn
#we want the legal actions for pacman when we maximize
pacmanLegalActions = state.getLegalActions(ai)
pacmanLegalActions.remove(Directions.STOP)
v = -1;
vSet = False
for a in pacmanLegalActions:
if vSet:
v = max (v, self.MinValue(state.generatePacmanSuccessor(a), numGhosts, ai, depth+1))
#this will only get done on the first iteration of the loop
if not vSet:
v = self.MinValue(state.generatePacmanSuccessor(a), numGhosts, ai, depth+1)
vSet = True
return v
def MinValue(self, state, numGhosts, ai, depth):
if self.terminalTest(state, depth):
return self.evaluationFunction(state)
import sys
v = sys.maxint
possibleActionSets = self.allActionsForAllGhosts(state, numGhosts)
import copy
for curSetOfActions in possibleActionSets:
newState = copy.deepcopy(state)
for actionIndex in range(len(curSetOfActions)):
#get the state after all ghosts have moved
#print "goes through for once", newState
newState = newState.generateSuccessor(actionIndex+1, curSetOfActions[actionIndex])
if self.terminalTest(newState, depth):
break
v = min (v, self.MaxValue(newState, numGhosts, ai, depth))
return v
#get
def allActionsForAllGhosts(self, state, numGhosts):
allGhostsActions = []
for ghost in range(1, numGhosts):
#get all actions for all ghosts
allGhostsActions.append(state.getLegalActions(ghost))
#get all combinations actions of ghost1, ghost2 etc.
from itertools import product
possibleActionSets = product (*allGhostsActions)
return possibleActionSets
# returns true if the game is over
# false if not
def terminalTest (self, state, depth):
if depth >= self.depth:
return True
#if no food is left the game is over
foodList = state.getFood().asList()
if len(foodList) == 0:
return True
#if pacman and ghost have the same position, the game is over
pacmanPos = state.getPacmanPosition()
ghostStates = state.getGhostStates()
#check if pacman eaten by ghost
for ghostState in ghostStates:
ghostPos = ghostState.getPosition()
if ghostPos == pacmanPos:
return True
#if there is still food left and pacman is not
#eaten by a ghost - return false (game is not over)
return False
class AlphaBetaAgent(MultiAgentSearchAgent):
""" Your minimax agent with alpha-beta pruning (question 3)"""
import sys
def getAction(self, gameState):
"""
Returns the minimax action using self.depth and self.evaluationFunction
"""
#print "getAction gets called"
"*** YOUR CODE HERE ***"
numAgents = gameState.getNumAgents()
ai = self.index #index of current agent
legalActions = gameState.getLegalActions(ai)
legalActions.remove(Directions.STOP)
numAgents = gameState.getNumAgents()
direction = self.a_b_Decision(gameState, legalActions, numAgents, ai)
return direction
#util.raiseNotDefined()
##############################################################################################
#returns the best action to take acording to a-b pruning
#returns the best action to take
def a_b_Decision(self, currentGameState, legalActions, numGhosts, ai):
import sys
curUtility = -1
bestUtility = -1
bestAction = legalActions[0]
nSet = True
for action in legalActions:
successorGameState = currentGameState.generatePacmanSuccessor(action)
#does the argmax part of the code:
curUtility = self.MinValue(successorGameState, numGhosts, ai, 0, -sys.maxint-1, sys.maxint)
if curUtility >= bestUtility or nSet:
bestAction = action
bestUtility = curUtility
nSet = False
return bestAction
#returns a utility value
def MaxValue(self, state, numGhosts, ai, depth,a,b):
if self.terminalTest(state, depth):
valToReturn = self.evaluationFunction(state)
return valToReturn
#we want the legal actions for pacman when we maximize
pacmanLegalActions = state.getLegalActions(ai)
pacmanLegalActions.remove(Directions.STOP)
import sys
v = -sys.maxint -1
vSet = False
for action in pacmanLegalActions:
v = max (v, self.MinValue(state.generatePacmanSuccessor(action), numGhosts, ai, depth+1,a,b))
if v >= b:
return v
a = max(a, v)
return v
def MinValue(self, state, numGhosts, ai, depth, a, b):
if self.terminalTest(state, depth):
return self.evaluationFunction(state)
import sys
v = sys.maxint
possibleActionSets = self.allActionsForAllGhosts(state, numGhosts)
import copy
for curSetOfActions in possibleActionSets:
newState = copy.deepcopy(state)
for actionIndex in range(len(curSetOfActions)):
#get the state after all ghosts have moved
newState = newState.generateSuccessor(actionIndex+1, curSetOfActions[actionIndex])
if self.terminalTest(newState, depth):
break
v = min (v, self.MaxValue(newState, numGhosts, ai, depth, a, b))
#v = min (v, self.MaxV(newState, numGhosts, ai, depth, a,b))
if v<=a:
return v
b = min(v, b)
return v
#get all combinations of actions that
#the ghosts can do no their move
def allActionsForAllGhosts(self, state, numGhosts):
allGhostsActions = []
for ghost in range(1, numGhosts):
#get all actions for all ghosts
allGhostsActions.append(state.getLegalActions(ghost))
#get all combinations actions of ghost1, ghost2 etc.
from itertools import product
possibleActionSets = product (*allGhostsActions)
return possibleActionSets
# returns true if the game is over
# false if not
def terminalTest (self, state, depth):
if depth >= self.depth:
return True
#if no food is left the game is over
foodList = state.getFood().asList()
if len(foodList) == 0:
return True
#if pacman and ghost have the same position, the game is over
pacmanPos = state.getPacmanPosition()
ghostStates = state.getGhostStates()
#check if pacman eaten by ghost
for ghostState in ghostStates:
ghostPos = ghostState.getPosition()
if ghostPos == pacmanPos:
return True
#if there is still food left and pacman is not
#eaten by a ghost - return false (game is not over)
return False
##############################################################################################
class ExpectimaxAgent(MultiAgentSearchAgent):
"""
Your expectimax agent (question 4)
"""
def getAction(self, gameState):
"""
Returns the expectimax action using self.depth and self.evaluationFunction
All ghosts should be modeled as choosing uniformly at random from their
legal moves.
"""
"*** YOUR CODE HERE ***"
ai = self.index #index of current agent
numAgents = gameState.getNumAgents()
direction = self.expectiMax_Decision(gameState, numAgents, ai)
return direction
#***************************************************************************************
#turn = true if pacman's turn
#turn = false otherwise
def expectiMax_Decision(self, state, numGhosts, ai):
result = self.ExpectiMaxPlayer(state, numGhosts, ai, 0, True)
#print "this is the result: ", result
return result[1]
# turn = true if it's pacman's turn; false otherwise
# return a tuple; at position 0 is v, at position 1 is the action we
# must take at this state
def ExpectiMaxPlayer(self, state, numGhosts, ai, depth, turn ):
if self.terminalTest(state, depth):
return (self.evaluationFunction(state), -1)
if turn: #pacman's turn
pacmanActions = state.getLegalActions(ai)
pacmanActions.remove(Directions.STOP)
maxV = -1
firstPass = True
bestAction = pacmanActions[0]
for a in pacmanActions:
v = self.ExpectiMaxPlayer(state.generatePacmanSuccessor(a), numGhosts, ai, depth +1, not turn)[0]
if maxV <= v or firstPass:
maxV = v
firstPass = False
bestAction = a
return (maxV, bestAction)
if not turn: #ghost turn
actionSetSum = 0 #accumulator
v = 0
possibleActionSets = self.allActionsForAllGhosts(state, numGhosts)
import copy
numActionSets = 0
for curSetOfActions in possibleActionSets:
numActionSets+=1
newState = copy.deepcopy(state)
for actionIndex in range(len(curSetOfActions)):#get the state after all ghosts have moved
newState = newState.generateSuccessor(actionIndex+1, curSetOfActions[actionIndex])
if self.terminalTest(newState, depth):
break
v = self.ExpectiMaxPlayer(newState, numGhosts, ai, depth, not turn)[0]
actionSetSum += v/ numActionSets
return (actionSetSum, -1)
#get all combinations of actions that
#the ghosts can do no their move
def allActionsForAllGhosts(self, state, numGhosts):
allGhostsActions = []
for ghost in range(1, numGhosts):
#get all actions for all ghosts
allGhostsActions.append(state.getLegalActions(ghost))
#get all combinations actions of ghost1, ghost2 etc.
from itertools import product
possibleActionSets = product (*allGhostsActions)
return possibleActionSets
# returns true if the game is over
# false if not
def terminalTest (self, state, depth):
if depth >= self.depth:
return True
#if no food is left the game is over
foodList = state.getFood().asList()
if len(foodList) == 0:
return True
#if pacman and ghost have the same position, the game is over
pacmanPos = state.getPacmanPosition()
ghostStates = state.getGhostStates()
#check if pacman eaten by ghost
for ghostState in ghostStates:
ghostPos = ghostState.getPosition()
if ghostPos == pacmanPos:
return True
#if there is still food left and pacman is not
#eaten by a ghost - return false (game is not over)
return False
#***************************************************************************************
def betterEvaluationFunction(currentGameState):
"""
Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
evaluation function (question 5).
DESCRIPTION: <write something here so we know what you did>
"""
"*** YOUR CODE HERE ***"
# the farther away the nearest ghost is, the better
# the closer the nearest food dot is, the better
#
import sys
pacPos = currentGameState.getPacmanPosition()
food = currentGameState.getFood()
capsulesList=currentGameState.getCapsules()
allghosts=currentGameState.getGhostStates()
#ghostscaredTimes = [ghos.scaredTimer for ghos in allghosts]
allghosts=currentGameState.getGhostStates()
#ghostpos=currentGameState.getGhostPositions()
noneDisabled=True
disabledGhostIndexes=[]
activeGhostIndexes=[]
#find the disabled and the normal ghost
ind=0
for ghost in allghosts:
if ghost.scaredTimer>0:
noneDisabled=False
disabledGhostIndexes.append(ind) #indexes of disabled ghosts
else:
activeGhostIndexes.append(ind)
ind=ind+1
#find shortest distance to an active ghost
shortestDistanceToActiveGhost=sys.maxint
for index in activeGhostIndexes:
#distance=abs(x - ghostpos[index][0]) + abs(y - ghostpos[index][1])
distance=astarMazeDistBetweenTwoPoints(currentGameState,pacPos,allghosts[index].getPosition())
if distance<shortestDistanceToActiveGhost:
#nearestGhostPos=ghost
shortestDistanceToActiveGhost=distance
#find shortest distance to a disabled ghost
shortestDistanceToDisabledGhost=sys.maxint
numTimesThroughLoop = 1
for index in disabledGhostIndexes:
#print "numTimesThroughLoop", numTimesThroughLoop
numTimesThroughLoop+=1
#print "ghost's position: ",allghosts[index].getPosition()
ghostPos = allghosts[index].getPosition()
xDecimal = abs(ghostPos[0] - int(ghostPos[0]))
yDecimal = abs(ghostPos[1] - int(ghostPos[1]))
if xDecimal > 0 or yDecimal >0:
a =ghostPos[0] + xDecimal
b = ghostPos[1] + yDecimal
ghostPos = (a, b)
distance = astarMazeDistBetweenTwoPoints(currentGameState,pacPos, ghostPos)/2
else:
distance = astarMazeDistBetweenTwoPoints(currentGameState,pacPos, allghosts[index].getPosition())/2
if distance < shortestDistanceToDisabledGhost:
shortestDistanceToDisabledGhost = distance
shortestDistanceToFood = sys.maxint
foodList = food.asList()
foodAndCapsulesList = foodList+capsulesList
for foodPiece in foodAndCapsulesList:
distance = astarMazeDistBetweenTwoPoints(currentGameState,pacPos,foodPiece)
if distance < shortestDistanceToFood:
shortestDistanceToFood = distance
if len(foodAndCapsulesList)==0:
return sys.maxint
if noneDisabled:
#print "ghosts not scared"
#return 2*shortestDistanceToActiveGhost-shortestDistanceToFood
return scoreEvaluationFunction(currentGameState) - shortestDistanceToFood
if not noneDisabled:
#print "ghosts scared!!"
#return shortestDistanceToActiveGhost+0.5*shortestDistanceToFood-1.5*shortestDistanceToDisabledGhost
return 2*scoreEvaluationFunction(currentGameState)-shortestDistanceToDisabledGhost
def astarMazeDistBetweenTwoPoints(currentGameState, pos1, pos2):
from game import Directions
from util import PriorityQueue
pos1dub=(float(pos1[0]),float(pos1[1]))
pos2dub=(float(pos2[0]),float(pos2[1]))
x=pos1dub
explored = set([x])
frontier=PriorityQueue()
path=[]
pathcost=0
frontier.push((x,path,pathcost),pathcost)
while True:
activeNode=frontier.pop()
#activeNode[0] is the location of the node, activeNode[1] is the path from active node back to the start, activeNode[2] is the pathcost of path
x=activeNode[0]
#print "pathcost of node just popped: ",activeNode[2]
if x[0]==pos2dub[0] and x[1]==pos2dub[1]: #goal test
#print "RETURNING: ",x,pos2dub
return activeNode[2]
succlist=getSuccessors(x,currentGameState) #is a list of triples
explored.add(x)
for i in succlist: #i is a triple, i[0] is the location, i[1] is direction, i[2] is the cost
path=activeNode[1]+[i[1]]
pathcost=activeNode[2]+i[2]
estpathcost=pathcost+heuristicManDis(i[0],pos2)
izfloat=(float(i[0][0]),float(i[0][1]))
if izfloat not in explored:
frontier.push((izfloat,path,pathcost),estpathcost)
def getSuccessors(state,currentGameState):
from game import Actions
"Returns successor states, the actions they require, and a cost of 1."
walls = currentGameState.getWalls()
successors = []
for direction in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
x,y = state
dx, dy = Actions.directionToVector(direction)
nextx, nexty = int(x + dx), int(y + dy)
if not walls[nextx][nexty]:
successors.append( ( (nextx, nexty), direction, 1) )
return successors
def heuristicManDis(virtualpos,pos2):
return abs(virtualpos[0] - pos2[0]) + abs(virtualpos[1] - pos2[1])
# Abbreviation
better = betterEvaluationFunction
class ContestAgent(MultiAgentSearchAgent):
"""
Your agent for the mini-contest
"""
def getAction(self, gameState):
"""
Returns an action. You can use any method you want and search to any depth you want.
Just remember that the mini-contest is timed, so you have to trade off speed and computation.
Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually
just make a beeline straight towards Pacman (or away from him if they're scared!)
"""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
|
938e05c4eff3d41a71d5290ad6e88359ed51786c | mudassarahmad/python | /calculator.func.py | 2,611 | 4.21875 | 4 | #Calculator Program
print " This program is a calculator program"
def table():
# print "Please enter the integer for the table"
table = int(raw_input("enter table :"))
last = int(raw_input("enter last :"))
print last
start = 1
while start <= last:
print table, "*", start, "=", int(table) * int(start)
start = int(start) + 1
loop2 = 1
choice2 = 0
while loop2 != 0:
print "do you want to continue:"
print " "
print "1) yes"
print "2) no"
choice2 =int(raw_input("please enter your choice: "))
if choice2 == 1:
print "Please enter the integer for the table"
table = int(raw_input("enter table :"))
start = 1
last = int(raw_input("enter last :"))
while start <= last:
print table, "*", start, "=", int(table) * int(start)
start = int(start) + 1
elif choice2 == 2:
loop2 = 0
def main():
print "Please enter the integer for the table calling from function"
table()
#main()
loop = 1
choice = 0
while loop != 0:
print "your options are:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Divison"
print "5) Tables"
print "6) Quit"
choice =int(raw_input("please enter your choice: "))
if choice == 1:
num1 = int(raw_input("enter num1 :"))
num2 = int(raw_input("enter num2 :"))
print num1, "+", num2, "=", int(num1) + int(num2)
elif choice == 2:
num1 = int(raw_input("enter num1 :"))
num2 = int(raw_input("enter num2 :"))
print num1, "-", num2, "=", int(num1) - int(num2)
elif choice == 3:
num1 = int(raw_input("enter num1 :"))
num2 = int(raw_input("enter num2 :"))
print num1, "*", num2, "=", int(num1) * int(num2)
elif choice == 4:
num1 = int(raw_input("enter num1 :"))
num2 = int(raw_input("enter num2 :"))
print num1, "/", num2, "=", int(num1) / int(num2)
elif choice == 5:
main()
elif choice == 6:
loop = 0
print " Thank you for using calculator.py"
|
dd6ec30d0e4d93e9ec37cc9645973cd042c592e5 | jlreagan/BIOL5153 | /chapters5.6.py | 1,025 | 3.8125 | 4 | #####CHAPTER Writing a function
#Defining a function
def get_at_content(dna):
length = len(dna)
a_count = dna.upper().count('A')
t_count = dna.upper().count('T')
at_content = (a_count + t_count) / length
return round(at_content, 2)
#return at_content will give all numbers
#return round(at_content, 2) will round to 2 sigfigs
get_at_content("ATGACTGGACCA")
my_at_content = get_at_content("ATGCGCGATCGATCGAATCG")
print("AT content is " + str(get_at_content("ATGACTGGACCA")))
print(str(my_at_content))
print(get_at_content("ATGCATGCAACTGTAGC"))
print(get_at_content("aactgtagctagctagcagcgta"))
#Defining a function without an argument
def get_a_number():
return 42
#calling functions with named arguments
#get_at_content("ATCGTGACTCG", 2)
#get_at_content(dna="ATCGTGACTCG", sig_figs=2)
#identical statements:
#get_at_content(dna="ATCGTGACTCG", sig_figs=2)
#get_at_content(sig_figs=2, dna="ATCGTGACTCG")
#get_at_content("ATCGTGACTCG")
#get_at_content("ATCGTGACTCG", 3)
#get_at_content("ATCGTGACTCG", sig_figs=4) |
f389d09c593d8924dc41c94ae3ddd0292a5afa1e | hy299792458/LeetCode | /python/606-constructString.py | 731 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def tree2str(self, t):
def search(root):
re = ''
if root == None:
return ''
else:
re += str(root.val)
if root.left:
re += '(' + search(root.left) + ')'
if root.right:
re += '(' + search(root.right) + ')'
elif root.right:
re += '()'
re += '(' + search(root.right) + ')'
return re
return search(t)
|
af8d21429e3a481857ae5f59151b06503fdce060 | Techsrijan/techpython | /wendingmachine.py | 285 | 3.890625 | 4 | n=int(input("How many toffe u want ?"))
stock=15
count=1
while count<=n:
if stock>=count:
print("Please collect toffee=",count)
else:
print("Out of stock")
break
count=count+1
else: # when loop properly runs
print("thanks Please visit again")
|
4f97a07611fd2b524aa789e96d990bd4a3a10f3f | goodnamehadbeeneatbydog/sunPythonLearning | /src/classlearn/定制类.py | 10,541 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# 看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的。
#
# __slots__我们已经知道怎么用了,__len__()方法我们也知道是为了能让class作用于len()函数。
#
# 除此之外,Python的class中还有许多这样有特殊用途的函数,可以帮助我们定制类。
#
# __str__
# 我们先定义一个Student类,打印一个实例:
#
# >>> class Student(object):
# ... def __init__(self, name):
# ... self.name = name
# ...
# >>> print(Student('Michael'))
# <__main__.Student object at 0x109afb190>
# 打印出一堆<__main__.Student object at 0x109afb190>,不好看。
#
# 怎么才能打印得好看呢?只需要定义好__str__()方法,返回一个好看的字符串就可以了:
#
# >>> class Student(object):
# ... def __init__(self, name):
# ... self.name = name
# ... def __str__(self):
# ... return 'Student object (name: %s)' % self.name
# ...
# >>> print(Student('Michael'))
# Student object (name: Michael)
# 这样打印出来的实例,不但好看,而且容易看出实例内部重要的数据。
#
# 但是细心的朋友会发现直接敲变量不用print,打印出来的实例还是不好看:
#
# >>> s = Student('Michael')
# >>> s
# <__main__.Student object at 0x109afb310>
# 这是因为直接显示变量调用的不是__str__(),而是__repr__(),两者的区别是__str__()返回用户看到的字符串,而__repr__()返回程序开发者看到的字符串,也就是说,__repr__()是为调试服务的。
#
# 解决办法是再定义一个__repr__()。但是通常__str__()和__repr__()代码都是一样的,所以,有个偷懒的写法:
#
# class Student(object):
# def __init__(self, name):
# self.name = name
# def __str__(self):
# return 'Student object (name=%s)' % self.name
# __repr__ = __str__
# __iter__
# 如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法,该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。
#
# 我们以斐波那契数列为例,写一个Fib类,可以作用于for循环:
#
# class Fib(object):
# def __init__(self):
# self.a, self.b = 0, 1 # 初始化两个计数器a,b
#
# def __iter__(self):
# return self # 实例本身就是迭代对象,故返回自己
#
# def __next__(self):
# self.a, self.b = self.b, self.a + self.b # 计算下一个值
# if self.a > 100000: # 退出循环的条件
# raise StopIteration()
# return self.a # 返回下一个值
# 现在,试试把Fib实例作用于for循环:
#
# >>> for n in Fib():
# ... print(n)
# ...
# 1
# 1
# 2
# 3
# 5
# ...
# 46368
# 75025
# __getitem__
# Fib实例虽然能作用于for循环,看起来和list有点像,但是,把它当成list来使用还是不行,比如,取第5个元素:
#
# >>> Fib()[5]
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'Fib' object does not support indexing
# 要表现得像list那样按照下标取出元素,需要实现__getitem__()方法:
#
# class Fib(object):
# def __getitem__(self, n):
# a, b = 1, 1
# for x in range(n):
# a, b = b, a + b
# return a
# 现在,就可以按下标访问数列的任意一项了:
#
# >>> f = Fib()
# >>> f[0]
# 1
# >>> f[1]
# 1
# >>> f[2]
# 2
# >>> f[3]
# 3
# >>> f[10]
# 89
# >>> f[100]
# 573147844013817084101
# 但是list有个神奇的切片方法:
#
# >>> list(range(100))[5:10]
# [5, 6, 7, 8, 9]
# 对于Fib却报错。原因是__getitem__()传入的参数可能是一个int,也可能是一个切片对象slice,所以要做判断:
#
# class Fib(object):
# def __getitem__(self, n):
# if isinstance(n, int): # n是索引
# a, b = 1, 1
# for x in range(n):
# a, b = b, a + b
# return a
# if isinstance(n, slice): # n是切片
# start = n.start
# stop = n.stop
# if start is None:
# start = 0
# a, b = 1, 1
# L = []
# for x in range(stop):
# if x >= start:
# L.append(a)
# a, b = b, a + b
# return L
# 现在试试Fib的切片:
#
# >>> f = Fib()
# >>> f[0:5]
# [1, 1, 2, 3, 5]
# >>> f[:10]
# [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
# 但是没有对step参数作处理:
#
# >>> f[:10:2]
# [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# 也没有对负数作处理,所以,要正确实现一个__getitem__()还是有很多工作要做的。
#
# 此外,如果把对象看成dict,__getitem__()的参数也可能是一个可以作key的object,例如str。
#
# 与之对应的是__setitem__()方法,把对象视作list或dict来对集合赋值。最后,还有一个__delitem__()方法,用于删除某个元素。
#
# 总之,通过上面的方法,我们自己定义的类表现得和Python自带的list、tuple、dict没什么区别,这完全归功于动态语言的“鸭子类型”,不需要强制继承某个接口。
#
# __getattr__
# 正常情况下,当我们调用类的方法或属性时,如果不存在,就会报错。比如定义Student类:
#
# class Student(object):
#
# def __init__(self):
# self.name = 'Michael'
# 调用name属性,没问题,但是,调用不存在的score属性,就有问题了:
#
# >>> s = Student()
# >>> print(s.name)
# Michael
# >>> print(s.score)
# Traceback (most recent call last):
# ...
# AttributeError: 'Student' object has no attribute 'score'
# 错误信息很清楚地告诉我们,没有找到score这个attribute。
#
# 要避免这个错误,除了可以加上一个score属性外,Python还有另一个机制,那就是写一个__getattr__()方法,动态返回一个属性。修改如下:
#
# class Student(object):
#
# def __init__(self):
# self.name = 'Michael'
#
# def __getattr__(self, attr):
# if attr=='score':
# return 99
# 当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性,这样,我们就有机会返回score的值:
#
# >>> s = Student()
# >>> s.name
# 'Michael'
# >>> s.score
# 99
# 返回函数也是完全可以的:
#
# class Student(object):
#
# def __getattr__(self, attr):
# if attr=='age':
# return lambda: 25
# 只是调用方式要变为:
#
# >>> s.age()
# 25
# 注意,只有在没有找到属性的情况下,才调用__getattr__,已有的属性,比如name,不会在__getattr__中查找。
#
# 此外,注意到任意调用如s.abc都会返回None,这是因为我们定义的__getattr__默认返回就是None。要让class只响应特定的几个属性,我们就要按照约定,抛出AttributeError的错误:
#
# class Student(object):
#
# def __getattr__(self, attr):
# if attr=='age':
# return lambda: 25
# raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr)
# 这实际上可以把一个类的所有属性和方法调用全部动态化处理了,不需要任何特殊手段。
#
# 这种完全动态调用的特性有什么实际作用呢?作用就是,可以针对完全动态的情况作调用。
#
# 举个例子:
#
# 现在很多网站都搞REST API,比如新浪微博、豆瓣啥的,调用API的URL类似:
#
# http://api.server/user/friends
# http://api.server/user/timeline/list
# 如果要写SDK,给每个URL对应的API都写一个方法,那得累死,而且,API一旦改动,SDK也要改。
#
# 利用完全动态的__getattr__,我们可以写出一个链式调用:
#
# class Chain(object):
#
# def __init__(self, path=''):
# self._path = path
#
# def __getattr__(self, path):
# return Chain('%s/%s' % (self._path, path))
#
# def __str__(self):
# return self._path
#
# __repr__ = __str__
# 试试:
#
# >>> Chain().status.user.timeline.list
# '/status/user/timeline/list'
# 这样,无论API怎么变,SDK都可以根据URL实现完全动态的调用,而且,不随API的增加而改变!
#
# 还有些REST API会把参数放到URL中,比如GitHub的API:
#
# GET /users/:user/repos
# 调用时,需要把:user替换为实际用户名。如果我们能写出这样的链式调用:
#
# Chain().users('michael').repos
# 就可以非常方便地调用API了。有兴趣的童鞋可以试试写出来。
#
# __call__
# 一个对象实例可以有自己的属性和方法,当我们调用实例方法时,我们用instance.method()来调用。能不能直接在实例本身上调用呢?在Python中,答案是肯定的。
#
# 任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用。请看示例:
#
# class Student(object):
# def __init__(self, name):
# self.name = name
#
# def __call__(self):
# print('My name is %s.' % self.name)
# 调用方式如下:
#
# >>> s = Student('Michael')
# >>> s() # self参数不要传入
# My name is Michael.
# __call__()还可以定义参数。对实例进行直接调用就好比对一个函数进行调用一样,所以你完全可以把对象看成函数,把函数看成对象,因为这两者之间本来就没啥根本的区别。
#
# 如果你把对象看成函数,那么函数本身其实也可以在运行期动态创建出来,因为类的实例都是运行期创建出来的,这么一来,我们就模糊了对象和函数的界限。
#
# 那么,怎么判断一个变量是对象还是函数呢?其实,更多的时候,我们需要判断一个对象是否能被调用,能被调用的对象就是一个Callable对象,比如函数和我们上面定义的带有__call__()的类实例:
#
# >>> callable(Student())
# True
# >>> callable(max)
# True
# >>> callable([1, 2, 3])
# False
# >>> callable(None)
# False
# >>> callable('str')
# False
# 通过callable()函数,我们就可以判断一个对象是否是“可调用”对象。
#
# 小结
# Python的class允许定义许多定制方法,可以让我们非常方便地生成特定的类。
#
# 本节介绍的是最常用的几个定制方法,还有很多可定制的方法,请参考Python的官方文档。 |
cc61a8f8185bd029b28cd9c95529828e66adb55b | tejaswiniR161/fewLeetCodeSolutions | /Strings/valid_parathesis.py | 726 | 3.703125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
t=list()
t.append(0)
for i in range(len(s)):
#print(s[i])
if t[-1]=="(" and s[i]==")":
#print("previous 1 matched")
t.pop(-1)
elif t[-1]=="[" and s[i]=="]":
#print("previous 1 matched")
t.pop(-1)
elif t[-1]=="{" and s[i]=="}":
#print("previous 1 matched")
t.pop(-1)
else:
#print("previous one did not match, appending")
t.append(s[i])
#print("t now ",t)
if len(t)<=1:
return True
else:
return False
|
d1a54f4aa5b2f4f27ba99696c6a303894a7dc27c | vaios84/Python-Tutorial | /while_loop.py | 240 | 3.703125 | 4 | secretNumber= 12
i=0
guessLimit= 3
while i<guessLimit:
guess = int(input('Make a guess (1-20): '))
i++
if guess == secretNumber:
print('You won')
break
else:
print('Sorry, you failed. Try again!') |
c18cef42358b19686cf114ad74ae03e6318810b4 | KorzhMorzh/cs102 | /homework01/vigener.py | 1,959 | 3.671875 | 4 | def encrypt_vigenere(plaintext: str, keyword: str) -> str:
"""
>>> encrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> encrypt_vigenere("python", "a")
'python'
>>> encrypt_vigenere("ATTACKATDAWN", "LEMON")
'LXFOPVEFRNHR'
"""
word = [i for i in plaintext]
keys = [i for i in keyword*(len(plaintext)//len(keyword)+1)]
ciphertext = ''
for i in range(len(word)):
code_of_simbol = ord(word[i])
code_of_key = ord(keys[i])
if 65 <= code_of_key <= 90:
code_of_key -= 65
elif 97 <= code_of_key <= 122:
code_of_key -= 97
if 65 <= code_of_simbol <= 90 - code_of_key or 97 <= code_of_simbol <= 122 - code_of_key:
word[i] = chr(code_of_simbol + code_of_key)
elif 90 - code_of_key < code_of_simbol <= 90 or 122 - code_of_key < code_of_simbol <= 122:
word[i] = chr(code_of_simbol + code_of_key - 26)
ciphertext += word[i]
return ciphertext
def decrypt_vigenere(ciphertext: str, keyword: str) -> str:
"""
>>> decrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> decrypt_vigenere("python", "a")
'python'
>>> decrypt_vigenere("LXFOPVEFRNHR", "LEMON")
'ATTACKATDAWN'
"""
word = [i for i in ciphertext]
keys = [i for i in keyword * (len(ciphertext) // len(keyword) + 1)]
ciphertext = ''
for i in range(len(word)):
code_of_simbol = ord(word[i])
code_of_key = ord(keys[i])
if 65 <= code_of_key <= 90:
code_of_key -= 65
elif 97 <= code_of_key <= 122:
code_of_key -= 97
if 65 + code_of_key <= code_of_simbol <= 90 or 97 + code_of_key <= code_of_simbol <= 122:
word[i] = chr(code_of_simbol - code_of_key)
elif 65 <= code_of_simbol < 65 + code_of_key or 97 <= code_of_simbol < 97 + code_of_key:
word[i] = chr(code_of_simbol - code_of_key + 26)
ciphertext += word[i]
return ciphertext
|
6df5cd994892a363fcff45fae7e12ce936569653 | advecchia/propor | /propor/src/parse.py | 1,171 | 3.765625 | 4 | import argparse
class Parse:
""" A class for manipulating the program input.
"""
def __init__(self):
#sys.path.append(os.path.join(os.getcwd(),os.path.dirname(__file__), 'src'))
pass
def parse(self):
parser = argparse.ArgumentParser(description="", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# group 1
# group1 = parser.add_argument_group("group name","infos")
# group1.add_argument(MIN_PORT, PORT, dest=PORT, nargs=1, metavar="number", default=DEFAULT_PORT, help="infos")
# group 2
# group2 = parser.add_argument_group("group name","infos")
# group2.add_argument(MIN_PORT, PORT, dest=PORT, nargs=1, metavar="number", default=DEFAULT_PORT, help="infos")
# args = parser.parse_args()
# params = vars(args)
#
# #"""
# # Removes the parameter not inserted in the input
# for key,value in params.items():
# if value is None:
# del params[key]
# elif not isinstance(value, list):
# params[key] = []
# params[key].append(value)
# #"""
# return params |
550aee15aed8623901e4deeb2e422c96c497adb5 | alicihandemir/Patika.dev_Python_Temel_Proje | /Python Proje/flatten.py | 256 | 4 | 4 | def flatten (a,b):
for i in a:
if type(i) != type([]):
b.append(i)
elif type(i) == type([]):
flatten(i, b)
return b
arr = [1,2,[3,4,5],6,7,[8,[9,10]]]
f_list = []
print(flatten(arr, f_list)) |
0db34572985497e66c28c8f848bb35e094b8cd48 | m104/aoc-2020 | /day02.py | 2,022 | 3.53125 | 4 | #!/usr/bin/env python3
#
# Debug:
# ./day02.py < day02.input.txt
# Run:
# ./day02.py < day02.input.txt 2>/dev/null
import sys
lines = []
for line in sys.stdin:
lines.append(line.strip())
def parse_first_policy(line):
policy_str, letter_str, password = line.split(" ")
letter = letter_str[0]
low, high = tuple(map(int, policy_str.split("-")))
policy = range(low, high + 1)
return (password, letter, policy)
def validate_first_policy(password, letter, policy):
count = len(list(filter(lambda c: c == letter, password)))
verdict = count in policy
print(
f"verdict={verdict} letter={letter} count={count} policy={policy} password={password}",
file=sys.stderr,
)
return verdict
def count_first_valid_passwords(lines):
def _validate_line(line):
password, letter, policy = parse_first_policy(line)
return validate_first_policy(password, letter, policy)
valid = filter(_validate_line, lines)
return len(list(valid))
def parse_second_policy(line):
policy_str, letter_str, password = line.split(" ")
letter = letter_str[0]
low, high = tuple(map(int, policy_str.split("-")))
policy = (low - 1, high - 1)
return (password, letter, policy)
def validate_second_policy(password, letter, indexes):
valid = filter(lambda index: password[index] == letter, indexes)
count = len(list(valid))
verdict = count == 1
print(
f"verdict={verdict} letter={letter} count={count} indexes={indexes} password={password}",
file=sys.stderr,
)
return verdict
def count_second_valid_passwords(lines):
def _validate_line(line):
password, letter, policy = parse_second_policy(line)
return validate_second_policy(password, letter, policy)
valid = filter(_validate_line, lines)
return len(list(valid))
answer = count_first_valid_passwords(lines)
print(f"Part I Answer: {answer}")
answer = count_second_valid_passwords(lines)
print(f"Part II Answer: {answer}")
|
8c01a599a72018ac9c18be14ea0a28104acd42c5 | DanielRahme/advent-of-code-2017 | /day_4/day_4.py | 1,193 | 3.546875 | 4 | import itertools
case_1 = ["aa", "bb", "cc", "dd", "ee"]
case_2 = ["aa", "bb", "cc", "dd", "aa"]
case_3 = ["aa", "bb", "cc", "dd", "aaa"]
case_matrix = []
case_matrix.append(case_1)
case_matrix.append(case_2)
case_matrix.append(case_3)
# Read the input file
matrix = []
with open("input.txt", "r") as f:
for line in f:
tmp = line.split(' ')
tmp[-1] = tmp[-1].strip()
#tmp = map(int, tmp)
matrix.append(tmp)
#
print(matrix)
def passphrase_check(matrix_input):
dupes_found = 0
valids = 0
for line in matrix_input:
for a, b in itertools.combinations(line, 2):
if (a == b):
dupes_found += 1
if (dupes_found == 0):
valids += 1
dupes_found = 0
return valids
def passphrase_check_2(matrix_input):
dupes_found = 0
valids = 0
for line in matrix_input:
for a, b in itertools.combinations(line, 2):
if (sorted(a) == sorted(b)):
dupes_found += 1
if (dupes_found == 0):
valids += 1
dupes_found = 0
return valids
# main #####################
print(passphrase_check(matrix))
print(passphrase_check_2(matrix))
|
49a764560e2323d921d082c9f5edecbbc8dc60b6 | southpawgeek/perlweeklychallenge-club | /challenge-122/cristian-heredia/python/ch-1.py | 752 | 3.84375 | 4 | '''
TASK #1 › Average of Stream
Submitted by: Mohammad S Anwar
You are given a stream of numbers, @N.
Write a script to print the average of the stream at every point.
Example
Input: @N = (10, 20, 30, 40, 50, 60, 70, 80, 90, ...)
Output: 10, 15, 20, 25, 30, 35, 40, 45, 50, ...
Average of first number is 10.
Average of first 2 numbers (10+20)/2 = 15
Average of first 3 numbers (10+20+30)/3 = 20
Average of first 4 numbers (10+20+30+40)/4 = 25 and so on.
'''
# Initial variable
N = (10, 20, 30, 40, 50, 60, 70, 80, 90)
# Other variables
counter = 1
result = []
sum = 0
for num in N:
sum += num
result.append(str(int(sum/counter)))
counter+=1
final = ", ".join(result)
print(f"Output: {final}") |
bb9c928989b8799406ad6b8cd50c19ca691e31ea | impiyush83/code | /CSCI-B505/assignment5/assignment5_3_1.py | 1,629 | 3.8125 | 4 | import random
import sys
def get_matrix_dimension():
"""
Accepts matrix dimensions
:return: list
"""
first_matrix = input("Enter the dimensions (p) of the matrices you want to"
" multiply (separated by space):\n")
return [int(j) for j in first_matrix.split()]
def brute_matrix_multiplication(p, i, j):
"""
Brute matrix multiplication
:param p: list
:param i: int
:param j: int
:return int
"""
if i == j:
return 0
n = len(p)
m = [[0 for __ in range(n)] for _ in range(n)]
m[i][j] = sys.maxsize
for k in range(i, j):
q = brute_matrix_multiplication(p, i, k) \
+ brute_matrix_multiplication(p, k + 1, j) \
+ (p[i - 1] * p[k] * p[j])
if q < m[i][j]:
m[i][j] = q
return m[i][j]
def inject_matrix(matrix_dimensions):
"""
Sends a matrix for multiplication
:param matrix_dimensions: list
:return: None
"""
print("\nMatrices' Dimensions:")
for i in range(len(matrix_dimensions) - 1):
print("\t[{}],[{}]".format(matrix_dimensions[i],
matrix_dimensions[i + 1]))
min_mul = brute_matrix_multiplication(matrix_dimensions, 1, len(matrix_dimensions) - 1)
print(
"Minimum number of multiplications to multiply {} matrices: {}".format(
len(matrix_dimensions) - 1, min_mul))
dimension_array = [30, 35, 15, 5, 10, 20, 25]
inject_matrix(dimension_array)
for _ in range(10): # Random Values
dimension_array = random.sample(range(1, 25), 6)
inject_matrix(dimension_array) |
f510d8da99bb4f1f68c37c16e863f67e403cbd47 | Banapple01/Coding_Dojo-School-work | /Dojo_Assignments/Algorithms/10-13-2020.py | 1,227 | 4.25 | 4 | import math
# Binary Search
# Given a sorted list of integers and a number, return a boolean
# if that number exists inside the list.
# Do not use a for loop to iterate over the entire list.
# Input: [1, 2, 3, 4, 5], 5
# Output: True
# Input: [2, 4, 6, 8], 9
# Output: False
# get middle value
# evaluate if < > =
# if not =
def binary_search(some_li, num):
# covering if number is not in list
if num == some_li[len(some_li)-1] or num == some_li[0]:
return True
# check if num is greater than value at middle index
elif some_li[math.ceil(len(some_li) / 2)] < num:
print('It was in the top half')
# call function on top half of list
return binary_search(some_li[math.ceil(len(some_li) / 2) + 1: len(some_li) - 1], num)
# Check if num is less than value at middle index
elif some_li[math.ceil(len(some_li) / 2)] > num:
print('It was in the bottom half')
#call function on bottom half of list
return binary_search(some_li[0: math.ceil(len(some_li) / 2) - 1], num)
# if num is not greater than or less than middle value it is middle value
else:
return True
my_list = [1,2,3,4,5,6,7,8,9,10]
print(binary_search(my_list, 7)) #8,5,2 |
53e96c323ef35ff5e5843c9c8a362d0d0395d299 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/sort/c4c131b2-0058-4a25-9810-a563cdd7edfe__keynat.py | 504 | 3.765625 | 4 | def keynat(string):
r'''A natural sort helper function for sort() and sorted()
without using regular expression.
>>> items = ('Z', 'a', '10', '1', '9')
>>> sorted(items)
['1', '10', '9', 'Z', 'a']
>>> sorted(items, key=keynat)
['1', '9', '10', 'Z', 'a']
'''
r = []
for c in string:
try:
c = int(c)
try: r[-1] = r[-1] * 10 + c
except: r.append(c)
except:
r.append(c)
return r |
5f8535f2e7a3ed01d17d4330dd9aee2f2b09f005 | adityaskarnik/algorithms | /LinearSearch/linear_search.py | 527 | 3.984375 | 4 | def linearSearch(myList, myItem):
found = False
position = 0
while position < len(myList) and not found:
if myList[position] == myItem:
found = True
position = position + 1
return found
if __name__ == "__main__":
shopping = ["apples", "banana", "chocolate", "pasta"]
item = input("What item you want to find? " )
isFound = linearSearch(shopping, item)
if (isFound):
print("Item is found")
else:
print("Item not found") |
26a1610a1c7b729d15811798c8d45b8de5c18d54 | lizhenggan/TwentyFour | /01_Language/01_Functions/python/intval.py | 2,063 | 3.578125 | 4 | # coding: utf-8
def intval(var, base=10):
if isinstance(var, (int, float)):
return int(var)
elif isinstance(var, bool):
return 1 if var else 0
elif isinstance(var, (list, tuple, set, dict)):
return 0 if len(var) == 0 else 1
return int(var, base)
if __name__ == '__main__':
'''
// echo intval(42) . "\n"; // 42
// echo intval(4.2) . "\n"; // 4
// echo intval('42') . "\n"; // 42
// echo intval('+42') . "\n"; // 42
// echo intval('-42') . "\n"; // -42
// echo intval(042) . "\n"; // 34
// echo intval('042') . "\n"; // 42
// echo intval(1e10) . "\n"; // 10000000000
// echo intval('1e10') . "\n"; // 10000000000
// echo intval(0x1A) . "\n"; // 26
// echo intval(42000000) . "\n"; // 42000000
// echo intval(420000000000000000000) . "\n"; // -4275113695319687168
// echo intval('420000000000000000000') . "\n"; // 9223372036854775807
// echo intval(42, 8) . "\n"; // 42
// echo intval('42', 8) . "\n"; // 34
// echo intval(array()) . "\n"; // 0
// echo intval(array('foo', 'bar')) . "\n"; // 1
// echo intval(false) . "\n"; // 0
// echo intval(true) . "\n"; // 1
'''
print(intval(42))
print(intval(4.2))
print(intval('42'))
print(intval('+42'))
print(intval('-42'))
print(intval(0o42))
print(intval('042'))
print(intval(1e10))
# print(intval('1e10'))
print(intval(0x1A))
print(intval(42000000))
print(intval(420000000000000000000))
print(intval('420000000000000000000'))
print(intval(42, 8))
print(intval('42', 8))
print(intval([]))
print(intval(["foo", "bar"]))
print(intval(False))
print(intval(True))
|
4071169cfd65608f79e5df4935b44615083dcf4a | CodecoolBP20161/python-pair-programming-exercises-2nd-tw-adam_mentorbot | /palindrome/palindrome_module.py | 153 | 3.578125 | 4 | def palindrome(str):
str = str.replace(' ', '').lower()
return str == str[::-1]
def main():
return
if __name__ == '__main__':
main()
|
b4f0a6740fecf50ee54298b170bbe1b2def0735d | kaitorque/ProSolve | /Prosolve-4 2017/C. Alien Communicator/solution.py | 218 | 3.71875 | 4 |
T = int(input())
for i in range(T):
statement = input()
statement = statement.split(" ")
statement = statement[::-1] # reverse list
new_statement = ' '.join(statement)
print(new_statement) |
363f36ff7655aa0e07a3ccda6bf16364ed531f91 | FrankCasanova/Python | /Sentencias Condicionales/3.2.1-32.py | 243 | 3.609375 | 4 | #Programa de calculo de perimetro y área de un cuadrado con lados de 3 metros.
#datos
lado = 3
#fórmulas
perímetro = lado * 4
área = lado * lado
print('El perímetro del cuadrado es {0} y el lado es {1}'.format(perímetro, área))
|
4e83f0c54270e7dfdcea60260c1a5c47bc701a3c | psitronic/Applied-Cryptography | /One Time Pad/one_time_pad.py | 2,999 | 4.28125 | 4 | """
An implementation of the one-time pad encryption technique.
"""
def encode_message(msg, key, nbits):
"""
The function to encrypt a message
Takes three arguments:
string msg - a message to be encoded
string key - a key with the length len(msg) * nbits. If key == None
the function finds a pseudorandom key
integer nbits - number of bits for each symbol in the message
Returns an encrypted message as a string
"""
from random import randint
msg_in_bits = message_to_bits(msg, nbits)
if key == None:
key = [randint(0,1) for i in range(len(msg_in_bits))]
else:
if len(key) < len(msg_in_bits):
raise ValueError("The key should have the same size as, or longer than, the message.")
else:
key = list(map(int, key))
encoded_msg = [msg_in_bits[i]^key[i] for i in range(len(msg_in_bits))]
return {'msg':''.join(str(el) for el in encoded_msg), 'key':''.join(str(el) for el in key)}
def message_to_bits(msg, nbits):
"""
Converts each letter in message to binary format with nbits length
Takes msg as a string and nbits as an integer
Returns a binary representation of the message as an array
"""
msg_in_bits = []
for char in msg:
msg_in_bits += int_to_bits(char_to_int(char), nbits)
return msg_in_bits.copy()
def int_to_bits(n, pad):
"""
Converts the decimal char representation to the binary format
Takes an integer number n - a decimal code of a letter; integer pad is a number of bits
Returns an array
"""
result = [0] * pad
pos = pad - 1
while n > 0:
result[pos] = (0 if n % 2 == 0 else 1)
n = n//2
pos -= 1
return result.copy()
def char_to_int(char):
return ord(char)
def decode_msg(msg,key,nbits):
"""
The function to decrypt the message
Takes three arguments:
string msg - a message to be decoded
string key - a key with the length len(msg) * nbits. If key == None
the function finds a pseudorandom key
integer nbits - number of bits for each symbol in the message
Returns an decrypted message as a string
"""
decoded_msg = ""
msg_in_bits = [int(msg[i])^int(key[i]) for i in range(len(msg))]
for n in range(len(msg_in_bits)//nbits):
pad = msg_in_bits[n * 7: (n + 1) *7]
char_code = bits_to_int(pad,nbits)
decoded_msg += int_to_char(char_code)
return decoded_msg
def bits_to_int(msg_in_bits, nbits):
"""
The fucntion to conver a binary representation to decimal
"""
loc = nbits - 1
code = 0
for bit in msg_in_bits:
if bit == 1:
code += 2**loc
loc -= 1
return code
def int_to_char(code):
return chr(code)
enc_msg = encode_message(msg = 'AB', key = None, nbits = 7)
dec_msg = decode_msg(enc_msg['msg'],enc_msg['key'],7)
print(dec_msg) |
8b5c6733e7a74468c8965e93092cf6f68ccfde8f | ryan-c44/Python-Assignments | /Python Assignments/Assignment1.py | 4,255 | 4.375 | 4 | # Ryan Castles, 6433236, CSIT110
# Question 1
print("Question 1. \n")
#Get input from user for title and author.
song_title = input("Your favourite song title: ")
song_author = input("Your favourite song author: ")
print()
#print the string using string addition.
print("Using string addition")
print("Your favourite song is " + song_title + " by " + song_author + ".")
print()
# Question 2
print("Question 2. \n")
#Get input from user for 3 integers and convert to int.
first_integer = input("Please enter the 1st positive integer: ")
number1 = int(first_integer)
second_integer = input("Please enter the 2nd positive integer: ")
number2 = int(second_integer)
third_integer = input("Please enter the 3rd positive integer: ")
number3 = int(third_integer)
#Calculate the result
result = number1 * number2 * number3
print()
print("Display using string addition: ")
print("Equation: " + str(first_integer) + " x " + str(second_integer) + " x " + str(third_integer) + " = " + str(result))
print()
# Question 3
print("Question 3. \n")
#Get input from user for the first subject and convert credit to int.
first_code = input("Enter the 1st subject code: ")
first_title = input("Enter the 1st subject title: ")
first_credit_point = input("Enter the 1st subject credit point: ")
credit_value1 = int(first_credit_point)
print()
#Get input from user for the second subject and convert credit to int.
second_code = input("Enter the 2nd subject code: ")
second_title = input("Enter the 2nd subject title: ")
second_credit_point = input("Enter the 2nd subject credit point: ")
credit_value2 = int(second_credit_point)
print()
#Display chosen subjects.
print("Your chosen subjects:")
print(first_code + ": " + first_title)
print(second_code + ": " + second_title)
print("Total credit points: " + str(credit_value1 + credit_value2))
print()
# Question 4
print("Question 4. \n")
#Get input from user an convert to integer value.
one_hundred_level = input("How many 100-level subjects you have completed: ")
one_hundred_credit = int(one_hundred_level) * 4
two_hundred_level = input("How many 200-level subjects you have completed: ")
two_hundred_credit = int(two_hundred_level) * 5
three_hundred_level = input("How many 300-level subjects you have completed: ")
three_hundred_credit = int(three_hundred_level) * 6
#Calculations
subject_count = int(one_hundred_level) + int(two_hundred_level) + int(three_hundred_level)
total_credit = one_hundred_credit + two_hundred_credit + three_hundred_credit
print()
#print using formatting
print("{0:<8}{1:<13}{2:>10}".format("Level", "Subject Count", "Credit"))
print("{0:<8}{1:>13}{2:>10}".format("100", str(one_hundred_level), str(one_hundred_credit)))
print("{0:<8}{1:>13}{2:>10}".format("200", str(two_hundred_level), str(two_hundred_credit)))
print("{0:<8}{1:>13}{2:>10}".format("300", str(three_hundred_level), str(three_hundred_credit)))
print("{0:<8}{1:>13}{2:>10}".format("Total", str(subject_count), str(total_credit)))
print()
# Question 5
print("Question 5. \n")
#Grab user input for adult tickets and convert to int then format.
adult_tickets = input("How many adult tickets you want to order: ")
adult_cost = int(adult_tickets) * 50.5
formatted_adult_cost = "{:.2f}".format(adult_cost)
#User input for child over 10
child_over_ten = input("How many children (>=10 years old) tickets: ")
child_over_cost = int(child_over_ten) * 10.5
formatted_child_over = "{:.2f}".format(child_over_cost)
#User input for child under 10
child_under_ten = input("How many children (<10 years old) tickets: ")
child_under_cost = "free"
total_cost = "{:.2f}".format(adult_cost + child_over_cost)
#Calculate total tickets
total_tickets = int(adult_tickets) + int(child_over_ten) + int(child_under_ten)
print()
#Print using formatting.
print("{0:<18}{1:>17}{2:>15}".format("Type", "Number of tickets", "Cost"))
print("{0:<18}{1:>17}{2:>15}".format("Adult", str(adult_tickets), "$" + str(formatted_adult_cost)))
print("{0:<18}{1:>17}{2:>15}".format("Children (>=10)", str(child_over_ten),"$" + str(formatted_child_over)))
print("{0:<18}{1:>17}{2:>15}".format("Children (<10)", str(child_under_ten), child_under_cost))
print("{0:<18}{1:>17}{2:>15}".format("Total", str(total_tickets), "$" + str(total_cost)))
|
183dddd5ae142eb271ebcad4108d269faaff718e | delisco/algorithm | /sorts/selection_sort.py | 1,049 | 3.78125 | 4 | '''
@__date__ = 2020.02.29
@author = DeLi
'''
import time
def selection_sort(a_list):
"""
Pure implementation of bubble sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> selection_sort([0, 5, 2, 3, 2])
[0, 2, 2, 3, 5]
>>> selection_sort([])
[]
>>> selection_sort([-23, 0, 6, -4, 34])
[-23, -4, 0, 6, 34]
>>> selection_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
True
"""
list_length = len(a_list)
for i in range(list_length-1):
least = i
for k in range(i+1, list_length):
if a_list[k] < a_list[least]:
least = k
if least != i:
a_list[least], a_list[i] = a_list[i], a_list[least]
return a_list
if __name__ == "__main__":
start = time.process_time()
print(selection_sort([0, 5, 2, 3, 2]))
print(f"Processing time: {time.process_time() - start}")
|
8c2173c9ea29fde9bb4f38184e9a8132348b39dd | leewalter/coding | /python/hackerrank/collections.Counter.py | 875 | 3.71875 | 4 | '''
https://www.hackerrank.com/challenges/collections-counter/problem
'''
import math
import os
import random
import re
import sys
from collections import Counter
if __name__ == '__main__':
shoes_count = int(input())
shoes1 = map(int, input().rstrip().split()) # rem to convert from string to int for later matching in c.get
order_count = int(input())
c = Counter(shoes1)
#print(c)
total = 0
for i in range(order_count):
order, price = (map(int, input().rstrip().split()))
#print(order,price)
#print(c.get(order), 0)
if c.get(order, 0) != 0 : # has this size in inventory
total += price # tally up the total
c[order] -= 1 # reduce inventory of this size by 1
print (total)
'''
test case:
inputs:
10
2 3 4 5 6 8 7 6 5 18
6
6 55
6 45
6 55
4 40
18 60
10 50
output:
200
'''
|
fc02ef2dce4976b9f8e271d217bdc2d5cf7719e8 | gsakkas/seq2parse | /src/tests/parsing_test_41.py | 349 | 3.859375 | 4 | class Rect:
def __init__(self, l, b):
self.length = l
self.breadth = b
def area(self):
return self.length * self.breadth
# initialize a Rect object r1 with length 20 and breadth 10
r1 = Rect(20, 10)
r2 = Rect(40, 30)
print('area of r1 : ', r1.area()) # Rect.area(r1)
print('area of r2 : ', r2.area()) # Rect.area(r2)
|
a7d02b2c5a15c63370be6d8e168be499b389282d | Sergey0987/firstproject | /Архив/10_Okno.py | 305 | 3.78125 | 4 | n=int(input("Введите количество бутылок: "))
list1=[]
for i in range(n): # Создали список из бутылок
list1.append(int(input()))
list1=tuple(list1)
minim,maxim=int(input()),int(input())
for j in list1:
if j<=maxim and j>=minim:
print(j)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.