blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
5c12a749074258c3adc63a9a47a68692fb1739ee | IMAYousaf/Typing_Speed | /main.py | 1,317 | 3.859375 | 4 | import random
import time
import difflib
def main():
choice = input("Type in \"EASY\" or \"HARD\" based upon your desired difficulty level:")
if choice in {"EASY", "easy"}:
text = open("The_Arabian_Nights.txt").readlines()
selection = random.choice(text).strip()
word_count = len(selection.split())
elif choice in {"HARD", "hard"}:
with open("The_Arabian_Nights.txt") as paragraphs:
text = paragraphs.read()
selection = text.split('\n\n')
selection = random.choice(selection)
word_count = len(selection.split())
print(selection)
begin = time.time()
assessment = input()
end = time.time()
if assessment == selection:
print("Correct")
else:
print("Incorrect")
elapsed = end - begin
print(elapsed, "seconds have elapsed.")
print ("You type at a speed of", 60 * word_count / elapsed, "words per minute.")
file = open("test.txt", "w")
file.write(selection)
file.write("\n\n")
file.write(assessment)
d = difflib.Differ()
difference = d.compare(selection.split(), assessment.split())
file.write("\n")
file.write(str(''.join(difference)))
s = difflib.SequenceMatcher(None, selection, assessment)
print("You were", s.ratio() * 100, "% correct")
main()
|
077340fff43e14d6eafcd347accd28ca528d59b1 | minh-quang98/nguyenminhquang-fundamental-c4e20 | /Session01/Homework/converst_ex.py | 96 | 3.5625 | 4 | Cel = int(input("Enter the temperature in celsius?"))
Fah = Cel * 1.8 + 32
print(Cel, "=", Fah) |
f744d47fb116c2b92bfaa60a991a6c3b8e554a7d | kishirasuku/atcoder | /arc/002/b.py | 835 | 4.09375 | 4 | import calendar
def main():
today = raw_input()
today = today.split("/")
today = [int(s) for s in today ]
year,month,day = today
while True:
if daycheck(year,month,day):
print str(year) + "/" + format(int(month),'02d') + "/" + format(int(day),'02d')
break
else:
if day == calendar.monthrange(year,month)[1]:
day = 1
if month == 12 :
month = 1
year += 1
else:
month += 1
else:
day += 1
def daycheck(year,month,day):
if float(year % month) == 0 :
if float(year / month) % day == 0:
return True
else:
return False
else:
return False
main()
|
ae9cf8951de63c7f987f003eb9f492b9227c650a | udaykd09/Algorithms | /PowerSet.py | 450 | 3.71875 | 4 | def getSubsets(set, index=0):
allSets = []
if len(set) == index:
allSets.append([])
else:
allSets = getSubsets(set, index+1)
item = set[index]
moreSubsets = []
for subset in allSets:
newSubset = []
newSubset += subset
newSubset.append(item)
moreSubsets.append(newSubset)
allSets += moreSubsets
return allSets
print(getSubsets([1, 2, 3])) |
7e2f2b668467c044f634a4fa128650bdf4bebd91 | ricardorosa-dev/Curso-Trybe | /35.2_entrada_saida_arq/ex01.py | 93 | 3.859375 | 4 | nome = input("Qual é o seu nome?")
for letter in range(len(nome)):
print(nome[letter])
|
9de922ad0f8821a055959782334a797ff49f9c5e | texrer/Python | /CIS007/Lab1/Lab1_PrintFormat_RichardRogers.py | 104 | 4 | 4 | print("a a^2 a^3")
for x in range (1,5):
print (format(x, "<5d"), format(x**2, "<7d"), x**3) |
4097ed53e7d899e9518a2ca15ad7136361704f61 | thomasren681/MIT_6.0001 | /ps4/ps4b.py | 12,673 | 3.828125 | 4 | # Problem Set 4B
# Name: Thomas Ren
# Collaborators: None
# Time Spent: About 3 hours
import string
### HELPER CODE ###
import numpy as np
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
'''
print("Loading word list from file...")
# inFile: file
inFile = open(file_name, 'r')
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.extend([word.lower() for word in line.split(' ')])
print(" ", len(wordlist), "words loaded.")
return wordlist
def is_word(word_list, word):
'''
Determines if word is a valid word, ignoring
capitalization and punctuation
word_list (list): list of words in the dictionary.
word (string): a possible word.
Returns: True if word is in word_list, False otherwise
Example:
# >>> is_word(load_words('words.txt'), 'bat')
# True
# >>> is_word(load_words('words.txt'), 'asdf')
# False
'''
word = word.lower()
word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
return word in word_list
# if __name__ == '__main__':
# word_list = load_words('words.txt')
# print(is_word(word_list, 'dance'))
def get_story_string():
"""
Returns: a story in encrypted text.
"""
f = open("story.txt", "r")
story = str(f.read())
f.close()
return story
### END HELPER CODE ###
WORDLIST_FILENAME = 'words.txt'
WORD_LIST = load_words(WORDLIST_FILENAME)
class Message(object):
def __init__(self, text):
'''
Initializes a Message object
text (string): the message's text
a Message object has two attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper function load_words)
'''
self.message_text = text
self.valid_words = list(text.split(' '))
def get_message_text(self):
'''
Used to safely access self.message_text outside of the class
Returns: self.message_text
'''
return str(self.message_text)
def get_valid_words(self):
'''
Used to safely access a copy of self.valid_words outside of the class.
This helps you avoid accidentally mutating class attributes.
Returns: a COPY of self.valid_words
'''
return self.valid_words.copy()
def build_shift_dict(self, shift):
'''
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the alphabet by the input shift. The dictionary
should have 52 keys of all the uppercase letters and all the lowercase
letters only.
shift (integer): the amount by which to shift every letter of the
alphabet. 0 <= shift < 26
Returns: a dictionary mapping a letter (string) to
another letter (string).
'''
dict = {'a':string.ascii_lowercase[-shift], 'b':string.ascii_lowercase[-shift+1],'c':string.ascii_lowercase[-shift+2],
'd': string.ascii_lowercase[-shift+3],'e':string.ascii_lowercase[-shift+4],'f':string.ascii_lowercase[-shift+5],
'g': string.ascii_lowercase[-shift+6],'h':string.ascii_lowercase[-shift+7],'i':string.ascii_lowercase[-shift+8],
'j': string.ascii_lowercase[-shift+9],'k':string.ascii_lowercase[-shift+10],'l':string.ascii_lowercase[-shift+11],
'm': string.ascii_lowercase[-shift+12],'n':string.ascii_lowercase[-shift+13],'o':string.ascii_lowercase[-shift+14],
'p': string.ascii_lowercase[-shift+15],'q':string.ascii_lowercase[-shift+16],'r':string.ascii_lowercase[-shift+17],
's': string.ascii_lowercase[-shift+18],'t':string.ascii_lowercase[-shift+19],'u':string.ascii_lowercase[-shift+20],
'v': string.ascii_lowercase[-shift+21],'w':string.ascii_lowercase[-shift+22],'x':string.ascii_lowercase[-shift+23],
'y': string.ascii_lowercase[-shift+24],'z':string.ascii_lowercase[-shift+25],'A':string.ascii_uppercase[-shift],
'B':string.ascii_uppercase[1-shift],'C':string.ascii_uppercase[2-shift],'D':string.ascii_uppercase[3-shift],
'E': string.ascii_uppercase[4-shift],'F':string.ascii_uppercase[5-shift],'G':string.ascii_uppercase[6-shift],
'H': string.ascii_uppercase[7-shift],'I':string.ascii_uppercase[8-shift],'J':string.ascii_uppercase[9-shift],
'K': string.ascii_uppercase[10-shift], 'L': string.ascii_uppercase[11-shift],'M': string.ascii_uppercase[12-shift],
'N': string.ascii_uppercase[13-shift], 'O': string.ascii_uppercase[14-shift],'P': string.ascii_uppercase[15-shift],
'Q': string.ascii_uppercase[16-shift], 'R': string.ascii_uppercase[17-shift],
'S': string.ascii_uppercase[18-shift],
'T': string.ascii_uppercase[19-shift], 'U': string.ascii_uppercase[20-shift],
'V': string.ascii_uppercase[21-shift],
'W': string.ascii_uppercase[22-shift], 'X': string.ascii_uppercase[23-shift],
'Y': string.ascii_uppercase[24-shift],'Z': string.ascii_uppercase[25-shift],
}
return dict
def apply_shift(self, shift):
'''
Applies the Caesar Cipher to self.message_text with the input shift.
Creates a new string that is self.message_text shifted down the
alphabet by some number of characters determined by the input shift
shift (integer): the shift with which to encrypt the message.
0 <= shift < 26
Returns: the message text (string) in which every character is shifted
down the alphabet by the input shift
'''
shifted_list = []
dict = self.build_shift_dict(shift)
for letter in self.message_text:
if letter.isalpha():
shifted_list.append(dict.get(letter, 0))
else:
shifted_list.append(letter)
shifted_str = ''.join(shifted_list)
return shifted_str
# if __name__ == '__main__':
# a = Message('abcd efg')
# encrypted_a = Message(a.apply_shift(2))
# decrypted_a = encrypted_a.apply_shift(26-2)
# print(encrypted_a.get_message_text())
# print(decrypted_a)
class PlaintextMessage(Message):
def __init__(self, text, shift):
'''
Initializes a PlaintextMessage object
text (string): the message's text
shift (integer): the shift associated with this message
A PlaintextMessage object inherits from Message and has five attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper function load_words)
self.shift (integer, determined by input shift)
self.encryption_dict (dictionary, built using shift)
self.message_text_encrypted (string, created using shift)
'''
Message.__init__(self, text)
self.shift = shift
self.encryption_dict = Message(self.message_text).build_shift_dict(self.shift)
self.message_text_encrypted = Message(self.message_text).apply_shift(26-self.shift)
def get_shift(self):
'''
Used to safely access self.shift outside of the class
Returns: self.shift
'''
return self.shift
def get_encryption_dict(self):
'''
Used to safely access a copy self.encryption_dict outside of the class
Returns: a COPY of self.encryption_dict
'''
return self.encryption_dict.copy()
def get_message_text_encrypted(self):
'''
Used to safely access self.message_text_encrypted outside of the class
Returns: self.message_text_encrypted
'''
return self.message_text_encrypted
def change_shift(self, shift):
'''
Changes self.shift of the PlaintextMessage and updates other
attributes determined by shift.
shift (integer): the new shift that should be associated with this message.
0 <= shift < 26
Returns: nothing
'''
self.shift = shift
return self.shift
# if __name__ == '__main__':
# plaintext = PlaintextMessage('hello', 2)
# print('Expected Output: jgnnq')
# # print('Actual Output:', plaintext.get_message_text_encrypted())
# print(plaintext.get_message_text_encrypted())
class CiphertextMessage(Message):
def __init__(self, text):
'''
Initializes a CiphertextMessage object
text (string): the message's text
a CiphertextMessage object has two attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper function load_words)
'''
Message.__init__(self,text)
def decrypt_message(self):
'''
Decrypt self.message_text by trying every possible shift value
and find the "best" one. We will define "best" as the shift that
creates the maximum number of real words when we use apply_shift(shift)
on the message text. If s is the original shift value used to encrypt
the message, then we would expect 26 - s to be the best shift value
for decrypting it.
Note: if multiple shifts are equally good such that they all create
the maximum number of valid words, you may choose any of those shifts
(and their corresponding decrypted messages) to return
Returns: a tuple of the best shift value used to decrypt the message
and the decrypted message text using that shift value
'''
NUM_WORDS = []
text = self.message_text
# text_list = self.valid_words
# word_list = load_words('words.txt')
for shift in range(26):
shifted_text = Message(text).apply_shift(shift)
shifted_text_list = list(shifted_text.split(' '))
temp = []
for word in shifted_text_list:
temp.append(is_word(WORD_LIST, word))
NUM_WORDS.append(sum(temp))
best_shift = np.argmax(NUM_WORDS)
decrypted_message = Message(self.message_text).apply_shift(best_shift)
return (26-best_shift, decrypted_message)
if __name__ == '__main__':
story = get_story_string()
encrypted_story = CiphertextMessage(story)
decrypted_story = encrypted_story.decrypt_message()
print(decrypted_story)
######################################################################################
#Here is the decrypted story
# 'Jack Florey is a mythical character created on the spur of a moment to help cover an insufficiently planned hack.
# He has been registered for classes at MIT twice before, but has reportedly never passed aclass.
# It has been the tradition of the residents of East Campus to become Jack Florey for a few nights
# each year to educate incoming students in the ways, means, and ethics of hacking.'
#####################################################################################
# #Example test case (PlaintextMessage)
# plaintext = PlaintextMessage('hello', 2)
# print('Expected Output: jgnnq')
# print('Actual Output:', plaintext.get_message_text_encrypted())
#
# #Example test case (CiphertextMessage)
# ciphertext = CiphertextMessage('jgnnq')
# print('Expected Output:', (24, 'hello'))
# print('Actual Output:', ciphertext.decrypt_message())
#TODO: WRITE YOUR TEST CASES HERE
#TODO: best shift value and unencrypted story
# test_text = 'abc def cat g.'
# test_text = Message(test_text)
# encrypted_text = test_text.apply_shift(3)
# print(encrypted_text)
# encrypted_text = CiphertextMessage(encrypted_text)
# decrypted_list = encrypted_text.decrypt_message()
# print(decrypted_list)
|
dc7a8b03fe4a24ae53d659b0a68d3230596af6e6 | varma1096/Python--CSEE5590-490 | /icp1/r1.py | 442 | 3.984375 | 4 | import random
gen_num = random.randint(0, 9)
while (1):
i_num = int(input('Enter a number which is in range of 0 to 9'))
if(gen_num == i_num):
print('perfect , guessed mumber is equal to the generated number')
break
elif(gen_num < i_num) :
print (' your number is greater than generated /expected number')
elif(gen_num > i_num) :
print (' your number is less than generated/expected number')
|
62f1913eda6e5f9985be25d62f7b16de82a94d74 | Gliklex/YPetrov_10_02_02 | /task_10_02_02_pizza.py | 5,345 | 3.59375 | 4 | # Программирование на языке высокого уровня (Python).
# https://www.yuripetrov.ru/edu/python
# Задание task_10_02_02.
#
# Выполнил: Фамилия И.О.
# Группа: !!!
# E-mail: !!!
class Пицца:
"""Класс Пицца содержит общие атрибуты для пиццы.
Дочерние классы будут их конкретизировать.
"""
def __init__(self):
"""Конструктор класса.
Инициализирует атрибуты пиццы (значения по умолчанию).
"""
self.название = "Заготовка"
self.тесто = "тонкое" # тонкое или пышное
self.соус = "кетчуп" # или другой
self.начинка = [] # список начинок (по умолчанию - нет)
self.цена = 0
def __str__(self):
"""Вернуть информацию о пицце: название, тесто, соус, начинка.
Формат вывода:
Пицца: Пепперони | Цена: 350.00 р.
Тесто: тонкое Соус: томатный
Начинка: пепперони, сыр моцарелла
"""
return "Пицца: {} | цена: {:.2f} р. \n Тесто: {} Соус: {} \n Начинка: {}"\
.format(self.название, self.цена, self.тесто, self.соус, self.начинка)
# Уберите raise и добавьте необходимый код
def подготовить(self):
"""Сообщить о процессе подготовки.
Формат вывода:
Начинаю готовить пиццу Пепперони
- замешиваю тонкое тесто...
- добавляю соус: томатный...
- и, конечно: пепперони, сыр моцарелла...
"""
return f'Начинаю готовить пиццу {self.название}\n' \
f' - замешиваю {self.тесто} тесто...\n' \
f' - добавляю соус: {self.соус}...\n' \
f' - и, конечно: {self.начинка}...'
# Уберите raise и добавьте необходимый код
def испечь(self):
"""Сообщить о процессе запекания пиццы.
Формат вывода: произвольное сообщение.
"""
return "Выпекаю пиццу... Готово!"
# Уберите raise и добавьте необходимый код
def нарезать(self):
"""Сообщить о процессе нарезки.
Формат вывода: произвольное сообщение.
"""
return "Нарезаю на кусочки..."
# Уберите raise и добавьте необходимый код
def упаковать(self):
"""Сообщить о процессе упаковки.
Формат вывода: произвольное сообщение.
"""
return "Упаковываю в фирменную упаковку и готово!"
# Уберите raise и добавьте необходимый код
class ПиццаПепперони(Пицца):
"""Класс ПиццаПепперони дополняет класс Пицца."""
def __init__(self):
super().__init__()
self.название = "Пепперони"
self.тесто = "тонкое" # тонкое или пышное
self.соус = "кетчуп" # или другой
self.начинка = "пепперони, сыр моцарелла" # список начинок
self.цена = 350
# Уберите raise и добавьте необходимый код
class ПиццаБарбекю(Пицца):
"""Класс ПиццаБарбекю дополняет класс Пицца."""
def __init__(self):
super().__init__()
self.название = "Барбекю"
self.тесто = "тонкое" # тонкое или пышное
self.соус = "барбекю" # или другой
self.начинка = "бекон, ветчина, зелень, сыр моцарелла" # список начинок
self.цена = 450
# Уберите raise и добавьте необходимый код
class ПиццаДарыМоря(Пицца):
"""Класс ПиццаДарыМоря дополняет класс Пицца."""
def __init__(self):
super().__init__()
self.название = "ДарыМоря"
self.тесто = "тонкое" # тонкое или пышное
self.соус = "Тар-тар" # или другой
self.начинка = "кальмары, креветки, мидии, сыр моцарелла" # список начинок
self.цена = 550
# Уберите raise и добавьте необходимый код
|
6e6efa2cd5c9dbcee684fbcd710d1ea0e508bbc7 | aadhi24/my-python-codes | /project 2 (tip calculation).py | 498 | 4 | 4 | #this code written by aadithyan
print("welcome to tip calculator")
bill_amount = float(input("what is the total bill? $"))
percentage_tip =float(input("what percentage tip would you like to give? 10 , 12 or 15 "))
split_bill = int(input("how many people to split the bill? : "))
per_tip = percentage_tip /100
mult_per_bill = bill_amount * per_tip
main_per_tip = mult_per_bill + bill_amount
split_bill = main_per_tip /split_bill
round_number = round(split_bill,2)
print(f"${round_number}") |
52df5ce0e9041403fcb78412bed84f68fd8cd53d | facaiy/book_notes | /leetcode/knapsack_0_1.py | 724 | 3.65625 | 4 | #!/usr/bin/env python
import numpy as np
def knapsack(data, max_weight):
if not data: return None
rows = max_weight + 1
cols = len(data[0]) + 1
dp = np.zeros((rows, cols))
for w in range(1, rows):
for n in range(1, cols):
id_ = n - 1
if data[0][id_] > w:
dp[w][n] = dp[w][n-1]
else:
weight = data[0][id_]
value = data[1][id_]
dp[w][n] = max(dp[w-weight][n-1] + value,
dp[w][n-1])
# print(dp)
return int(max(dp[-1]))
if __name__ == "__main__":
data = [[10, 20, 30], # weight
[60, 100, 120]] # value
print(knapsack(data, 50))
|
ba67e4c4674f5099fa6d6fadebbc1a7f46634e34 | Ronnieyang97/notes | /py_training/most-far-can-reach.py | 1,294 | 3.59375 | 4 | # .机器人的运动范围
# 题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,
# 但是不能进入行坐标和列坐标的数位之和大于k的格子。请问该机器人能够达到多少个格子?
def farest(m, n, k): # 获取棋盘的大小,和k的大小
m, n = str(m), str(n)
x, y = '', ''
loc_m, loc_n = 0, 0
while k > 0 and loc_m < len(m) and loc_n < len(n):
if int(m[loc_m]) + int(n[loc_n]) > k:
if m[loc_m] > n[loc_n]:
m = m[:loc_m] + str(int(m[loc_m])-1) + m[loc_m+1:]
else:
n = n[:loc_n] + str(int(n[loc_n])-1) + n[loc_n+1:]
continue
else:
x += m[loc_m]
y += n[loc_n]
k -= (int(m[loc_m]) + int(n[loc_n]))
loc_m += 1
loc_n += 1
x, y = int(x), int(y)
while len(str(x)) < len(m):
x *= 10
while len(str(y)) < len(n):
y *= 10
return x, y
# 发现了一个很严重的问题,如果要抵达(100,100)必须经过(99, 100)或(100,99),如果数位之和的上限k为12,则(100,100)符合条件但是前一个点不合符条件,程序有误
|
e780d7256717917f5d769ba68218068a244d28ed | foTok/data_driven_diagnosis | /bpsk_navigate/msg_generator.py | 765 | 3.59375 | 4 | """
this module generate msg randomly
"""
import fractions
import numpy as np
class Msg:
"""
Msg generate msg randomly
"""
def __init__(self, code_rate=None, sample_rate=None):
self.code_rate = 1023000 if code_rate is None else code_rate
self.sample_rate = self.code_rate * 10 if sample_rate is None else sample_rate
self.initial_time = fractions.Fraction(0)
self.msg = -1
def sample(self, time):
"""
sample a point randomly
"""
time_step = fractions.Fraction(1, self.code_rate)
if (time - self.initial_time) > time_step:
self.msg = 1 if np.random.random() < 0.5 else -1
self.initial_time = self.initial_time + time_step
return self.msg
|
5724e2d7f2e36197df1d1ff332b18e1d04277db1 | ctefaniv/Homework | /HW7/cw1.py | 272 | 3.765625 | 4 | def count_positives_sum_negatives(arr):
positives = []
negatives = []
for i in arr:
if i > 0:
positives.append(i)
elif i < 0:
negatives.append(i)
return [len(positives), sum(negatives)] if arr != [] else [] |
aa82ac04921b5ccd2ecdfb3d78f9c13dc4b18ba7 | wizardshowing/pyctise | /cal_evaluator.py | 2,053 | 3.765625 | 4 | #
# This is an example of how to evaluate expressions
#
class ExpNode(object):
def __init__(self, name, left, right):
self.name = name
self.left = left
self.right = right
def _evaluate_child(self, child):
if child:
return child.evaluate()
else:
return None
def evaluate(self):
left_value = self._evaluate_child(self.left)
right_value = self._evaluate_child(self.right)
return self._eval(left_value, right_value)
def _eval(self, left_value, right_value):
raise NotImplementedError()
def __str__(self):
return '({} {} {})'.format(self.left, self.name, self.right)
def __repr__(self):
return str(self)
class AddExpNode(ExpNode):
def __init__(self, left, right):
super().__init__('+', left, right)
def _eval(self, left_value, right_value):
return left_value + right_value
class SubExpNode(ExpNode):
def __init__(self, left, right):
super().__init__('-', left, right)
def _eval(self, left_value, right_value):
return left_value - right_value
class MulExpNode(ExpNode):
def __init__(self, left, right):
super().__init__('*', left, right)
def _eval(self, left_value, right_value):
return left_value * right_value
class DivExpNode(ExpNode):
def __init__(self, left, right):
super().__init__('/', left, right)
def _eval(self, left_value, right_value):
return left_value / right_value
class ValueNode(ExpNode):
def __init__(self, value):
super().__init__(str(value), None, None)
def _eval(self, left_value, right_value):
return float(self.name)
def __str__(self):
return self.name
if __name__ == '__main__':
# parsed AST of (1 + 5 - 2) * 3 / 4
add = AddExpNode(ValueNode(1), ValueNode(5))
sub = SubExpNode(add, ValueNode(2))
mul = MulExpNode(sub, ValueNode(3))
root = DivExpNode(mul, ValueNode(4))
print(root)
print(root.evaluate()) |
7804dbebe2f68198efbff2ac189edb06a1631fec | AKASHRANA931/Python-Program-Akash-Rana- | /add.py | 88 | 3.796875 | 4 | a = int(input("Enter the number"))
b = int(input("Enter the number"))
p = a + b
print(p) |
2fde54c4ca1d41c52ae10af5041fa5f7ed31dd6b | Chaitalk-csk/test | /hungry.py | 123 | 4.03125 | 4 | r = input("are you hungry? answer yes or no?")
if r == "yes":
print("Eat Pav bhaji!!")
else:
print("do your work")
|
ce61eb9622e047c217b5d8ce56066aba325b05d7 | CodingMarathon/All_Algorithm | /HMM/hmm.py | 10,573 | 3.71875 | 4 | """
@author:CodingMarathon
@date:2020-03-18
@blog:https://blog.csdn.net/Elenstone/article/details/104902120
"""
from typing import List, Any
import numpy as np
import random
class HMM(object):
def __init__(self, n, m, a=None, b=None, pi=None):
# 可能的隐藏状态数
self.N = n
# 可能的观测数
self.M = m
# 状态转移概率矩阵
self.A = a
# 观测概率矩阵
self.B = b
# 初始状态概率矩阵
self.Pi = pi
# 观测序列
self.X = None
# 状态序列
self.Y = None
# 序列长度
self.T = 0
# 定义前向算法
self.alpha = None
# 定义后向算法
self.beta = None
def forward(self, x):
"""
前向算法
计算给定模型参数和观测序列的情况下,观测序列出现的最大概率
:param x: 观测序列
:return: 观测值
"""
# 序列长度
self.T = len(x)
self.X = np.array(x)
# alpha是一个具有T行N列的矩阵
self.alpha = np.zeros((self.T, self.N))
# 初始状态
for i in range(self.N):
self.alpha[0][i] = self.Pi[i] * self.B[i][self.X[0]]
# 递推
for t in range(1, self.T):
for i in range(self.N):
probability_sum = 0
for j in range(self.N):
probability_sum += self.alpha[t - 1][j] * self.A[j][i]
self.alpha[t][i] = probability_sum * self.B[i][self.X[t]]
# 终止
return sum(self.alpha[self.T - 1])
def backward(self, x):
"""
后向算法
"""
# 序列长度
self.T = len(x)
self.X = np.array(x)
# beta是一个T行N列的矩阵
self.beta = np.zeros((self.T, self.N))
# 当t=T时,置值为1
for i in range(self.N):
self.beta[self.T - 1][i] = 1
# 从t=T-1递推到t=1
for t in range(self.T - 2, -1, -1):
for i in range(self.N):
for j in range(self.N):
self.beta[t][i] += self.A[i][j] * self.B[j][self.X[t + 1]] * self.beta[t + 1][j]
# 终止
sum_probability = 0
for i in range(self.N):
sum_probability += self.Pi[i] * self.B[i][self.X[0]] * self.beta[0][i]
return sum_probability
def calculate_gamma(self, t, i):
"""
给定模型参数和观测序列,计算在t时刻处于状态q_i的概率
:param i: 状态
:param t: 时刻
:return: 时刻t处于状态i的概率
"""
# 分子
numerator = self.alpha[t][i] * self.beta[t][i]
# 分母
denominator = 0
for j in range(self.N):
denominator += self.alpha[t][j] * self.beta[t][j]
return numerator / denominator
def calculate_xi(self, t, i, j):
"""
给定模型参数和观测序列,在时刻t处于状态q_i且时刻t+1处于状态q_j的概率
:param i: 时刻t的状态
:param j: 时刻t+1的状态
:param t: 时刻t
:return: 在时刻t处于状态q_i且时刻t+1处于状态q_j的概率
"""
# 分子
numerator = self.alpha[t][i] * self.A[i][j] * self.B[j][self.X[t + 1]] * self.beta[t + 1][j]
# 分母
denominator = 0
for i in range(self.N):
for j in range(self.N):
denominator += self.alpha[t][i] * self.A[i][j] * self.B[j][self.X[t + 1]] * self.beta[t + 1][j]
return numerator / denominator
def init(self):
"""
训练时初始化HMM模型
"""
self.A = np.zeros((self.N, self.N))
self.B = np.zeros((self.N, self.M))
self.Pi = np.zeros(self.N)
def train(self, train_data):
"""
训练模型,使用最大似然估计
:param train_data: 训练数据,每一个样本:[观测值,隐藏状态值]
:return: 返回一个HMM模型
"""
self.T = int(len(train_data[0]) / 2)
sample_num = len(train_data)
# 初始化
self.init()
# 初始状态概率矩阵的估计
for sequence in train_data:
self.Pi[sequence[0 + self.T]] += 1
self.Pi = self.Pi / sample_num
# 状态转移矩阵的估计
a_num = np.zeros((self.N, self.N))
for sequence in train_data:
for i in range(self.T - 1):
a_num[sequence[i + self.T]][sequence[i + 1 + self.T]] += 1.0
temp = a_num.sum(axis=1).reshape((3, 1))
self.A = a_num / temp
# 发射概率矩阵的估计
b_num = np.zeros((self.N, self.M))
for sequence in train_data:
for i in range(self.T - 1):
b_num[sequence[i + self.T]][sequence[i]] += 1.0
temp = b_num.sum(axis=1).reshape((3, 1))
self.B = b_num / temp
def baum_welch(self, x, criterion=0.001):
self.T = len(x)
self.X = x
while True:
# 为了得到alpha和beta的矩阵
_ = self.forward(self.X)
_ = self.backward(self.X)
xi = np.zeros((self.T - 1, self.N, self.N), dtype=float)
for t in range(self.T - 1):
# 笨办法
# for i in range(self.N):
# gamma[t][i] = self.calculate_gamma(t, i)
# for j in range(self.N):
# xi[t][i][j] = self.calculate_psi(t, i, j)
# for i in range(self.N):
# gamma[self.T-1][i] = self.calculate_gamma(self.T-1, i)
# numpy矩阵的办法
denominator = np.sum(np.dot(self.alpha[t, :], self.A) *
self.B[:, self.X[t + 1]] * self.beta[t + 1, :])
for i in range(self.N):
molecular = self.alpha[t, i] * self.A[i, :] * self.B[:, self.X[t+1]]*self.beta[t+1, :]
xi[t, i, :] = molecular / denominator
gamma = np.sum(xi, axis=2)
prod = (self.alpha[self.T-1, :]*self.beta[self.T-1, :])
gamma = np.vstack((gamma, prod / np.sum(prod)))
new_pi = gamma[0, :]
new_a = np.sum(xi, axis=0) / np.sum(gamma[:-1, :], axis=0).reshape(-1, 1)
new_b = np.zeros(self.B.shape, dtype=float)
for k in range(self.B.shape[1]):
mask = self.X == k
new_b[:, k] = np.sum(gamma[mask, :], axis=0) / np.sum(gamma, axis=0)
if np.max(abs(self.Pi - new_pi)) < criterion and \
np.max(abs(self.A - new_a)) < criterion and \
np.max(abs(self.B - new_b)) < criterion:
break
self.A, self.B, self.Pi = new_a, new_b, new_pi
def viterbi(self, x):
self.X = x
self.T = len(x)
self.Y = np.zeros(self.N)
# 初始化delta和xi
delta = np.zeros((self.T, self.N))
psi = np.zeros((self.T, self.N))
# 初始化,t=1时
for i in range(self.N):
delta[0][i] = self.Pi[i] * self.B[i][self.X[0]]
psi[0][i] = 0
# 递推
for t in range(1, self.T):
for i in range(self.N):
temp = 0
index = 0
for j in range(self.N):
if temp < delta[t - 1][j] * self.A[j][i]:
temp = delta[t - 1][j] * self.A[j][i]
index = j
delta[t][i] = temp * self.B[i][self.X[t]]
psi[t][i] = j
# 最终
self.Y[-1] = delta.argmax(axis=1)[-1]
p = delta[self.T - 1][int(self.Y[-1])]
# 回溯
for i in range(self.T - 1, 0, -1):
self.Y[i - 1] = psi[i][int(self.Y[i])]
return p, self.Y
def generate_train_data(n, m, t, a, b, pi, nums=10000):
"""
生成训练数据
:param pi: 初始状态概率矩阵
:param b: 发射概率矩阵
:param a: 状态转移矩阵
:param n: 隐藏状态数量
:param m:观测值数量
:param t: 序列长度
:param nums: 样本数量
:return: 训练数据集
"""
train_data = []
for i in range(nums):
state_sequence = []
observation_sequence = []
# 初始状态
temp = 0
p = random.random()
for j in range(n):
temp += pi[j]
if p > temp:
continue
else:
state_sequence.append(j)
break
# 递推
for t_index in range(t):
# 生成状态
if t_index != 0:
temp = 0
p = random.random()
for state in range(n):
temp += a[state_sequence[-1]][state]
if p > temp:
continue
else:
state_sequence.append(state)
break
# 生成观测序列
temp = 0
p = random.random()
for observation in range(m):
temp += b[state_sequence[-1]][observation]
if p > temp:
continue
else:
observation_sequence.append(observation)
break
observation_sequence.extend(state_sequence)
train_data.append(observation_sequence)
return train_data
if __name__ == '__main__':
q = [1, 2, 3]
v = ["红", "白"]
n = len(q)
m = len(v)
x = ["红", "白", "红"]
# 建立一个字典
char_to_id = {}
id_to_char = {}
for i in v:
char_to_id[i] = len(char_to_id)
id_to_char[char_to_id[i]] = i
X = [char_to_id[i] for i in x]
a = np.array([[0.5, 0.2, 0.3],
[0.3, 0.5, 0.2],
[0.2, 0.3, 0.5]])
b = np.array([[0.5, 0.5],
[0.4, 0.6],
[0.7, 0.3]])
pi = np.array([0.2, 0.4, 0.4])
# hmm = HMM(n, m, a, b, pi)
# print(hmm.backward(X))
# 预测
# 产生数据
# train_data = generate_train_data(n, m, 8, a, b, pi)
# print(train_data)
# hmm = HMM(n, m)
# hmm.train(train_data)
# print(hmm.Pi)
# print(hmm.A)
# print(hmm.B)
# # 使用维特比
# hmm = HMM(n, m, a, b, pi)
# p, y = hmm.viterbi(X)
# print(p)
# print(y)
# 使用baum-welch
hmm = HMM(n, m, a, b, pi)
hmm.baum_welch(X)
|
ad0a43440ee229ebf6a918b63f72205f06d63409 | araschermer/python-code | /algorithms_and_data_structures/linked_lists/remove_nth_element.py | 1,289 | 4.375 | 4 | from linked_lists_util import print_linked_list, insert_list, Node
class LinkedList:
def __init__(self):
self.head = None
def remove_nth_node_from_end(self, n: int):
"""Removes the node at the nth position from the end of the linked list."""
pointer1 = self.head
pointer2 = self.head
for _ in range(n + 1):
# move the second pointer to be distant by n+1 positions from the first pointer
pointer2 = pointer2.next_node
# move the second pointer to the end of the list
while pointer2 is not None:
pointer2 = pointer2.next_node
pointer1 = pointer1.next_node
# after the while loop , pointer 2 is pointing at none
# and pointer 1 is at element before the nth position from the end of the linked list
# remove the element at the nth position from the list
temp = pointer1.next_node
pointer1.next_node = None
pointer1.next_node = temp.next_node
return self
if __name__ == '__main__':
linked_list = LinkedList()
insert_list(linked_list, [1, 1, 1, 1, 1, 1, 1, 1, -10, 'element_to_remove', 3, 4, 8])
print_linked_list(linked_list)
linked_list.remove_nth_node_from_end(4)
print_linked_list(linked_list)
|
c50da511eb3a90f61e8003ec59f7b4f4b9f32fe8 | fdm1/Euler | /python/solved/01.py | 419 | 3.78125 | 4 | # /*************************************
# *
# * Find the sum of all the multiples of 3 or 5 below 1000
# *
# **************************************/
import time
from functools import reduce
start_time = time.time()
nums = list(filter(lambda x: x % 3 == 0 or x % 5 == 0, range(0,1000)))
res = reduce(lambda x,y: x + y, nums)
print("answer: %s\n\n--- Complete in %s seconds ---" % (res, time.time() - start_time))
|
63ac37df5e490e1d2ebd6933986c9555b189bd92 | fishla1202/hometest | /q1.py | 284 | 3.765625 | 4 | def fib(n):
f = dict()
f[0] = 1
f[1] = 1
f[2] = 2
if n == 0 or n == 1:
return 1
elif n == 2:
return 2
for i in range(3, n + 1):
f[i] = f[i - 1] + f[i - 2] + f[i - 3]
return f[n]
if __name__ == '__main__':
print(fib(5))
|
5004c69f8b7a2a22c952482a9db1c06773b5c1b4 | cnlong/everyday_python | /06_day_important-word/test3.py | 1,150 | 3.65625 | 4 | from collections import Counter
import re
import string
import os
def get_word(txtFile):
'''
从一个txt文件中找出出现次数最高的词及其对应次数,以元组形式返回
'''
# 过滤词
stop_word = ['the', 'in', 'of', 'and', 'to', 'has', 'that', 'this', 's', 'is', 'are', 'a', 'with', 'as', 'an']
f = open(txtFile, 'r', encoding="UTF-8")
content = f.read().lower()
pat = '[a-z0-9\']+'
words = re.findall(pat, content)
wordList = Counter(words)
for i in stop_word:
wordList[i] = 0
f.close()
return wordList.most_common()[0]
def traverseFile(path):
'''
遍历路径文件夹中的所有文件,并调用get_word函数,输出统计结果
'''
for txtName in os.listdir(path):
txtFile = os.path.join(path, txtName)
# 调用get_word函数
most_important = get_word(txtFile)
print(most_important[0] + ' is the most important word in the essay:' + txtName)
print('the using times of ' + most_important[0] + " is:" + repr(most_important[1]))
print("")
if __name__ == "__main__":
traverseFile(r'diary')
|
901d488e2bd0a60b19c245e20da0d1c4d13e7001 | danong/leetcode-solutions | /solutions/longest_repeating_character_replacement.py | 944 | 3.578125 | 4 | """https://leetcode.com/problems/longest-repeating-character-replacement/description/"""
from collections import defaultdict
class Solution:
def characterReplacement(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
if not s:
return 0
char_counts = defaultdict(int)
start = end = length = 0
while end < len(s):
end_char = s[end]
char_counts[end_char] += 1
end += 1
counter = end - start - max(char_counts.values())
while counter > k:
start_char = s[start]
char_counts[start_char] -= 1
start += 1
counter = end - start - max(char_counts.values())
length = max(length, end - start)
return length
a = Solution()
print(a.characterReplacement('ABAB', 2))
print(a.characterReplacement('AABABBA', 1))
|
4701acc8e7509159cefe8c87a50657059e090a49 | JhonEddi/Repaso-de-pyhon | /ejercicio 80.py | 92 | 3.703125 | 4 | def fibonacci (n):
if n<=2:
return 1;
if n>2:
return fibonacci(n-1)+fibonacci(n-2) |
8bdf9d4ac5cf8550415016a5d7f7bb7923b0c684 | vito-dante/Days-Boring | /python_examples/fibonacci.py | 402 | 4.0625 | 4 |
# def fibonacci(number: int) -> int:
# if(number <= 1):
# return 1
# else:
# return fibonacci(number - 1) + fibonacci(number - 2)
# print(fibonacci(9))
from typing import Iterator
def fib(n: int) -> Iterator[int]:
a,b = 0,1
while a<n:
yield a
a, b = b, a + b
for item in fib(9):
print(item)
def greet(name: str) -> str:
return "Hi "+ name
|
86cef72772541d7f5650e1a2df1c63e871635a17 | uycuhnt2467/-offer | /從尾到頭列印list.py | 731 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 8 15:31:51 2021
@author: a8520
"""
# 是否能改變原始list?
# 後進先出 -> stack
class Node():
def __init__(self, val, next_ = None):
self.val = val
self.next= next_
def hasNext(self):
if (self.next) == None:
return False
else:
return True
node5 = Node(5)
node4 = Node(3, node5)
node3 = Node(11, node4)
node2 = Node(2, node3)
node1 = Node(1, node2)
def reversePrint(node):
stack = []
cur = node
while cur.hasNext():
stack.append(cur)
cur = cur.next
stack.append(cur)
while stack:
cur_node = stack.pop()
print(cur_node.val)
# reversePrint(node1)
|
6cf3cdc83b1e001d2f4ff275f489dfa035452986 | theunkn0wn1/uci-bootcamp-2021 | /uci_bootcamp_2021/examples/mistaking_equality_for_assigment.py | 785 | 4.0625 | 4 | """
uci_bootcamp_2021/examples/mistaking_equality_for_assigment.py
Demonstrates the common beginner error of mistaking `==` equality for `=` assignment.
WARNING: this file will not run and nor should it be used in any downstream applications,
as it contains intentionally invalid syntax.
"""
# NOTE: Do not mistake the equality operator `==` for the assignment operator `=`
x = 42
y = 42
# Demonstrate comparing two variables by equality
if x == y:
print("x and y are equivalent!")
else:
print("x and y are not equivalent!")
z = 17
# NOTE: The following line is erroneous; and is included for demonstration purposes ONLY.
# NOTE: Most linters will throw a warning / error here!
if x = z:
print("x and y are equivalent!")
else:
print("x and y are not equivalent!")
|
1d746c2dc234ecb6ac17952f30adf04f4ba49689 | JaksoSoftware/jakso-ml | /jakso_ml/utils/rect_utils.py | 355 | 3.828125 | 4 | def intersection(r1, r2):
'''
Intersection of two rectangles
'''
x1, y1, w1, h1 = r1
x2, y2, w2, h2 = r2
x = max(x1, x2)
y = max(y1,y2)
w = min(x1 + w1, x2 + w2) - x
h = min(y1 + h1, y2 + h2) - y
if w <= 0 or h <= 0:
return (0, 0, 0, 0)
return (x, y, w, h)
def area(r):
'''
Area of a rectangle
'''
return r[2] * r[3]
|
a1d6f11a72622f75207f88599ab6a486203d7b96 | shirleymramirez/ProblemSet2_PayingDebtOffInAYear | /ProblemSet2_PayingDebtOffinaYear.py | 869 | 4.375 | 4 | outstandingBalance = float(raw_input('Enter the outstanding balance on your credit card: '))
annualInterestRate = float(raw_input('Enter the annual interest rate as a decimal: '))
""" Calculates the minimum fixed monthly payment needed in order to pay off credit card balance within
12 months. Not Dealing with a minimum monthly payment rate."""
minMonthlyPayment = 0
monthlyInterestRate = annualInterestRate/12
balance = outstandingBalance
while balance > 0:
balance = outstandingBalance
month = 0
minMonthlyPayment += 10
while balance > 0 and month < 12:
balance = balance*(1+monthlyInterestRate) - minMonthlyPayment
month += 1
balance = round(balance, 2)
print 'RESULT'
print 'Monthly payment to pay off debt in 1 year: ' , minMonthlyPayment
print 'Number of months needed: ', month
print 'Balance: ', balance
|
54d5fc3467314edadf86700b688043b6ca539400 | eneajorgji/programowanieObiektowe | /wyklad_2.py | 830 | 3.578125 | 4 | class Auto:
licznik = 0
def __init__(self, silnik, rok, marka): # self odnosi sie do obiektu
self.silnik = silnik
self.rok = rok
self.marka = marka
self.public, self._protected, self.__private = 8, 10, 20
Auto.licznik += 1
def __del__(self):
Auto.licznik -= 1
def print(self):
print(f"Auto ma {self.silnik}, zostal wyprodukoway w {self.rok} jest marki {self.marka}")
@staticmethod
def ile_auto():
return Auto.licznik
car_1 = Auto(1.5, 2011, "Toyota")
car_2 = Auto(2.0, 1997, "Audi")
car_3 = Auto(1.1, 2016, "Fiat")
# Mozna teraz dodac metody
car_1.print()
car_2.print()
car_3.print()
print(car_1.marka)
print(car_1.public)
print(car_1._protected)
print(car_1._Auto__private)
car_3 = None
print(f"Liczba aut jest: {Auto.ile_auto()}")
|
9b0b36fd3400269cf662c11b322b7fc8b08ece13 | eduard-netsajev/Personal-Practice | /Python/Games/2ndDrawing.py | 2,583 | 3.765625 | 4 | __author__ = 'Netšajev'
import random
import math
import pygame
pygame.init()
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
pi = 3.141592653
size = [700, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Eduard's Cool Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
time = 0
while not done:
# --- Main event loop
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
# --- Game logic should go here
time += 0.1
# --- Drawing code should go here
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
screen.fill(BLACK)
#Drawing
pygame.draw.rect(screen, WHITE, [20, 20, 250, 100], 3)
pygame.draw.ellipse(screen, RED, [20, 20, 250, 100], 3)
pygame.draw.arc(screen, GREEN, [20, 20, 250, 100], pi/3, 4*pi/3, 5)
pygame.draw.arc(screen, GREEN, [100,200,250,100], pi/2, pi, 2)
pygame.draw.arc(screen, WHITE, [100,200,250,100], 0, pi/2, 2)
pygame.draw.arc(screen, RED, [100,200,250,100],3*pi/2, 2*pi, 2)
pygame.draw.arc(screen, BLUE, [100,200,250,100], pi, 3*pi/2, 50)
# This draws a triangle using the polygon command
pygame.draw.polygon(screen, WHITE, [[300,300], [200,400], [400,400]], 5)
pygame.draw.polygon(screen, (160, 100, 190), [[310, 10], [330, 120], [390, 180], [440, 150], [350, 50]], 5)
# Select the font to use, size, bold, italics
font = pygame.font.SysFont('Calibri', 25, True, False)
# Render the text. "True" means anti-aliased text.
# Green is the color. The variable GREEN was defined above
# Note: This line creates an image of the letters,
# but does not put it on the screen yet.
output_string = "Time: {:.6}".format(time)
text = font.render(output_string, True, GREEN)
# Put the image of the text on the screen at 250x250
screen.blit(text, [250, 250])
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit() |
ffef9333bf3de98de111bea5e89167b4ce7abbc6 | mauleypeach/pythonthehardway | /learnpythonthehardwayorg/ex.py/ex17.py | 643 | 3.625 | 4 | from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
in_data = open(from_file).read()
print "The input file is %d bytes" %len(in_data)
print "Does the output file exist %r" % exists(to_file)
print "Does the input file exist %r" %exists(from_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
print (in_data)
out_file = open(to_file,'w')
out_file.write(in_data)
print (out_file)
print "Alright, all done."
out_file.close()
# The line below is not require because python already closes the file.
#from_close = open(from_file).close()
|
84bdbbff05f16c1fdf99e58696e64992efd84bdb | here0009/LeetCode | /Python/1540_CanConvertStringinKMoves.py | 2,881 | 3.9375 | 4 | """
Given two strings s and t, your goal is to convert s into t in k moves or less.
During the ith (1 <= i <= k) move you can:
Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.
Do nothing.
Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times.
Remember that any index j can be picked at most once.
Return true if it's possible to convert s into t in no more than k moves, otherwise return false.
Example 1:
Input: s = "input", t = "ouput", k = 9
Output: true
Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.
Example 2:
Input: s = "abc", t = "bcd", k = 10
Output: false
Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.
Example 3:
Input: s = "aab", t = "bbb", k = 27
Output: true
Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.
Constraints:
1 <= s.length, t.length <= 10^5
0 <= k <= 10^9
s, t contain only lowercase English letters.
"""
# from collections import Counter
class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
if len(s) != len(t):
return False
move_dict = {}
for s_l, t_l in zip(s, t):
if s_l != t_l:
move = (ord(t_l) - ord(s_l)) % 26
if move in move_dict:
move_dict[move] += 26
else:
move_dict[move] = move
if move_dict[move] > k:
return False
# print(move_dict)
# print(len(s), len(move_dict))
return True
class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
cnt = [0] * 26
for cs, ct in zip(s, t):
diff = (ord(ct) - ord(cs)) % 26
if diff > 0 and cnt[diff] * 26 + diff > k:
return False
cnt[diff] += 1
return len(s) == len(t)
S = Solution()
s = "input"
t = "ouput"
k = 9
print(S.canConvertString(s, t, k))
s = "abc"
t = "bcd"
k = 10
print(S.canConvertString(s, t, k))
s = "aab"
t = "bbb"
k = 27
print(S.canConvertString(s, t, k))
s = "jicfxaa"
t ="ocxltbp"
k = 15
print(S.canConvertString(s, t, k))
s ="mygdwuntwkoc"
t ="btydmdiatnhx"
k = 48
print(S.canConvertString(s, t, k))
# def move(s, t):
# move = (ord(t) - ord(s)) % 26
# return move
# print(move('a', 'z'))
# print(move('a', 'b'))
# print(move('b', 'a'))
# print(move('z', 'a'))
|
1648870dd600b282f7d08cd0ca262a239592f1cf | nena6/Python-Tutorial | /exercises_10.py | 1,969 | 3.6875 | 4 | import string
#Exercise 1
fname = input('Enter a file name: ')
try:
myfile = open(fname)
except:
print('File cannot be opened.')
exit()
words = []
senders = dict()
for line in myfile:
if not line.startswith('From'):
continue
words = line.split()
if len(words) > 2:
senders[words[1]] = senders.get(words[1], 0) + 1
# def cb(key):
# return senders[key]
#max_sender = max(senders, key=lambda key: senders[key])
#print(max_sender, senders[max_sender])
sender_list = list()
for sender, count in list(senders.items()):
sender_list.append((count, sender))
sender_list.sort(reverse=True)
print(sender_list[0][1], sender_list[0][0])
#Exercise 2
fname = input('Enter a file name: ')
try:
myfile = open(fname)
except:
print('File cannot be opened.')
exit()
words = []
hours = dict()
for line in myfile:
if not line.startswith('From'):
continue
words = line.split()
if len(words) > 5:
words = words[5].split(':')
hours[words[0]] = hours.get(words[0], 0) + 1
hours_list = list(hours.items())
hours_list.sort()
for hour,count in hours_list:
print(hour, count)
#Exercise 3
fname = input('Enter a file name: ')
try:
myfile = open(fname)
except:
print('File cannot be opened.')
exit()
count = dict()
total = 0
for line in myfile:
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
for c in word:
if c.isalpha():
count[c] = count.get(c, 0) + 1
total += 1
# for letter in count:
# if total > 0:
# print('Letter: %s %g%%' % (letter, count[letter]*100/total))
letter_list = list()
for letter, cnt in list(count.items()):
letter_list.append((cnt, letter))
letter_list.sort(reverse=True)
for cnt, letter in letter_list:
if total > 0:
print('Letter: %s %g%%' % (letter, cnt*100/total))
|
5cc32150ae561a890f85589723a57e9603467cdf | rLoopTeam/eng-embed-sim | /code_samples/tkinter/tkinter_grid_matplotlib.py | 1,914 | 3.53125 | 4 | # @see http://www.tkdocs.com/tutorial/grid.html
#from Tkinter import *
import ttk
import Tkinter as tk
root = tk.Tk()
content = ttk.Frame(root)
frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=600, height=300)
namelbl = ttk.Label(content, text="Name")
name = ttk.Entry(content)
onevar = tk.BooleanVar()
twovar = tk.BooleanVar()
threevar = tk.BooleanVar()
onevar.set(True)
twovar.set(False)
threevar.set(True)
one = ttk.Checkbutton(content, text="One", variable=onevar, onvalue=True)
two = ttk.Checkbutton(content, text="Two", variable=twovar, onvalue=True)
three = ttk.Checkbutton(content, text="Three", variable=threevar, onvalue=True)
ok = ttk.Button(content, text="Okay")
cancel = ttk.Button(content, text="Cancel", command=root.quit)
content.grid(column=0, row=0)
frame.grid(column=0, row=0, columnspan=3, rowspan=2)
namelbl.grid(column=3, row=0, columnspan=2)
name.grid(column=3, row=1, columnspan=2)
one.grid(column=0, row=3)
two.grid(column=1, row=3)
three.grid(column=2, row=3)
ok.grid(column=3, row=3)
cancel.grid(column=4, row=3)
#root.mainloop()
# ----------
import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
#import Tkinter as Tk
import sys
f = Figure(figsize=(4,2), dpi=100)
a = f.add_subplot(1, 1, 1)
######################
# the networkx part
import networkx as nx
G=nx.path_graph(8)
pos=nx.spring_layout(G)
nx.draw(G,pos,ax=a)
######################
# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=frame)
canvas.show()
#canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
canvas.get_tk_widget().grid()
#toolbar = NavigationToolbar2TkAgg( canvas, root )
#toolbar.update()
#canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
# -----------
print "Got to the main loop..."
tk.mainloop() |
e03f35ac1bd806baaf86dfc1249b7e77cdc71e8d | huyquangbui/buiquanghuy-fundamental-c4e23 | /session2/hw/se1.py | 331 | 4.0625 | 4 | h = int(input("your height in cm: "))
h1 = h/100
print("which is",h1,"in m")
w = int(input("your weight in kg: "))
BMI = w/h1**2
if BMI < 16:
print("severly underweight")
elif BMI < 18.5:
print("underweight")
elif BMI < 25:
print("normal")
elif BMI < 30:
print("overweight")
else:
print("obese")
print("bye") |
5911aa7ac34e627253367cdd4925f1aff96605d7 | Gunnstein/fastlib | /fastlib/_template.py | 3,303 | 3.71875 | 4 | # -*- coding: utf-8 -*-
import string
__all__ = ["TemplateStringFormatter", "TemplateFileFormatter"]
class TemplateStringFormatter(object):
fmt_dict = {}
def __init__(self, template_str):
"""Use a template from a string
Load a template string and substitute the
template keys with property values of this class.
Assume that the following template string is defined
a = ${a}
b = ${b}
then instanciate the TemplateStringFormatter and add properties
corresponding to the template keys (${}) found in the template file.
>>> ft = FileTemplater("template.txt")
>>> ft.a = 9
>>> ft.b = "hello"
you can then return the template string with the property values
substituted for the template keys by the substitute method
>>> ft.substitute()
a = 9
b = hello
it is also possible to write the substitute results directly to a file
>>> ft.write("result.txt")
and the "result.txt" file will contain
a = 9
b = hello
Arguments
---------
template_str : str
A template string where ${key} is to substituted with the `key`
property value.
"""
self.template = string.Template(template_str)
def str_formatter(self, key, val):
try:
fmt = self.fmt_dict[key]
except KeyError:
fmt = "{0:>11}"
sval = str(val)
if isinstance(val, float):
if val > 1e6:
sval = '{0:.5E}'.format(val)
try:
s_fmt = fmt.format(sval)
except TypeError:
s_fmt = None
return s_fmt
def substitute(self):
out_dict = {key: self.str_formatter(key, val)
for key, val in self.__dict__.items()}
try:
return self.template.substitute(**out_dict)
except KeyError as e:
print(
"{0}Error: key {1} found in template but not as property of {0}.".format(
self.__class__.__name__, e))
def write(self, filename):
with open(filename, 'w+') as fout:
fout.write(self.substitute())
class TemplateFileFormatter(TemplateStringFormatter):
def __init__(self, filename):
"""Use a template from a text file.
Load a template file from a text file and substitute the
template keys with property values of this class.
Assume that a template file "template.txt" exists with the following
content
a = ${a}
b = ${b}
then instanciate the TemplateFileFormatter and add properties
corresponding to the template keys (${}) found in the template file.
>>> ft = FileTemplater("template.txt")
>>> ft.a = 9
>>> ft.b = "hello"
>>> ft.write("result.txt")
then the "result.txt" file will contain
a = 9
b = hello
Arguments
---------
filename : str
Filename of the template file.
"""
with open(filename, 'r') as fin:
super(TemplateFileFormatter, self).__init__(fin.read()) |
026beb0b9c6f43099f5f641e0efc485476fdef42 | ealexisaraujo/basicoPython | /dictionary_comprehension.py | 596 | 3.84375 | 4 | # -*- coding: utf-8 -*-
def listComprehension():
pares = []
for num in range(1, 31):
if num % 2 == 0:
pares.append(num)
print(pares)
def comprehension():
even = [num for num in range(1, 31) if num % 2 == 0]
print(even)
def cuaddrados():
cuadrados = {}
for num in range(1, 11):
cuadrados[num] = num**2
def squares():
square = {num: num**2 for num in range(1, 11)}
print(square)
if __name__ == '__main__':
# print(listComprehension())
# print(comprehension())
# print(cuaddrados())
print(squares())
|
27684781cc1a1ca2797ffa3ab31521cbbcdbdd50 | bapata/PYTHON | /kaprekarno.py | 938 | 3.671875 | 4 | #!/usr/bin/python
import sys
## Kaprekar's number 6174
def high_to_low(n):
n_as_str=str(n)
slist = sorted(n_as_str)
slist.reverse()
sdigit_str = ''.join(slist)
return int(sdigit_str)
def low_to_high(n):
n_as_str=str(n)
slist = sorted(n_as_str)
sdigit_str = ''.join(slist)
return int(sdigit_str)
# main
def main():
if len(sys.argv)!=2:
print "USAGE: kaprekarno.py <4-digit-number>"
sys.exit(1)
n=int(sys.argv[1])
if (n<1000) or (n>9999):
print "Digit has to be between 1000 and 9999 .."
exit(1)
KNUM=6174
print "You started with initial number = " + str(n)
while(n!=KNUM):
a=high_to_low(n)
print "high_to_low: " + str(a)
b=low_to_high(n)
print "low_to_high: " + str(b)
n=a-b
if(n<=0):
print "digits should be unique, please try again"
exit(1)
print "intermediate number is: " + str(n)
print "We have hit kaprekars number: " + str(n)
main()
|
f6ccddf53374d0d077cb97ba80d6312692a2c56b | Emma-ZSS/repo-zhong253 | /repo-zhong253/homeworks/HW2/HW2_A.py | 597 | 4.03125 | 4 | #CSCI1133,Lab Section 004,HW2 Shanshan Zhong,Problem2A
import math
# Define the poiseuille function
def poiseuille(L,r,n):
return((8*n*L)/((math.pi)*(r**4)))
# Define the main function
def main(L,r,n):
if (L > 0) and (r >0) and (n > 0):
print('The resistance is: ', poiseuille(L,r,n))
else:
print('Failed due to input error. Please make sure your inputs are all positive. Exiting program.')
# Input and run funtions
L = float(input('Please enter the length: '))
r = float(input('Please enter the radius: '))
n = float(input('Please enter the viscosity: '))
main(L,r,n)
|
e40039d7e7f579d7760b4c87ee012d4419e4b1d7 | jennyChing/onlineJudge | /10696.py | 367 | 3.53125 | 4 | def f91(N,memo):
if N in memo:
return memo[N]
if N <= 100:
memo[N] = f91(f91((N+11),memo),memo)
elif N >= 101:
ans = N - 10
memo[N] = ans
return memo[N]
if __name__ == '__main__':
memo = {}
while True:
try:
value = int(input())
if value == 0:
break
N = f91(value,memo)
print("f91(",value,") = ", N,sep='')
except(EOFError):
break
|
89ba2990eb1dd2cf3821cb5915130c0cb488dcee | navneethkour/LeetCode-Python-1 | /Number/PowerOfThree.py | 405 | 3.875 | 4 | import math
class Solution(object):
def isPowerOfThree1(self, n):
return math.log10(n) // math.log10(3) % 1 == 0
def isPowerOfThree2(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 1: return False
if n == 1: return True
while n > 1:
if n % 3 != 0:
return False
n //= 3
return True |
ffab7845fe7f06d3cb03205e49dc2c4e0b829cc6 | neitan626/prova_algoritmos2 | /Furadeira.py | 1,292 | 3.71875 | 4 | from Ferramenta import Ferramenta
class Furadeira(Ferramenta):
def __init__(self,nome,tensao,preco,potencia):
self._nome = nome
self._tensao = tensao
self._preco = preco
self._potencia = potencia
@property
def nome(self):
return self._nome
@nome.setter
def nome(self,valor):
self._nome = valor
@property
def tensao(self):
return self._tensao
@tensao.setter
def tensao(self,valor):
self._tensao = valor
@property
def preco(self):
return self._preco
@preco.setter
def preco(self,valor):
self._preco = valor
@property
def potencia(self):
return self._potencia
@potencia.setter
def potencia(self,valor):
self._potencia = valor
def getImprimir(self):
print("--Furadeira--")
print("nome:",self._nome)
print("tensao:",self._tensao)
print("preco:",self._preco)
print("potencia:",self._potencia)
def cadastrar(self):
print("--------------------")
print("nome:",self._nome)
print("tensao:",self._tensao)
print("preco:",self._preco)
print("potencia:",self._potencia)
print("Furadeira cadastrada com sucesso!")
|
06c293fa107acca8cd5d7a2efda5dd256b4582d8 | schraderSimon/FYS-STK | /project1/code/testfunksjoner.py | 2,287 | 3.75 | 4 | import numpy as np
from small_function_library import *
tol=1e-12
def test_matrix_creation():
"""Test whether the Design Matrix is set up properly"""
testmatrix=np.zeros((3,6))
x=np.array([0,1,2])
y=np.array([1,2,3])
testmatrix[:,0]=1;
testmatrix[:,1]=y;
testmatrix[:,2]=x;
testmatrix[:,3]=x**2;
testmatrix[:,4]=x*y;
testmatrix[:,5]=y**2;
calc_matrix=DesignMatrix_deg2(y,x,2,include_intercept=True)
for i in range(3):
for j in range(6):
assert abs(calc_matrix[i,j]-testmatrix[i,j])<tol
def test_linear_regression():
"""Test wether OLS is correctly implemented using a simple straight function"""
test_alpha=0.3
test_beta=0.7
x=np.linspace(-5,5,100)
y=test_alpha*x+test_beta
X=DesignMatrix(x,2) # create a fit where we expect the coefficient for X**2 to be zero
beta,betavar=LinearRegression(X,y)
assert abs(beta[0]-test_beta)<tol
assert abs(beta[1]-test_alpha)<tol
assert abs(beta[2])<tol
def test_ridge():
"""Test wether Ridge is correctly implemented using a simple straight function at lambda=0"""
test_alpha=0.3
test_beta=0.7
x=np.linspace(-5,5,100)
y=test_alpha*x+test_beta
X=DesignMatrix(x,2)
beta,betavar=RidgeRegression(X,y,0)
assert abs(beta[0]-test_beta)<tol
assert abs(beta[1]-test_alpha)<tol
assert abs(beta[2])<tol
def test_lasso():
"""Test wether Lasso is correctly implemented using a simple straight function at lambda=0 (even though it doesn't work well)"""
test_alpha=0.3
test_beta=0.7
x=np.linspace(-5,5,100)
y=test_alpha*x+test_beta
X=DesignMatrix(x,2)
beta=LASSORegression(X,y,0,tol=tol,iter=1e5)
assert abs(beta[0]-test_beta)<tol
assert abs(beta[1]-test_alpha)<tol
assert abs(beta[2])<tol
def test_R2():
"""Test wether the R2 score of to identical arrays is equal to one"""
y=np.random.randn(1000)
ystrek=np.copy(y)
assert abs(R2(ystrek,y)-1)<tol
def test_MSE():
"""Test wether the MSE sore of to identical arrays is equal to zero"""
y=np.random.randn(1000)
ystrek=np.copy(y)
assert abs(MSE(ystrek,y))<tol
test_matrix_creation()
test_linear_regression()
test_ridge()
test_lasso()
test_R2()
test_MSE()
"""
run as: python3 testfunksjoner.py
"""
|
f0043c939697a60d8ae9de9dd259b0087d65f48e | kene111/DS-ALGOS | /Hackerrank and Leetcode/Kadane's algorithm.py | 1,404 | 3.953125 | 4 | """
def max_subarray(numbers):
best_sum = 0
current_sum = 0
for x in numbers:
current_sum = max(0, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
"""
'''
def max_subarray(numbers):
best_sum = 0
best_start = 0
best_end = 0
current_sum = 0
for current_end, x in enumerate(numbers):
if current_sum <= 0:
current_start = current_end
current_sum = x
else:
current_sum += x
if current_sum > best_sum:
best_sum = current_sum
best_start = current_start
best_end = current_end + 1
return best_sum, best_start, best_end
'''
''' SAMMAD'S SOLUTION
def max_subarray(nums):
best_sum = nums[0]
current_sum = nums[0]
for x in nums[1:]:
if current_sum <= 0:
current_sum = x
else:
current_sum += x
if current_sum > best_sum:
best_sum = current_sum
return best_sum
'''
# MY SOLUTION
def max_subarray(nums):
best_sum = 0
current_sum = 0
for x in nums:
if current_sum <= 0:
current_sum = x
else:
current_sum += x
if current_sum > best_sum:
best_sum = current_sum
return best_sum
array1 = [-1]
array = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
check = max_subarray(array1)
print(check)
|
08316a51bcb2bca6ead20fc240a9437c74159be2 | lcsdn/RL-alphazero | /RLcode/data_structures/tree.py | 1,111 | 4 | 4 | class DictTreeNode:
"""
Define a tree data structure, whose children are encoded in a dictionary
and whose value at each node is also encoded in a dictionary.
Instantiate a tree by its root node.
"""
def __init__(self, dict_value, parent=None, children=None):
self._dict = dict_value
self.parent = parent
if children is None:
self.children = {}
def __len__(self):
return len(self.children)
def __getitem__(self, key):
return self._dict[key]
def __setitem__(self, key, value):
self._dict[key] = value
def get(self, key, default=None):
return self._dict.get(key, default)
def add_children_values_dict(self, children_values_dict):
for key, value in children_values_dict.items():
self.children[key] = DictTreeNode(value, parent=self)
def isroot(self):
return self.parent is None
def isleaf(self):
return len(self.children) == 0
def __repr__(self):
return f'{self._dict} {list(self.children.keys())}' |
85e181019e9c92aeb22acc165c8a8ea725f61d58 | jaford/thissrocks | /Python_Class/py3intro3day/EXAMPLES/sequence_operators.py | 650 | 3.90625 | 4 | #!/usr/bin/env python
colors = ["red", "blue", "green", "yellow", "brown", "black"]
months = (
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
)
print("yellow in colors: ", ("yellow" in colors)) # <1>
print("pink in colors: ", ("pink" in colors))
print("colors: ", ",".join(colors)) # <2>
del colors[4] # remove brown <3>
print("removed 'brown':", ",".join(colors))
colors.remove('green') # <4>
print("removed 'green':", ",".join(colors))
sum_of_lists = [True] + [True] + [False] # <5>
print("sum of lists:", sum_of_lists)
product = [True] * 5 # <6>
print("product of lists:", product)
|
27d9ab2b5a11c523ded85d12138ea1b58705326f | CodeNovice2017/Python-Studying | /链表,单双链表,循环链表.py | 2,512 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author:CodeMonster
@file: 链表,单双链表,循环链表.py
@time: 2017/10/13 10:26
"""
class LNode:
def __init__(self,elem,next_=None):
self.elem = elem
self.next = next_
# list1 = LNode(1)
# q = list1
# for i in range(2,11):
# q.next = LNode(i)
# q = q.next
#
# q = list1
# while q is not None:
# print(q.elem)
# q = q.next
class LinkekListUnderFlow(ValueError):
pass
class LList:
def __init__(self):
self._head = None
def is_empty(self):
return self._head is None
def prepend(self,elem):
self._head = LNode(elem,self._head)
def pop(self):
if self._head is None:
raise LinkekListUnderFlow("in pop")
e = self._head.elem
self._head = self._head.next
return e
def append(self,elem):
if self._head is None:
self._head = LNode(elem)
p = self._head
while p.next is not None:
p = p.next
p.next = LNode(elem)
def pop_last(self,elem):
if self._head is None:
raise LinkekListUnderFlow("in pop_last")
p = self._head
if p.next is None:
e = p.elem
self._head = None
return e
if p.next.next is not None:
p = p.next
e = p.next.elem
p.next = None
return e
def find(self, pred):
p = self._head
while p is not None:
if pred(p.elem):
return p.elem
p = p.next
def printall(self):
p = self._head
while p is not None:
print(p.elem)
if p.next is not None:
print(",")
p = p.next
print('')
#传统技术,优点是比较规范,缺点是不够灵活,不容易与其他编程机制配合
def for_each(self,proc):
p = self._head
while p is not None:
proc(p.elem)
p = p.next
#为了解决,人们经常使用lamda表达式顶指出在这里使用的操作函数
def elements(self):
p = self._head
while p is not None:
yield p.elem
p = p.next
# for x in list1.element()
# print(x)
def filter(self,pred):
p = self._head
while p is not None:
if pred(p.elem):
yield p.elem
p = p.next
|
8a35979e7887c2ee166a60c145e3300a4b1f7cbd | imagine5am/project-euler | /p006.py | 141 | 3.53125 | 4 | square_of_sum = sum(range(101)) ** 2
sum_of_square = 0
for i in range(101):
sum_of_square += i ** 2
print(square_of_sum - sum_of_square)
|
5073516df87a481f1cc2e0d9167361f6423023fd | whencespence/python | /unit-3/dictionary.py | 1,036 | 4.3125 | 4 | # Dictionary and key/value pairs
student = {'name': 'Christina', 'age': '10', 'city': 'Toronto'}
# Access elements in dictionary using dictionary name followed by key
print(student['name'], student['age'], student['city'])
# Dictionary cannot have duplicate keys
car = {} # creates empty dictionary
car['make'] = 'Toyota' # adding items to dictionary...
car['model'] = 'Prius'
car['year'] = 2019
car['color'] = 'silver'
for item in car:
print(item) # prints keys
print(car[item]) # prints values
# List of dictionaries
cars = [
{'year': '2000', 'make': 'Toyota', 'colour': 'black'},
{'year': '2001', 'make': 'Ford', 'colour': 'white'},
{'year': '2002', 'make': 'Acura', 'colour': 'red'},
{'year': '2003', 'make': 'Toyota', 'colour': 'red'}
]
# print(cars[0]) # print by index
total = 0
for car in cars:
if car['make'] == 'Toyota':
total += 1
print(total)
print(student.keys())
print(student.values())
print(student.items())
for key, value in student.items(): # returns/iterates over compound values
print(key, value) |
c05c8cb0164d17a5561254bf64cf8da926420af9 | Seo-GwangHyeon/Code-Test-for-Job | /studied/1st Assingment/Other/crane.py | 617 | 3.5625 | 4 |
def solution(board, moves):
depth =len(board)
arr=[]
answer=0
for move in moves:
for i in range(depth):
if board[i][move-1]>0:
arr.append(board[i][move-1]);
board[i][move - 1]=0
if len(arr)>=2 :
if arr[len(arr)-2]==arr[len(arr)-1]:
arr.pop()
arr.pop()
answer += 2;
break;
return answer
print(solution(
[[0,0,0,0,0],
[0,0,1,0,3],
[0,2,5,0,1],
[4,2,4,4,2],
[3,5,1,3,1]],
[1,5,3,5,1,2,1,4] ))
|
9233b3922e6af26df8553e9dd2be5fa728b6fd4c | daddyawesome/CodingP | /OOP/ooprobot.py | 271 | 3.75 | 4 | class Robot:
def introduce_self(self):
print("My name is "+ self.name) # This in Java
r1 =Robot()
r1.name = "Tom"
r1.color = "Red"
r1.weight = 30
r2=Robot()
r2.name = "Jerry"
r2.color = "Blue"
r2.weight = 40
r1.introduce_self()
r2.introduce_self()
|
da234f9de093d6347a3781c1bd3843680471a2f3 | kanishkd4/Python_Learning_code | /Datacamp - Intro to python/Python Lists.py | 3,030 | 4.5 | 4 | # area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50
# Create list areas
areas = [hall, kit, liv, bed, bath]
# Print areas
print(areas)
# Adapt list areas
areas = ["hallway", hall, "kitchen", kit, "living room", liv, "bedroom", bed, "bathroom", bath]
# Print areas
print(areas)
# List of lists
# house information as list of lists
house = [["hallway", hall],
["kitchen", kit],
["living room", liv],
["bedroom", bed], ["bathroom", bath]]
# Print out house
print(house)
# Print out the type of house
type(house)
# Subsetting lists
# Python indexes start with 0; unlike R where indexes start with 1
# negetive indexes start with -1 (for the last entry)
# list slicing: subsetting a list as a list
# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Print out second element from areas
print(areas[1])
# Print out last element from areas
print(areas[-1])
# Print out the area of the living room
print(areas[5])
# Sum of kitchen and bedroom area: eat_sleep_area
eat_sleep_area = areas[3] + areas[7]
# Print the variable eat_sleep_area
print(eat_sleep_area)
# Slicing and dicing
# Use slicing to create downstairs
downstairs = areas[0:6]# does not include the last one!
# Use slicing to create upstairs
upstairs = areas[6:10]
# Print out downstairs and upstairs
print(downstairs); print(upstairs)
# Alternative slicing to create downstairs
downstairs = areas[:6]# does not include the last one!
# Alternative slicing to create upstairs
upstairs = areas[6:]
# Replace list elements
# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
# Correct the bathroom area
areas[9] = 10.50
# Change "living room" to "chill zone"
areas[4] = "chill zone"
# Create the areas list and make some changes
areas = ["hallway", 11.25, "kitchen", 18.0, "chill zone", 20.0,
"bedroom", 10.75, "bathroom", 10.50]
# Add poolhouse data to areas, new list is areas_1
areas_1 = areas + ["poolhouse", 24.5]
# Add garage data to areas_1, new list is areas_2
areas_2 = areas_1 + ["garage", 15.45]
# Deleting elements. as soon as elements are deleted, the list indexes change
# Inner working of lists
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Create areas_copy
areas_copy = areas # the two are linked
# Change areas_copy
areas_copy[0] = 5.0 # This also changes areas! so damn weird
# Print areas
print(areas)
# to prevent a change in area_copy from affecting area, we need to do a more
# explicit copy of areas
`# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Create areas_copy; create a deep copy using list() or :
areas_copy = areas[:]
# Change areas_copy
areas_copy[0] = 5.0
# Print areas
print(areas)
|
049125c00f7225fced51ef74321ce4e77ff3c03c | nervig/Starting_Out_With_Python | /Chapter_10_programming_tasks/algorithmic_simulator_2.py | 819 | 3.859375 | 4 | class Book:
def __init__(self, title, name_of_author, name_of_make):
self.__title = title
self.__name_of_author = name_of_author
self.__name_of_make = name_of_make
def set_title(self, title):
self.__title = title
def set_name_of_author(self, name_of_author):
self.__name_of_author = name_of_author
def set_name_of_make(self, name_of_make):
self.__name_of_make = name_of_make
def get_title(self):
return self.__title
def get_name_of_author(self):
return self.__name_of_author
def get_name_of_make(self):
return self.__name_of_make
def __str__(self):
return "Title: " + self.__title + \
"\nName of author: " + self.__name_of_author + \
"\nName of maker: " + self.__name_of_make
|
64210fd61ac05184c4f48f7777bc16052742c4a3 | Dosache/RepositorioPython006 | /ciclosfor1.py | 616 | 3.78125 | 4 | import os
par=0
impar=0
cont = 0
for x in range(10):
print("")
print("Ingrese el digito numero",cont)
num = int(input())
if num%2==0:
print("")
print("El numero es par")
par = par+1
cont = cont+1
else:
print("")
print("Es impar")
impar = impar+1
cont = cont+1
x = x+1
print("")
print("La cantidad de numeros pares es: "+str(par))
print("La cantidad de numeros impares es: "+str(impar))
print("")
#el + se ocupa para concadenar con la palabra str o int, y con comas se utiliza la variable sin la necesidad de escribir str o int |
2c60e84b81b8efad867d28bdde4bfc2f9288fdde | asperaa/programming_problems | /dp/house_robber_1d_dp.py | 347 | 3.515625 | 4 | """House Robber. 1D DP. Time - O(n). Space - O(n)"""
def max_loot(nums):
length = len(nums)
dp = [None] * (length + 1)
dp[0] = 0
dp[1] = nums[0]
for i in range(2, length + 1):
dp[i] = max(nums[i-1]+ dp[i-2], dp[i-1])
return dp[length]
if __name__ == "__main__":
arr = [1, 2, 3, 1]
print(max_loot(arr))
|
a6ac912f19232bfd806d5205e312386daac11202 | linuxheels/linuxheels | /udemy_learning/random_int.py | 324 | 4.15625 | 4 | import random
#This will create a random whole number
#random_integer = random.randint(1, 10)
#print(random_integer)
#random.random() -> Returns the next random floating point number between [0.0 to 1.0)
#This will create a random float, which is a *.* type of number
random_float = random.random() * 5
print(random_float) |
ce7de0a325b38ed36556404a56e200d8b0b03cc4 | Bsmurfy/DNAalignment | /SequenceAlignment.py | 7,495 | 3.5625 | 4 | '''
Brendan Murphy
A program to globally align multiple DNA sequences from a FASTA file.
'''
def main():
match = 5
mismatch = -4
gap = -11
# read the FASTA file
fastafull = readfasta('MidCS4.fasta')
numofseq = min(4, len(fastafull)) # allows up to four DNA sequences, for now
dnalist = []
for i in range(0, numofseq):
dnasequence = fastafull[i][2]
dnalist.append(dnasequence)
# run alignment loop until only one sequence is left
while (numofseq > 1):
candidates = [] # initialize/clear candidates list
# make list of DNA sequences from FASTA file
for seq1 in dnalist:
for seq2 in dnalist:
if (dnalist.index(seq2) > dnalist.index(seq1)):
candidates = align(candidates, seq1, seq2, match, mismatch, gap)
scores = []
# form list of scores to determine max (best) alignment score
for candidate in candidates:
scores.append(int(candidate[1]))
bestscore = max(scores)
print('test')
for candidate in candidates:
if (candidate[1] == bestscore):
dnalist.insert(0, candidate[0]) # add the aligned sequence to the list of DNA...
dnalist.remove(candidate[2]) # ...and remove the two old strings
dnalist.remove(candidate[3])
numofseq = numofseq - 1
bestalign = ''.join(dnalist)
print('The best alignment of these sequences is: ')
print(bestalign)
def align(candidatelist, a, b, match, mismatch, gap):
m = len(a)
n = len(b)
matrix = [[0 for x in range(m)] for y in range(n)]
# create scoring matrix reflecting match/mismatch scores
# score_matrix = [[match, mismatch, mismatch, mismatch],
#[mismatch, match, mismatch, mismatch],
#[mismatch, mismatch, match, mismatch],
#[mismatch, mismatch, mismatch, match]]
# initialize matrix with 0's
for i in range(0, m):
for j in range (0, n):
matrix[i][j] = 0
# intialize score as 0
score = 0
# build matrix (except for first row and first column, which stays 0's)
if isinstance(a, list):
for item in a: # if the first item is a list (i.e. has already been assigned)
for i in range(2, m):
for j in range(2, n):
# note: this uses if/elif and comparison to determine match/mismatch
# rather than a scoring matrix
if (item[i] == b[j]) and (item[i] != '_'):
matrix[i][j] = max(matrix[i-1][j-1] + match,
matrix[i-1][j] + gap,
matrix[i][j-1] + gap)
else:
matrix[i][j] = max(matrix[i-1][j-1] + mismatch,
matrix[i-1][j] + gap,
matrix[i][j-1] + gap)
score = score + matrix[m-1][n-1]
else:
for i in range(1, m):
for j in range(1, n):
# note: this uses if/elif and comparison to determine match/mismatch
# rather than a scoring matrix
if (a[i] == b[j]) and (a[i] != '_'):
matrix[i][j] = max(matrix[i-1][j-1] + match,
matrix[i-1][j] + gap,
matrix[i][j-1] + gap)
else:
matrix[i][j] = max(matrix[i-1][j-1] + mismatch,
matrix[i-1][j] + gap,
matrix[i][j-1] + gap)
score = matrix[m-1][n-1]
score = str(score) # the score is the last value in the matrix
i = m - 1
j = n - 1
newa = ''
newb = ''
# backtrack through the matrix we built
while (i > 1) and (j > 1): # exits when either sequence is completed
if (((matrix[i][j] - match) == matrix[i-1][j-1]) or
((matrix[i][j] - mismatch) == matrix[i-1][j-1])):
newa = a[i-1].join(newa) # we're going through the sequences backwards, so add to front of string
newb = b[j-1].join(newb)
i = i - 1 # increment counters
j = j - 1
elif ((matrix[i][j] - gap) == matrix[i][j-1]):
newa = '_'.join(newa) # add a gap to one of the strings
newb = b[j-1].join(newb) # add nucleotide to the other string
j = j - 1 # only increment one of the counters in gaps
elif ((matrix[i][j] - gap) == matrix[i-1][j]):
newa = a[i-1].join(newa)
newb = '_'.join(newb)
i = i - 1
# now, fill the other sequence with gaps as needed
if (i > 1):
while (i > 1):
newa = a[i-1].join(newa)
newb = '_'.join(newb)
i = i - 1
elif (j > 1):
while (j > 1):
newa = '_'.join(newa)
newb = b[j-1].join(newb)
j = j - 1
alignedinfo = []
newseqlist = [newa, newb]
alignedinfo.extend((newseqlist, score, a, b))
candidatelist.append(alignedinfo)
return candidatelist
'''
parseHeader - split out the label from the header line
Parameter: a string starting with ">" and ending without a newline
Return:
1. the first item in the string, after the ">", up to the first space
'''
def parseHeaderLine(line):
header = line[1:]
label = header.split(' ')[0]
return label
'''
readfasta - the subroutine that reads the fasta file
Parameter: a filename that must be in fasta format. The file is
assumed to have:
1. the first line a header line
2. arbitrary blank lines
3. every line (especially including the last) is terminated by a newline
terminator (enter key)
4. no line has only spaces on it
Return: a list of lists. Each inner list will have three elements:
1. the sequence identifier, the characters between the leading ">"
and the first space
2. the entire header, the entire first line not including the ">"
3. the sequence, a single string of all the letters with no line terminators
'''
def readfasta(filename):
resultList = []
infile = open(filename, 'r')
# process the first line, which must be a header line
line = infile.readline()
headerLine = line.rstrip()
label = parseHeaderLine(headerLine)
# initialize the sequence accumulator
sequence = ''
# process all the rest of the lines in the file
for line in infile:
line = line.rstrip()
# ignore blank lines
if line != '':
# if it's a header line, finish the previous sequence
# and start a new one
if line[0] == '>':
resultList.append([label, headerLine, sequence])
label = parseHeaderLine(line)
headerLine = line.rstrip()
sequence = ''
# if we're here, we must be in letters of the sequence
else:
sequence += line
# we're done, so clean up, terminate the last sequence, and return
infile.close()
resultList.append([label, headerLine, sequence])
return resultList
main()
|
66fbc42e8c1a4c7fa23ef884b19d7eea75730c2b | g0dgamerz/workshop | /assignment1/dt18.py | 145 | 4.28125 | 4 | # Write a Python program to get the largest number from a list
list1 = [1, 2, 3]
list1.sort()
print("largest numer from the list is", list1[-1])
|
ebd4226cd29156923175d6b1ef12bf61017d2274 | bayeslabs/AiGym | /NLP/assignment2/utils/general_utils.py | 2,281 | 3.59375 | 4 | import sys
import time
import numpy as np
def get_minibatches(data, minibatch_size, shuffle=True):
"""
Iterates through the provided data one minibatch at at time. You can use this function to
iterate through data in minibatches as follows:
for inputs_minibatch in get_minibatches(inputs, minibatch_size):
...
Or with multiple data sources:
for inputs_minibatch, labels_minibatch in get_minibatches([inputs, labels], minibatch_size):
...
Args:
data: there are two possible values:
- a list or numpy array
- a list where each element is either a list or numpy array
minibatch_size: the maximum number of items in a minibatch
shuffle: whether to randomize the order of returned data
Returns:
minibatches: the return value depends on data:
- If data is a list/array it yields the next minibatch of data.
- If data a list of lists/arrays it returns the next minibatch of each element in the
list. This can be used to iterate through multiple data sources
(e.g., features and labels) at the same time.
"""
list_data = type(data) is list and (type(data[0]) is list or type(data[0]) is np.ndarray)
data_size = len(data[0]) if list_data else len(data)
indices = np.arange(data_size)
if shuffle:
np.random.shuffle(indices)
for minibatch_start in np.arange(0, data_size, minibatch_size):
minibatch_indices = indices[minibatch_start:minibatch_start + minibatch_size]
yield [_minibatch(d, minibatch_indices) for d in data] if list_data \
else _minibatch(data, minibatch_indices)
def _minibatch(data, minibatch_idx):
return data[minibatch_idx] if type(data) is np.ndarray else [data[i] for i in minibatch_idx]
def test_all_close(name, actual, expected):
if actual.shape != expected.shape:
raise ValueError("{:} failed, expected output to have shape {:} but has shape {:}"
.format(name, expected.shape, actual.shape))
if np.amax(np.fabs(actual - expected)) > 1e-6:
raise ValueError("{:} failed, expected {:} but value is {:}".format(name, expected, actual))
else:
print(name, "passed!")
|
df0b15a8b8107b254a12bd8e0bfc03a8bc527e67 | preetisethi24/Python_work | /matrixReshape.py | 464 | 3.625 | 4 | from numpy import reshape as np
def matrixReshape(nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
len_of_orig_mat=len(nums)*len(nums[0])
len_of_output_mat=r*c
if len_of_orig_mat!=len_of_output_mat:
return nums
else:
print(type(np(nums,r*c).tolist()))
return np(nums,r*c)
print(matrixReshape([[1,2],[3,4]],1,4))
|
590d1b16b74c5ffa7fda50609e6911043628c502 | daecazu/pensamiento_computacional | /busqueda_binaria.py | 368 | 3.765625 | 4 | objetivo = int(input('Escoge un número: '))
epsilon = 0.01
bajo= 0.0
alto = max(1.0, objetivo)
respuesta = (alto + bajo) / 2
while abs(respuesta**2 - objetivo) >= epsilon:
if respuesta**2 < objetivo:
bajo = respuesta
else:
alto = respuesta
respuesta = (alto + bajo) / 2
print(f'La raiz cuadrada de {objetivo} es {respuesta}')
|
01e39ba7dc547ee9ce53b1efe47ba1b0512ddc71 | ROB-Seismology/layeredbasemap | /data_types/circle.py | 1,631 | 3.515625 | 4 | """
Circle data
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from .point import MultiPointData
__all__ = ['CircleData', 'GreatCircleData']
class CircleData(MultiPointData):
"""
radii: in km
"""
def __init__(self, lons, lats, radii, values=[], labels=[], azimuthal_resolution=1):
z = None
super(CircleData, self).__init__(lons, lats, z, values, labels)
self.radii = radii
self.azimuthal_resolution = 1
class GreatCircleData(MultiPointData):
"""
Class representing data to plot great circles.
Note that Basemap cannot handle situations in which the great circle
intersects the edge of the map projection domain, and then re-enters
the domain.
:param lons:
array containing longitudes of start and end points of great circles,
as follows: [start_lon1, end_lon1, start_lon2, end_lon2, ...]
:param lats:
array containing latitudes of start and end points of great circles,
as follows: [start_lat1, end_lat1, start_lat2, end_lat2, ...]
:param resolution:
float, resolution in km for plotting points in between start and end
(default: 10)
"""
def __init__(self, lons, lats, resolution=10):
assert len(lons) % 2 == 0 and len(lons) == len(lats)
super(GreatCircleData, self).__init__(lons, lats)
self.resolution = resolution
def __len__(self):
return len(self.lons) // 2
def __getitem__(self, index):
"""
:return:
(start_lon, start_lat, end_lon, end_lat) tuple of each great circle
"""
i = index
return (self.lons[i*2], self.lats[i*2], self.lons[i*2+1], self.lats[i*2+1])
|
e0dda16699e452b381e0576515c03894f30b1145 | subhakani/python | /even or odd.py | 104 | 4.25 | 4 | n = int(input('Enter any number: '))
if n% 2 == 0:
print(n, "is EVEN")
else:
print(n, "is ODD")
|
045251e8ec5cc12655d91b579723973d8f4d1a57 | MitsosPng/PythonProjects | /PrimeNumbers.py | 793 | 3.953125 | 4 | import math
def f(x, y):
a = math.floor(math.log10(y))
return int(x*10**(1+a)+y)
def string_to_number():
string=input('Give me a string: ')
list=[]
count=0
number=0
for i in string:
count+=1
list.append(ord(i))
for i in range(count):
number=f(number,list[i])
print("The list of the string in ASCII is",list)
print("The Number Is: ",number)
if number > 1:
for i in range(2, number//2):
if (number % i) == 0:
print(number, "is not a prime number")
break
else:
print(number, "is a prime number")
else:
print(number, "is not a prime number")
string_to_number()
|
88c43d189566d9a61a67a4ae0fe5c37fe1e3a74f | dhairyachandra/CSEE5590-Python-Deep-Learning-Programming | /ICP1/Source Code/replace.py | 362 | 4.4375 | 4 | # Write a program that accepts a sentence and replace each occurrence of ‘python’ with ‘pythons’ without using regex
str = "I love playing with Python"
spt = str.split()
result = list()
final = ""
print (spt)
for i in spt:
if i == "Python":
i = "Pythons"
result.append(i)
for x in result:
final += x
final += " "
print(final)
|
c0d713923c6679608b97a7047abb41ac83075348 | cdunne10361551/10361551_DBS_CA_5 | /ConnorDunne_CA5_partB_Test.py | 6,642 | 3.671875 | 4 | #Name: Connor Dunne
#Student Number: 10361551
#Calculator Function Testing
#This programme tests the Calculator module to ensure expected values are returned
import numpy
from ConnorDunne_CA5_partB import Calculator #import Calculator module from file
import unittest #import unit test to run self assertion tests to ensure exact value is calculated
import numpy.testing as npt #import numpy testing module to run tests where approximation will do. Assigned name npt
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator() #assign Calculator() function to self.calc
#Test add() function using self assert
def test_calculator_add_method_returns_correct_result(self):
result = self.calc.add([2,3,4])
self.assertEqual(9, result)
result = self.calc.add([10])
self.assertEqual(10, result)
result = self.calc.add([2,-2])
self.assertEqual(0, result)
#Test subtract() function using self assert
def test_calculator_subtract_method_returns_correct_result(self):
result = self.calc.subtract([2,2])
self.assertEqual(0, result)
result = self.calc.subtract([2,2,2])
self.assertEqual(-2, result)
result = self.calc.subtract([2,-4])
self.assertEqual(6, result)
#Test multiply() function using self assert
def test_calculator_multiply_method_returns_correct_result(self):
result = self.calc.multiply([2,3],[1,1,1])
self.assertEqual([2,2,2,3,3,3], result)
result = self.calc.multiply([2,2,2],[1,1,-1])
self.assertEqual([2,2,-2,2,2,-2,2,2,-2], result)
result = self.calc.multiply([2,-4],[1])
self.assertEqual([2,-4], result)
#Test divide() function using self assert
def test_calculator_divide_method_returns_correct_result(self):
result = self.calc.divide([2,2],[2,2,2])
self.assertEqual([1,1,1,1,1,1], result)
result = self.calc.divide([4,4],[4,2])
self.assertEqual([1,2,1,2], result)
result = self.calc.divide([2,4,2],[1,1])
self.assertEqual([2,2,4,4,2,2], result)
result = self.calc.divide([-4,2],[4,-4])
self.assertEqual([-1,1,0,-1], result)
#Test squareroot() function using assert_almost_equal. Tests result to 12 decimal places. Anything else is ignored
def test_calculator_squareroot_method_returns_correct_result(self):
result = self.calc.squareroot([2,2])
npt.assert_almost_equal([1.4142135623730951,1.4142135623730951], result, decimal = 12)
result = self.calc.squareroot([4,4])
npt.assert_almost_equal([2.0,2.0], result, decimal = 12)
result = self.calc.squareroot([4.0,4])
npt.assert_almost_equal([2.0,2.0], result, decimal = 12)
#Test sine() function using assert_almost_equal
def test_calculator_sine_method_returns_correct_result(self):
result = self.calc.sine([2,2])
npt.assert_almost_equal([0.9092974268256817,0.9092974268256817], result, decimal = 12)
result = self.calc.sine([4,4])
npt.assert_almost_equal([-0.7568024953079282,-0.7568024953079282], result, decimal = 12)
result = self.calc.sine([-4,-4])
npt.assert_almost_equal([0.7568024953079282,0.7568024953079282], result, decimal = 12)
#Test cosine() function using assert_almost_equal
def test_calculator_cosine_method_returns_correct_result(self):
result = self.calc.cosine([2,2])
npt.assert_almost_equal([-0.4161468365471424,-0.4161468365471424], result, decimal = 12)
result = self.calc.cosine([4,4])
npt.assert_almost_equal([-0.6536436208636119,-0.6536436208636119], result, decimal = 12)
result = self.calc.cosine([-4,-4])
npt.assert_almost_equal([-0.6536436208636119,-0.6536436208636119], result, decimal = 12)
#Test tangent() function using assert_almost_equal
def test_calculator_tangent_method_returns_correct_result(self):
result = self.calc.tangent([2,2])
npt.assert_almost_equal([-2.185039863261519,-2.185039863261519], result, decimal = 12)
result = self.calc.tangent([4,4])
npt.assert_almost_equal([1.1578212823495775,1.1578212823495775], result, decimal = 12)
result = self.calc.tangent([-4,-4])
npt.assert_almost_equal([-1.1578212823495775,-1.1578212823495775], result, decimal = 12)
#Test b10log() function using assert_almost_equal
def test_calculator_b10log_method_returns_correct_result(self):
result = self.calc.b10log([2,2])
npt.assert_almost_equal([0.3010299956639812,0.3010299956639812], result, decimal = 12)
result = self.calc.b10log([4,4])
npt.assert_almost_equal([0.6020599913279624,0.6020599913279624], result, decimal = 12)
result = self.calc.b10log([4.0,4.0])
npt.assert_almost_equal([0.6020599913279624,0.6020599913279624], result, decimal = 12)
#Test exponent() function using self assert
def test_calculator_exponent_method_returns_correct_result(self):
result = self.calc.exponent([2,2],2)
self.assertEqual([4,4], result)
result = self.calc.exponent([2,2],4)
self.assertEqual([16,16], result)
result = self.calc.exponent([2,2],-4)
self.assertEqual([0.0625,0.0625], result)
#test for negative results to ensure ValueError is raised
def test_calculator_returns_error_message_if_both_args_not_numbers(self):
self.assertRaises(ValueError, self.calc.add, ['two',1],)
self.assertRaises(ValueError, self.calc.subtract, ['three',2])
self.assertRaises(ValueError, self.calc.multiply, ['one','two'], [1,1])
self.assertRaises(ValueError, self.calc.divide, [1,1], [1,'three'])
self.assertRaises(ValueError, self.calc.squareroot, ['two','three'])
self.assertRaises(ValueError, self.calc.sine, ['two',1])
self.assertRaises(ValueError, self.calc.cosine, [1,'two'])
self.assertRaises(ValueError, self.calc.tangent, [1,1,'two'])
self.assertRaises(ValueError, self.calc.b10log, ['two',1,1])
self.assertRaises(ValueError, self.calc.exponent, [2,2,2], 'three')
#test for negative results in math domain error
def test_calculator_returns_error_message_if_argument_outside_domain(self):
self.assertRaises(ValueError, self.calc.squareroot, [-1,2,3])
self.assertRaises(ValueError, self.calc.b10log, [0,2,3])
if __name__ == '__main__':
unittest.main() |
1e5c5a10333522f3ceebcb790cc2b63194d725a1 | fwang1395/LeetCode | /python/String/ReverseString.py | 1,791 | 4.28125 | 4 | #!/usr/bin/python
# _*_ coding: UTF-8 _*_
#Reverse String
#Write a function that takes a string as input and returns the string reversed.
# Example:
# Given s = "hello", return "olleh".
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
ret = s[::-1]
print ret
return ret
def reverseString1(self, s):
"""
:type s: str
:rtype: str
"""
length = len(s)
ret = ""
if length == 0:
return ret
k=5
while (length - k) > 0:
for index in range(length-k,length)[::-1]:
ret += s[index]
length -= k
for index in range(length)[::-1]:
ret += s[index]
print ret
return ret
def reverseString2(self, s):
"""
:type s: str
:rtype: str
"""
length = len(s)
ret = ""
if length == 0:
return ret
index = 0
while index<length:
print index
newIndex = length-1-index
ret += s[newIndex]
index += 1
print "final index : %s"%index
return ret
if __name__ == "__main__":
solution = Solution()
s = '''A man
a plan
a cameo
Zena
Bird
Mocha
Prowel
a rave
Uganda
Wait
a lobola
Argo
Goto
Koser
Ihab
Udall
a revocation
Ebarta
Muscat
eyes
Rehm
a cession
Udella
E-boat
OAS
a mirage
IPBM
a caress
Etam
FCA
a mica
Ojai
Lebowa
Yaeger
a barge
Rab
Alsatian
a mod
Adv
a rps
Ileane
Valeta
Grenada
Hetty
Fayme
REME
HCM
Tsan
Owena
Tamar
Yompur
Isa
Nil
Lorrin
Riksdag
Mona
Ronn
O'Conner
Kirk
an okay
Nafl
Lira
Robi
Rame
FIFA
a need
Rodi
Muharram
Ober
a coma
carri
Hwang
Taos
Salado
Olfe
Camag'''
solution.reverseString(s) |
e79fca89480ebcd80a66577aa6e349bbc0f51791 | i1196689/GitPython | /test.py | 377 | 3.671875 | 4 | n = 3
i_list = []
j_list = []
k_list = []
i = 0
while i < n :
i_list.append(i)
i = i + 1
j = 0
while j < i :
j = j + 1
j_list.append(j)
k = 0
while k < j :
k = k + 1
k_list.append(k)
print('i:%s'%len(i_list))
print(i_list)
print('j:%s'%len(j_list))
print(j_list)
print('k:%s'%len(k_list))
print(k_list) |
a0191a69a952d3752fa18cac43b3810ac21548b7 | r1409/unis_linguagens_de_programacao | /1 - Idade.py | 347 | 3.703125 | 4 | dia = int(input("Digite os dias vividos: "))
idade_anos = ano2 - ano
if mes >= mes2:
if mes == mes2:
if data > data2:
idade_anos - 1
else:
idade_anos - 1
dias_passados = (30 - data) + ((12 - mes)*30) + ((mes2 - 1)*30) + data2 + (idade_anos)*365
print("Você viveu",dias_passados,"dias.")
|
82bad5f4b540ab0c905950a5a5a59d8b92331d55 | indrekots/py-challanges | /dict_to_string/test_dictToString.py | 526 | 3.515625 | 4 | import unittest
from dictToString import dictToString
class TestDictToString(unittest.TestCase):
def test_simple_dictionary(self):
self.assertEqual(dictToString({'test1':1}), 'test1=1;')
def test_with_none_value(self):
self.assertEqual(dictToString({'test1':1, 'test2':None}), 'test1=1;')
def test_longer_input(self):
self.assertEqual(dictToString({'test1':1, 'test2':2}), 'test1=1;test2=2;')
def test_one_none_value(self):
self.assertEqual(dictToString({'test':None}), '') |
b061c5058d011301c9f4101a2173f0959f58e61b | chavhanpunamchand/PythonPractice | /List_Data_Structure/reverse_string.py | 186 | 3.65625 | 4 | def convert(s):
new=""
for x in s:
new+=x
#print()
return new
s="Punamchand is scientiest"
l=s.split()
d=l[::-1]
print(d)
print(" ".join(convert(d))) |
5fafd6d4d89fb4ba602e32a166a25c95f8406ef3 | remir88/leetcode_cn | /~2.两数相加.py | 884 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#
# @lc code=start
# Definition for singly-linked list.
#class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoLists(self, l1: ListNode, l2: ListNode, l: ListNode) -> bool:
p = False
if (l1.next != None):
p = self.addTwoLists(l1.next, l2.next, l)
t = ListNode(l1.val + l2.val)
if (p):
t.val += 1
p = False
if (t.val > 10):
t.val -= 10
p = True
l.next = t
return p
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l = ListNode(0)
if (self.addTwoLists(l1, l2, l)):
t = ListNode(1)
t.next = l
return t
else:
return l
# @lc code=end
|
c06b397a66b4d12154159606e7f5592139ab473e | alferesx/Python-Exercises | /EstruturaRepetição/Exercicio-20.py | 278 | 3.9375 | 4 | fatorial = -1
while fatorial != 16:
fatorial = int(input('Digite o valor da fatorial: '))
if fatorial == 16:
break
total = 1
while fatorial != 1:
total = total * fatorial
fatorial = fatorial - 1
print( 'Fatorial: ',total)
|
7b09b097e1b69a00df496464bc655d75dd72f0d0 | Gambrinus/Rosalind | /Python/SSET.py | 1,801 | 4.3125 | 4 | #!/usr/bin/env python
""" Rosalind project - Problem: Enumerating Subsets
Problem
A set is the mathematical term for a loose collection of objects, called elements.
Examples of sets include {the moon, the sun, Wilford Brimley} and R, the set
containing all real numbers. We even have the empty set, represented by [] or {},
which contains no elements at all. Two sets are equal when they contain the same
elements. In other words, in contrast to permutations, the ordering of the elements
of a set is unimportant (e.g., {the moon, the sun, Wilford Brimley} is equivalent
to {Wilford Brimley, the moon, the sun}). Sets are not allowed to contain duplicate
elements, so that {Wilford Brimley, the sun, the sun} is not a set.
You may recognize sets from 'Overlap Graphs', where we introduced a two-element set {v,w}
to represent an edge connecting nodes v and w.
A set A is a subset of B if every element of A is also an element of B, and we write AU=B.
For example, {the sun, the moon}U={the sun, the moon, Wilford Brimley}, and [] is a subset
of every set (including itself!).
The first natural question we can ask about subsets is: How many subsets can a given set have?
Given: A positive integer n (n<=1000).
Return: The total number of subsets of {1,2,...,n} modulo 1,000,000.
Sample Dataset
3
Sample Output
8
Hint
What does counting subsets have to do with characters and "ON"/"OFF" switches?
"""
__author__ = "Daniel J. Barnes"
__email__ = "ghen2000@gmail.com"
__status__ = "Working"
import itertools
filename = raw_input("Enter input path: ")
filein = open(filename,'r')
fileout = open('SSET_output.txt','w')
lines = filein.read().splitlines()
n = int(lines[0])
out = 2**n % 1000000
print out
fileout.write(str(out)) |
aa517d0b7cbd0d16c7407c6587e55b523bc1c7c8 | AkshaySadhu/ShopLocally-Internship | /objpython.py | 428 | 3.734375 | 4 | class myclass:
def __init__(self, name, age, phno):
self.myName = name
self.myAge = age
self.phoneNum = phno
@property
def name(self):
return self.myName
@name.setter
def name(self, name):
self.myName = name
obj = myclass("Akshay",20,9036)
print(type(obj.myName), type(obj.myAge), type(obj.phoneNum))
print(obj.name())
obj.name("Bleh")
print(obj.name())
|
2ce3abb5a331ee6a8d77033711b0d71c169da74e | JohnCrissman/topic-model-creator | /testing_simple.py | 819 | 3.515625 | 4 | # testing simple functions
# '''
# classifications = ['good', 'bad']
# n = 5
# list_of_classifications = [item for item in classifications for i in range(n)]
# print(list_of_classifications)
# '''
# classifications = ['bad', 'good']
# n = 999
# list_of_classifications = [item for item in classifications for i in range(n)]
# print(list_of_classifications)
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer()
corpus = [
'This is the first document.',
'This is the second second document',
'And the third one.',
'Is this the first document?',
]
X = vectorizer.fit_transform(corpus)
analyze = vectorizer.build_analyzer()
print(analyze("This is a text document to analyze.") == (
['this', 'is', 'text', 'document', 'to', 'analyze']))
print(X.toarray()) |
1d3ce3214ebfb9f3eafe37bf4ebc81f1656577d6 | anabeatrizzz/exercicios-pa-python | /exercicios_4/exercicios_4_02.py | 636 | 3.9375 | 4 | """
Escreva um programa que leia o nome e o preço de 10 produtos.
Logo após realizar o cadastro dos produtos, pedir para o usuário digitar um valor,
no qual deverá ser realizada uma pesquisa e exibir apenas os produtos que possuem preço até o valor digitado pelo usuário.
"""
nomes = []
precos = []
for c in range(0, 10):
nomes.append(str(input(f"Digite o nome do {c+1} produto")))
print()
for d in range(0, 10):
precos.append(float(input(f"Digite o preco para o produto {nomes[d]}")))
print()
valor = float(input(f"Digite um valor: "))
for e in range(0, 10):
if precos[e] <= valor:
print(f"{nomes[e]} custa {precos[e]}")
|
bb65c8bb0d3b0bfb9a3cd4c8783e64dacba7506e | Barret-ma/leetcode | /32. Longest Valid Parentheses.py | 1,420 | 3.828125 | 4 | # Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
# Example 1:
# Input: "(()"
# Output: 2
# Explanation: The longest valid parentheses substring is "()"
# Example 2:
# Input: ")()())"
# Output: 4
# Explanation: The longest valid parentheses substring is "()()"
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
# stack = []
# res = 0
# start = 0
# n = len(s)
# for i in range(n):
# if s[i] == '(':
# stack.append(i)
# elif s[i] == ')':
# if len(stack) == 0:
# start = i + 1
# else:
# stack.pop()
# if len(stack) == 0:
# res = max(res, i - start + 1)
# else:
# res = max(res, i - stack[-1])
# return res
res = 0
n = len(s)
dp = [0 for _ in range(n + 1)]
for i in range(n + 1):
j = i - 2 - dp[i - 1]
if (s[i - 1] == '(' or j < 0 or s[j] == ')'):
dp[i] = 0
else:
dp[i] = dp[i - 1] + 2 + dp[j]
res = max(res, dp[i])
return res
s = Solution()
s.longestValidParentheses('()(())') |
dc72351469ecce193c0d0aec8c7dea75d765f22f | Kateryna252/Start_dragon | /Module_3_min_2_min/duplicate.py | 309 | 3.875 | 4 | import random
n = int(input("please write lenght of list\n"))
list1 = []
for i in range(n):
list1.append(random.randint(0,n))
# print(set(list1))
list1_without_dublicates = []
for i in list1:
if i not in list1_without_dublicates:
list1_without_dublicates.append(i)
print(list1_without_dublicates)
|
6455792ed822e1c284fd96602ca66c3fe02e0b32 | or12k/Hangman_python_code | /hangman_unit/hangman_unit_8.py | 1,296 | 3.984375 | 4 | def print_hangman(num_of_tries):
"""
VARIABLE- HANGMAN_PHOTOS (dict)- from unit 1
the FUNCTION PRINT:
one of the 7 photos in HANGMAN_PHOTOS-
with the help of a VARIABLE-num_of_tries that represent
how many times the user
guessed the wrong letter, and HANGMAN_PHOTOS
dict[key] = value
"""
# images for the wrong gusses
# picture 1:
image1 = "x-------x"
# picture 2:
image2 = """x-------x
|
|
|
|
|"""
# picture 3:
image3 = """x-------x
| |
| 0
|
|
|"""
# picture 4:
image4 = """x-------x
| |
| 0
| |
|
|"""
# picture 5:
image5 = """x-------x
| |
| 0
| /|\\
|
|"""
# picture 6:
image6 = """x-------x
| |
| 0
| /|\\
| /
|"""
# picture 7:
image7 = """x-------x
| |
| 0
| /|\\
| / \\
|"""
HANGMAN_PHOTOS = {0: image1, 1: image2, 2: image3, 3: image4, 4: image5, 5: image6, 6: image7}
if num_of_tries in HANGMAN_PHOTOS.values():
# if value in HANGMAN_PHOTOS.values():
print("x")
print(num_of_tries)
# print(HANGMAN_PHOTOS[num_of_tries])
num_of_tries = 6
print_hangman(num_of_tries)
num_of_tries = 0
print_hangman(num_of_tries)
num_of_tries = 3
print_hangman(num_of_tries)
|
eb8b21718c1882cc7a94701812fc81c6996c6eab | Sabakalsoom/Learning-Python | /Arithmetic_Order_of_Precedence.py | 517 | 4.1875 | 4 | """
multiplication and division have the same order of precedence so it does not matter which one we do before
and has a higher precedence over + and -
"""
print(2+4*3/2)
"""
we use parenthesis when we want our own order of precedences.
"""
print((2+4)*3/2)
print((2+4*2)*3/2) #Multiplication has a higher precedence over addition
a = 10
print(a)
a = a+10
print(a) #after adding 10 to a
a+=10 #shortcut for above
print(a)
a-=10
print(a)
a*=10
print(a)
a/=10
print(a)
|
5267aecc0af112e2974a527cbd78855bfb6b9273 | kdockman96/CS0008-f2016 | /ch4-ex/ch4-ex12.py | 1,079 | 4.25 | 4 | # Ask the user for the starting number of organisms
organisms = int(input('Enter the starting number of organisms: '))
# As the user the average daily population increase as a percentage
daily_pop_increase = float(input('Enter the average daily population increase as a decimal: '))
if daily_pop_increase < 0 or daily_pop_increase > 1:
print('Error')
daily_pop_increase = float(input('Enter the correct population increase as a decimal: '))
# Ask the user what the number of days the organisms will be left to multiply will be
days_multiply = int(input('Enter the number of days to multiply: '))
# Create a variable that references a Boolean value
first = True
# display table headings
print('')
print('Day Approximate\tPopulation')
# Write a for loop with an if statement and running total
# Display the results
for days_multiply in range(organisms, days_multiply + 1):
if first:
print(1, '\t\t\t\t', organisms)
first = False
add = organisms * daily_pop_increase
organisms += add
print(days_multiply, format(organisms, '20.3f'))
|
b7a0b6138844a869b49d60d58b0bab414b2a1851 | TheSleepingAssassin/CodeFolder | /py/Morse/functions.py | 664 | 3.78125 | 4 | from dictionary import *
def encrypt(message):
cipher = ''
for letter in message:
if letter != ' ':
cipher += code[letter] + ' '
else:
cipher += ' '
return cipher
def decrypt(message):
message += ' '
decipher = ''
citext = ''
for letter in message:
if letter != ' ':
i = 0
citext += letter
else:
i += 1
if i == 2:
decipher += ' '
else:
decipher += list(code.keys()
)[list(code.values()).index(citext)]
citext = ''
return decipher
|
c9da3d82628308138d3fcc42e52d0d45c6d5405c | bfark13/PythonExercises | /IntroProjects/CodeStruct.py | 1,010 | 3.6875 | 4 | def print_artist(album):
print(album['Artist_Name'])
def change_list(list_from_user):
list_from_user[2] = 5
def print_name(album):
print(album["Album_Title"])
def make_album(name, title, numSongs=10):
album = {'Artist_Name': name, 'Album_Title': title}
if numSongs:
album["Song_Count"] = numSongs
return album
def main():
albums = []
bsb = make_album("Back Street Boys","I want it that way")
print_artist(bsb)
print_name(bsb)
num_track = [1,3,6,7]
print(num_track)
change_list(num_track)
print(num_track)
# bsb = {
# Artist_Name: "Back Street Boys"
# Album_Title: "I want it that way"
# Song_count: 10
# }
artist1 = "Joe"
title1 = "Buck"
albums.append(make_album(artist1,title1))
albums.append(make_album('Marylin Manson', 'Mechanical Animals'))
albums.append(make_album('Less Than Jake', 'Borders and Boundaries', 12))
albums.append(make_album("N'Sync", 'No Strings Attached'))
print(albums)
main() |
691df28180fb0c0888484e8f0cde9c06f745bd4a | indy728/python_course | /Python_Type_DataStructure_Basics/lists.py | 439 | 4.15625 | 4 | # lists are indexed and can be sliced and can hold any variety of data types
my_list = [1, 2, 3]
print(len(my_list))
print(my_list[1:])
next_list = [4, 5, 6]
double_list = my_list + next_list
print(my_list + next_list)
print(double_list)
# lists are mutable
double_list[4] = "turd sandwich"
print(double_list)
double_list.append(7)
print(double_list)
print(double_list.pop(-3))
print(double_list)
double_list.reverse()
print(double_list)
|
681ff8795111dff6c05e64e70d5aa9e30c10acbe | Elie-Kh/COMP472---AI | /Game.py | 5,592 | 3.609375 | 4 | from minmaxAI import summon_ai_overlord
from win_check import win_check
from Board import board_game,x_dict,column_letters,move_check
# Variables below are used in the function
# p_play variables are for getting user input
play_x = 0
play_y = 0
p_play_x = 0
p_play_y = 0
play_x_old = 0
play_y_old = 0
p1_turn = True
p1_tokens = 15
p2_tokens = 15
current_tokens = 0
moves = 0
win = False
validMove = False
mover = False
ai_mode = True
# printing a 10 x 12 array to set up the game board
def gameboard():
# Creating the board
# Labelling columns with alphabet letters
for i in range(len(column_letters)):
if i == 0:
print(' ' + column_letters[i], end='')
else:
print(' ' + column_letters[i], end='')
print()
# labelling each row with numbers and printing the board
for row in range(len(board_game)):
for col in range(len(board_game[row])):
if col != 0:
print(board_game[row][col], end='')
else:
print(str(row) + " " + board_game[row][col], end='')
print()
return board_game
gameboard()
print("\n")
print('Welcome to X-Rudder!')
startingPlayer = input('Do you want to go first? Enter Y or N').upper()
while startingPlayer not in ("Y", "N"):
startingPlayer = input('Do you want to go first? Enter Y or N').upper()
if startingPlayer == "Y":
p1_turn = True
else:
p1_turn = False
while moves != 30 and win is False:
print("Moves remaining: %d" % (30 - moves))
if p1_turn:
player_turn = "Player 1 (X)"
current_tokens = p1_tokens
else:
if not ai_mode:
player_turn = "Player 2 (O)"
else:
player_turn = "AI (O)"
current_tokens = p2_tokens
if p1_turn or not ai_mode:
while validMove is False:
if p1_turn:
p_play_x = input("%s: Enter X coordinate" % player_turn).upper()
p_play_y = input("%s: Enter Y coordinate" % player_turn)
checker = move_check(p_play_y, p_play_x, p1_turn, False, current_tokens)
validMove = checker[2]
mover = checker[3]
if p1_turn:
p1_tokens = checker[4]
else:
p2_tokens = checker[4]
if validMove is True:
play_x = checker[0]
play_y = checker[1]
if mover is True:
confirm = input('Are you sure you want to move your token? Enter Y or N').upper()
while confirm not in ("Y", "N"):
confirm = input('Are you sure you want to move your token? Enter Y or N').upper()
if confirm == "Y":
moves += 1
print("Choose your new position")
play_x_old = play_x
play_y_old = play_y
validMove = False
mover = True
while validMove is False:
p_play_x = input("%s: Enter X coordinate" % player_turn).upper()
p_play_y = input("%s: Enter Y coordinate" % player_turn)
checker = move_check(p_play_y, p_play_x, p1_turn, mover, current_tokens)
validMove = checker[2]
if validMove is True:
play_x = checker[0]
play_y = checker[1]
else:
validMove = False
mover = False
continue
# AI turn logic
else:
counter_bad = 0
while validMove is False:
counter_bad += 1
move = summon_ai_overlord(board_game, p1_turn, current_tokens,counter_bad)
if current_tokens <= 0:
# validMove = True
play_y_old = move[0][1]
play_x_old = move[0][0]
play_y = move[1][1]
play_x = move[1][0]
checker = move_check(play_y, play_x, False, True, current_tokens)
validMove = checker[2]
if validMove is False:
continue
mover = True
moves += 1
print("\nAI Move: (%s, %s) to (%s, %s)" % (list(x_dict.keys())[list(x_dict.values()).index(str(play_x_old))], str(play_y_old), list(x_dict.keys())[list(x_dict.values()).index(str(play_x))], str(play_y)))
else:
play_y = move[1]
play_x = move[0]
checker = move_check(play_y, play_x, False, False, current_tokens)
validMove = checker[2]
if validMove is False:
continue
p2_tokens = current_tokens - 1
print("\nAI Token Placed: (%s, %s)" % (list(x_dict.keys())[list(x_dict.values()).index(str(play_x))], str(play_y)))
if p1_turn is True:
board_game[play_y][play_x] = "(X)"
p1_turn = False
else:
board_game[play_y][play_x] = "(O)"
p1_turn = True
if mover is True:
board_game[play_y_old][play_x_old] = "( )"
validMove = False
mover = False
print("\n")
gameboard()
print("\n")
if win_check(board_game, p1_turn):
if not p1_turn:
print("\nThe game has been won by Player 1\n")
else:
if ai_mode:
print("\nThe game has been won by the AI\n")
else:
print("\nThe game has been won by Player 2\n")
win = True
if moves == 30:
print("\nThe game has tied\n")
print("Game Over")
|
c88efde09bc8d821fd427557d4e8f4071797f972 | Assa-goDori/python | /pythonex/0811/comprehensionex1.py | 910 | 3.90625 | 4 | '''
Created on 2020. 8. 11.
@author: GDJ24
comprehensionex1.py : 컴프리핸션 예제
패턴이 있는 list, dictionary, set을 간편하게 작성할 수 있는 기능
'''
numbers = []
for n in range(1, 11) :
numbers.append(n)
print(numbers)
#컴프리핸션 표현
print([x for x in range(1, 11)])
clist = [x for x in range(1, 11)]
print(clist)
#1~10까지의 짝수 리스트 생성
evenlist = []
for n in range(1, 11) :
if n % 2 == 0 :
evenlist.append(n)
print(evenlist)
#컴프리헨션 표현
evenlist = [x for x in range(1, 11) if x%2 == 0]
print(evenlist)
#2의 배수이고, 3의 배수인 값만 리스트에 추가하기
evenlist = [x for x in range(1, 11) if x%2 == 0 if x%3 == 0]
print(evenlist)
#중첩사용 컴프리 핸션 사용하기
matrix = [[1,2,3], [4,5,6], [7,8,9]]
print(matrix)
list1=[x for row in matrix for x in row]
print(list1) |
12e7a2c3e52b27789b0047f31588d2b3e4ad9385 | YanqingWu/Sci-kit-Learning | /数据降维.py | 1,035 | 3.671875 | 4 | #PCA(主成分分析)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets,decomposition,manifold
%matplotlib
def load_data():
iris = datasets.load_iris()
return iris.data,iris.target,iris.target_names
def test_PCA(*data):
X,y = data
pca = decomposition.PCA()
pca.fit(X)
print('explained varians ratio : %s' %str(pca.explained_variance_ratio_))
X,y,target_names = load_data()
test_PCA(X,y)
def plot_PCA(*data):
X,y,target_names = data
pca = decomposition.PCA(n_components = 2)
pca.fit(X)
print('explained varians ratio : %s' %str(pca.explained_variance_ratio_))
X_r = pca.transform(X)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
colors = ['navy', 'turquoise', 'darkorange']
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=2,label=target_name)
ax.set_title('PCA')
X,y,target_names = load_data()
plot_PCA(X,y,target_names)
|
604eeed856456477b79ea7bd69fb294e33403082 | Danilo-Xaxa/python_curso_em_video | /Opa meu rei 2.py | 152 | 3.6875 | 4 | a = ('Opa meu rei')
print(a.split())
print(' '.join(a))
print(a.replace('Opa', 'Eae'))
#Inclusive, aqui dá pra eu escrever qualquer coisa que eu quiser |
f6892abad6f52c63535cfc3cd3f4082b291fb832 | KyleLopin/Potentiostat_GUI | /tkinter_canvas_graph.py | 1,766 | 3.546875 | 4 | __author__ = 'Kyle Vitautas Lopin'
import Tkinter as tk
class canvas_graph_embed(tk.Frame):
def __init__(self, master, properties):
tk.Frame.__init__(self, master=master)
self.graph = tk.Canvas(master=self, width=_properties['width'], height=_properties['height'])
self.graph.pack(expand=True, fill=tk.BOTH)
self.height = _properties['height']
self.width = _properties['width']
self.draw_axis(_properties)
self.graph.bind("<Configure>", self.on_resize)
def draw_axis(self, _props):
# get the dimensions of where to put the lines and tick marks
y_origin = .8*self.height
x_origin = .1*self.width
x_end = .9*self.width
y_end = .1*self.height
# draw x and y axes lines
self.graph.create_line(x_origin, y_origin, x_end+1, y_origin, width=2) # x axis
self.graph.create_line(x_origin, y_origin, x_origin, y_end, width=2) # y axis
#make markings on the x axis
x_spacing = (x_end-x_origin)
tick_len = 6
for i in range(11):
x = x_origin + (i*x_spacing/10)
self.graph.create_line(x, y_origin, x, y_origin+tick_len, width=2)
print 'testing'
def on_resize(self, event):
"""
Rescale all the widgets in the Canvas, see
http://stackoverflow.com/questions/22835289/how-to-get-tkinter-canvas-to-dynamically-resize-to-window-width
for more details
:param event:
:return:
"""
# get ratio of old and new height
wscale = float(event.width)/self.width
hscale = float(event.height)/self.height
self.width = event.width
self.height = event.height
self.graph.scale("all",0,0,wscale,hscale)
|
ad302f4e9411abedc0dda5b135677abae9f50a0c | caianne/mc102 | /exercicios/Aula 5/Slide_19.py | 993 | 4.09375 | 4 | #Slide 19 da Aula 05
print('Programa para calcular o valor da comissão, dada o valor da transação.')
transação=float(input('Informe o valor da transação: R$ '))
if (transação<=2500.00):
comissão=30+0.017*transação
if (comissão>39.00):
print('O valor da comissão é: R$ %.2f' %comissão)
else:
print('O valor da comissão é: R$ 39.00')
elif (transação>2500.00) and (transação<=6250.00):
print('O valor da comissão é: R$ %.2f' %(56+0.0066*transação))
elif (transação>6250.00) and (transação<=20000.00):
print('O valor da comissão é: R$ %.2f' %(76+0.0034*transação))
elif (transação>20000.00) and (transação<=50000.00):
print('O valor da comissão é: R$ %.2f' %(100+0.0022*transação))
elif (transação>50000.00) and (transação<=500000.00):
print('O valor da comissão é: R$ %.2f' %(155+0.0011*transação))
elif (transação>500000.00):
print('O valor da comissão é: R$ %.2f' %(255+0.0009*transação))
|
cc9c93c60566f684091fa183ed49ea52fa12d3e6 | rwgeaston/alias-method-discrete-finite-probability | /next_num.py | 2,894 | 3.671875 | 4 | # https://en.wikipedia.org/wiki/Alias_method
import random
from math import floor
from numbers import Real
class InvalidInputs(Exception):
pass
class RandomGen:
_distribution = None
def __init__(self, distribution, random_source=None):
if not distribution:
raise InvalidInputs("Don't give an empty distribution because weird things will happen")
if not all(
isinstance(probability, Real) and (probability >= 0)
for probability in distribution.values()
):
raise InvalidInputs("Probabilities must be non-negative numbers")
# Technically if the probabilities don't add exactly to 1, it's a measure not a probability distribution.
# However the rest of the code works perfectly fine in either scenario.
# Let's just normalise them.
total_measure = sum(distribution.values())
if not total_measure:
raise InvalidInputs("Your measure/probability distribution cannot add to 0!")
for key in distribution:
distribution[key] /= total_measure
self.n = n = len(distribution)
self._distribution = [
{
'u': n * probability, # u is used probability, also terminology used on wikipedia
'k': None,
'value': value,
} for value, probability in distribution.items()
]
for _ in range(n): # we will be done before this many redistributions
# Doing this every time is wasteful but we only do it in the init
self._distribution.sort(key=lambda u: u['u'])
underfull = self.get_underfull()
if not underfull:
break
overfull = self._distribution[-1] # easy because we sorted
underfull['k'] = overfull['value']
overfull['u'] = overfull['u'] + underfull['u'] - 1
else:
# If this happens my code logic is wrong so abandon ship
raise Exception("I deliberately put too many iterations in the for loop so this will never happen.")
self.random_source = random_source or random.Random()
def get_underfull(self):
for entry in self._distribution:
# Floating point errors means sometimes the exactly full entries are actually 0.99999999 not 1
if entry['u'] < 0.999999999999 and not entry['k']:
return entry
# Didn't find one so we should be good to stop
return None
def next_num(self):
random_key = self.n * self.random_source.random()
i = floor(random_key)
y = random_key - i
random_value = self._distribution[i]
if y < random_value['u']:
return random_value['value']
return random_value['k']
|
ed737dddd5f705fbc5100b423b40a9dd64e92ec2 | Audarya07/Daily-Flash-Codes | /Week3/Day2/Solutions/Python/prog4.py | 110 | 3.734375 | 4 | val = 1
for i in range(1,5):
for j in range(i):
print(val**3,end=" ")
val+=1
print()
|
22b850eb44f441f73d0381235b02dda06a234608 | aleksey-masl/hello_world | /functions.py | 1,611 | 3.8125 | 4 | def say(message, times = 1):
print(message * times)
say('Привет')
say('Мир', 5)
print('#########################################################')
# Ключевые аргументы
def func(a, b=5, c=10):
print('a равно', a, ', b равно', b, ', а c равно', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
func(a='обязательно надо назначить, так как не определили сразу в функции',b=30)
print('#########################################################')
# Локальные переменные
x = 50
def func(x):
print('x равен', x)
x = 2
print('Замена локального x на', x)
func(x)
print('x по-прежнему', x)
print('#########################################################')
# global
x = 50
def func():
global x
print('x равно', x)
x = 2
print('Заменяем глобальное значение x на', x)
func()
print('Значение x составляет', x)
print('#########################################################')
# Переменное число параметров
def total(a=5, *numbers, **phonebook):
print('a', a)
#проход по всем элементам кортежа
for single_item in numbers:
print('single_item', single_item)
#проход по всем элементам словаря
for first_part, second_part in phonebook.items():
print(first_part,second_part)
print(total(10,1,2,3,5,Jack=1123,John=2231,Inge=1560,Nina=1234))
s = "hello"
print(s.capitalize()) |
9dd9e7244f8bc089c4f81cb759649724a807b0fe | nagask/CrackingTheCodingInterview | /StacksAndQueues/Stack.py | 425 | 3.703125 | 4 | class Stack():
def __init__(self):
self.array=[]
self.t=-1
def pop(self):
a=self.array.pop(self.t)
self.t=self.t-1
return a
def push(self,x):
self.array.append(x)
self.t=self.t+1
def peek(self):
return self.array[self.t]
def isEmpty(self):
if self.t==-1:
return True
else:
return False |
250693ad6bea3efc8e537cdbf1fbdadbd0d1bce4 | sksumanta/python3Basic | /listComprehension.py | 926 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 10:31:48 2018
@author: Sumanta
"""
# The range function in the loop
for i in range(5):
print(i)
##################### List Comprenhension ############################
lis=[]
for x in range(7):
lis.append(2**x)
print(lis) # -------- [1, 2, 4, 8, 16, 32, 64]
lis=[2**x for x in range(7)]
print(lis) # -------- [1, 2, 4, 8, 16, 32, 64] same output as above in list Comprenhension
lis=[]
for x in range(7):
if x>3:
lis.append(2**x)
print(lis) # -------- [16, 32, 64]
lis=[2**x for x in range(7) if x>3] # find the power list if x > 3
print(lis) # ----- [16, 32, 64] same output as above in list Comprenhension
lis1=[x for x in range(7) if x%2==0 ]
print(lis1)
lis1=[x for x in range(7) if x%2==1 ]
print(lis1)
###### [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
|
75f73f0dcad89a01808ff44176bac3987c8b784c | van7b/PythonCompiler | /compiler/examples/lexer_syntax/c5.py | 107 | 3.71875 | 4 | def findmax(x,y):
if x > y:
a=[1,2,3,4]
if y > x:
b=[1]
l=[0,1,"hello","world"]
print findmax(2,4)+6
|
d47b083cda7924f7101f3fad0dafc862a7645483 | domarcone/Exercicios-Python | /ex4.py | 367 | 3.875 | 4 | #Faça um Programa que peça as 4 notas bimestrais e mostre a média.
def main():
m1 = int(input("insira a primeira nota \n "))
m2 = int(input("insira a segunda nota \n"))
m3 = int(input("insira a terceira nota \n"))
m4 = int(input("insira a quarta nota \n"))
total = ((m1 + m2 + m3 + m4) / 4)
print("sua média é ", total)
main() |
642295cb9f0efdea183ec26c1d6d004f32238c44 | comojin1994/Algorithm_Study | /Sungjin/Math/1247.py | 340 | 3.5625 | 4 | import sys
input = sys.stdin.readline
def check(N):
if N == 0: return "0"
elif N < 0: return "-"
elif N > 0: return "+"
else: return "Error"
if __name__ == '__main__':
for _ in range(3):
N = int(input())
total = 0
for _ in range(N):
total += int(input())
print(check(total)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.