blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
89ffd786d982bc2c96ac235ec93b5ee0df0155b0 | pianorita/lab6 | /recitation test.py | 361 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 15:32:21 2017
@author: Rita
"""
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num - 1)
def main():
number= int(input('Enter a nonnegative integer:'))
fact = factorial(number)
print('The factorial of',number,'is',fact)
main() | false |
99b3f30eff84ec601734b54f2bdf596fda25fc37 | Stevella/Early-days | /regexSearch.py | 1,092 | 4.3125 | 4 | # python 3
#regexSearch.py opens all .txt files in a folder and searches for any
# line that matches a user-supplied regular expression. results are printed to the screen
import os,re,glob,sys
#print(sys.argv[1])
if len(sys.argv) < 3:
#ask for directory and regexpattern if commandline arguments is insufficient
folder = input('Enter the folder path: ')
regexPattern = input('Enter the Regex: ')
else:
folder = sys.argv[1]
regexPattern = sys.argv[2]
# verify the provided folder path is a directory
if os.path.isdir(r'%s' %(folder)):
#using os.walk to find the files recursively(folders,subfolders)
# r= root, d = directories, f = files
for r,d,f in os.walk(folder):
for file in f:
if '.txt' in file:
fhand = open(os.path.join(r, file))
for line in fhand:
match = re.findall(r'%s' %(regexPattern),line)
if len(match) > 0:
print('the file [%s] has %s match(es).' %(file,len(match)))
print(match)
| true |
eae604c50b0450db7ee01da3b9600149bdca2ac2 | mark-kohrman/python_practice | /python_practice.py | 1,626 | 4.25 | 4 |
# 1. Write a while loop to print the numbers 1 through 10.
i = 1
while i <= 10:
print i
i = i + 1
# # # 2. Write a while loop that prints the word "hello" 5 times.
i = 1
while i <= 5:
print "hello"
i += 1
# 3. Write a while loop that asks the user to enter a word and will run forever until the user enters the word "stop".
while True:
print("Please enter a word")
word = input()
if word == "stop":
break
# 4. Write a while loop that prints the numbers 0 through 100, increasing by 5 each time.
i = 0
while i <= 100:
print (i)
i += 1
# 5. Write a while loop that prints the number 9000 ten times.
number = 9000
i = 0
while i < 10:
print (number)
i += 1
# 6. Write a while loop that asks the user to enter a number and will run forever until the user enters a number greater than 10.
while True:
print("Please enter a number")
x = int(input())
if x > 10:
break
# 7. Write a while loop that prints the numbers 50 to 70.
x = 50
while x < 71:
print(x)
x +=1
# 8. Write a while loop that prints the phrase "Around the world" 144 times.
i = 1
while i < 145:
print("Around the world")
print(i)
i += 1
# 9. Write a while loop that asks the user to enter a word and will run forever until the user enters a word with more than 5 letters.
while True:
print("Please enter a word")
word = input()
if len(word) > 5:
break
# 10. Write a while loop that prints the even numbers from 2 to 40.
x = 2
while x < 41:
print(x)
x += 2
# SOLUTIONS: https://gist.github.com/peterxjang/c4ec0e0f8f6e123d65ada9bf3100068b | true |
6afdce799ca7121e1ce5cf1274660407706cf732 | diketj0753/CTI110 | /P2_PayRate_DiketJohn.py | 472 | 4.25 | 4 | Hours=float(input('How many hours did you work last week? '))
# Creates a variable named PRate with user generated information.
GrossPay=float(input('How much did you make over this time? '))
# Multiplies the two variables together to determine Gross Pay and rounds to
# two decimal places.
PRate=float(GrossPay/Hours)
# Outputs the Gross Pay for the user
print('Your Hourly Rate for the previous week was $',
format(PRate,',.2f'), sep='')
input()
| true |
7d8f996b50024904bdabed331ba996578ab1dd44 | planets09/HB_Final-Project | /ToDoList.py | 1,459 | 4.15625 | 4 | #NOTE: Final project
Rena_to_do = {"Shopping":"Groceries", "Pay_Bills":"Rent", "Pay_Utilities":"Water, Heat and Electric", "Repair": "Car", "Pet_Care": "Dog grooming"}
print "Welcome to Rena's TO DO List!"
while(True):
instructions = "Type A to see list., Type B to see Shopping, Type C to see Pay_Bills, Type D to see Pay_Utilities, Type E to see Repair, Type F to see Pet_Care, Type X for Exit. "
user_answer = raw_input(instructions) #NOTE: Takes the input from user and stores it in the variable labeled user_answer.
if user_answer.upper() == "A": #Note: "A" is the expected answer that the user will type. You are also checking to see if user is typing "A", otherwise it won't print list.
print Rena_to_do
elif user_answer.upper() == "B":
del Rena_to_do['Shopping']
elif user_answer.upper() == "C":
print Rena_to_do['Pay_Bills']
elif user_answer.upper() == "D":
print Rena_to_do['Pay_Utilities']
elif user_answer.upper() == "E":
print Rena_to_do['Repair']
elif user_answer.upper() == "F":
print Rena_to_do['Pet_Care']
elif user_answer.upper() == "X":
print "Exiting the List. Good-bye!"
break
else:
print "Ooops! Please try again!"
print "********************************************"
# complete_tasks = {}
# for x in complete_tasks:
# print x
# if x in complete_tasks:
# complete_tasks[x] = complete_tasks[x] + 1
# else:
# complete_tasks[x] = 1
# print complete_tasks
| true |
fe33f96dae69f5469d83f9c69f7df77d4862557d | Irlet/Python_SelfTraining | /Find_multiply.py | 750 | 4.625 | 5 | """ In this simple exercise, you will build a program that takes a value, integer,
and returns a list of its multiples up to another value, limit.
If limit is a multiple of integer, it should be included as well.
There will only ever be positive integers passed into the function, not consisting of 0.
The limit will always be higher than the base.
For example, if the parameters passed are (2, 6), the function should return [2, 4, 6]
as 2, 4, and 6 are the multiples of 2 up to 6.
"""
def find_multiples(integer, limit):
multiples = []
for element in range(integer, limit+1):
if element % integer == 0:
multiples.append(element)
return multiples
print(find_multiples(5, 25))
print(find_multiples(-5, 25))
| true |
d40b3893bef288d7a47b2ddb1537df43e3a6c85b | Irlet/Python_SelfTraining | /Text_analyser_1st_lvl.py | 1,107 | 4.1875 | 4 | # Ask over text and check: no. of characters, find vowels, every second char., no. of letters in words,
# find indicated character and element
my_text = input("Enter text: ")
number_of_text_char = len(my_text)
my_text_splitted = my_text.split()
vowels = "AaEeIiOoUuYy"
vowels_in_text = []
every_second_char = []
print(f"Number of characters in text: {number_of_text_char}")
for letter in my_text:
if letter in vowels:
vowels_in_text.append(letter)
print(f"Vowels in text: {vowels_in_text}")
for i in range(len(my_text)):
if i % 2 != 0:
every_second_char.append(my_text[i])
print(f"Every second characters: {every_second_char}")
print("Number of letters in words: ")
for word in my_text_splitted:
print(len(word))
char_number_to_find = input("Enter ref. number of character to find: ")
char_find = (my_text[int(char_number_to_find)-1])
print(f"'{char_find}'is the {char_number_to_find}. character")
element_to_find = input("Enter the element to find: ")
if element_to_find in my_text:
print("Contain entered element")
else:
print("Doesn't contain entered element")
| true |
a272c7266131e411c60eefaa5c2474dd466b780a | abanuelo/Code-Interview-Practice | /LeetCode/Google Interview/Interview Process/lisence-key-formatting.py | 2,189 | 4.15625 | 4 | '''
You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.
Given a non-empty string S and a number K, format the string according to the rules described above.
Armando Banuelos 1/27/2021
'''
'''
Solution: For this, I first go through the array once to extract all characters. And insert them in reverse
order in an array. Next from that reversed array, I make groups of K size and add them to an all_groups list.
Lastly I query from all_groups and concatenate together to make the required output.
Time Complexity: O(n) - each time we only iterate through the n characters once to get what chars are available
Space Complexity: O(n^2) - because of all_chars along with all_groups
'''
class Solution:
def licenseKeyFormatting(self, S: str, K: int) -> str:
#First go through string S to get all chars available starting from the end
all_chars = []
for i in range(len(S)-1, -1, -1):
if S[i] != "-":
all_chars.append(S[i])
#Next we form groups of K from all_chars
all_groups=[]
curr_group_size = 0
curr_string = ""
for c in all_chars:
if curr_group_size == K:
all_groups.append(curr_string[::-1])
curr_group_size = 0
curr_string = ""
curr_string += c.upper()
curr_group_size += 1
all_groups.append(curr_string[::-1])
result = ""
#We retrieve all groups and append the dash from reverse order of all_groups
for i in range(len(all_groups)-1, -1, -1):
if i > 0:
result += all_groups[i] + "-"
else:
result += all_groups[i]
return result | true |
33b19d17c43d84e6254c945b2fe105b058ccf692 | NGHTMAN/study_0022-03 | /NM5&7.py | 2,335 | 4.25 | 4 | # Наша функция
def create_dict():
# Первый список слов
first_words = input("Введи первый список слов через запятую: ")
# split - разбиение строки на части
# В нашем случае разделитель - запятая
first_list = first_words.split(',')
# Вывод количества слов с помощью поиска пробелов + 1, так как в конце строки пробел не ставится
word_count = first_words.count(" ") + 1
print("Вы ввели количество слов в первом списке:", word_count)
# Благодаря F-strings подставляем в {} необходимые нам переменные
second_words = input(f"Введи второй список из {word_count} слов через запятую: ")
second_list = second_words.split(',')
# dict - словарь (ключ: значение); zip - "цикл" прохождения по массиву из слов
final_dict = dict(zip(first_list, second_list))
print(final_dict)
# Конструкция для открытия и закрытия файла
# 'w' - открытие на запись, содержимое файла удаляется; если файла не существует, то создается новый
# key - ключи словаря, val - значения словаря
# write - запись в файл
with open('secret.txt', 'w', encoding='utf-8') as f:
for key, val in final_dict.items():
f.write(f'{key}:{val}\n')
return 0
# Просто красивое название
print("\n\n<-------------------------------| Добро пожаловать в программу-словарик! |------------------------------->")
print("\n\n")
print("Введи 1, чтобы создать словарь\nВведи 0, чтобы завершить работу\n")
operation = input("Answer: ")
while operation != "0":
# Вызов функции
create_dict()
print("\n\n")
print("Введи 1, чтобы создать словарь\nВведи 0, чтобы завершить работу\n")
operation = input("Answer: ")
| false |
20fa547df238d952da01752d372a0e7118214c89 | dcantor/python-fun1 | /dictionaries/dictionary1.py | 526 | 4.53125 | 5 | # Dictionary sample (key value pair)
food = {'chocolate' : 101, 'cheese' : 102, 'soup' : 103}
print "Food dictionary is: "
print food
print
# what is the value for key chocolate
print food['chocolate']
print
# for loop test
print "iterate over the food dictionary"
for x in food:
print food[x]
# add new key/value pairs to the food dictionary
food['salad'] = 104
print food
print "There are ", len(food), " items in the food dictionary"
print
# delete a key from the dictionary
del food['chocolate']
print food
print | true |
b7d768961b7dfa886096d40d0c808e04a9fc03f1 | vtu4869/Hangman | /hangmen.py | 2,664 | 4.28125 | 4 | #author: Vincent Tu
#modules to use for the game
import time
import random
#Asked for the username
name = input("Input your player name: ")
choice = False
#Different difficulties choice of words for the user to choose
ListOfDifficulties = [" ", "easy", "medium", "hard"]
EasyWords = ["listen", "phones", "games", "smile", "angry"]
MediumWords = ["janurary", "mysterious", "mission", "official", "heading"]
HardWords = ["azure", "blizzard", "buffalo", "cobweb", "banjo"]
print ("Hello, %s" % name, "Ready for a game of hangmen?")
#Delay the execution by 1.5 seconds to get the user ready
time.sleep(1.5)
#Ask user to select a difficulty
print("Select your difficulty, %s:" %name)
print("1. easy")
print("2. medium")
print("3. hard")
#A while loop for edge cases of when user did not input the numbers 1-3
while choice == False:
difficulty = int(input("Enter your choice: "))
if difficulty == 1 or difficulty == 2 or difficulty == 3:
choice = True
else:
print("Invalid Input, Please Input Another Number")
#Generate a word by choosing a random number in the array
print("Generating a random", ListOfDifficulties[difficulty] + " word.")
time.sleep(1.5)
random = random.randint(0, 5)
#set the number of tries and word based on the difficulty
if(difficulty == 1):
word = EasyWords[random]
tries = 5
elif(difficulty == 2):
word = MediumWords[random]
tries = 9
elif(difficulty == 3):
word = HardWords[random]
tries = 13
#initalize the user guess
guesses = ''
print("All done, start guessing %s." %name)
#A while loop that keeps running until the tries ran out
while tries > 0:
#Update the word as the game progresses
numberofDashes = 0
for char in word:
if char in guesses:
print (char + ' ', end = '')
else:
print ("_ ", end = '')
numberofDashes += 1
print('\n')
#end the loop if user guessed the word
if numberofDashes == 0:
print ('Nice Job %s , You guessed the word!' %name)
break
#Prompt user to guess a character in the "secret" word
UserGuess = input("guess a character, %s: " %name)
#add the character to the list of guesses
guesses += UserGuess
#if the guess is not in the word, reduce the number of tries
if UserGuess not in word:
tries -= 1
print ('Wrong, guess again')
#Update the user on how many tries they have left
print ("You have", + tries, 'more guesses')
#If ran out of tries, show game over and reveal the answer of the secret word
if tries == 0:
print ('Sorry %s ,' %name, 'You ran out of tries. The hidden word is %s' %word)
| true |
1df0550461b931a48c1a0a2b6144cb5e418fca24 | jen8/Python-Chapters | /MISC/Collabedit_Tests_2.py | 1,055 | 4.25 | 4 | def num_odd_digits(n):
"""
>>> num_odd_digits(1234567)
2
>>> num_odd_digits(2468)
0
>>> num_odd_digits(1357)
4
>>> num_odd_digits(1)
1
>>> num_odd_digits(31)
2
"""
count = 0
while n:
if n % 2 != 0:
count = count + 1
n = n / 10
return count
def print_digits(n):
"""
>>> print_digits(13789)
9 8 7 3 1
>>> print_digits(39874613)
3 1 6 4 7 8 9 3
>>> print_digits(213141)
1 4 1 3 1 2
"""
n = n / 10
print n
def sum_of_squares_of_digits(n):
"""
>>> sum_of_squares_of_digits(1)
1
>>> sum_of_squares_of_digits(9)
81
>>> sum_of_squares_of_digits(11)
2
>>> sum_of_squares_of_digits(121)
6
>>> sum_of_squares_of_digits(987)
194
"""
current_digit = n
sum = 0
while n:
current_digit = current_digit**2
sum = sum + current_digit
n = n / 10
return sum
| false |
31ccc7fba49171694ab5b62dc42f61ea3961cf2d | jen8/Python-Chapters | /CH6/ch06.py | 2,713 | 4.15625 | 4 | # print "produces\nthis\noutput."
def sqrt(n):
approx = n/2.0
better = (approx + n/approx)/2.0
while better != approx:
print better
approx = better
better = (approx + n/approx)/2.0
return approx
#print sqrt(25)
def print_multiples(n):
i = 1
while i <= 6:
print n * i, '\t',
i += 1
print
def print_mult_table():
i = 1
while i <= 6:
print_multiples(i)
i += 1
def print_triangular_numbers(n):
x = 1
var = 1
while x <= n:
print (x, "\t", var)
x += 1
var += x
def is_prime(n):
"""
>>> is_prime(5)
True
>>> is_prime(6)
False
>>> is_prime(7)
True
"""
i = 2
while i <= n - 1:
if n % i == 0:
return False
i += 1
return True
if __name__ == '__main__':
import doctest
doctest.testmod()
def num_digits(n):
"""
>>> num_digits(12345)
5
>>> num_digits(0)
1
>>> num_digits(-12345)
5
"""
if n == 0:
return 1
if n < 0:
n = n * (-1)
count = 0
while n:
count = count + 1
n = n / 10
return count
def num_even_digits(n):
"""
>>> num_even_digits(123456)
3
>>> num_even_digits(2468)
4
>>> num_even_digits(1357)
0
>>> num_even_digits(2)
1
>>> num_even_digits(20)
2
"""
if n == 0:
return 1
if n < 0:
n = n * (-1)
count = 0
while n:
current_digit = n % 10
if current_digit % 2 == 0:
count = count + 1
n = n / 10
return count
def print_digits(n):
"""
>>> print_digits(13789)
9 8 7 3 1
>>> print_digits(39874613)
3 1 6 4 7 8 9 3
>>> print_digits(213141)
1 4 1 3 1 2
"""
if n == 0:
print 0,
while n:
current_digit = n % 10
print current_digit,
n = n / 10
print
def sum_of_squares_of_digits(n):
"""
>>> sum_of_squares_of_digits(1)
1
>>> sum_of_squares_of_digits(9)
81
>>> sum_of_squares_of_digits(11)
2
>>> sum_of_squares_of_digits(121)
6
>>> sum_of_squares_of_digits(987)
194
"""
if n == 0:
return 0
sum = 0
while n:
current_digit = n % 10
sum = sum + current_digit**2
n = n / 10
return sum
def countdown(n):
while n > 0:
print n
n = n-1
print "Blastoff!"
countdown(7)
def blah():
x = 1
while x < 13:
print x, '\t', 2**x
x += 1
blah()
| false |
b4ede7dd7bb11b4b691e0830040f6f8388ac1434 | rekhert/Python3 | /lesson4taskA.py | 880 | 4.1875 | 4 |
'''
Задание A
Напишите функцию которая будет конвертировать время
из 24 часового представления в 12 часовое представление с суффиксом AM
если это первая половина дня и PM если вторая
'''
time = input("Введите время в формате ЧЧ:ММ")
def timeconverter (time):
h = int(time[:2])
m = int(time[-2:])
if h > 24 or h < 0:
raise Exception ('ЧЧ не может превышать 24 или быть отрицательным')
elif m > 59 or m < 0:
raise Exception ('ММ не может превышать 59 или быть отрицательным')
elif h >= 12:
h -= 12
z = 'PM'
else:
z = 'AM'
print (h, ":", m , z)
timeconverter(time)
| false |
93c406f2a2c14bce1fd123df16aba1dadb53e732 | dtilney/minimax | /ttt.py | 2,947 | 4.125 | 4 | '''
ttt.py
Implements a general tic tac toe board.
'''
class Board:
'''
__init__
Sets up an empty tic tac toe board
R: number of rows
C: number of columns
N: number to get in a row to win
'''
def __init__(self, R, C, N):
self.R = R
self.C = C
self.N = N
self.state = [ [ str(c + self.C * r) for c in range(self.C) ] for r in range(self.R) ]
'''
__str__
Returns the string representation of the current board state
ex: if self.state = [[1, 2, X], [4, 5, O]]
then __str__(self) is:
+---+---+---+
| 1 | 2 | X |
+---+---+---+
| 4 | 5 | O |
+---+---+---+
'''
def __str__(self):
max_display_number = self.R * self.C - 1
entry_width = len(str(max_display_number))
row_seperator = (('+' + '-' * (entry_width + 2)) * self.C) + '+\n'
s = ''
for row in self.state:
s += row_seperator
for entry in row:
s += '| ' + entry.center(entry_width) + ' '
s += '|\n'
s += row_seperator
return s
def make_move(self, r, c, char):
self.state[r][c] = char
'''
horizontal_winner
checks for horizontal wins
if there is a horizontal win, then returns the winning symbol
otherwise returns None
'''
def horizontal_winner(self):
for r in range(self.R):
c = 0; count = 0; current_symbol = None
while self.C - c + count >= self.N: #A win is possible in this row
if self.state[r][c] == current_symbol:
count += 1
if count == self.N:
return current_symbol
else:
current_symbol = self.state[r][c]
count = 1
c += 1
return None
'''
vertical_winner
checks for vertical wins
if there is a vertical win, then returns the winning symbol
otherwise returns None
'''
def vertical_winner(self):
for c in range(self.C):
r = 0; count = 0; current_symbol = None
while self.R - r + count >= self.N: #A win is possible in this row
if self.state[r][c] == current_symbol:
count += 1
if count == self.N:
return current_symbol
else:
current_symbol = self.state[r][c]
count = 1
r += 1
return None
def diagonal_winner(self):
return None
'''
winner
returns the winning symbol if the game is over, otherwise returns None
'''
def winner(self):
w = self.horizontal_winner()
if w is not None:
return w
w = self.vertical_winner()
if w is not None:
return w
w = self.diagonal_winner()
return w
| false |
0ea1e3024677c97325c93bf4d7984b11521d64b6 | CereliaZhang/leetcode | /217_Contains_Duplicate.py | 745 | 4.125 | 4 | '''
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
'''
def containsDuplicate(nums):
list = set()
for n in nums:
if n in list:
return n
else:
list.add(n)
def containsDuplicate2(nums):
list = []
for i in range(0, len(nums)):
if nums[i] in list:
return True
else:
list.add(nums[i])
return False
a = containsDuplicate([1,2,13,1])
print a | true |
a41aef1333c2dbfef42e99ef46b288dd2cfeffc7 | yousuf550/Basic_Python_Projects | /Grocery_Cashier.py | 1,452 | 4.21875 | 4 | #Grocery Store
'''
The program evaluates the total bill price and the discount price of the bill
according to the membership grade. The product price and buying list are both
presented in dictionary format. Then we create two functions that read the
dictionaries to get the bill price and the discount price.
'''
def get_price(product, quantity):
sub_total = price_dic[product] * quantity
print(product + ": $ " + str(price_dic[product]) + " x " + str(quantity) + " = " +\
str(sub_total))
return sub_total
def get_discount(bill_price, membership):
discount = 0
if bill_price >= 25:
if membership == "gold":
bill_price = bill_price * 0.75
discount = 25
elif membership == "silver":
bill_price = bill_price * 0.85
discount = 15
elif membership == "bronze":
bill_price = bill_price * 0.95
discount = 5
print(str(discount) + "% off for " + membership + \
" membership at total price no less than $25")
return bill_price
buying_dic = {"biscuit": 2, "chicken": 5, "egg": 20}
price_dic = {"biscuit": 2, "fish": 3, "chicken": 5, "cabbage": 2, "egg": 0.2}
bill_price = 0
for key, value in buying_dic.items():
bill_price += get_price(key, value)
membership = "gold"
bill_price = get_discount(bill_price,membership)
print("The total price is $" + str(bill_price)) | true |
fd0035ec10de79eb8fe60970267e7780238b7a11 | Sumedh3113/Python-codes | /pangram.py | 796 | 4.21875 | 4 | """
Write a Python function to check whether a string is pangram or not.
Note : Pangrams are words or sentences containing every letter of the alphabet at least once.
For example : "The quick brown fox jumps over the lazy dog"
"""
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
str1.lower()
if alphabet in str1:
return True
else:
return False
#---Actual Solution----#
import string
def ispangram(str1, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
#print(set(str1.lower()))
return alphaset <= set(str1.lower()) #here we are creating two sets one contains all the alphabet and other contains letter
#from the string then alphabet set should be <= set of string as it might contains two letters repeatedly
| true |
7e047589467b22af0f793518d32f31b4c583da4a | yenandrew/CIS3260 | /Assignment 1/Chapter 3/Assignment 3.9.py | 1,102 | 4.3125 | 4 | #Write a program that reads the following information and prints a payroll statement:
#Employee’s name (e.g., Smith)
#Number of hours worked in a week (e.g., 10)
#Hourly pay rate (e.g., 9.75)
#Federal tax withholding rate (e.g., 20%)
#State tax withholding rate (e.g., 9%)
name=input("Enter employee's name: ")
hour=int(input("Enter number of hours worked in a week: "))
rate=float(input("Enter hourly pay rate (onit dollar sign): "))
Ftax=float(input("Enter federal tax withholding rate (omit percent sign): "))
Stax=float(input("Enter state tax withholding rate (omit percent sign): "))
pay=(hour*rate)
Fholding=pay*Ftax/100
Sholding=pay*Stax/100
TotalD=Fholding+Sholding
NetP=pay-TotalD
print("Employee Name: "+str(name))
print("Hour Worked: "+str(hour))
print("Pay Rate: $"+str(rate))
print("Gross Pay: $"+str(pay))
print("Deductions:")
print("\tFederal Withholding("+str(Ftax)+"%): $"+str(Fholding))
print("\tState Withholding("+str(Stax)+"%): $"+str(Sholding))
print("\tTotal Deduction: $"+str(TotalD))
print("Net Pay: $"+str(NetP)) | true |
be34debf56b4f2435eda7501f8b78cdb6d6b3f9c | yenandrew/CIS3260 | /Assignment 1/Chapter 4/Assignment 4.8.py | 370 | 4.3125 | 4 | # (Sort three integers) Write a program that prompts the user to enter three integers
# and displays them in increasing order.
n1, n2, n3 = eval(input("Enter 3 integers separated by commas no spaces"))
if n1 > n2:
n1, n2 = n2, n1
if n2 > n3:
n2, n3 = n3, n2
if n1 > n2:
n1, n2 = n2, n1
print("Sorted: " + str(n1) + " " + str(n2) + " " + str(n3)) | true |
f08d2357990b536e5dd686f565d4c9973b99eccc | tecnoedm/PyChat | /PyChat/client/gui/helper/stack.py | 1,328 | 4.1875 | 4 | #!/usr/bin/env python2
##
# PyChat
# https://github.com/leosartaj/PyChat.git
#
# Copyright (c) 2014 Sartaj Singh
# Licensed under the MIT license.
##
"""
Upper key and lower key functionality
when pressed gives last written text
"""
class stack:
"""
Makes a stack
that can be cycled
up and down
"""
def __init__(self, textList=[]):
self.textList = textList
self.reset_point()
def reset_point(self):
"""
Sets the pointer to the end of the list
"""
self.point = len(self.textList)
def push(self, text):
"""
Push new text in stack
"""
textList = self.textList
textList.append(text)
self.reset_point()
return textList # only for testing purposes
def pop(self):
"""
Returns the previous text in textList
"""
if self.point > 0:
text = self.textList[self.point - 1]
self.point -= 1
return text
return None
def up(self):
"""
Cycles up the stack
returns the text if possible
returns None if already at top
"""
if self.point + 1 < len(self.textList):
self.point += 1
text = self.textList[self.point]
return text
return None
| true |
b04ca479ff18300017bcf2b1f853fbf4a34ec1ca | mmorrow1/Simple-Calculator | /Simple Calculator.py | 604 | 4.25 | 4 | #simple calculator
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
choice = input("Do you want to add, subtract, multiply, or divide? ")
if choice.upper() == "ADD":
answer = num1 + num2
print(num1, "+", num2, "=", answer)
elif choice.upper() == "SUBTRACT":
answer = num1 - num2
print(num1, "-", num2, "=", answer)
elif choice.upper() == "MULTIPLY":
answer = num1 * num2
print(num1, "x", num2, "=", answer)
elif choice.upper() == "DIVIDE":
answer = num1 / num2
print(num1, "/", num2, "=", answer)
else:
print("Invalid input.")
| false |
8dd41e21cde0e2106cbed0f6a9ada793c16035b3 | Brenno-Daniel/estudos-python | /app-python/aula8_lambda.py | 932 | 4.15625 | 4 | # nome da função,
# lambda para dizer que é uma função anonima,
# um parametro que é necessário, no caso lista,
# devolver uma lista e quantas letras tem cada palavra dentro da lista
contador_letras = lambda lista: [len(x) for x in lista]
lista_animais = ['cachorro', 'gato', 'elefante']
print(contador_letras(lista_animais))
#Calculadora com lambda
soma = lambda a, b: a + b
subtracao = lambda a, b: a - b
print(soma(5, 10))
print(subtracao(10, 5))
# Calculadora com dicionario de funções lambda
calculadora = {
'soma': lambda a, b: a + b,
'subtracao': lambda a, b: a - b,
'multiplicacao': lambda a, b: a * b,
'divisao': lambda a, b: a / b,
}
print(type(calculadora)) # tipo: dict = dicionário
soma = calculadora['soma']
#soma = lambda a, b: a + b
multiplicacao = calculadora['multiplicacao']
print('A soma é: {}'.format(soma(10, 5)))
print('A multiplicação é: {}'.format(multiplicacao(10, 2)))
| false |
5859033462563e5a8977e2dd568bbb75f78807f8 | Martijnde/Jupyter_Portfolio | /Python basics/Regular expressions.py | 1,457 | 4.28125 | 4 | #A regular expression is a sequence of characters that describes a search pattern.
#In practice, we say that certain strings match a regular expression if the pattern can be found anywhere within those strings (as a substring).
#The simplest example of regular expressions is an ordinary sequence of characters. Any string that contains that sequence of characters,
#all adjacent and in the proper order, is said to match that regular expression. Here are a couple examples:
#Assign a regular expression that is 4 characters long and matches every string in strings to the variable regex
strings = ["data science", "big data", "metadata"]
regex = ""
regex = "data"
#We assign a regular expression (3 characters long) that matches every string in strings to the variable regex
strings = ["bat", "robotics", "megabyte"]
regex = "."
regex = "b.t"
#We can use "^" to match the start of a string and "$" to match the end of string.
#"^a" will match all strings that start with "a".
#"a$" will match all strings that end with "a".
#You can use any combination of special characters in a regex. Let's combine what we've learned so far to create some more advanced regular expressions
#Assign a regular expression that is 7 characters long and matches every string in strings, but not bad_string, to the variable regex
strings = ["better not put too much", "butter in the", "batter"]
bad_string = "We also wouldn't want it to be bitter"
regex = "^b.tter" | true |
cfa66cc2bac72dfc53c43e7035ad3f4851a16e3f | MatheusSaloma0/Clustering | /Python/point.py | 708 | 4.15625 | 4 | # Estrutura representando um ponto de d coordenadas(dimensoes).
# Cada ponto apresenta um identificador(index) que corresponde a ordem deste
# durante o processo de leitura do arquivo contendo todos os pontos.
class Point:
# Inicializa um ponto.
def __init__(self, coordenates, index):
self.coordenates = coordenates
self.index = index
# Metodo ToString do ponto.
def __str__(self):
return str(self.index)
# Calcula a distancia euclidiana entre dois pontos.
def euclideanDistance(self,point):
sum = 0.0
for i in range(len(self.coordenates)):
sum += (self.coordenates[i] - point.coordenates[i])**2
return sum**(0.5)
| false |
8b1385f2e1e7646d18c29b309c2d78cdb6661d8a | georich/python_bootcamp | /rock_paper_scissors/rps_ai.py | 1,386 | 4.375 | 4 | from random import choice
player_wins = 0
computer_wins = 0
to_win = 3
print("Time to play rock paper scissors, first to three wins!")
while player_wins < to_win and computer_wins < to_win:
player = input("Enter your choice: ").lower()
computer = choice(["rock", "paper", "scissors"])
print(f"The computer plays: {computer}")
if player == computer:
print("A draw!")
elif player == "rock":
if computer == "scissors":
print("Player wins!")
player_wins += 1
elif computer == "paper":
print("Computer wins!")
computer_wins += 1
elif player == "paper":
if computer == "rock":
print("Player wins!")
player_wins += 1
elif computer == "scissors":
print("Computer wins!")
computer_wins += 1
elif player == "scissors":
if computer == "rock":
print("Computer wins!")
computer_wins += 1
elif computer == "paper":
print("Player wins!")
player_wins += 1
else:
print("Something has gone wrong, please try again")
if player_wins < 3 and computer_wins < 3:
print(f"The current score is, Player {player_wins} - {computer_wins} Computer")
if player_wins == 3:
print("Congratulations player, you won!")
else:
print("Uh oh, the computer won")
| true |
030d63e2bb296078a7306d414dcd5e5a0212d540 | georich/python_bootcamp | /lambdas_and_builtin/filter.py | 676 | 4.15625 | 4 | # returns only values which return true to the lambda
l = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, l))
print(evens)
# combining filter and map
names = ["Lassie", "Colt", "Rusty"]
#return a list with the string "Your instructor is "
# + each value in array, only if less than 5 characters
# sends filtered names into the map function
filtered_names = list(map(lambda name: f"Your instructor is {name}", filter(lambda value: len(value) < 5, names)))
print(filtered_names)
# list comprehension solution, much more pythonic solution
filtered_list_comp_names = [f"Your instructor is {name}" for name in names if len(name) < 5]
print(filtered_list_comp_names)
| true |
8346b24ee1c6abb2484391b16940152612a48af4 | gadtab/tutorials | /Python/ex01_ConvertKM2Miles.py | 218 | 4.15625 | 4 | print("This program converts kilometers to miles")
number = float(input("Please enter a number in kilometers: "))
print("You have entered", number, "km")
print("which is", round(number / 1.609344, 4), "miles")
| true |
3e462da7979ae4d023ff1617d1530f46bd9b382d | yasykurrafii/Python_Tkinter | /Basic_Code/Icon.py | 778 | 4.125 | 4 | from tkinter import *
#library untuk memasukan image
#yang di install libnya adalah lib Pillow
#karena Lib Pillow adalah upgrade-an dari lib PIL
from PIL import ImageTk, Image
root = Tk()
root.title("Learn Tkinter")
#Change Icon
root.iconbitmap('C:/Users/Rajwa/Documents/Rafii/Python/Tkinter/Basic_Code/fb.ico')
#Create Image
#To Create Image needs 3 step
#1. Define the Image
#2. Put the Define Into Variable
#3. Put The Variable into Label Variable
#Step2 Step1
my_img=ImageTk.PhotoImage(Image.open("gambar-bunga-sepatu.jpg"))
#Step3
my_label = Label(image = my_img)
#Creating button
button_quit = Button(root, text = 'Quit', command = root.quit)
#Positioning
my_label.pack()
button_quit.pack()
#Looping screen
root.mainloop()
| false |
946f7c3d02074091f7ea3d2f588982d730ee5922 | magnusm18/assignment5 | /max_int.py | 303 | 4.125 | 4 | num_int = int(input("Input a number: ")) # Do not change this line
max_int = 0
while True:
num_int = int(input("Input a number: "))
if num_int < 0:
break
if num_int > max_int:
max_int = num_int
print("The maximum is", max_int) # Do not change this line
print ("lalala") | false |
79ebe029b626361c6a180e10949585183bafcbc3 | niuniu6niuniu/Leetcode | /IV-Perm&Comb.py | 562 | 4.25 | 4 | # # # Combination # # #
# Example
# For several given letters, print out all the combination of it's letters
# Input: 1 2 3
# Output: 1 2 3
# 1 3 2
# 2 1 3
# 2 3 1
# 3 1 2
# 3 2 1
from itertools import permutations,combinations
def comb(n,*args):
_list = []
for letter in args:
_list.append(letter)
perm = permutations(_list)
comb = combinations(_list, n)
for p in perm:
print(p)
print("============")
for c in comb:
print(c)
comb(3, 3,1,2)
| true |
abb6d702f4d52de7239e13a6d601a6578444243b | niuniu6niuniu/Leetcode | /LC-Robot_Moves.py | 1,521 | 4.1875 | 4 | # # # Robot Return to Origin # # #
# There is a robot starting at position (0, 0), the origin, on a 2D plane.
# Given a sequence of its moves, judge if this robot ends up at (0, 0)
# after it completes its moves.
# The move sequence is represented by a string, and the character moves[i]
# represents its ith move. Valid moves are R (right), L (left), U (up), and
# D (down). If the robot returns to the origin after it finishes all
# of its moves, return true. Otherwise, return false.
# Example 1:
# Input: "UD"
# Output: true
# Explanation: The robot moves up once, and then down once. All moves have the
# same magnitude, so it ended up at the origin where it started. Therefore, we
# return true.
# Example 2:
# Input: "LL"
# Output: false
# Explanation: The robot moves left twice. It ends up two "moves" to the left
# of the origin. We return false because it is not at the origin at the end of
# its moves.
# Idea: 1. Check each letter in the moves string
# 2. Up: +2, Down: -2, Left: -1, Right: +1
class Solution:
def judgeCircle(self, moves):
count = 0
for move in moves:
if move == "U":
count += 2
elif move == "D":
count -= 2
elif move == "L":
count -= 1
else:
count += 1
if count == 0:
return True
else:
return False
t = Solution()
moves = "UDRL"
print(t.judgeCircle(moves))
| true |
37d300cd616de4bde0c9d60c6c0cbcf722c6805e | niuniu6niuniu/Leetcode | /Sort_Heap.py | 1,037 | 4.15625 | 4 | # Heap Sort
# Best case & Worst case: O(nlogn)
# Average case: O(nlogn)
# Idea: Build max heap & Remove
# Heapify
# Set root at index i, n is the size of heap
def heapify(arr, n, i):
largest = i # Initialize largets as root
l = 2 * i + 1 # Left child
r = 2 * i + 2 # Right child
# See if left child is greater than the root
if l < n and arr[l] > arr[i]:
largest = l
# See if right child is greater than the root
if r < n and arr[n] > arr[largest]:
largest = r
# Change root, if needed
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] # Swap
# Heapify the root
heapify(arr, n, largest)
# The main function to sort an array
def heapSort(arr):
n = len(arr)
# Build max heap
for i in range(n, -1, -1):
heapify(arr, n, i)
# One by one extract element
for i in range(n-1, 0, -1):
arr[i] = arr[0]
arr[0] = arr[i]
heapify(arr, i, 0)
| true |
23de9a39fae97d6b47d6c3e07aef68415e7f57f2 | ParkDongJo/python3_algorithm_training | /algorithm/sort_and_searching.py | 2,079 | 4.15625 | 4 | '''
정렬과 탐색에 대해서 내용 정리
'''
'''
python 리스트 정렬
- sorted(list) : 정렬된 새로운 리스트를 얻어냄
- list.sort() : 해당 리스트를 정렬함
- sorted(list, reverse=True)
- list.reverse() or list.sort(reverse=True)
'''
'''
문자열 정렬
- sorted() 정렬에 이용하는 key를 지정
- sort() 정렬에 이용하는 key를 지정
'''
str_list = ['abcd', 'xyz', 'spamd']
print(sorted(str_list, key=lambda x: len(x)))
dic_list = [{'name': 'Xohn','score':70}, {'name': 'Paul', 'score': 90}]
dic_list.sort(key=lambda x:x['name'])
print(dic_list)
dic_list.sort(key=lambda x:x['score'], reverse=True)
print(dic_list)
print('\n')
'''
탐색 알고리즘 1
- 선형탐색 (linear search)
- 시간복잡도 O(n)
'''
L = [ 2, 10, 4, 5, 8 , 3, 9]
def linear_search(list, x):
i=0
while i < len(list) and list[i] != x:
i += 1
if i < len(list):
return i
else:
return -1
print(linear_search(L, 5))
print(L.index(5))
'''
탐색 알고리즘 1
- 이진탐색 (binary search)
- divide & conquer = 한번 비교가 일어날 때마다 리스트 반씩 줄임
- 시간복잡도 O(log n)
- lower , middle, upper를 설정
- middle = (lower + upper) // 2
- middle 이 찾고자하는 값보다 작으면 middle 왼쪽 배열 값을 무시하고 lower을 그 다음 배열인덱스 값을 가르키도록 한다
- middle 이 찾고자하는 값보다 크면 middle 오른쪽 배열 값을 무시하고 upper을 그 전의 배열인덱스 값을 가르키도록 한다
- 값을 찾을 때 까지 반복한다.
'''
def binary_search(list, target):
lower = 0
upper = len(list) -1
idx = -1
while lower <= upper:
middle = (lower + upper) // 2
if list[middle] == target:
return middle
elif list[middle] < target:
lower = middle + 1
else:
upper = middle - 1
return -1
print(binary_search(L, 6))
print(binary_search(L, 5))
| false |
1cbe3db493217a7e138404e710b221e9d2424532 | periyandavart/ty.py | /leap.py | 285 | 4.125 | 4 | print("Enter the year")
year=input()
if ((year%4==0)and(year%100!=0)):
print("The year is a leap year")
elif((year%100==0)and(year%400==0)):
print("The year is a leap year")
elif(year%400==0):
print("The year is a leap year")
else:
print("The year is not a leap year")
| true |
d78dfa16dff3d735f5ec17d5b757ee279741d52b | changwang/Union-Find | /src/datastructure.py | 1,550 | 4.25 | 4 | '''
Created on Nov 8, 2009
@author: changwang
Define some data structures that could be used by other data structure.
'''
class Node:
''' The node class represents the node in the disjoint set and union-find tree. '''
def __init__(self, value):
''' construct function. '''
# The parent node of current node, at first each node points to itself.
self.parent = self
# The data is contained in the node.
self.value = value
# The rank means how many nodes are contained by current node.
self.rank = 1
# Name of the set current node belongs to.
self.name = self.value
def __eq__(self, other):
''' This method is used to handle whether two nodes are equal,
like node1 == node2.
Actually, if the value in node is the same, two nodes are the same. '''
return self.value == other.value
def __ne__(self, other):
''' This method is used to handle wheter two nodes are not equal,
like node1 != node2 or node1 <> node2.
Acutally, if the value in node is not the same, two nodes are different. '''
return self.value != other.value
def __repr__(self):
''' This method is used to help debug,
which give the console a readable information. '''
return 'Node: ' + str(self.value)
def __hash__(self):
''' The node should be hashable,
due to the dictionary requirement. '''
return hash(self.value) | true |
3a7b06004f0d3f2079c7adcb3c808b85c666de9e | pawwahn/python_practice | /searches/bisect_algorithm.py | 833 | 4.21875 | 4 | # Python code to demonstrate the working of
# bisect(), bisect_left() and bisect_right()
# importing "bisect" for bisection operations
import bisect
# initializing list
li = [1, 3, 4, 4, 4, 6, 7]
# using bisect() to find index to insert new element
# returns 5 ( right most possible index )
print ("The rightmost index to insert, so list remains sorted is : ", end="")
print (bisect.bisect(li, 4))
# using bisect_left() to find index to insert new element
# returns 2 ( left most possible index )
print ("The leftmost index to insert, so list remains sorted is : ", end="")
print (bisect.bisect_left(li, 4))
# using bisect_right() to find index to insert new element
# returns 4 ( right most possible index )
print ("The rightmost index to insert, so list remains sorted is : ", end="")
print (bisect.bisect_right(li, 4, 0, 4))
| true |
0f2637e48a465145b7aaedd032287a493d250998 | pawwahn/python_practice | /dateutil/no_of_days_since_a_date.py | 382 | 4.46875 | 4 | # Python3 program to find number of days
# between two given dates
from datetime import date
def numOfDays(date1, date2):
return (date2 - date1).days
cur_date = date.today()
#print(cur_date)
yy,mm,dd = cur_date.year, cur_date.month, cur_date.day
#print(yy,mm,dd)
# Driver program
date1 = date(1947, 12, 13)
date2 = date(yy, mm, dd)
print(numOfDays(date1, date2), "days")
| true |
ad8d1457b814b898f82616824adb1bd04c51eb02 | pawwahn/python_practice | /lists.py | 1,429 | 4.21875 | 4 | a = []
print(a)
print(type(a))
b = [1,2,3]
print("length of b is: {}".format(len(b)))
c = [{'a':1,'b':2}]
print("length of dictonary c is: {}".format(len(c)))
d = [{'a':1},{'b':2},{}]
print("length of d is: {}".format(len(d)))
a = [1,2,3]
print("The value of a is: {}".format(a))
a.extend([4,5,6])
print("The extended value of a is : {}".format(a))
##loops##
b = [1,2,3]
for i in b:
print(i)
j=0
c = ['a',[1,2,3],{'a':1,'b':2},10]
for i in c:
j=j+1
print("The {}th element is {}:".format(j,i))
#append
a = [1,2,3]
print("The List before appending is : {}".format(a))
a.append([2,3])
print("The List after appending is : {}".format(a))
#specific element
print("The 2nd element is '{}'".format(a[2]))
#negative indexing
a = [1,2,3,4,5]
print("The negative index is : {}".format(a[-1]))
print("The negative index is : {}".format(a[-2]))
#slicing
a = [1,2,3,4,5]
print("The slicing is : {}".format(a[:3]))
print("The slicing is : {}".format(a[:-1]))
print("The slicing is : {}".format(a[1:2]))
#update list
a = [1,2,3,4,5]
print("The 0th element before updating is : '{}'".format(a[0]))
a[0]='a'
print("The 0th element before updating is : '{}'".format(a[0]))
#shuffel
from random import shuffle
a = [100,1,40,2,3]
a.sort(reverse=True)
print(a)
a.sort()
print("sorted list :{} -- line 63".format(a))
a = "Pavan Kumar"
print(a[2:5])
print(a[::-1]) | false |
0073e180f453878708da80052f1c3c0201a424f6 | pawwahn/python_practice | /logical_or_tough/triplets.py | 707 | 4.125 | 4 | # Sample Input 0
# 5 6 7
# 3 6 10
# Sample Output 0
# 1 1
# Explanation 0
#
# In this example:
#
# Now, let's compare each individual score:
#
# , so Alice receives point.
# , so nobody receives a point.
# , so Bob receives point.
# Alice's comparison score is , and Bob's comparison score is . Thus, we return the array .
#
# Sample Input 1
#
# 17 28 30
# 99 16 8
# Sample Output 1
#
# 2 1
def triplets(a,b):
a_sum = 0
b_sum = 0
for i,j in a,b:
print(a[i])
# if a[i] > b[j]:
# a_sum = a_sum+1
# elif a[i] < b[j]:
# b_sum = b_sum+1
# else:
# pass
# return (a_sum,b_sum)
print(triplets([1,2,3],[4,5,1]))
| false |
081a411eaa519f60eb34c97f5653f6ba1a0e4f54 | pawwahn/python_practice | /oops_python/create_class_and_object_in_python.py | 426 | 4.21875 | 4 | class Parrot:
# class attribute
species = 'bird'
#instance attribute
def __init__(self,name,age):
self.name = name
self.age = age
#instantiating the class
blu = Parrot("blu",5)
#prints the class object
print(blu)
# 1st way of retriving class attribute
print(Parrot.species)
#2nd way of retriving the class attribute,
print(blu.__class__.species)
#retrive object attributes
print(blu.name) | true |
c72a5e7822f21baa6c077a6dbf168de8ae08e6d7 | pawwahn/python_practice | /regular_expressions/reg_exp8_replace.py | 885 | 4.28125 | 4 | # replace a word in the given string
# to replace a word or substring , we need to compile by giving the search pattern
import re
str = "rat pat 'zat' 'fat', 'Mat' ,'hat' ,'Lat', zaq cat string integer"
#regx = re.compile("[d-z]at") # output --- food food food food Mat food Lat zaq cat string integer
out_put1 = re.findall("[^d-z]at",str)
print "output 1*--->",out_put1
regx = re.compile("[^d-z]at") # output --- rat pat zat fat food hat food zaq food string integer ## used ^ sym
#print regx,"\n"
str1 = regx.sub("food",str)
print str1,"\n"
out_put2 = re.findall("[d-z]at",str)
print "output 2*--->",out_put2
regx1 = re.compile("[d-z]at")
print regx1,"\n ------------>>"
str2 = regx1.sub("dude",str) # dude dude 'dude' 'dude', 'Mat' ,'dude' ,'Lat', zaq cat string integer
print str2 | false |
bf135b43e94f7e7863b621876f4e5e415e431911 | pawwahn/python_practice | /mnc_int_questions/data_abstraction.py | 1,157 | 4.28125 | 4 | class Employee:
__count = 10
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
def __secured(self):
print("Inside secured function..")
def get_count(self):
print("Employee count is :",Employee.__count)
emp = Employee()
emp2 = Employee()
#print(Employee.__dict__)
print(Employee()._Employee__secured())
print(Employee()._Employee__count)
print("The private variable is : {}".format(Employee._Employee__count))
try:
print(emp.__count) # can not access the private values directly even with the help of class or its object.. one can acheive it by using functions
#print(Employee().get_count())
except Exception as e:
print("Exception is : {}".format(e))
finally:
emp.display()
#################################
class A:
__dummy = 10
dummy = 100
print(dummy)
#print(_dummy) # u can not directly access __dummy value
#print(A().__dummy) # u can not directly create an object and call the private variables
def display_dummy(self):
print(A.__dummy)
A().display_dummy() | true |
c9cbfafce0956bb999662e6ad30ff458c2bf7ea4 | pawwahn/python_practice | /exceptions/except2.py | 356 | 4.15625 | 4 | lists = ['white','pink','Blue','Red']
clr = input('Enter the color you wish to find ??')
print(clr)
try:
if clr in lists:
print ("{} color found".format(clr))
else:
print("Color not found ")
except Exception as e:
print (e)
print ("IOException: Color not found")
finally:
print("There are several colors in the world")
| true |
036925d524f9407f11d1fc957881ef8c565d03b4 | pawwahn/python_practice | /numpy concepts/numpy1.py | 657 | 4.53125 | 5 | import numpy as np
a = np.array([1,2,3])
print("The numpy array created is {}".format(a))
print("The numpy array type is {}".format(type(a)))
print("The length of numpy array is {}".format(len(a)))
print("The rank of numpy array is {}".format(np.ndim(a)))
print("*************")
b = np.array([(1,2,3),(4,5,6,7)])
print(b)
print("The numpy array type is {}".format(type(b)))
print("The length of numpy array is {}".format(len(b)))
print("The length of b[0] is {}".format(len(b[0])))
print("The length of b[1] is {}".format(len(b[1])))
'''
reasons for using numpy even as we have lists:
1. occupies less memory
2. fast to access
3. convenient to use
''' | true |
c6b80e32d305b9007a2a2f38cc2ae25b1d3c5afc | Viveknegi5832/Python- | /Practicals.1.py | 1,155 | 4.59375 | 5 | ''' Ques.1 Write a function that takes the lengths of three sides :
side1, side2 and side3 of the triangle as the in put from the user using input function and
return the area and perimeter of the triangle as a tuple. Also , assert that sum of the length of
any two sides is greater than the third side
'''
import math
def Calculate(side1,side2,side3): # For calculating perimeter and area
area = 0
perimeter = 0
if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2 :
print("Given sides forms a Triangle ")
perimeter = side1 + side2 + side3
s = perimeter / 2
area = math.sqrt(s*(s - side1)*(s - side2)*(s - side3))
else :
print("Given sides Does not form a Triangle ")
return perimeter,area
def main():
side1 = int(input("Enter first side : "))
side2 = int(input("Enter second side : "))
side3 = int(input("Enter third side : "))
perimeter , area = Calculate(side1 , side2 , side3)
print()
print("Perimeter : ", perimeter)
print("Area : ", int(area))
main() | true |
855ff19d45c7bde65a07fc84a27cc10bc848919f | Viveknegi5832/Python- | /Practicals.7.py | 2,282 | 4.34375 | 4 | '''
Ques.7 Write a menu driven program to perform the following on strings :
a) Find the length of string.
b) Return maximum of three strings.
c) Accept a string and replace all vowels with “#”
d) Find number of words in the given string.
e) Check whether the string is a palindrome or not.
'''
def len_str():
str = input("Enter the string: ")
print("Length of string: ", len(str))
def maximum():
str1 = input("Enter string 1: ")
str2 = input("Enter string 2: ")
str3 = input("Enter string 3: ")
if len(str1) > len(str2) and len(str1) > len(str3) :
max = str1
elif len(str2) > len(str1) and len(str2) > len(str3) :
max = str2
elif len(str3) > len(str1) and len(str3) > len(str2) :
max = str3
print("Maximum : " , max)
def replace_vowels():
str = input("Enter the string: ")
new_str = ""
vowels = ['a','e','i','o','u']
for i in range(0, len(str), 1):
if str[i].lower() in vowels:
new_str += "#"
else:
new_str += str[i]
print("Replaced string: ", new_str)
def numofwords():
str = input("Enter the string: ")
str = str.strip() + " "
count = 0
for i in range(0, len(str), 1):
if str[i] == " ":
count += 1
print("No of words: ", count)
def palindrome():
str = input("Enter the string: ")
new_str = str[::-1] #This will reverse the string
if str == new_str:
print(str," is palindrome ")
else:
print(str," is not palindrome")
def main():
ch = 'y'
while ch == 'y' or ch == 'Y':
print("\nMenu")
print("-"*30)
print("1. Length of string")
print("2. Maximum of three strings")
print("3. Replace vowels with '#'")
print("4. No. of words")
print("5. Check Palindrome")
print("6. Exit")
print("-"*30)
option = input("Your choice: ")
switcher = {
'1' : len_str,
'2' : maxof_three,
'3' : replace_vowels,
'4' : numofwords,
'5' : palindrome,
'6' : quit
}
func = switcher.get(option, lambda: print("Invalid Choice!"))
func()
ch = input("\nWant to continue? (y/n) : ")
main()
| true |
deb484aa1ad4612c916100e222b7629065824a6b | asadmshah/cs61a | /week2/hw.py | 1,689 | 4.15625 | 4 | """
CS61A Homework 2
Asad Shah
"""
from operator import add
from operator import mul
def square(x):
"""
Return square of x.
>>> square(4)
16
"""
return x * x
# Question 1
def summation(n, term):
"""
Return the sum of the first n terms in a sequence.
>>> summation(4, square)
30
"""
t, i = 0, 1
while i <= n:
t += term(i)
i += 1
return t
def product(n, term):
"""
Return the product of the first n terms in a sequence.
>>> product(4, square)
576
"""
t, i = 1, 1
while i <= n:
t *= term(i)
i+=1
return t
def factorial(n):
"""
Return n factorial by calling product.
>>> factorial(4)
24
"""
return product(n, lambda x: x)
# Question 2
def accumulate(combiner, start, n, term):
"""
Return the result of combining the first n terms in a sequence.
"""
t, i = start, 1
while i <= n:
t = combiner(t, term(i))
i += 1
return t
def summation_using_accumulate(n, term):
"""
An implementation of summation using accumulate.
>>> summation_using_accumulate(4, square)
30
"""
return accumulate(add, 0, n, term)
def product_using_accumulate(n, term):
"""
An implementation of product using accumulate.
>>> product_using_accumulate(4, square)
576
"""
return accumulate(mul, 1, n, term)
# Question 3
def double(function):
"""
Return a function that applies f twice.
>>> double(square)(2)
16
"""
def functioner(x):
return function(function(x))
return functioner
# Question 4
def repeated(f, n):
"""
Return the function that computes the nth application of f.
>>> repeated(square, 2)(5)
625
>>> repeated(square, 4)(5)
152587890625
"""
f = double(f)
while n > 3:
f = double(f)
n -= 1
return f
# Question 5
| true |
43bfeab6ec2085e850820b2ed4adb8ed3d94ac12 | andyzhuravlev/python_practice | /task_1.py | 918 | 4.1875 | 4 |
"""
Есть список a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89].
Выведите все элементы, которые меньше 5.
Самый простой вариант, который первым приходит на ум — использовать цикл for:
for elem in a:
if elem < 5:
print(elem)
Также можно воспользоваться функцией filter, которая фильтрует элементы согласно заданному условию:
print(list(filter(lambda elem: elem < 5, a)))
И, вероятно, наиболее предпочтительный вариант решения этой задачи — списковое включение:
print([elem for elem in a if elem < 5])
"""
lis = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
lis.sort()
i = 0
item = lis[i]
while item < 5:
print(item)
i += 1
item = lis[i]
| false |
a48bf0b58650a53816aaa76dafee51b5bc369ae5 | marcmanley/mosh | /python_full/HelloWorld/test.py | 972 | 4.28125 | 4 | # How to print multiple non-consecutive values from a list with Python
from operator import itemgetter
animals = ['bear', 'python', 'peacock',
'kangaroo', 'whale', 'dog', 'cat', 'cardinal']
print(itemgetter(0, 3, 4, 1, 5)(animals))
print(animals)
print(type(animals))
# Slicing indexes
course_name = "Python Programming"
print(len(course_name))
print(course_name[0])
print(course_name[-1])
# Note here that the slicing ends at "t" and not at "h" because the indexing starts at [0]
print(course_name[0:3])
# if you leave off the opening number, Python will automotically assume it to be [0]
print(course_name[:3])
# This returns a copy of the original string
print(course_name[:])
# ESC character
new_course = "\"Intermediate\" Programming"
print(new_course)
# How to use backslash in a str
new__new_course = "Python\\Programming"
print(new__new_course)
# Breaks on a new line
new_new_new_course = "Python\nProgramming"
print(new_new_new_course)
| true |
bbc19563fe8ff2af7dc2f97aa0fbdb945cdcb0cf | py1-10-2017/OliviaHan-py1-2017 | /Funwithfunctions.py | 736 | 4.125 | 4 | def odd_even():
for i in range (1, 5):
if i%2 != 0:
print "Number is",i,".", "This is an odd number."
else:
print "Number is", i,".", "This is an even number."
odd_even()
# a is for the list. b is the number be multiplied. c is for the results list
def multiply(a,b):
for i in range (0,len(a)):
a[i] = a[i]*b
return a
multiply([2,4,5],3)
def layered_multiples(arr):
newArray = []
for i in range (0,len(arr)):
ll = []
for j in range (0,arr[i]):
ll.append(1)
newArray.append(ll)
print newArray
layered_multiples(multiply([2,4,5],3))
# # output
# >>>[[1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
| false |
f2fdb7074f35dab7a898f8981df7bd5102abaf22 | godaipl/python3study | /2python基础/1数据类型和变量/1数据类型.py | 556 | 4.1875 | 4 | # 数据类型
# 整数 int
a = 1
b = 100
c = -100
d = 0
# 浮点数 float
f_a = 1.0
# 1.23乘以10的9次方
f_b = 1.23e9
print('1.23e9 is ', f_b)
# 字符串 string
str1 = 'a'
str2 = "'a'"
str3 = "I'm OK"
str4 = "I'm \"OK\""
print(str4)
# 使用 r'' 来标注相应内容无需转义
print(r'\t\n')
# 使用以下方式替换\n 换行操作
print('''aaaaaa
bbbbbb
cccccc''')
# 布尔值 boolean
print(True)
print(False)
print(True or False)
print(True and True)
print(not True)
# 空值
print(None)
if None:
print(1)
if not None:
print(2) | false |
5b05967d412a28c2085b2de504eec80831b6f67b | maskalja/WD1-12_Functions | /12.3_Geography Quiz/main.py | 429 | 4.15625 | 4 | import random
count = 0
capitals = {"Slovenia": "Ljubljana", "Austria": "Vienna", "Hungary": "Budapest", "USA": "Washington"}
countries = ["Slovenia", "Austria", "Hungary", "USA"]
for country in countries:
count += 1
r = random.randint(0, count-1)
answer = input(f"What is the capital of {countries[r]}? ")
if answer.lower() == capitals[countries[r]].lower():
print("Correct answer!")
else:
print("Wrong answer!") | true |
37f5758d6dd77e5a90ccb4a4fd11e8f8b8649041 | kevinjyee/PythonExcercises | /Excercise02_21.py | 480 | 4.4375 | 4 | '''Write a program that prompts the user to enter a monthly saving amount and
displays the account value after the sixth month. Here is a sample run of the
program:
'''
def main():
interest = .05;
total = 0;
savings = int(input("Enter the monthly saving amount: "));
for i in range(0,6):
savings = savings*(1+interest/12);
total += savings;
print("After the sixth month, the account value is ",total);
if __name__ == '__main__':
main()
| true |
bad718105eadf1f0206a4335278b0f74415f457b | kevinjyee/PythonExcercises | /Excercise04_19.py | 510 | 4.3125 | 4 | '''(Compute the perimeter of a triangle) Write a program that reads three edges for a
triangle and computes the perimeter if the input is valid. Otherwise, display that
the input is invalid. The input is valid if the sum of every pair of two edges is
greater than the remaining edge. Here is a sample run'''
def main():
a,b,c = eval(input("Enter three edges: "));
if(a+b < c or b+c < a or a+c < b):
print("The input is invalid");
else:
print(a+b+c);
if __name__ == '__main__':
main() | true |
5e47ac70f312466460693882b93afc8746a3017b | Barret-ma/leetcode | /63. Unique Paths II.py | 1,807 | 4.28125 | 4 | # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
# Now consider if some obstacles are added to the grids. How many unique paths would there be?
# An obstacle and empty space is marked as 1 and 0 respectively in the grid.
# Note: m and n will be at most 100.
# Example 1:
# Input:
# [
# [0,0,0],
# [0,1,0],
# [0,0,0]
# ]
# Output: 2
# Explanation:
# There is one obstacle in the middle of the 3x3 grid above.
# There are two ways to reach the bottom-right corner:
# 1. Right -> Right -> Down -> Down
# 2. Down -> Down -> Right -> Right
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
height = len(obstacleGrid)
if height == 0:
return 0
width = len(obstacleGrid[0])
dirs = [(-1, 0), (0, -1)]
dp = [[0 for _ in range(width)] for i in range(height)]
dp[0][0] = 0 if obstacleGrid[0][0] == 1 else 1
for i in range(height):
for j in range(width):
if i == 0 and j == 0:
continue
if obstacleGrid[i][j] == 1:
continue
for dir in dirs:
right = j + dir[0]
down = i + dir[1]
if right < 0 or down < 0 or right >= width or down >= height:
continue
dp[i][j] += dp[down][right]
return dp[height - 1][width - 1]
s = Solution()
print(s.uniquePathsWithObstacles(
[
[1]
]
)) | true |
f6b4a44ec75285d1d43e9767e3c0ed3a6cde25ca | Barret-ma/leetcode | /543. Diameter of Binary Tree.py | 1,407 | 4.375 | 4 | # Given a binary tree, you need to compute the length of the
# diameter of the tree. The diameter of a binary tree is the
# length of the longest path between any two nodes in a tree.
# This path may or may not pass through the root.
# Example:
# Given a binary tree
# 1
# / \
# 2 3
# / \
# 4 5
# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
# Note: The length of path between two nodes is represented by the number of edges between them.
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
res = 0
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res = 0
self.maxDepth(root)
return self.res
def maxDepth(self, root):
if not root:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
self.res = max(self.res, left + right)
return max(left, right) + 1
root1 = TreeNode(1)
root2 = TreeNode(2)
root3 = TreeNode(3)
root4 = TreeNode(4)
root5 = TreeNode(5)
root6 = TreeNode(6)
root1.left = root2
root2.left = root3
root2.right = root4
root3.left = root5
root4.right = root6
s = Solution()
print(s.diameterOfBinaryTree(root1))
| true |
4b8d187a174a15db189f2095ccd00d689b4b991a | Barret-ma/leetcode | /112. Path Sum.py | 1,507 | 4.125 | 4 | # Given a binary tree and a sum, determine if the tree has
# a root-to-leaf path such that adding up all the values along
# the path equals the given sum.
# Note: A leaf is a node with no children.
# Example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ \
# 7 2 1
# return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return
return self.travel(root, root.val, sum)
def travel(self, root, sum, target):
if not root:
return False
if not root.left and not root.right:
return sum == target
sumRight = 0
sumLeft = 0
if root.right:
sumRight = root.right.val
if root.left:
sumLeft = root.left.val
return self.travel(root.left, sum + sumLeft, target) or self.travel(root.right, sum + sumRight, target)
root5 = TreeNode(5)
root4 = TreeNode(4)
root11 = TreeNode(11)
root7 = TreeNode(7)
root2 = TreeNode(2)
root5.left = root4
root4.left = root11
root11.left = root7
root11.right = root2
s = Solution()
print(s.hasPathSum(root5, 22))
| true |
aea69a498caab1fe218aa0df397d93e9e5a937d7 | alexanch/Data-Structures-implementation-in-Python | /BST.py | 2,038 | 4.28125 | 4 | """ Binary Search Tree Implementation: search, insert, print methods. """
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
return self.insert_helper(self.root,new_val)
def insert_helper(self,start,new_val):
"""
Helper function for recursive insert method.
"""
if new_val>start.value:
if start.right:
self.insert_helper(start.right,new_val)
else:
start.right = Node(new_val)
elif new_val<start.value:
if start.left:
self.insert_helper(start.left,new_val)
else:
start.left = Node(new_val)
def search(self, find_val):
return self.search_helper(self.root,find_val)
def search_helper(self, start, find_val):
"""
Helper function for recursive search method.
"""
if start:
if start.value == find_val:
return True
elif find_val>start.value:
return self.search_helper(start.right,find_val)
elif find_val<start.value:
return self.search_helper(start.left,find_val)
return False
def print_tree(self):
return self.print_helper(self.root)[:-1]
def print_helper(self,next,traversal =''):
"""
Helper function for recursive print method.
"""
if next:
traversal +=(str(next.value)+'-')
traversal = self.print_helper(next.left, traversal)
traversal = self.print_helper(next.right,traversal)
return traversal
"""
Test case:
# Set up tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
# Check search
# Should be True
print tree.search(4)
# Should be False
print tree.search(6)
"""
| true |
3ef383f3fa3969f09a16c32ae03a47a039b42737 | Ibbukanch/Python-programs | /pythonprograms/Algorithm/sqrtnewton.py | 255 | 4.46875 | 4 | # program to find the sqrt of number using newton method
# Take input from user
n=float(input("Enter the Number"))
t = n
# calculates the sqrt of a Number
while abs(t- n/t) > 1e-15 * t:
t = (n/t + t) / 2
# Print the sqrt of a number
print(round(t,2))
| true |
bb44f2a3045953f5c844f233f07e4e310c9aebf4 | ajaybhatia/python-practical-2020 | /18-practical.py | 1,753 | 4.25 | 4 | '''
Practical 18:
Perform following operations on two matrices.
1) Addition 2) Subtraction 3) Multiplication
'''
def print_matrix(matrix):
for row in range(len(matrix)):
for col in range(len(matrix[0])):
print(matrix[row][col], end=" ")
print()
def matrix_addition(a, b):
if len(a[0]) == len(b[0]) and len(a) == len(b):
new_matrix = []
for r in range(len(a)):
row_ = []
for c in range(len(a[0])):
row_.append(a[r][c]+b[r][c])
new_matrix.append(row_)
return new_matrix
else:
print("Matrices are not equal")
def matrix_subtraction(a, b):
if len(a[0]) == len(b[0]) and len(a) == len(b):
new_matrix = []
for r in range(len(a)):
row_ = []
for c in range(len(a[0])):
row_.append(a[r][c]-b[r][c])
new_matrix.append(row_)
return new_matrix
else:
print("Matrices are not equal")
def matrix_multiplication(a, b):
if len(a[0]) == len(b):
new_matrix = []
for r in range(len(a)):
row_ = []
for c in range(len(b[0])):
sum = 0
for k in range(len(a[0])):
sum += a[r][k]*b[k][c]
row_.append(sum)
new_matrix.append(row_)
return new_matrix
else:
print("Matrices row and col are not equal")
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
print("Addition Resultant: ")
print_matrix(matrix_addition(matrix1, matrix2))
print("Subtraction Resultant: ")
print_matrix(matrix_subtraction(matrix1, matrix2))
print("Multiplication Resultant: ")
print_matrix(matrix_multiplication(matrix1, matrix2))
| false |
b701916d7032b3449af2d316638b828cfcbe4267 | ajaybhatia/python-practical-2020 | /27-practical.py | 1,289 | 4.125 | 4 | '''
Practical 27
Perform following operations on dictionary
1) Insert 2) delete 3) change
'''
book = {
1: "Compute sum, subtraction, multiplication, division and exponent of given variables input by the user.",
2: "Compute area of following shapes: circle, rectangle, triangle, square, trapezoid and parallelogram.",
3: "Compute volume of following 3D shapes: cube, cylinder, cone and sphere.",
4: "Compute and print roots of quadratic equation ax 2 +bx+c=0, where the values of a, b, and c are input by the user.",
5: "Print numbers up to N which are not divisible by 3, 6, 9,, e.g., 1, 2, 4, 5, 7,....",
6: "Write a program to determine whether a triangle is isosceles or not?",
7: "Print multiplication table of a number input by the user.",
8: "Compute sum of natural numbers from one to n number.",
9: "Print Fibonacci series up to n numbers e.g. 0 1 1 2 3 5 8 13.....n",
10: "Compute factorial of a given number."
}
# Insert
print("Insertion...")
book[11] = "Count occurrence of a digit 5 in a given integer number input by the user."
print(book, end="\n\n")
# Delete
print("Deletion...")
book.pop(4)
print(book, end="\n\n")
# Update
print("Updation...")
book[8] = "Compute product of natural numbers from one to n number."
print(book)
| true |
056eec7bf4c59ea34c4248341d289d168cff0771 | imshile/Python_Regex_Engine | /Python_Regex_Search_Vs_Match.py | 2,149 | 4.375 | 4 | # Python Regex
# re Regular expression operations.
# This module provides regular expression matching operations similar to those found in Perl.
# Both patterns and strings to be searched can be Unicode strings (str) as well as 8-bit strings (bytes).
# However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match a Unicode string with a byte pattern or vice-versa; similarly,
# when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string.
# Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their
# special meaning. This collides with Pythons usage of the same character for the same purpose in string literals; for example, to match a literal
# backslash, one might have to write '\\\\' as the pattern string, because the regular expression must be \\, and each backslash must be expressed
# as \\ inside a regular Python string literal.
#
# search() vs. match()
# Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while
# re.search() checks for a match anywhere in the string (this is what Perl does by default).
#
# For example:
#
re.match("c", "abcdef") # No match
re.search("c", "abcdef") # Match
# OUTPUT: <re.Match object; span=(2, 3), match='c'>
#
# Regular expressions beginning with '^' can be used with search() to restrict the match at the beginning of the string:
#
re.match("c", "abcdef") # No match
re.search("^c", "abcdef") # No match
re.search("^a", "abcdef") # Match
# OUTPUT: '<re.Match object; span=(0, 1), match='a'>'
#
# Note however that in MULTILINE mode match() only matches at the beginning of the string, whereas using search() with a regular expression beginning
# with '^' will match at the beginning of each line.
#
re.match('X', 'A\nB\nX', re.MULTILINE) # No match
re.search('^X', 'A\nB\nX', re.MULTILINE) # Match
# OUTPUT: '<re.Match object; span=(4, 5), match='X'>'
| true |
6a62677db52869b3aeb03c3c1ee041a98623ab91 | imshile/Python_Regex_Engine | /Python_Regular_Expressions_Named_Group.py | 2,785 | 4.3125 | 4 | # Python Regular Expressions
# Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python
# and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you want to match; this
# set might contain English sentences, or e-mail addresses, or TeX commands, or anything you like.
# You can then ask questions such as Does this string match the pattern?, or Is there a match for the pattern anywhere in this string?.
# You can also use REs to modify a string or to split it apart in various ways.
#
# Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C.
# For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to
# produce bytecode that runs faster. Optimization isnt covered in this document, because it requires that you have a good understanding of the matching
# engines internals.
#
# The regular expression language is relatively small and restricted, so not all possible string processing tasks can be done using regular expressions.
# There are also tasks that can be done with regular expressions, but the expressions turn out to be very complicated. In these cases, you may be better
# off writing Python code to do the processing; while Python code will be slower than an elaborate regular expression, it will also probably be more
# understandable.
#
# The syntax for a named group is one of the Python-specific extensions: (?P<name>...). name is, obviously, the name of the group.
# Named groups behave exactly like capturing groups, and additionally associate a name with a group. The match object methods that deal with capturing
# groups all accept either integers that refer to the group by number or strings that contain the desired groups name.
# Named groups are still given numbers, so you can retrieve information about a group in two ways:
#
p = re.compile(r'(?P<word>\b\w+\b)')
m = p.search( '(((( Lots of punctuation )))' )
m.group('word')
# OUTPUT: 'Lots'
m.group(1)
# OUTPUT: 'Lots'
#
# Named groups are handy because they let you use easily-remembered names, instead of having to remember numbers.
#
# Heres an example RE from the imaplib module:
#
InternalDate = re.compile(r'INTERNALDATE "'
r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
r'(?P<year>[0-9][0-9][0-9][0-9])'
r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
r'"')
| true |
8dbc06994034f1868cb5bc9ea6675c41b7600fbe | jake20001/Hello | /everydays/20200814/4.py | 1,623 | 4.125 | 4 | # coding: utf-8
"""
@author: zhangjk
@file: 14.py
@date: 2020-02-28
说明:iter 迭代器
"""
import sys # 引入 sys 模块
def f1():
# list=[1,2,3,4]
list = "hello world"
it = iter(list) # 创建迭代器对象
while True:
try:
print(next(it))
except StopIteration:
sys.exit()
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
# NEW
i = 0
a = 65
def func():
global i
i += 1
return chr(a+i)
def iter2():
# nstr = "Hello Python"
# s = iter(nstr)
# print('xxxx',s)
# # for i in s:
# # print(i)
# while True:
# try:
# print(next(s))
# except:
# break
for i in iter(func,'P'):
print(i)
def iter3():
nstr = "Hello Python"
next()
class data:
list: list = [1, 2, 3, 4, 5, 6]
index = 0
def __call__(self, *args, **kwargs):
item = self.list[self.index]
self.index += 1
return item
def __iter__(self):
self.i = iter(self.list)
return self.i
# for item in iter(data(), 3): #每一次迭代都会调用一次__call__方法,当__call__的返回值等于3是停止迭代
# print(item)
def main():
f1()
# myclass = MyNumbers()
# myiter = iter(myclass)
# print(next(myiter))
# print(next(myiter))
# print(next(myiter))
# print(next(myiter))
# print(next(myiter))
# iter2()
# pass
if __name__ == '__main__':
main() | false |
aa61fb4c0ea2ae4e8d0b3c89c1e3c690d056a993 | PabloNunes/AceleraDev | /2_Segundo_Modulo/main.py | 2,437 | 4.3125 | 4 | from abc import ABC, abstractclassmethod
class Department:
# Department class: Stores department name and code
def __init__(self, name, code):
self.name = name
self.code = code
class Employee(ABC):
# Employee class: A abstract class for inheritance
# Constants for our Employees
WORKLOAD = 8
PERCENTAGE_BONUS = 0.15
def __init__(self, code, name, salary, department):
"""
Employee class constructor:
- Employee code {int}
- Name {string}
- Salary {float}
- Department (Protected) {department class}
"""
self.code = code
self.name = name
self.salary = salary
self.__department = department
@abstractclassmethod
def calc_bonus(self):
# Computes the bonus for the month - Abstract method
pass
@classmethod
def get_hours(cls):
# Returns work hours - Class method
return cls.WORKLOAD
def get_department(self):
# Returns Department name
return self.__department.name
def set_department(self, departament_name):
# Changes department name if needed
self.__department.name = departament_name
class Manager(Employee):
def __init__(self, code, name, salary):
"""
Manager class constructor (Inherits from Employee):
- Employee code {int}
- Name {string}
- Salary {float}
- Department (Protected) {department class}
"""
super().__init__(code, name, salary, Department('managers', 1))
def calc_bonus(self):
# Computes Bonus - Uses the Employee class method
return self.salary * Employee.PERCENTAGE_BONUS
class Seller(Employee):
def __init__(self, code, name, salary):
"""
Seller class constructor (Inherits from Employee):
- Employee code {int}
- Name {string}
- Salary {float}
- Department (Protected) {department class}
"""
super().__init__(code, name, salary, Department('sellers', 2))
self.__sales = 0
def calc_bonus(self):
# Computes Bonus - Uses the Employee class method
return self.__sales * Employee.PERCENTAGE_BONUS
def get_sales(self):
return self.__sales
def put_sales(self, sale):
# Adding a new sale to the total
self.__sales += sale
| true |
cf428b248dd28892aba4affa59ddb983211cc495 | andrefisch/EvanProjects | /text/emailsToSpreadsheet/splitNames.py | 1,054 | 4.21875 | 4 | # Extract first, last, and middle name from a name with more than 3 parts
# determine_names(listy)
def determine_names(listy):
dicty = {}
lasty = []
middley = []
# first spot is always first name at this point
dicty['first_name'] = listy[0]
dicty['middle_name'] = ""
dicty['last_name'] = ""
del listy[0]
if len(listy) == 0:
return dicty
# - reverse list
# - take first name in reversed list (last name) and add it to last name list, delete it
# - look at next name and see if it is capitalized
# - if not add to last name list, repeat
# - otherwise add this and rest to middle name list
listy = listy[::-1]
lasty.append(listy[0])
del listy[0]
lasts = True
for i in range(0, len(listy)):
if (not listy[i].istitle()) and lasts:
lasty.insert(0, listy[i])
else:
lasts = False
middley.insert(0, listy[i])
dicty['middle_name'] = ' '.join(middley)
dicty['last_name'] = ' '.join(lasty)
return dicty
| true |
58f1a8fe9eeea28a52f4742358d4095a80309a51 | luizhuaman/platzi_python | /p16_limitRecursividad.py | 2,451 | 4.1875 | 4 | def me():
"""
- INICIO
Este código teiene como propósito Encontrar el límite de recursión teórico de mi máquina y compararlo con el real.
1. Defino una funcion recursiva
2. Le paso dos argumentos: n y resultado_suma haciendo referencia a un número n y mi suma.
3. Imprimo el resultado de suma iterado después de pasarlo por un ciclo for
- FINAL
El resultado que me va a devolver al final es:
=>
[Previous line repeated 993 more times]==> Cuando mi límite de recursiónteórico es de 1000
...
RecursionError: maximum recursion depth exceeded while calling a Python object
- RECURSION LIMIT
Para cambiar el límite de recursiónen python se usa la función: sys.setrecursionlimit(limit)
Esta función ajusta mi limite máximo de profundidad del stack del interprete de pyhton, este límite previene que la recursión "infinita" crashee el "C stack" de Pyhton
- CONSIDERACIONES
El límite es directamente proporcional a la máquina. Es plataforma dependiente y es mejor usarlo cuando el contexto lo amerite.
Si el nuevo límite de profundidad en la recursión es muy bajo el error RecursionError aparece.
https://docs.python.org/3/library/sys.html#sys.setrecursionlimit
- ¿CUAL ES MI LÍMITE DE RECURSIÓN?
=> Para saber el límite de recursiónse usa: sys.getrecursionlimit()
Me devuelve el valor actual del limite de recursión para el stackde python.
# Modificamos el limite de recursion a 2000 con la funcion sys.setrecursionlimit() que trae el modulo sys
sys.setrecursionlimit(2000)
"""
pass
#Con este import traigo palabra reservada sys. del sistema
import sys
print(help(me))
print(f'Mi límite de recursión teórico es: {sys.getrecursionlimit()}')
if __name__ == '__main__':
def recursive_function (n , resultado_sum):
if n < 1:
print(f'Vuelve siempre cero para quese ejecute un true infinito {n}. Soy el resultado de una suma y tengo el valor de: {resultado_sum} ')
return sum
else:
# Soy la suma inicialmente de la forma => n = n+1
# Y mi resultado lo voy a iterar, repetir como una suma => (n + 1) + resultado_suma
recursive_function(n - 1, resultado_sum + n)
#El valor de c me dará indicacióndeque empieza
c = 0
# Le digo que me itere hasta 998.
for i in range(998):
c += 1
valor_iterado = recursive_function(c, 0) | false |
be6d059dbd1b40680f329f5f38330c506e32f85e | ontasedu/eric-courses | /python_advanced_course/Ericsson Python Adv Solutions/q1_nested_if.py | 783 | 4.1875 | 4 | '''
Get the user to input a list of numbers.
Then output a menu for the user to select either the sum/average/max/min.
Then execute the selected function :-
- using nested ifs
- using a dict
'''
from __future__ import division
def average(numbers):
return sum(numbers) / len(numbers)
'get user to input 4 numbers'
numbers = [ ]
for _ in xrange(4):
number = int(raw_input('pls input number '))
numbers.append(number)
action = raw_input('type sum/max/min/average ')
result = 0
if action == 'sum':
result = sum(numbers)
elif action == 'average':
result = average(numbers)
elif action == 'max':
result = max(numbers)
elif action == 'min':
result == min(numbers)
print result
| true |
307264ac158f25b11562a3f745eaec1d71c4e8ef | jonyachen/TestingPython | /bubblesort3.py | 735 | 4.28125 | 4 | #Bubble sort that's a combo of 1 and 2. while and for loop geared towards FPGA version
myList = [5, 2, 1, 4, 3]
def bubblesort(list):
max = len(list) - 1
sorted = False
i = 0
j = i + 1
while not sorted:
sorted = True
for j in range(0 , max): # or (0, length)
a = list[i]
b = list[j]
if a > b:
sorted = False
list[i] = b
list[j] = a
i = i + 1
j = j + 1
if ( j == max):
i = 0
j = i + 1
print list
return list
#bubblesort(myList)
#print myList
print bubblesort(myList)
WRONG because for loop already iterates through everything automatically | true |
c7c79c54d109229c76ebf8c4ad5b6a309958385c | AlexandreBalataSouto/Python-Games | /PYTHON BASICS/basic_05.py | 363 | 4.28125 | 4 | #List
names = ["Alo","Marco","Lucia"]
print(len(names))
print(names)
names.append("Eustaquio")
print(names)
print(names[1])
print(names[0:3])
print("------------------Loop 01--------------------------")
for name in names:
print(name)
print("------------------Loop 02--------------------------")
for index in range(0,len(names)):
print(names[index]) | true |
41f389f0a9213dc6aada4ae8ffc136e7133a9145 | dinglight/corpus_tools | /scripts/char_frequency.py | 1,071 | 4.375 | 4 | """count the every char in the input file
Usage:
python char_frequency.py input_file.txt
"""
import sys
import codecs
def char_frequency(file_path):
"""count very char in the input file.
Args:
file_path: input file
return:
a dictionary of char and count
"""
char_count_dict = dict()
with codecs.open(file_path, encoding='utf-8-sig') as input_file:
for line in input_file.readlines():
line = line.rstrip()
# jump over empty line
if not line:
continue
word = line.split()[0]
for char in word:
keys = char_count_dict.keys()
if char in keys:
char_count_dict[char] += 1
else:
char_count_dict[char] = 1
return char_count_dict
if __name__ == '__main__':
char_count_dict = char_frequency(sys.argv[1])
sorted_char_count_dict = sorted(char_count_dict.items(), key=lambda x:x[0])
for char, count in sorted_char_count_dict:
print(char, count)
| true |
3159b7ac32f5389d64ee595deca47a02d38e4d5f | FrimpongAlbertAttakora/pythonWith_w3school | /18-Array.py | 1,595 | 4.5625 | 5 | #Arrays are used to store multiple values in one single variable:
cars = ["Ford", "Volvo", "BMW"]
#You refer to an array element by referring to the index number.
'''
x = cars[0]
print(x)
'''
#Modify the value of the first array item:
'''
cars[0] = "Toyota"
print(cars)
'''
#Use the len() method to return the length of an array (the number of elements in an array).
'''
x = len(cars)
print(x)
'''
#You can use the for in loop to loop through all the elements of an array.
'''
for x in cars:
print(x)
'''
#You can use the append() method to add an element to an array.
'''
cars.append("Honda")
print(cars)
'''
#You can use the pop() method to remove an element from the array.
'''
cars.pop(1)
print(cars)
'''
#You can also use the remove() method to remove an element from the array.
'''
cars.remove("Volvo")
print(cars)
'''
#Array Methods
'''
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
'''
| true |
debbe8e2675c001a9ef890b134bd00fd1218e807 | FrimpongAlbertAttakora/pythonWith_w3school | /20-Inheritance.py | 2,930 | 4.65625 | 5 | #Inheritance allows us to define a class that inherits all the methods and properties from another class.
#Parent class is the class being inherited from, also called base class.
#Child class is the class that inherits from another class, also called derived class.
#Any class can be a parent class, so the syntax is the same as creating any other class:
'''
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
#child class
class Student(Person):
pass
#Now the Student class has the same properties and methods as the Person class.
x = Student("Mike", "Olsen")
x.printname()
'''
#We want to add the __init__() function to the child class (instead of the pass keyword).
'''
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
'''
#When you add the __init__() function, the child class will no longer inherit
# the parent's __init__() function.
#To keep the inheritance of the parent's __init__() function, add a call to
# the parent's __init__() function:
'''
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
'''
#Python also has a super() function that will make the child class inherit all the
# methods and properties from its parent:
'''
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
'''
#Add a property called graduationyear to the Student class:
'''
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
'''
#Add a method called welcome to the Student class:
'''
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2020)
x.welcome()
'''
| true |
5688b0bcff2e91ab54d0b6ba33b6d825adc4d93d | manankshastri/Python | /Python Exercise/exercise61.py | 304 | 4.25 | 4 | #function to check if a number is prime or not
def is_prime(n):
if (n>1):
for i in range(2,n):
if(n%i ==0):
print(n,"is not Prime\n")
break
else:
print(n,"is Prime\n")
else:
print(n,"is not Prime\n")
is_prime(31)
| true |
ea407b375b5f63593b1b16e16ccb7d8d10281f0c | manankshastri/Python | /rps.py | 1,291 | 4.1875 | 4 | from random import randint
def rock_paper_scissors():
player = input('Rock (r/R) , Paper (p/P) or Scissor (s/S)? ')
# a random number is generated (1/2/3)
c = randint(1, 3)
if player == 'r' or player == 'R':
print("O vs", end=" ")
f = 0
p = 1
elif player == 'p' or player == 'P':
print("____ vs", end=" ")
f = 0
p = 2
elif player == 's' or player == 'S':
print(">8 vs", end=" ")
f = 0
p = 3
# for invalid choice
else:
f = 1
# if valid choice
if f == 0:
if c == 1:
print("O")
elif c == 2:
print("____")
else:
print(">8")
# if valid choice
if f != 1:
if p == c:
print("DRAW!!!")
elif p == 1 and c == 3:
print("Player won!!!")
elif p == 1 and c == 2:
print("Computer won!!!")
elif p == 2 and c == 1:
print("Player won!!!")
elif p == 2 and c == 3:
print("Computer won!!!")
elif p == 3 and c == 2:
print("Player won!!!")
elif p == 3 and c == 1:
print("Computer won!!!")
# if invalid choice
else:
print("Invalid Choice!!!")
rock_paper_scissors() | false |
8b443ea764bf7e9c05ff2da982fade77b90fc742 | isobelfc/eng84_python_data_collections | /dictionaries.py | 1,422 | 4.1875 | 4 | # Dictionaries
# Dictionaries use Key Value pairs to save the data
# The data can be retrieved by its value or the key
# Syntax {}
# Within the dictionary we can also have list declared
# Let's create one
dev_ops_student = {
"key": "value",
"name": "James",
"stream": "devops",
"completed_lesson": 3,
"completed_lesson_names": ["variables", "data types", "collections"]
}
# print(dev_ops_student)
# # Confirm the type
# print(type(dev_ops_student))
# print(dev_ops_student["name"])
# print(dev_ops_student["completed_lesson"])
# print(dev_ops_student["completed_lesson_names"][1])
#
# print(dev_ops_student.keys())
# print(dev_ops_student.values())
# Add "operators" in completed_lesson_names
# dev_ops_student["completed_lesson_names"].append("operators")
# print(dev_ops_student["completed_lesson_names"])
#
# # Change completed_lesson from 3 to 4
# dev_ops_student["completed_lesson"] = 4
# print(dev_ops_student["completed_lesson"])
#
# # Remove the "data type" from completed_lesson_names
# dev_ops_student["completed_lesson_names"].remove("data types")
# print(dev_ops_student["completed_lesson_names"])
# Sets and the difference
# Syntax {}
# Let's create a set
car_parts = {"wheels", "windows", "doors"}
print(car_parts)
print(type(car_parts))
car_parts.add("seats")
print(car_parts)
# Use discard() to remove values
car_parts.discard("doors")
print(car_parts)
# Frozen sets - homework
| true |
5fe2d1240e185760046c977c435724982867b4b2 | NehaNayak09/Coding-Tasks | /marathon programs/marathon_time_calculator.py | 433 | 4.125 | 4 | # Marathon time calculator
pace = input("Enter Pace in km (mm:ss): ")
mm, ss = map(int, pace.split(":")) #spliting the input in minute and second
paceInSec = mm * 60 + ss #converting the pace in sec
distance = float(input("Enter Distance (km): "))
time = int(paceInSec * distance)
#time in HH:MM formate
hr = time // 3600
mm = (time % 3600) // 60
print("Time = ", end="")
print(hr, mm, sep=":")
| true |
af6a76432233bc4da387b2d96ac3f2977e2e0e7a | imaadfakier/turtle-crossing | /player.py | 1,059 | 4.1875 | 4 | from turtle import Turtle
SHAPE = 'turtle'
COLOR = 'black'
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
class Player(Turtle):
"""
Inherits or sub-classes from Turtle class of Turtle module;
creates an instance of the Player class each time a Player
object is created.
"""
# class attributes
# ...
def __init__(self, direction):
super().__init__()
self.shape(name=SHAPE)
self.color(COLOR)
self.penup()
# self.x, self.y = STARTING_POSITION
# self.goto(x=self.x, y=self.y)
# self.reset_position()
self.ready_set_go()
self.setheading(to_angle=direction)
def move(self):
self.forward(distance=MOVE_DISTANCE)
def is_at_edge(self):
if self.ycor() == FINISH_LINE_Y:
# self.reset_position()
self.ready_set_go()
return True
return False
# def reset_position(self):
def ready_set_go(self):
# def go_to_start(self):
self.goto(x=STARTING_POSITION)
| true |
19c2dfbeb81139e9c4b88db28c8ba9fbbc5a9c5f | Nazar3000/Python_Task2 | /task2.py | 2,379 | 4.3125 | 4 | import re
def input_password():
"""A function that accepts a comma separated list of passwords
from console input.
:return: password: Password string"""
password = input("Input your passwords: ")
password_validator(password)
return password
def password_validator(password):
"""A function that accepts a string of passwords.
Validates a string of passwords and splits them into two lists
that have passed validation and are not valid.
:param password:"password1, passwor2"
:return: (valid_output_list, false_output_list), password lists"""
list_of_passwords = password.split(',')
valid_output_list = []
false_output_list = []
for item in list_of_passwords:
x = True
while x:
if (len(item) < 4 or len(item) > 6):
false_output_list.append(item)
break
elif not re.search("[a-z]", item):
false_output_list.append(item)
break
elif not re.search("[0-9]", item):
false_output_list.append(item)
break
elif not re.search("[A-Z]", item):
false_output_list.append(item)
break
elif not re.search("[*#+@]", item):
false_output_list.append(item)
break
elif re.search("\s", item):
false_output_list.append(item)
break
else:
valid_output_list.append(item)
x = False
break
output_print(valid_output_list, false_output_list)
return valid_output_list, false_output_list
def output_print(valid_output_list, false_output_list):
"""A function that turns a list into a string with a delimiter ",".
Prints lists to the console.
:param valid_output_list: ['password1', 'passwor2']
:param false_output_list: ['password1', 'passwor2']
:return:(password1, passwor2) password strings"""
valid_output_list = ",".join(valid_output_list)
if false_output_list:
false_output_list = ",".join(false_output_list)
if valid_output_list:
print(f"List of Valid Passwords: {valid_output_list}")
if false_output_list:
print(f"List of Not Valid Passwords: {false_output_list}")
return valid_output_list, false_output_list
input_password()
| true |
4ddccf6bcc18b5c1b2fd4b6484d1f534453721b6 | fengzongming/python_practice | /day27_反射和内置方法/demo_02_反射.py | 693 | 4.21875 | 4 | """
hasattr: 检测属性和方法
getattr: 获取属性和方法
delattr: 删除属性和方法
"""
class Foo:
f = '类的静态变量'
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
print('hi,%s' % self.name)
obj = Foo('mike', 73)
# 检测对象是否有某属性和方法
print(hasattr(obj, "name"))
print(hasattr(obj, "say_hi"))
name = getattr(obj, "name", "没找到这个属性哦")
# 输出:mike
print(name)
sex = getattr(obj, "sex", "没找到年龄属性")
# 输出: 没找到年龄属性
print(sex)
# delattr(obj, "name")
# print(obj.name)
obj.say_hi()
delattr(obj, "say_hi")
# obj.say_hi()
| false |
9cd8c350db842c1e8d9bd403f1fd720842db6d44 | CodeVeish/py4e | /Completed/ex_10_03/ex_10_03.py | 641 | 4.25 | 4 | #Exercise 3: Write a program that reads a file and prints the letters in decreasing order of frequency.
#Your program should convert all the input to lower case and only count the letters a-z.
# Your program should not count spaces, digits, punctuation, or anything other than the letters a-z.
# Find text samples from several different languages and see how letter frequency varies between languages.
# Compare your results with the tables at https://wikipedia.org/wiki/Letter_frequencies.
handle = open('clown.txt')
for line in handle :
line = line.lower()
line = line.replace(" ","")
#print(line)
print(list(line))
| true |
e45cfc043dabf423f899827ad3dfb0913204f85a | CodeVeish/py4e | /Completed/ex_05_02/ex_05_02.py | 567 | 4.1875 | 4 | largest = None
smallest = None
while True :
feed = input('Enter a number: ')
if feed == 'done' :
break
try :
float_feed = float(feed)
except :
print('Invalid Input')
continue
if largest is None :
largest = float_feed
if smallest is None :
smallest = float_feed
if float_feed > largest :
largest = float_feed
# print(largest)
if float_feed < smallest :
smallest = float_feed
# print(smallest)
print('Maximimum is', largest)
print('Minimum is', smallest) | true |
c5bbf518cb35e39b0927709c77dde307e400a386 | ferdiokt/py4Eexercise | /exercise5_2.py | 591 | 4.25 | 4 | # Compute the largest and the smallest program
largest = None
smallest = None
# Loop to keep inputting until user enter done
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
inum = int(num)
except:
print('Invalid input')
continue
# Conditional statement for the largest and smallest
if largest is None or inum > largest:
largest = inum
if smallest is None or inum < smallest:
smallest = inum
# Output
print("Maximum is", largest)
print("Minimum is", smallest)
| true |
4c1ade5b1b5b1fb6e3effba351450e881795381d | tchoang408/Text-Encryption | /Vigenere_cipher.py | 2,308 | 4.21875 | 4 | #Tam Hoang
# this program encrypting a sentence or words using vigenerr
# cypher.
from string import*
def createVigenereTable(keyword):
vigenereTable = []
alphabetList = []
keywordList = []
alphabet = ascii_lowercase
for i in range(len(alphabet)):
alphabetList.append(alphabet[i])
index = 0
for i in range(len(keyword)):
tempList = list(alphabetList)
while(alphabetList[index] != keyword[i]):
tempList.append(tempList[0])
tempList.pop(0)
index += 1
index = 0
keywordList.append(tempList)
vigenereTable.append(alphabetList)
for i in range (len(keyword)):
vigenereTable.append(keywordList[i])
return vigenereTable
def encryption():
keyword = input("Please enter your keyword to encrypt a message: ")
table = createVigenereTable(keyword)
text = input("Please enter a message for encryption: ")
counter = 1
encryptedCode =''
for i in range(len(text)):
if(counter >= len(table)):
counter = 1
index = table[0].index(text[i])
letter = table[counter][index]
counter += 1
encryptedCode += letter
return encryptedCode
def decryption():
encryptedText = input("Please enter the encrypted message for decryption: ")
keyword = input("Please enter your keyword to decrypt a message: ")
message = ''
vigTable = createVigenereTable(keyword)
ele = 1
for i in range(len(encryptedText)):
if ele == len(vigTable):
ele = 1
index = vigTable[ele].index(encryptedText[i])
ele += 1
message += vigTable[0][index]
return message
cont =1
while(cont):
print(" Please enter a choice\n\n")
print("Press 1: Encrypt a message\n"
"Press 2: Decrypt a message\n"
"Press 3: Quit")
choice = int(input("Enter your choice: "))
if (choice == 1):
encryptedText = encryption()
print("The encrypted messages: %s\n\n" % (encryptedText))
elif choice == 2:
decryptedMess = decryption()
print("The decrypted messages: %s\n\n" % (decryptedMess))
else:
cont = 0
| true |
d9f85aa910b7bb9cd4b6257713947f2ee23e2f09 | alhambrasoftwaredevelopment/FIAT-LINUX | /Bounties/10ToWin.py | 666 | 4.1875 | 4 | print("")
print("I can tell you if the sum of two numbers is 10 or if one of the numbers is 10 ")
print("False means that neither the sum nor one of the numbers equals 10 ")
print("True means that either the sum or one of the numbers equals 10 ")
print("")
while True:
num1 = int(input("give me a number: "))
num2 = int(input("give me another number: "))
sum = num1 + num2
if sum == 10:
print("True")
print("")
elif num1 == 10:
print("True")
print("")
elif num2 == 10:
print("True")
print("")
else:
print("False")
print("")
# 10 to Win
# Maria Gamino
| true |
a23bfb4d750b9526f6f495c87f2ce8eb2fbbf098 | RobZybrick/TelemetryV1 | /Step_2.py | 1,109 | 4.25 | 4 | # Using python, create CSV file with 5 rows and 5 columns with specified numbers
# Store the CSV file onto the desktop
# majority of the code referenced from -> https://www.geeksforgeeks.org/working-csv-files-python/
# file path location referenced from -> https://stackoverflow.com/questions/29715302/python-just-opening-a-csv-file-from-desktop-on-mac-os
# importing the csv module
import csv
# field names
fields = ['Number 1', 'Number 2', 'Number 3', 'Number 4', 'Number 5']
# data rows of csv file
rows = [ ['0', '1', '2', '3', '4'],
['5', '6', '7', '8', '9'],
['10', '11', '12', '13', '14'],
['50', '100', '150', '200', '250'],
['0', '10', '200', '3000', '4000'],
['-1', '-10', '-200', '-3000', '-4000']]
# name of csv file
#filename = "TelemetryV1_Milestron1_Method1.csv"
# writing to csv file
with open('/Users/rfzybrick/Desktop/TelemetryV1/Step2.csv', 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)
| true |
ab9f6fb487d4b3a1cf182982d0fbdf467925cb05 | kubicodes/100-plus-python-coding-problems | /3 - Loop Related/2_largest_element_of_list.py | 589 | 4.34375 | 4 | """
Category 3 - Loop Related
Problem 5: Largest Element of a List
The Problem:
Find the largest element of a list.
"""
"""
Input must be a list of numbers.
Returns the largest value of the list
"""
def largestElement(listOfNumbers):
assert not type(listOfNumbers) != list, ('You have to give a list as input.')
largest_element = listOfNumbers[0]
for i in listOfNumbers:
if i > largest_element:
largest_element = i
return largest_element
list_of_numbers = [3,5,-2,94,3,7]
print("The largest element is", largestElement(list_of_numbers)) | true |
dc35bb302151340f6c295c8f5ec59e9965950f5c | kubicodes/100-plus-python-coding-problems | /3 - Loop Related/3_sum_of_squares.py | 807 | 4.15625 | 4 | """
Category 3 - Loop Related
Problem 3: Sum of Squares
The Problem:
Take a number as input. Then get the sum of the numbers. If the number is n. Then get
"""
"""
Input must be a number.
Returns the sum of the numbers. If the number is n. Then get
0^2+1^2+2^2+3^2+4^2+.............+n^2
"""
def sumOfSquares(number):
assert not type(number) != int, 'You must type in a number'
sum_of_numbers = 0
for i in range(0,number+1):
sum_of_numbers += i**2
return sum_of_numbers
while True:
try:
user_number = int(input("Type in a number n wich you want to get sum from 0 to n."))
break
except ValueError:
print("Could not convert to a number.")
continue
sum_of_squares = sumOfSquares(user_number)
print(sum_of_squares)
| true |
9ebcbb00242c1753bcbd2aae984aacb09b3af811 | pingao2019/lambdata13 | /Stats/stats.py | 937 | 4.15625 | 4 |
class Calc:
def __init__(self, a, b):
''' __init__ is called as a constructor. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.'''
self.a = a
self.b = b
def add_me(self):
return self.a + self.b
def sub_me(self):
return self.a - self.b
class MulDiv(Calc):
def mul_me(self):
return self.a * self.b
def div_me(self):
return self.a / self.b
if __name__ == "__main__":
if MulDiv(1, 2).add_me() == 3:
print('Addition looks good!')
if MulDiv(1, 2).sub_me() == -1:
print('Subtraction looks good!')
if MulDiv(1, 2).mul_me() == 2:
print('Multiplication looks good!')
if MulDiv(1, 2).div_me() == 0.5:
print('Division looks good!')
class calculation():
def __init__():
| true |
970a24b801a9009e4126b71e54bf478022b1bae5 | alaouiib/DS_and_Algorithms_Training | /Fibonacci_2_algos.py | 1,448 | 4.25 | 4 | from functools import lru_cache
# O(2^n) Time
def fibonacci_slow(n):
if n in [0, 1]:
return n
return fibonacci_slow(n - 1) + fibonacci_slow(n - 2)
# O(n) Time
@lru_cache(maxsize=1000)
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
# ~ O(n) Time
def fibonacci_optimized(n):
cache = {}
if n in cache:
return cache[n]
if n < 0:
# edge case where n is negative
raise ValueError("Index negative")
elif n in [0, 1]:
return n
result = fibonacci_optimized(n - 1) + fibonacci_optimized(n - 2)
cache[n] = result
return result
# bottom up approach
## O(n) time and O(1) space.
def fibonacci_bottom_up(n):
# Compute the nth Fibonacci number
if n<0:
raise ValueError(' no such thing as a negative index in a series')
if n in [0,1]:
return n
prev_prev = 0
prev = 1
# start building the serie from the bottom up
for _ in range(n-1):
current = prev + prev_prev
prev_prev = prev
prev = current
return current
"""
# Fibonacci Series using Dynamic Programming (bottom up)
def fibonacci(n):
# Taking 1st two fibonacci nubers as 0 and 1
f = [0, 1]
for i in range(2, n+1):
f.append(f[i-1] + f[i-2])
return f[n]
"""
"""
TODO: Fibonacci using Matrix multiplication => O(log(n))
"""
| false |
a7a9c403e54281cbec2f86ea955f976de3306cf3 | alaouiib/DS_and_Algorithms_Training | /second_largest_element_bst.py | 1,523 | 4.25 | 4 |
def find_rightmost_soft(root_node):
current = root_node
while current:
if not current.right:
return current.value
current = current.right
def find_rightmost(root_node):
if root_node is None:
raise ValueError('Tree must have at least 1 node')
if root_node.right:
return find_rightmost(root_node.right)
return root_node.value
# Complexity: O(h) Time and Space, O(1) Space if we use find_rightmost_soft function
# h is the height of the tree
def find_second_largest(root_node):
# Find the second largest item in the binary search tree
# idea: find the rightmost node, and take the parentNode if the rightmost node doesn't have a left node
# else: reiterate the rightmost function on the left node.
# edge cases: no right subtree existing, and a tree with no root or with 1 node
# raise error if there is one or no node in the tree
if (root_node is None or
(root_node.left is None and root_node.right is None)):
raise ValueError('Tree must have at least 2 nodes')
# we dont have a right subtree => 2nd largest is the largest in the left subtree
if root_node.left and not root_node.right:
return find_rightmost(root_node.left)
if root_node.right and (not root_node.right.left and not root_node.right.right):
return root_node.value
# otherwise: the largest and 2nd largest are in the right subtree ( that should have several nodes )
return find_second_largest(root_node.right)
| true |
6c5c74f931b6def3987696eeca57dd57de2fc937 | joshhilbert/exercises-for-programmers | /Exercise_35.py | 848 | 4.15625 | 4 |
# Exercise 35: Picking a Winner
# 2019-05-26
# Notes: Populate an array then pick a random winner
import random
# Get names for array
def get_entrant():
value = input("Enter a name: ")
return value
# Pick winner after all names entered
def pick_winner(n):
value = random.randint(0, n)
return value
def main():
contestant = []
entrant = " "
# Get names for array
while len(entrant) > 0:
entrant = get_entrant()
if len(entrant) > 0:
contestant.append(entrant)
# Pick winner after all names entered
max_number = len(entrant)
ticket = pick_winner(max_number)
# Get name from array at index
winner = contestant[ticket]
message_output = f'The winner is.... {winner}.'
print(message_output)
# Call main
main()
| true |
52fdeebc2126aba020c08ceaadc5140003b652ba | joshhilbert/exercises-for-programmers | /Exercise_11.py | 576 | 4.25 | 4 |
# Exercise 11: Currency Conversion
# 2019-05-24
# Notes: Convert currency to another currency
# Unable to solve due to exchange rate conversion issues
# Define variables
user_euro = int(input("How many euros are you exchanging? "))
user_exchange_rate = float(input("What is the exchange rate? "))
# Unsure how to calculate exchange rates
us_dollar = round(user_euro * user_exchange_rate, 2)
# Construct output
message_output = f'{user_euro} euros at an exchange rate of {user_exchange_rate} is \n{us_dollar} U.S. dollars.'
print(message_output) # WRONG
| true |
3ff448ac7500b9f42566403de2a3ee0f14d40709 | ClaudiaN1/python-course | /bProgramFlow/challenge.py | 507 | 4.3125 | 4 | # ask for a name and an age. When both values have been entered,
# check if the person is the right age to go on on an 18-30 holiday.
# They must be over 18 and under 31. If they are, welcome them to the
# holiday, otherwise print a, hopefully, polite message refusing them entry.
name = input("Please enter your name: ")
age = int(input("How old are you? "))
if 18 <= age < 31:
print("Welcome club 18-30 holidays, {0}".format(name))
else:
print("I'm sorry, our holidays are only for cool people") | true |
f600ba0043ca20d5b6c3055189699b457eeea12d | jieck/python | /guess.py | 2,119 | 4.1875 | 4 | def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
for c in secretWord:
if c not in lettersGuessed:
return False
return True
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
# FILL IN YOUR CODE HERE...
medi = list(secretWord)
for x in range(len(secretWord)):
if secretWord[x] not in lettersGuessed :
medi[x] = '_'
medi = ' '.join(medi)
return medi
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
# FILL IN YOUR CODE HERE...
s = list(string.ascii_lowercase)
for x in lettersGuessed:
if x in s:
s.remove(x)
s = ''.join(s)
return s
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
'''
# FILL IN YOUR CODE HERE...
secretWord = raw_input('Please guess a letter: ')
| true |
3ac7dff543c156e29f8c04246f99ab6fe6cb0936 | JaredGarza444/Programacionavanzada | /preguntadatos.py | 1,417 | 4.25 | 4 | #En este programa se estableceran funciones que
#Permitiran preguntas datos sin ninguna validacion
import datetime
#Los datos otorgados pueden ser de diferente tipo
def main():
Datostring=input ("Dame un dato tipo string:")
#Los datos string no es necesario procesarlos
#Ya que todos los datos otrogados por el usuario
#Son del tipo string
Datosint=input ("Dame un dato de tipo entero:")
Datosint=int(Datosint)
#Los datos tipo int son dats enteros de tipo numerico
Datosfloat = input("Dame un dato float: ")
Datosfloat =float(Datosfloat)
#Los datos del tipo float son datos numericos pero a
#Diferencia de los enteros poessen decimales
Datosdate=input ("Dame una fecha yyy/mm/dd:")
#Este tipo de datos se refieren a fechas
año=Datosdate[0:4]
mes=Datosdate[5:7]
dia=Datosdate[-2:]
#En este paso se realizan el acomodo de los numeros
#De esta manera el formato adquirido al imrpimir el resultado
#Es de una forma de fecha
print(año)
print(mes)
print(dia)
#Se imprimen los resultados del paso anterior para que el usuario
#´Pueda corroborar
Datosdate =datetime.datetime(int(año),int(mes),int(dia))
print("Resultados...")
print(Datostring)
print(type(Datostring))
print(Datosint)
print(type(Datosint))
print(Datosfloat)
print(type(Datosfloat))
print(Datosdate)
print(type(Datosdate))
#Los datos resultantes de nuestro programa se imprimen
#Para el usuario
| false |
c2b40bdfab321a1d4111d7b272f9453b966d3f0d | kvntma/coding-practice | /python_exercises/Exercise 5.3.py | 432 | 4.125 | 4 | def check_fermat(a, b, c, n):
if ((a ** n) + (b ** n)) == c ** n and n > 2:
print("Holy smokes, Fermat was wrong!")
else:
print("No, that doesn't work")
def check_numbers():
a = int(input("Choose number for a: \n"))
b = int(input("Choose number for b: \n"))
c = int(input("Choose number for c: \n"))
n = int(input("Choose number for n: \n"))
return check_fermat(a,b,c,n)
check_numbers() | false |
cd967e9601b0e5da13b32a4b5b4f057792e714c2 | qordpffla12/p1_201011101 | /w6Main12.py | 353 | 4.125 | 4 | import random
def upDown(begin, end):
rn = random.randrange(begin, end, 1)
num = 0
count = 0
while num != rn:
num = int(raw_input("enter num: "))
count = count+1
if num < rn:
print 'up'
elif num > rn:
print 'down'
else:
print 'right', count
upDown(1,100) | true |
7488518bd1c6ad6778022c0f70eec312be866d5b | AFranco92/pythoncourse | /controlstatements/homework.py | 454 | 4.21875 | 4 | maths = int(input("Enter maths marks: "))
physics = int(input("Enter physics marks: "))
chemistry = int(input("Enter chemistry marks: "))
if maths >= 35 and physics >= 35 and chemistry >= 35:
print "You have passed the exam!"
average = (maths+physics+chemistry)/3
if average <= 59:
print "You got a C."
elif average <= 69:
print "You got a B."
else:
print "You got a A."
else:
print "You failed the exam." | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.