blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7a7ab6085f25abdc688ab65ebe6373cdc9e05530 | Anonsurfer/Simple_Word_List_Creator | /Word_List_Creator.py | 835 | 4.28125 | 4 | # This simple script allows you to create a wordlist and automatically saves it as .txt
# if the final value of wordlist is 100 - it will create the wordlist from 0,1,2,3,4.... so on to 100.
import os # Importing the Os Module
keys_ = open("keys.txt",'w') # Creating a new txt file
keys_range = int(input("Enter the final value of the wordlist: ")) # aking the user for the length
print("Creating Wordlist !")
print("Please wait....")
for x in range(0,keys_range + 1):
keys_.write(str(x)) # Chainging x to string so we can write inside the file !
keys_.write("\n") # \n - new line so, we won't get the values on the same line !
print("Done Creating the Wordlist !")
print("Your File Is Saved Right here: {}".format(os.getcwd()))
print("File Name = 'keys.txt'")
# Feel Free to change and use the code for your personal use ;-)
| true |
7f12c500ecd0bac47473615ddf95185f7bc23993 | josterpi/python | /python1.py | 2,734 | 4.21875 | 4 | #!/usr/bin/env python
# initialized at 1, I have two actions I can do on the number
# line. I can jump forward and jump backwards.
# The jump forward is 2*current position + 1
# The jump back is the current position - 3
# Can you hit all of the integers?
# If not, what can't you hit? What can you? Any patterns?
# When you're jumping back, what's the last positive integer you can hit?
#
# As you jump back from a position, eventuallly you'll hit a number you've
# hit before. From then on, you won't get any new numbers.
# Given a number, where will you hit an already hit number?
#
# Going back from a number, what is the ratio of hits to misses?
#
# If you want to hit every number you can up to n, how far forward of n
# do you have to go?
# Something like:
# [(2,4),(3,9),(4,16),(5,33),(6,64),(7,129),(8,256),(9,513),(10, 1024)]
import sys
class Jumper:
def __init__(self):
self.current = 1
self.print_me = False
self.hit = [1]
def forward(self):
self.current = 2*self.current+1
if self.current not in self.hit:
self.hit.append(self.current)
self.hit.sort()
if self.print_me:
print self.current
def back(self):
self.current = self.current - 3
if self.current not in self.hit:
self.hit.append(self.current)
self.hit.sort()
if self.print_me:
print self.current
def printing(self):
self.print_me = True
def noprinting(self):
self.print_me = False
def reset(self,n = 1):
self.current = n
def __repr__(self):
return str(self.current) + "\n" + str(self.hit)
def forward(n):
return 2*n+1
def back(n):
return n-3
def forward_range(n):
current = 1
fseq = [1]
for i in range(n):
current = forward(current)
fseq.append(current)
return fseq
def add_forward(seq, n):
current = seq[-1]
for i in range(n):
current = forward(current)
seq.append(current)
return seq
def main():
seq = forward_range(int(sys.argv[1]))
print seq
nline = forward_range(int(sys.argv[1]))
for i in seq:
hit = miss = first_miss = last_miss = 0
h_m = -1
j = back(i)
print "----------------------------------"
print j
while j>1:
if nline.count(j)==0:
nline.append(j)
hit = hit + 1
else:
if (miss == 0):
first_miss = j
if j==3 or j==4:
last_miss = j
miss = miss + 1
j = back(j)
if miss != 0:
h_m = float(hit)/miss
print "hits: ",hit
print "misses: ",miss
print "h/m: ",h_m
print "first miss: ",first_miss
print "last miss: ",last_miss
nline.sort()
print nline
if __name__ == '__main__':
main()
| true |
2b8a5961e68d32283401892eec11dbfade6c80d2 | HarrisonHelms/helms | /randomRoll/roll2.py | 350 | 4.25 | 4 | from random import random
R = random()
sides = input("Enter the number of sides on the die: ")
'''
rolled = (sides - 1) * R
rolled = round(rolled)
rolled += 1
'''
def roll(sides):
rolled = (sides - 1) * R
rolled = round(rolled)
rolled += 1
return rolled
num = roll(int(sides))
num = str(num)
print("Your random roll is: " + num)
| true |
e4a71284092ec0a1cc7a9e2a29eaf719e51a6ca4 | denglert/python-sandbox | /corey_schafer/sorting/sort.py | 2,775 | 4.4375 | 4 | # - Original list
lst = [9,1,8,2,7,3,6,4,5]
print('Original list:\t', lst )
# - Sort list with sorted() function
s_lst = sorted(lst)
print('Sorted list: {0}'.format(s_lst) )
# - Sort lits Using subfunction .sort()
lst.sort()
print('Sorted list:\t', lst )
# - Sort list in reverse order with sorted() function
s_lst = sorted(lst, reverse=True)
print('Sorted list:\t', s_lst )
# - Sort list in reverse order with .sort() subfunction
lst.sort(reverse=True)
print('Sorted list:\t', lst )
#########################
# The sorted() function has more flexibility
# You can also apply it to tuples and dictionaries
# sorted(): tuple -> list
# sorted(): dictionary -> list of keys
# - Original tuple
tup = (9,1,8,2,7,3,6,4,5)
print('Original tuple:\t', tup )
# - Sort tuple into a list
s_tup = sorted( tup )
print('Sorted tuple:\t', s_tup )
# - Original dictionary
di = {'name': 'Bruce', 'job': 'businessman', 'age': 32}
print('Original dictionary:\t', di)
# - sorted(dictionary) gives you the sorted list of keys
di = {'name': 'Bruce', 'job': 'businessman', 'age': 32}
s_di = sorted(di)
print('Sorted dictionary:\t', s_di )
# - Sort based on a specific criteria
# - Original list
lst = [-9,1,-8,2,-7,-3,-6,4,5]
print('Original list:\t', lst )
# - Sort list
s_lst = sorted(lst)
print('Sorted list:\t', s_lst )
# - Sort list with absolute value as key
s_lst = sorted(lst, key=abs)
print('Sorted list:\t', s_lst )
#########################
####################################
# - List of custom class objects - #
####################################
class Employee():
def __init__ (self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def __repr__ (self):
return '({},{},{})'.format(self.name, self.age, self.salary)
e1 = Employee('Carl', 37, 70000)
e2 = Employee('Sarah', 29, 80000)
e3 = Employee('John', 43, 90000)
employees = [e1,e2,e3]
print('Employees:\t', employees )
# Naiveliy try to sort the class
# s_employees = sorted(employees)
# TypeError: unorderable types: Employee() < Employee()
# - Custom key function to order insatnces of the class
def e_sort(emp):
return emp.name
# - Sort the list
s_employees = sorted(employees, key=e_sort)
print('Employees:\t', s_employees )
def e_sort(emp):
return emp.salary
# - Sort the list in reverse
s_employees = sorted(employees, key=e_sort, reverse=True)
print('Employees:\t', s_employees )
# - We can also sort using lambda functions
s_employees = sorted(employees, key=lambda e: e.age)
print('Employees:\t', s_employees )
# Attribute getter
from operator import attrgetter
# - We can also sort using attrgetter
s_employees = sorted(employees, key=attrgetter('salary'))
print('Employees:\t', s_employees )
| true |
3dbfd602383d5791f2f5a4bcfc4c5e54b07e9ce7 | denglert/python-sandbox | /corey_schafer/namedtuples/namedtuples.py | 932 | 4.40625 | 4 | ############################
### --- Named tuples --- ###
############################
from collections import namedtuple
### --- Tuple --- ###
# Advantage:
# - Immutable, can't change the values
color_tuple = (55, 155, 255)
print( color_tuple[0] )
### --- Dictionaries --- ###
# Disadvantage:
# - Requires more typing
# - You need to define new colours also in this format
#
color_dict = {'red': 55, 'green': 155, 'blue': 255}
print( color_dict['red'] )
### --- Named tuple --- ###
# Advantage:
# - Has the nice features of both tuple and dictionary
# - You define it only once typing in the names, but can access the element with
# both [int] and .name
Color_ntuple = namedtuple('Color', ['red', 'green', 'blue'])
color_ntuple = Color_ntuple(55, 155, 255)
color_ntuple = Color_ntuple(red=55, green=155, blue=255)
print( "color_ntuple[0]", color_ntuple[0] )
print( "color_ntuple.red", color_ntuple.red )
| true |
fe7dad7782ed143451c1c48fe9b82333393a41e3 | mmarotta/interactivepython-005 | /guess-the-number.py | 2,540 | 4.15625 | 4 | import simplegui
import random
import math
# int that the player just guessed
player_guess = 0
# the number that the player is trying to guess
secret_number = 0
# the maximum number in the guessing range (default 100)
max_range = 100
# the number of attempt remaining (default 7)
attempts_remaining = 7
# helper function to start and restart the game
def new_game():
# what range are we working with (0 to 100 by default)
global max_range, attempts_remaining
# set a random number that the player will try and guess
global secret_number, max_range
secret_number = random.randrange(0, max_range)
# set the number of attempt the player has remaining
attempts_remaining = int(math.ceil(math.log(max_range, 2)))
# print a welcome message
print ""
print "Let's play guess the number, 0 to", max_range
print "You have", attempts_remaining, "attempts remaining"
# define event handlers for control panel
def change_range(new_max_range):
global max_range, attempts_remaining
# check the value that was passed in
max_range = int(new_max_range)
print "You changed the range to 0 to", max_range
if (max_range == None):
max_range = 100
# start a new game
new_game()
def input_guess(guess):
# define the globals
global secret_number, attempts_remaining
# print out the player's guess
print "Guess was", guess
player_guess = int(guess)
# decrement guess counter
attempts_remaining -= 1
# how did the player do?
if player_guess == secret_number:
print "player wins"
# let's play again... how about a nice game of chess
print "That was fun, let's do it again!"
new_game()
return
elif player_guess > secret_number:
print "too high... ", attempts_remaining, "attempts left"
elif player_guess < secret_number:
print "too low...", attempts_remaining, "attempts left"
else:
# this should never happen....
print "i've got a bad feeling about this"
# check if any attempts left
if attempts_remaining == 0:
print "Sorry, you are out of guesses!"
print "Play again"
new_game()
# create frame
main_frame = simplegui.create_frame('Guess the number', 300, 200)
# register event handlers for control elements and start frame
main_frame.add_input("My Guess is:", input_guess, 100)
main_frame.add_input("Change Range, 0 to:", change_range, 100)
main_frame.start()
# call new_game
new_game()
| true |
0fabb98b1c2a86dc202f5eecb58b9a5d3011019e | effedib/the-python-workbook-2 | /Chap_06/Ex_142.py | 463 | 4.4375 | 4 | # Unique Characters
# Determine which is the number of unique characters that composes a string.
unique = dict()
string = input('Enter a string to determine how many are its unique characters and to find them: ')
for c in string:
if c not in unique:
unique[c] = 1
num_char = sum(unique.values())
print("'{}' has {} unique characters\nand it/they is/are:".format(string.upper(), num_char))
for c in unique:
print("'{}'".format(c), end=' ')
| true |
f3a3d5e579092cfe05d7dd072336f7bb1336aafc | effedib/the-python-workbook-2 | /Chap_04/Ex_87.py | 536 | 4.28125 | 4 | # Shipping Calculator
# This function takes the number of items in an orger for an online retailer and returns the shipping charge
def ShippingCharge(items: int) -> float:
FIRST_ORDER = 10.95
SUBSEQ_ORDER = 2.95
ship_charge = FIRST_ORDER + (SUBSEQ_ORDER * (items - 1))
return ship_charge
def main():
order = int(input("How many items are included in your order? "))
shipping_charge = ShippingCharge(order)
print("Shipping Charge: {:.2f}".format(shipping_charge))
if __name__ == "__main__":
main() | true |
182bf7a4858162954223f42c72bae8ff258c9ef0 | effedib/the-python-workbook-2 | /Chap_04/Ex_96.py | 816 | 4.125 | 4 | # Does a String Represent an Integer?
def isInteger(string: str) -> bool:
string = string.strip()
string = string.replace(' ', '')
if string == "":
return False
elif string[0] == '+' or string[0] == '-':
if len(string) == 1:
return False
for i in string[1:]:
if not i.isdigit():
return False
else:
for i in string:
if not i.isdigit():
return False
return True
def main():
integ = input("Enter a string to verify if it's a string: ")
verify = isInteger(integ)
if verify is True:
print("The string is an Integer")
else:
print("The string is not an Integer")
if __name__ == "__main__":
main() | true |
0050797557855d27088eed9dbf73027031d5de12 | effedib/the-python-workbook-2 | /Chap_01/Ex_14.py | 390 | 4.46875 | 4 | # Height Units
# Conversion rate
FOOT = 12 # 1 foot = 12 inches
INCH = 2.54 # 1 inch = 2.54 centimeters
# Read height in feet and inches from user
feet = int(input("Height in feet: "))
inches = int(input("Add the number of inches: "))
# Compute the conversion in centimeters
cm = (((feet * FOOT) + inches) * INCH)
# Display the result
print("Height in centimeters: %.2f" % cm) | true |
9b15b4f104947f8fd306784d22c0d4f12c574c55 | effedib/the-python-workbook-2 | /Chap_02/Ex_48.py | 1,934 | 4.46875 | 4 | # Birth Date to Astrological Sign
# Convert a birth date into its zodiac sign
# Read the date from user
birth_month = input("Enter your month of birth: ").lower()
birth_day = int(input("Enter your day of birth: "))
# Find the zodiac sign
if (birth_month == 'december' and birth_day >= 22) or (birth_month == 'january' and birth_day <= 19):
zodiac = 'Capricorn'
elif (birth_month == 'january' and birth_day >= 20) or (birth_month == 'february' and birth_day <= 18):
zodiac = 'Aquarius'
elif (birth_month == 'february' and birth_day >= 19) or (birth_month == 'march' and birth_day <= 20):
zodiac = 'Pisces'
elif (birth_month == 'march' and birth_day >= 21) or (birth_month == 'april' and birth_day <= 19):
zodiac = 'Aries'
elif (birth_month == 'april' and birth_day >= 20) or (birth_month == 'may' and birth_day <= 20):
zodiac = 'Taurus'
elif (birth_month == 'may' and birth_day >= 21) or (birth_month == 'june' and birth_day <= 20):
zodiac = 'Gemini'
elif (birth_month == 'june' and birth_day >= 21) or (birth_month == 'july' and birth_day <= 22):
zodiac = 'Cancer'
elif (birth_month == 'july' and birth_day >= 23) or (birth_month == 'august' and birth_day <= 22):
zodiac = 'Leo'
elif (birth_month == 'august' and birth_day >= 23) or (birth_month == 'september' and birth_day <= 22):
zodiac = 'Virgo'
elif (birth_month == 'september' and birth_day >= 23) or (birth_month == 'october' and birth_day <= 22):
zodiac = 'Libra'
elif (birth_month == 'october' and birth_day >= 23) or (birth_month == 'november' and birth_day <= 21):
zodiac = 'Scorpio'
elif (birth_month == 'november' and birth_day >= 22) or (birth_month == 'december' and birth_day <= 21):
zodiac = 'Sagittarius'
else:
zodiac = ''
# Display the result
if zodiac == '':
print("Invalid date!")
else:
print("If your birthday is {} {}, your zodiac sign is: {}!".format(birth_month.capitalize(), birth_day, zodiac)) | true |
cc33896b761eba91b55e31d018a0b90fcfc46321 | effedib/the-python-workbook-2 | /Chap_05/Ex_113.py | 504 | 4.28125 | 4 | # Avoiding Duplicates
# Read words from the user and display each word entered exactly once
# Read the first word from the user
word = input("Enter a word (blank to quit): ")
# Create an empty list
list_words = []
# Loop to append words into the list until blank is entered and if is not a duplicate
while word != '':
if word not in list_words:
list_words.append(word)
word = input("Enter another word (blank to quit): ")
# Display the result
for word in list_words:
print(word)
| true |
2acaac01a17a6d6f066b5f0a07cd1d59c8edccf1 | effedib/the-python-workbook-2 | /Chap_03/Ex_69.py | 708 | 4.1875 | 4 | # Admission Price
# Compute the admission cost for a group of people according to their ages
# Read the fist age
first_age = input("Enter the age of the first person: ")
# Set up the total
total_cost = 0
age = first_age
while age != "":
# Cast age to int type
age = int(age)
# Check the cost
if age <= 2:
cost = 0
elif 3 <= age <= 12:
cost = 14.00
elif age >= 65:
cost = 18.00
else:
cost = 23.00
# Update the total cost
total_cost += cost
# Check for the next loop or exit
age = input("Enter the age of the next person (blank to quit): ")
# Display the result
print("Total cost for the group: {:.2f}".format(total_cost)) | true |
dcbcbadbe3b33e0e50b792d7dafb00039f7ac41a | effedib/the-python-workbook-2 | /Chap_08/Ex_183.py | 1,706 | 4.21875 | 4 | # Element Sequences
# This program reads the name of an element from the user and uses a recursive function to find the longest
# sequence of elements that begins with that value
# @param element is the element entered by the user
# @param elem_list is the list of elements to check to create the sequence
# @return the best sequence as a list
def elementSequences(element: str, elem_lst: list) -> list:
# base condition, if the string is empty
if element == "":
return []
# the best sequence, initialized as empty list
best_seq = []
# check the last letter of the first/current element
last_letter = element[len(element) - 1].lower()
# a for loop to find which element in the elem_list begins with last_letter
for i in range(len(elem_lst)):
first_letter = elem_lst[i][0].lower()
if first_letter == last_letter:
# find the best sequence calling the recursive function
candidate = elementSequences(elem_lst[i], elem_lst[:i] + elem_lst[i+1:len(elem_lst)])
if len(candidate) > len(best_seq):
best_seq = candidate
best_seq = [element] + best_seq
if len(best_seq) > 1 and best_seq[0] == best_seq[1]:
del best_seq[0]
return best_seq
def main():
file = open('elements.txt')
elements_lst = []
for ele in file:
# Replace to delete the escape character
ele = ele.replace("\n", "")
ele = ele.split(",")
elements_lst.append(ele[2])
file.close()
element_to_start = input("Enter the word to start the sequence of elements: ")
print(elementSequences(element_to_start, elements_lst))
if __name__ == "__main__":
main()
| true |
95cffa4e93b281b5534b209ec831400b7c320de7 | effedib/the-python-workbook-2 | /Chap_04/Ex_99.py | 463 | 4.21875 | 4 | # Next Prime
# This function finds and returns the first prime number larger than some integer, n.
def nextPrime(num: int):
from Ex_98 import isPrime
prime_num = num + 1
while isPrime(prime_num) is False:
prime_num += 1
return prime_num
def main():
number = int(input("Enter a non negative number: "))
print("The next prime number after {:d} is {:d}.".format(number, nextPrime(number)))
if __name__ == "__main__":
main()
| true |
aaa01b2ce41701e351067b0ea953db842e7a391f | effedib/the-python-workbook-2 | /Chap_03/Ex_84.py | 784 | 4.3125 | 4 | # Coin Flip Simulation
# Flip simulated coins until either 3 consecutive faces occur, display the number of flips needed each time and the average number of flips needed
from random import choices
coins = ('H', 'T')
counter_tot = 0
for i in range(10):
prev_flip = choices(coins)
print(prev_flip[0], end=" ")
counter = 1
counter_line = 1
while counter < 3:
flip = choices(coins)
if flip == prev_flip:
counter += 1
else:
counter = 1
prev_flip = flip
print(prev_flip[0], end=" ")
counter_line += 1
if counter == 3:
print(" ({} flips)".format(counter_line))
counter_tot += counter_line
avg = counter_tot / 10
print("On average, {:.2f} flips were needed".format(avg)) | true |
ecc22e65773bcc269fbd5fcc18abff21ab301162 | effedib/the-python-workbook-2 | /Chap_04/Ex_95.py | 734 | 4.1875 | 4 | # Capitalize It
# This function takes a string as its only parameter and returns a new copy of the string that has been correctly capitalized.
def Capital(string: str) -> str:
marks = (".", "!", "?")
new_string = ""
first = True
for i, c in enumerate(string):
if c != " " and first is True:
first = False
new_string += c.capitalize()
elif c in marks:
new_string += c
first = True
elif c == 'i' and (string[i-1]) == ' ' and (string[i+1] == ' ' or string[i+1] in marks):
new_string += c.capitalize()
else:
new_string += c
return new_string
stringa = input("Inserisci una frase: ")
print(Capital(stringa)) | true |
c0e3387fb01e402d647e3c7954a4d8ccba653f6f | effedib/the-python-workbook-2 | /Chap_01/Ex_22.py | 325 | 4.34375 | 4 | import math
s1 = float(input('Enter the length of the first side of the triangle:'))
s2 = float(input('Enter the length of the second side of the triangle:'))
s3 = float(input('Enter the length of the third side of the triangle:'))
s = (s1+s2+s3)/2
A = math.sqrt(s*(s-s1)*(s-s2)*(s-s3))
print('The area of the triangle is',A) | true |
d41046ceabddad69bcbf57fdf7cad495c3a2b6d0 | effedib/the-python-workbook-2 | /Chap_03/Ex_76.py | 908 | 4.1875 | 4 | # Multiple Word Palindromes
# Extend the solution to EX 75 to ignore spacing, punctuation marks and treats uppercase and lowercase as equivalent
# in a phrase
# Make a tuple to recognize only the letters
letters = (
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z"
)
# Read the sentence from the user
phrase = input("Enter a phrase: ").lower()
# Create a new string that contains only letters
new_phrase = ""
for c in phrase:
if c in letters:
new_phrase += c
# Analyse if the string is palindrome
final = len(new_phrase) - 1
is_palindrome = True
i = 0
while i < final:
if new_phrase[i] != new_phrase[final]:
is_palindrome = False
break
i += 1
final -= 1
if is_palindrome is False:
print("This phrase is not a palindrome!")
else:
print("This phrase is palindrome!!")
| true |
4259b2e9d383daf2f189f50f7e40923b3354b1ae | effedib/the-python-workbook-2 | /Chap_08/Ex_182.py | 2,174 | 4.21875 | 4 | # Spelling with Element Symbols
# This function determines whether or not a word can be spelled using only element symbols.
# @param word is the word to check
# @param sym is the list of symbols to combine to create the word
# @param result is the string to return at the end, it was initialized as empty string
# @param index is the index to be increased to iterate the list "sym" calling the recursion
def combineElements(word: str, sym: list, result: str = "", index: int = 0) -> str:
# base conditions, if word == result or if it's impossible to combine elements
if result.replace(' - ', '').upper() == word.upper():
return result
elif index >= len(sym):
return "Impossible to spell the word {} with element symbols".format(word)
else:
# check if every letter is in "sym" and add to "result"
if word[index].capitalize() in sym:
if result == "":
result += word[index].capitalize()
else:
result += " - " + word[index].capitalize()
index += 1
return combineElements(word, sym, result, index)
# check if the double letter is a symbol and add to "result"
elif index < (len(sym) - 2) and (word[index].capitalize() + word[index + 1]) in sym:
if result == "":
result += word[index].capitalize() + word[index + 1]
else:
result += " - " + word[index].capitalize() + word[index + 1]
index += 2
return combineElements(word, sym, result, index)
else:
return "Impossible to spell the word {} with element symbols".format(word)
def main():
file = open('elements.txt')
symbols = []
for element in file:
# Replace to delete the escape character but I don't need this index in the list, than I ignore it
# line = line.replace("\n", "")
element = element.split(",")
symbols.append(element[1])
file.close()
word_to_check = input("Enter the word to check with element symbols: ")
print(combineElements(word_to_check, symbols))
if __name__ == "__main__":
main()
| true |
edbe35d0172d1c78007e551e10f97d53ac12cee4 | axelniklasson/adventofcode | /2017/day4/part2.py | 1,640 | 4.34375 | 4 | # --- Part Two ---
# For added security, yet another system policy has been put in place. Now, a valid passphrase must contain no two words that are anagrams of each other - that is, a passphrase is invalid if any word's letters can be rearranged to form any other word in the passphrase.
# For example:
# abcde fghij is a valid passphrase.
# abcde xyz ecdab is not valid - the letters from the third word can be rearranged to form the first word.
# a ab abc abd abf abj is a valid passphrase, because all letters need to be used when forming another word.
# iiii oiii ooii oooi oooo is valid.
# oiii ioii iioi iiio is not valid - any of these words can be rearranged to form any other word.
# Under this new system policy, how many passphrases are valid?
# Load passphrase list from input file
f = open("input.txt", "r")
lines = f.readlines()
count = 0
for line in lines:
# Store all found words as keys to keep track
found_words = {}
# Load all words in the line and format the data
words = line.split(" ")
words[len(words) - 1] = words[len(words) - 1].strip() # Remove \n character
i = 0
valid = True
# Go through all words and check for anagrams
while i < len(words):
j = 0
while j < len(words) and j != i:
# Use magic function sorted() to sort characters of strings into array
# If they are equal, they are anagrams of each other
if sorted(words[i]) == sorted(words[j]):
valid = False
break
j += 1
i += 1
if valid:
count += 1
print "There are %d valid passphrases." % count
| true |
bcd5658e96365509fc455058cdb7d7a7fc7109c2 | couchjd/School_Projects | /Python/EXTRA CREDIT/6PX_12.py | 2,279 | 4.25 | 4 | #12 Rock, Paper, Scissors Game
import random
import time
def numberGen(): #generates a random value to be used as the computer's choice
random.seed(time.localtime())
return random.randrange(1,3)
def compare(compChoice, userChoice): #compares user choice vs computer choice
compDict = {1:'rock', 2:'paper', 3:'scissors'}
if compDict[compChoice] == userChoice: #retry if user and computer choose
return 'retry' #the same value
#compare user choice vs computer choice and returns win or lose values
elif userChoice == 'rock' or userChoice == 'paper' or userChoice == 'scissors':
if userChoice == 'rock':
if compChoice == 2:
return 'lose'
elif compChoice == 3:
return 'win'
elif userChoice == 'paper':
if compChoice == 1:
return 'win'
elif compChoice == 3:
return 'lose'
elif userChoice == 'scissors':
if compChoice == 1:
return 'lose'
elif compChoice == 2:
return 'win'
else:
return 'invalid' #check for invalid input
def main():
userInput = ''
while userInput != 'q': #terminate on 'q'
compChoice = numberGen()
while True:
userInput = input("Rock\nPaper\nScissors\n"
"Enter your selection('q' to quit): ")
if userInput == 'q':
break
elif compare(compChoice, userInput) == 'lose':
print("---------")
print("You lose.")
print("---------")
break
elif compare(compChoice, userInput) == 'win':
print("--------")
print("You win!")
print("--------")
break
elif compare(compChoice, userInput) == 'retry':
print("-----------------")
print("Tie! Try Again!")
print("-----------------")
elif compare(compChoice, userInput) == 'invalid':
print("--------------------------")
print("Invalid entry! Try Again!")
print("--------------------------")
main()
| true |
dee422c3e12ec0314c0e72fe187454934fd3104e | couchjd/School_Projects | /Python/EXTRA CREDIT/6PX_5.py | 394 | 4.15625 | 4 | #5 Kinetic Energy
def kinetic_energy(mass, velocity):
kEnergy = ((1/2)*mass*velocity**2) #calculates kinetic energy, given a
return kEnergy #mass and velocity
def main():
print("The kinetic energy is %.2f joules." %
kinetic_energy(float(input("Enter mass of object: ")),
float(input("Enter velocity of object: "))))
main()
| true |
0cb19f7f08eafd81fcffed36d46a2a7ac42eda3a | MandipGurung233/Decimal-to-Binary-and-vice-versa-conversion-and-adding | /validatingData.py | 2,976 | 4.25 | 4 | ## This file is for validating the entered number from the user. When user are asked to enter certain int number then they may enter string data type
## so if such cases are not handled then their may occur run-time error, hence this is the file to handle such error where there is four different function..:)
def validatingInput1 (out1): ## Asked value to user is only b,B,d,D So if user enter other than this than this function
## handle such error.....
if out1 in [""]:
return "Error....Empty field.."
if out1 in ["b","D","B","d"] :
return "Thank you for correct value.. :)"
try: ## this is to handle run-time error......
exception = int (out1)
except:
return "Error....Special character"
if int(out1) < 0:
return "Error....Negative value"
for integers in out1:
if int(integers) in [0,1,2,3,4,5,6,7,8,9]:
return "Error....Integers value"
def validatingDecimal (out1): ## this function validate decimal number......
if out1 in [""]:
return "Error....Empty field.."
try:
exception = int (out1)
except:
return "Error....Special character"
if int(out1) < 0:
return "Error....Negative value"
if int(out1) > 255:
return "Error....more than 255"
for integers in out1:
if int(integers) in [0,1,2,3,4,5,6,7,8,9]:
return "Thank you for correct value.."
def validatingBinary (out3): ## this function validate binary number
if out3 in [""]:
return ("Error...Empty field")
try:
exception = int (out3)
except:
return ("Error...Special character")
if int(out3) < 0:
return ("Error...Negative value")
if len (out3) > 8:
return ("Error...More than 8 digit")
if len (out3) < 8:
return ("Error...less than 8 digit")
for integers in out3:
if int(integers) not in [0,1]:
return ("Error...value other than 0 and 1 found...")
for integers in out3:
if int(integers) in [0,1]:
return ("Thank you for correct value..")
def validating (u_s_e_r): ## Asked value to user is only y,Y,n,N So if user enter other than this than this function
## handle such error.....
if u_s_e_r in [""]:
return "Error...Empty field"
if u_s_e_r in ["Y","y","n","N"] :
return "Thank you for correct value"
try:
exception = int (u_s_e_r)
except:
return "Error...Special character"
if int(u_s_e_r) < 0:
return "Error...Negative value"
for digitNumeric in u_s_e_r:
if int(digitNumeric) in [0,1,2,3,4,5,6,7,8,9]:
return "Error....Numeric value"
| true |
73ef198d2a47801f75df1a48393244febed9e85a | daneven/Python-programming-exercises | /Exersise_4.py | 1,034 | 4.34375 | 4 | #!/usr/bin/python3
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'''
@Filename : Exersises
@Date : 2020-10-28-20-31
@Project: Python-programming-exercises
@AUTHOR : Dan Even
'''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'''
Question 4
Level 1
Question:
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
Suppose the following input is supplied to the program:
34,67,55,33,12,98
Then, the output should be:
['34', '67', '55', '33', '12', '98']
('34', '67', '55', '33', '12', '98')
'''
#################
str=(input("Enter coma separated numbers"))
l=list()
t=tuple()
nstr = ''
for i in str:
if i !="," :
nstr = nstr + i
else:
l.append(nstr)
t = t + (nstr,)
nstr = ''
l.append(nstr)
t = t + (nstr,)
print(l,t)
################################
values=(input("Enter coma separated numbers"))
mylist=values.split(",")
mytuple=tuple(mylist)
print(g,k)
| true |
e1bf679159088e4653f0c21ebac8311e63b6b304 | daneven/Python-programming-exercises | /Exersise_5.py | 1,104 | 4.375 | 4 | #!/usr/bin/python3
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'''
@Filename : Exersises
@Date : 2020-10-28-20-31
@Project: Python-programming-exercises
@AUTHOR : Dan Even
'''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'''
Question 5
Level 1
Question:
Define a class which has at least two methods:
getString: to get a string from console input
printString: to print the string in upper case.
Also please include simple test function to test the class methods.
Hints:
Use __init__ method to construct some parameters
'''
class Myclass():
def __init__(self):
self.text = ""
def getString(self):
self.text=input("Enter text")
def printString(self):
print(self.text)
strObj=Myclass()
strObj.getString()
strObj.printString()
'''################################
class InputOutString(object):
def __init__(self):
self.s = ""
def getString(self):
self.s = raw_input()
def printString(self):
print self.s.upper()
strObj = InputOutString()
strObj.getString()
strObj.printString()
''' | true |
386a08d884f31869297b8579cd3e2742bfe796a7 | dragomir-parvanov/VUTP-Python-Exercises | /03/2-simple-calculator.py | 1,049 | 4.375 | 4 | # Python Program to Make a Simple Calculator
def applyOperator(number1, operator,number2):
if currentOperator == "+":
number1 += float(number2)
elif currentOperator == "-":
number1 -= float(number2)
elif currentOperator == "*":
number1 *= float(number2)
elif currentOperator == "/":
number1 /= float(number2)
elif currentOperator == "":
number1 = float(number2)
else:
raise Exception("malformed input")
return number1
taskInput = input(
"Input an expression like 3+1*2. This doesnt support parenthesis and negative numbers, but supports substractions\n")
firtNumber = True
result = 0.00
currentNumber = ""
currentOperator = ""
for char in taskInput:
if char.isdigit():
currentNumber += char
else:
result = applyOperator(result,currentOperator,currentNumber)
currentOperator = char
currentNumber = ""
result = applyOperator(result,currentOperator,currentNumber)
print(taskInput,"=",result)
| true |
e937a40b941f9599bcd2ecf407d8cc03376403b4 | dragomir-parvanov/VUTP-Python-Exercises | /02/8-negative-positive-or-zero.py | 237 | 4.40625 | 4 | # Check if a Number is Positive, Negative or 0
numberInput = int(input("Enter a number: "))
if numberInput > 0:
print("Number is Positive")
elif numberInput < 0:
print("Number is negative")
else:
print("Number is 0(ZERO)")
| true |
88ff525e751b4e21af01de0d2aa9cc52d988ed40 | da1dude/Python | /OddOrEven.py | 301 | 4.28125 | 4 | num1 = int(input('Please enter a number: ')) #only allows intigers for input: int()
check = num1 % 2 # Mudelo % checks if there is a remainder based on the number dividing it. In this case 2 to check if even or odd
if check == 0:
print('The number is even!')
else:
print('The number is odd!') | true |
b9bd153886194726840fa940231afed161399585 | andrew5205/Python_cheatsheet | /string_formatting.py | 712 | 4.15625 | 4 |
name = "Doe"
print("my name is John %s !" %name)
age = 23
print("my name is %s, and I am %d years old" %(name, age))
data = ["Jonh", "Doe", 23]
format_string = "Hello {} {}. Your are now {} years old"
print(format_string.format(data[0], data[1], data[2]))
# tuple is a collection of objects which ordered and immutable
format_string2 = "Hello %s %s, you are %s years old"
print(format_string2 % tuple(data))
# %s - String (or any object with a string representation, like numbers)
# %d - Integers
# %f - Floating point numbers
# %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
# %x/%X - Integers in hex representation (lowercase/uppercase)
| true |
0edbe19fc1c3b187309f943ad7c1c1c18383c733 | ersmindia/accion-sf-qe | /workshop_ex1.py | 697 | 4.25 | 4 | '''Exercise 1:
A) Create a program that asks the user to enter their name and their age. Print out a message that tells them the year that they will turn 50 and 100 years old.
B)Add on to the previous program by asking the user for another number and printing out that many copies of the previous message.
'''
from datetime import datetime
name = raw_input("Enter your name: ")
age = int(raw_input("Enter your Age: "))
thisYear = datetime.today().year
result = "You will turn 50 @ " + str(thisYear - age + 50) + " and you will turn 100 @ " + str(thisYear - age + 100)
print result
numbersToPrint = int(raw_input("Number of copies to print: "))
for i in range(numbersToPrint):
print result
| true |
d08c53ba5fe5c06c84b199b253554cfb6cecdc80 | standrewscollege2018/2019-year-13-classwork-ostory5098 | /Object orientation Oscar.py | 1,608 | 4.6875 | 5 | # This is an intro to Object orientation
class Enemy:
""" This class contains all the enemies that we will fight.
It has attributes for life and name, as well as functions
that decrease its health and check its life. """
def __init__(self, name, life):
""" the init function runs automatically when a new object is created. It sets the name and life of the new object. """
''' _ makes it private variable have to ask for it '''
self._name = name
self._life = life
def attack(self, damage):
""" This function runs when the enemy is attacked.
It prints Ouch and decreases life by 1. """
print("Ouch")
self._life = damage
def checkLife(self):
""" This function prints I am dead when life is less than
or equal to zero and otherwise displays the amount of life left. """
if self._life <= 0:
print("I am dead")
else:
print("{} has {} life left".format(enemy1.get_name(), enemy1.get_life()))
def get_name(self):
""" This function returns the name of the object. """
return self._name
def get_life(self):
""" This function returns the life of the object. """
return self._life
#To create an instance of a class, we set it as a variable
enemy1 = Enemy("Dr Evil", 10)
enemy2 = Enemy("Gru", 5)
# To call a function, we use "dot syntax", the name of the variable followed by a dot and then the function
enemy1.attack(5)
enemy1.checkLife()
print("{} has {} life left"(enemy1.get_name(), enemy1.get_life()))
| true |
a3d457ff813c70b7e43e6903222308eaae6ff7ae | FreeTymeKiyan/DAA | /ClosestPair/ClosestPair.py | 2,642 | 4.4375 | 4 | # python
# implement a divide and conquer closest pair algorithm
# 1. check read and parse .txt file
# 2. use the parsed result as the input
# 3. find the closest pair in these input points
# 4. output the closest pair and the distance between the pair
# output format
# The closest pair is (x1, x2) and (y1, y2).
# The distance between them is d = xxx.
from sys import argv
from random import randint, randrange
from operator import itemgetter, attrgetter
infinity = float('inf')
# calculate the square of a number
#def square(x):
# return x * x
# calculate distance between two points
#def square_distance(p, q):
# return square(p[0] - q[0]) + square(p[1] - q[1])
# closest_pair, use real numbers to express points
def closest_pair(point):
x_p = sorted(point, key = attrgetter('real')) # x is the real part
#print 'x_p: ', x_p
y_p = sorted(point, key = attrgetter('imag')) # y is the imaginary part
#print 'y_p: ', y_p
return divide_and_conquer(x_p, y_p)
#
def brute_force(point):
n = len(point)
if n < 2:
return infinity, (None, None)
return min( ((abs(point[i] - point[j]), (point[i], point[j]))
for i in range(n - 1)
for j in range(i + 1, n)),
key = itemgetter(0))
#
def divide_and_conquer(x_p, y_p):
n = len(x_p) # number of points
if n <= 3:
return brute_force(x_p)
print 'n: ', n
p_l = x_p[:n / 2] # when n == 1, p_l is empty
p_r = x_p[n / 2:]
print 'p_l: ', p_l
print 'p_r: ', p_r
y_l, y_r = [], []
x_divider = p_l[-1].real # last x of p_l, when p_l is empty, wrong
print 'x_divider: ', x_divider
for p in y_p:
if p.real <= x_divider:
y_l.append(p)
else:
y_r.append(p)
d_l, pair_l = divide_and_conquer(p_l, y_l) # divide into left and right
d_r, pair_r = divide_and_conquer(p_r, y_r)
d_m, pair_m = (d_l, pair_l) if d_l < d_r else (d_r, pair_r)
close_y = [p for p in y_p if abs(p.real - x_divider) < d_m]
n_close_y = len(close_y) # points with d_m
if n_close_y > 1:
closest_y = min(((abs(close_y[i] - close_y[j]), (close_y[i], close_y[j]))
for i in range(n_close_y - 1)
for j in range(i+1, min(i+8, n_close_y))),
key = itemgetter(0))
return (d_m, pair_m) if d_m <= closest_y[0] else closest_y
else:
return d_m, pair_m
# main start from here
point_list = [randint(0,5) + 1j * randint(0, 5) for i in range(10)]
print point_list
print ' closest pair:', closest_pair(point_list)
# read .txt file
#script, filename = argv
#txt = open(filename)
#print "Here's your file %r: " % filename
# check read result
# print txt.read()
# parse .txt file
#for line in txt:
# x = line.split(',')[0]
# y = line.split(',')[1]
# print x,
# print y
# remember to close
#txt.close()
| true |
7e5f9155c0e22abb671c826d940da51c3ba46294 | danmaher067/week4 | /LinearRegression.py | 985 | 4.1875 | 4 | # manual function to predict the y or f(x) value power of the input value speed of a wind turbine.
# Import linear_model from sklearn.
import matplotlib.pyplot as plt
import numpy as np
# Let's use pandas to read a csv file and organise our data.
import pandas as pd
import sklearn.linear_model as lm
# read the dataset
#df = pd.read_csv('https://raw.githubusercontent.com/ianmcloughlin/2020A-machstat-project/master/dataset/powerproduction.csv')
df =pd.read_csv('powerproduction.csv')
# Plots styles.
# Plot size.
plt.rcParams['figure.figsize'] = (14, 10)
# Create a linear regression model instance.
m = lm.LinearRegression()
df.isnull().sum()
x=df[["speed","power"]]
y=df["power"]
m.fit(x,y)
m.intercept_
m.coef_
m.score(x,y)
z=df["speed"]
q=df["power"]
np.polyfit(z,q,1)
m,c =np.polyfit(z,q,1)
a,b,c,d = np.polyfit(z,q,3)
def findy(x):
print('x =',x)
y = (a*x**3) + (b*x**2) + (c*x) +d
if y < 0:
y = 0
return '{:.2f}'.format(y)
print('y = ', findy(10))
| true |
56635b0819e7cdbc8b96ec68bb4de313ca0da587 | Woobs8/data_structures_and_algorithms | /Python/Sorting/bubble_sort.py | 2,850 | 4.1875 | 4 | import argparse
import timeit
from functools import partial
import random
from sorting import BaseSort
class BubbleSort(BaseSort):
"""
A class used to encapsulate the Bubble Sort algorithm
Attributes
----------
-
Methods
-------
sort(arr, in_place=False)
Sorts an array using the bubble sort algorithm by iteratively comparing each element with its adjacent element
swapping the two if the sort condition is satisfied.
"""
def __repr__(self):
return 'Bubble Sort'
def sort(self, arr: list, in_place=False) -> list:
"""
Sorts an array using the bubble sort algorithm by iteratively comparing each element with its adjacent element
swapping the two if the sort condition is satisfied.
Parameters:
arr (list): list to be sorted
in_place (bool): whether the list should be sorted in place
Returns:
list: the sorted list
"""
n = len(arr)
if in_place:
work_arr = arr
else:
work_arr = arr.copy()
# outer pass: n passes required to guarantee the array is sorted
for i in range(n):
swapped = False
# inner pass: iterate all 0:n-i elements, as last i elements will already be sorted
for j in range(n-i-1):
if work_arr[j] > work_arr[j+1]:
work_arr[j], work_arr[j+1] = work_arr[j+1], work_arr[j]
swapped = True
# if no swaps in inner loop, the array is sorted
if not swapped:
break
return work_arr
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Bubble sorting algorithm')
parser.add_argument('-data', help='parameters for generating random data [len, seed]', nargs=2, type=int)
parser.add_argument('-t', help='measure the execution time', nargs=2, required=False, type=int)
args = parser.parse_args()
n = args.data[0]
seed = args.data[1]
t = args.t
# shuffle data randomly with seed
sorted_data = list(range(n))
random.seed(seed)
random_data = random.sample(sorted_data, n)
sorting_algo = BubbleSort()
# verify that list is sorted correctly
if not sorting_algo.sort(random_data) == sorted_data:
print('Error sorting array using <{}>'.format(sorting_algo))
exit(1)
if args.t:
times = timeit.Timer(partial(sorting_algo.sort, random_data)).repeat(t[1], t[0])
# average time taken
time_taken = min(times) / t[0]
print('Timing analysis')
print('Sorting method: {}'.format(sorting_algo))
print('Data length: {}'.format(n))
print('Executions: {}'.format(t[0]))
print('Average time: {}s'.format(time_taken)) | true |
2e6ebd01b1e1e5b508501d5a2536d5b85883af23 | lbray/Python-3-Examples | /file-analyzer.py | 370 | 4.28125 | 4 | # Program returns the number of times a user-specified character
# appears in a user-specified file
def char_count(text, char):
count = 0
for c in text:
if c == char:
count += 1
return count
filename = input("Enter file name: ")
charname = input ("Enter character to analyze: ")
with open(filename) as f:
data = f.read()
print (char_count(data, charname))
| true |
281085709d44facc168cbb6324aa7429bc36f9ce | macoopman/Python_DataStructures_Algorithms | /Recursion/Projects/find.py | 1,934 | 4.15625 | 4 | """
Implement a recrsive function with the signature find(path, name) that reports
all entries of the file system rooted at the given path having the given file name
"""
import os, sys
def find(path, name):
"""
find and return list of all matches in the given path
"""
found = [] # list of found items
def find_recursive(path, name, found): # recursive function to traverse tree and append found items
path_abs = os.path.abspath(path) # get the absolute path name
try:
dir_items = os.listdir(path_abs)
except:
print(f"ERROR: Directory {path} not found...")
sys.exit(1)
dir_items = os.listdir(path_abs) # list all times in the currrent directory
for item in dir_items: # iterate over the dir list
full_path = os.path.join(path_abs, item) # get the full path name path + filename/directory
if os.path.isdir(full_path): # if is a directory
find_recursive(full_path, name, found) # make recursive call to function
if os.path.isfile(full_path): # if a file
if item == name: # check for name equality
found.append(full_path) # if true: add to list
find_recursive(path, name, found) # call recursive function
return found
if __name__ == "__main__":
if len(sys.argv) >= 3:
path, name = sys.argv[1:]
else:
print("Usage: python3 find.py path name")
sys.exit(1)
found_files = find(path, name)
print("Found Files:")
for item in found_files:
print("...", item)
| true |
83046855b03c830defd9e840123d8a6abe0d44f5 | macoopman/Python_DataStructures_Algorithms | /Recursion/Examples/Linear_Recursion/recursive_binary_search.py | 968 | 4.25 | 4 | """
Recursive Binary Search:
locate a target value within a "sorted" sequence of n elements
Three Cases:
- target == data[mid] - found
- target < data[mid] - recur the first half of the sequence
- target > data[mid] - recur the last half of the sequence
Runtime => O(log n)
"""
def binary_search(data, target, low, high):
""" Return True if target is found in indicated portion of a Python List """
if low > high: # Base Case: interval is empty; no match
return False
else:
mid = (low + high) // 2 # find new mid point
if target == data[mid]: # found your target - exit search
return True
elif target < data[mid]:
# recur on the ortion left of the middle
return binary_search(data, target, low, mid-1)
else:
# recure on the portion right of the middle
return binary_search(data, target, mid+1, high)
| true |
008317fe6ca28ef600fc024c049a39c6bf7db163 | myszunimpossibru/shapes | /rectangles.py | 1,843 | 4.25 | 4 | # coding: utf8
from shape import Shape
import pygame
class Rectangle(Shape):
"""
Class for creating the rectangular shape
Parameters:
pos: tuple
Tuple of form (x, y) describing the position of the rectangle on the screen.
Reminder: PyGame sets point (0, 0) as the upper left corner and the point with highest value of coordinates
as the lower right corner.
a: integer
Length of the first side
b: integer
Length of the second side
scale: integer (default scale=50)
Value used for scaling the shape while drawing. In default case 1 unit is equal to 50 pixels.
"""
a = None
b = None
def __init__(self, pos, a, b, scale=50):
super().__init__(pos, scale)
self.a = a
self.b = b
if self.a <= 0 or self.b <= 0:
raise ValueError("Size cannot be negative or zero")
def area(self):
return self.a * self.b
def perimeter(self):
return 2 * (self.a + self.b)
def __str__(self):
return "Rectangle of dimensions {} x {}".format(self.a, self.b)
def __repr__(self):
return "Rectangle({}, {}, {})".format(self.pos, self.a, self.b)
def draw(self, screen):
points = [self.pos, (self.pos[0] + self.a * self.scale, self.pos[1]), (self.pos[0] + self.a * self.scale, self.pos[1] + self.b * self.scale), \
(self.pos[0], self.pos[1] + self.b * self.scale)]
return pygame.draw.polygon(screen, (255, 255, 255), points)
class Square(Rectangle):
"""
Rectangle with even sides.
See help of Rectangle class for more information.
"""
def __init__(self, a):
super().__init__(a, a)
def __repr__(self):
return "Square({}, {})".format(self.pos, self.a)
| true |
fe0d6c09f4eacfc2d14944e9a7661ad7d1658a3a | rufi91/sw800-Coursework | /ML-14/ex.py | 1,442 | 4.21875 | 4 | """
1) Implement MLPClassifier for iris dataset in sklearn.
a. Print confusion matrix for different activation functions
b. Study the reduction in loss based on the number of iterations.
2) Implement MLPRegressor for boston dataset in sklearn . Print performance
metrics like RMSE, MAE , etc.
"""
from sklearn.neural_network import MLPClassifier, MLPRegressor
import numpy as np
from sklearn.datasets import load_iris, load_boston
from sklearn.metrics import confusion_matrix, mean_squared_error, mean_absolute_error
from sklearn.model_selection import train_test_split
#1
data=load_iris()
X=data.data
y=data.target
X_train,X_test, y_train, y_test = train_test_split(X, y)
activations=list('identity logistic tanh relu'.split())
for a in activations:
mlp= MLPClassifier(activation=a,verbose=True, hidden_layer_sizes=200, max_iter=500)
mlp.fit(X_train,y_train)
p=mlp.predict(X_test)
print "\n Accuracy matrix for method %s \n"%a,"\n", confusion_matrix(y_test,p)
#2
dataReg=load_boston()
XReg=dataReg.data
yReg=dataReg.target
Xr_train,Xr_test, yr_train, yr_test = train_test_split(XReg, yReg, test_size=0.2)
mlpr=MLPRegressor()
mlpr.fit(Xr_train,yr_train)
pr=mlpr.predict(Xr_test)
print "\n Performance metrics for MLPR: \n\n\t Mean Squared Error: %f \n\t Mean Absolute Error: %f \n\t RMSE: %f"%(mean_squared_error(yr_test,pr),mean_absolute_error(yr_test,pr), np.sqrt(mean_squared_error(yr_test,pr)))
| true |
6049135043f6aa6b446c2856ee89cee66e7f706f | rufi91/sw800-Coursework | /Python/py-24/ex.py | 2,164 | 4.375 | 4 | """
Open python interpreter/ipython and do the following.
0.import pandas
1.create a dataframe object from a (10,4)2D array consisting of random integers between 10 and 20 by making c1,c2,c3,c4 as column indices.
2.Sort the above oject based on the key 'c1' in ascending and then by 'c3' in descending order.
"""
import numpy as np
import pandas as pd
from pandas import Series as s
from pandas import DataFrame as df
l1=(np.random.randint(10,20, 40)).reshape(10,4)
print l1
df1=df(l1, columns=['c1','c2','c3','c4'])
print df1
df1.sort_values(['c1','c3'], ascending=[True,False])
"""
3.write script to store item,place and total sale in a dataframe object.There should be 3 or more places and 4 or more items in the set.
Based on the choice entered by user,
(ii) show placewise rank for a particular item (for a given item name).
(iii)Show itemwise rank for a particular place (for a given place name).
""" """
dic1= {'item':['apple','banana','orange','grape','apple','orange'],\
'place':['kochi','tvm','clt','kochi','clt','tvm'],\
'sales':[200,100,220,300,450,190]}
df2=df(dic1)
item1= raw_input("Enter the item required: ")
#df2=df2.sort_values(['item','sales'], ascending=[True,False])
df2=df2[df2['item']==item1]
print df2
df2['rank']=df2['sales'].rank(ascending=False)
print df2
##################################
place1= raw_input("Enter the place required: ")
df3=df(dic1)
df3=df3[df3['place']==place1]
print df3
df3['rank']=df3['sales'].rank(ascending=False)
print df3
4.switch to home directory and send the output of ls -l command to a file named lsf1
5.create another file lsf2 by replacing all the spaces with ',' use tr command tr ' ' ',' < lsf1 > lsf2
6.create another file lsf3 by squeezing multiple ',' use tr command - tr -s ',' < lsf2 > lsf3
7.using pandas read the file lsf3 and sort it based on file size (fifth column)
8.write the above dataframe obj (sorted) to a new file named lsf5
"""
df4=pd.read_csv('/home/ai21/lsf3.txt', delimiter=',')
print df4,"\n",df4.shape,"\n"
df4.columns='a b c d f g h i j'.split()
df4=df4.sort_values(['f'])
print df4
df4.to_csv('lsf5.txt')
| true |
e7b8ac86e23d9ddd1a03dba8f75789e4b3288b57 | nshoa99/Leetcode | /List/1324.py | 1,268 | 4.1875 | 4 | '''
Medium
Given a string s. Return all the words vertically in the same order in which they appear in s.
Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column there will be only one word.
Example 1:
Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically.
"HAY"
"ORO"
"WEU"
Example 2:
Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE"," T"]
Explanation: Trailing spaces is not allowed.
"TBONTB"
"OEROOE"
" T"
Example 3:
Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]
Constraints:
1 <= s.length <= 200
s contains only upper case English letters.
It's guaranteed that there is only one space between 2 words.
'''
def printVertically(s):
sList = s.split(" ")
maxlenth = 0
for word in sList:
maxlenth = max(maxlenth, len(word))
result = ["" for _ in range(maxlenth)]
for i in range(0, maxlenth):
for word in sList:
result[i] += word[i] if i < len(word) else " "
result[i] = result[i].rstrip(" ")
return result
print(printVertically("TO BE OR NOT TO BE")) | true |
076ac8dcc7af8424b0e1b5fb4da98a8b9a9478c3 | nshoa99/Leetcode | /String/524.py | 1,338 | 4.1875 | 4 | '''
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output:
"apple"
Example 2:
Input:
s = "abpcplea", d = ["a","b","c"]
Output:
"a"
'''
# 2 pointers and sort
# def findLongestWord(s = "abpcpleeee", d = "apple"):
# i, j = 0, 0
# word = ""
# while i < len(s) and j < len(d):
# if s[i] != d[j]:
# i += 1
# else:
# word += s[i]
# i += 1
# j += 1
# return word
# print(findLongestWord())
def check(s, word):
i, j = 0, 0
while i < len(s) and j < len(word):
if s[i] != word[j]:
i += 1
else:
i += 1
j += 1
return j == len(word)
def findLongestWord(s, d):
result = ""
for word in d:
if check(s, word):
if len(word) > len(result) or len(word) == len(result) and word < result:
result = word
return result
print(findLongestWord(s = "abpcplea", d = ["ale","apple","monkey","plea"]))
| true |
ee64bbec7eee7449b7d526f5147d749b07942740 | haroldhyun/Algorithm | /Sorting/Mergesort.py | 1,998 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 7 20:04:26 2021
@author: Harold
"""
def Mergesort(number):
"""
Parameters
----------
number : list or array of numbers to be sorted
Returns
-------
sorted list or array of number
"""
# First divide the list by two halves
n = len(number)
# If there is only 1 element, we don't need to sort.
if n == 1:
return number
# Mergesort is a divide and conquer method. Divide into two halves
half = n // 2
first = number[:half]
last = number[half:]
# Now we can recursively sort the two halves
sort_first = Mergesort(first)
sort_last = Mergesort(last)
# Then we can merge the two
sort = merge(sort_first, sort_last)
return sort
def merge(one, two):
"""
Parameters
----------
one : list or array
numbers to be sorted
two : list or array
numbers to be sorted
Returns
-------
sorting: sorted and merged array of one and two
"""
# First create new empty array.
sorting = []
# Let's loop and compare until one or two runs out of element
while len(one) != 0 and len(two) != 0:
if one[0] < two[0]:
sorting.append(one[0])
one.pop(0)
else:
sorting.append(two[0])
two.pop(0)
# When the first while loop is complete, either one or two has no more elements
# Then we just have to add whatever is remaining to sorting
if len(one) != 0:
sorting = sorting + one
elif len(two) != 0:
sorting = sorting + two
# Now we just return our sorted array
return sorting
| true |
a985d1439e1f07522b6d141260b8e299278e045b | Kritika05802/DataStructures | /area of circle.py | 235 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
radius = float(input("Enter the radius of the circle: "))
area = 3.14 * (radius) * (radius)
print("The area of the circle with radius "+ str(radius) +" is " + str(area))
# In[ ]:
| true |
f066e25dd7044e0a2e7fb37a9f0729e6190c38e7 | prd-dahal/sem4_lab_work | /toc/lab7.py | 684 | 4.5625 | 5 | #Write a program for DFA that accepts all the string ending with 3 a's over {a,b}\#Write a program for DFA that accepts the strings over (a,b) having even number of a's and b's
def q0(x):
if(x=='a'):
return q1
else:
return q0
def q1(x):
if(x=='a'):
return q2
else:
return q0
def q2(x):
if(x=='a'):
return q3
else:
return q0
def q3(x):
if(x=='a'):
return q3
else:
return q0
x=input("Enter a string to check if it belongs to the DFA::")
t=q0(x[0])
for i in range(1,len(x)):
t=t(x[i])
t=(str(t))
t=(t[10:12])
if(t=='q3'):
print("String Accepted")
else:
print("String Rejected") | true |
0b7c2b351c39fa1b718a156eb41ffc9e19b9382e | felixguerrero12/operationPython | /learnPython/ex12_Prompting_asking.py | 397 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# Created on July 27th
# Felix Guerrero
# Exercise 12 - Prompting - Learn python the hard way.
#Creating Variables with Direct Raw_Input
age = raw_input("How old are you? \n")
height = raw_input("How tall are you? \n")
weight = raw_input("How much do you weight? \n")
# Print Variables
print "So, you are %r old, you are %r tall, and weight %r pounds." % (age, height, weight)
| true |
3a069734693a40536828bdaf82eb3db7188d5e2e | felixguerrero12/operationPython | /learnPython/ex03_Numbers_And_Variable_01.py | 703 | 4.34375 | 4 | # Created on July 26th
# Felix Guerrero
# Exercise 3 - Numbers and math - Learn python the hard way.
#Counting the chickens
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
#Counting the eggs
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Verifying if one is greater than the other.
print "Is it true that 3 + 2 < 5 - 7"
print 3 + 2 < 5 - 7
# Basic Operations
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
# More complicated operations
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
| true |
840747d89d7f2d84c7b819b5d26aa4ac1ea93254 | felixguerrero12/operationPython | /learnPython/ex15_Reading_Files.py | 739 | 4.25 | 4 | # Felix Guerrero
# Example 15 - Reading Files
# June 28th, 2016
# Import the sys package and import the arguement module
from sys import argv
# The first two command line arguements in the variable will be
# these variables
script, filename = argv
# 1. Open up variable filename
# 2. Give the content of the file to txt
txt = open(filename)
# 1. Print the Variable Filename
# 2. Read the variable txt
print "Here's your file %r" % filename
print txt.read()
# 1. Print the variable filename again:"
# but with a different format instead.
print "Type the filename again:"
file_again = raw_input("> ")
# 1. Open the file and give the content to variable txt_again
# 2. print txt_again.read()
txt_again = open(file_again)
print txt_again.read()
| true |
451700ee74f47681206b30f81e7c61b80c798f8c | ChiefTripodBear/PythonCourse | /Section7/utils/database.py | 1,803 | 4.1875 | 4 | import sqlite3
"""
Concerned with storing and retrieving books from a list.
Format of the csv file:
[
{
'name': 'Clean Code',
'author': 'Robert',
'read': True
}
]
"""
def create_book_table():
connection = sqlite3.connect('Section7/data/data.db')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS books(name text primary key, author text, read integer)')
connection.commit()
connection.close()
# adds a book to our dictionary
def add_book(name, author):
connection = sqlite3.connect('Section7/data/data.db')
cursor = connection.cursor()
cursor.execute('INSERT INTO books VALUES(?, ?, 0)', (name, author))
connection.commit()
connection.close()
# returns the dictionary of all books
def get_all_books():
connection = sqlite3.connect('Section7/data/data.db')
cursor = connection.cursor()
cursor.execute('SELECT * from books')
#a list of tuples [(name, author, read), (name, author, read)]
books = [{'name': row[0], 'author': row[1], 'read': row[2]} for row in cursor.fetchall()]
connection.close()
return books
# marks a book as read, given the book name from the user
def mark_book_as_read(name):
connection = sqlite3.connect('Section7/data/data.db')
cursor = connection.cursor()
cursor.execute('UPDATE books SET read = 1 WHERE name = ?', (name,))
connection.commit()
connection.close()
# deletes a book from the dictionary
def delete_book(name):
connection = sqlite3.connect('Section7/data/data.db')
cursor = connection.cursor()
cursor.execute('DELETE from books WHERE name = ?', (name,))
connection.commit()
connection.close()
| true |
625707a1917c8f1e91e3fd9f2ee4a51102f27af5 | golddiamonds/LinkedList | /LinkedList.py | 2,790 | 4.28125 | 4 | ##simple linked list and node class written in python
#create the "Node" structure
class Node:
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
def getData(self):
return self.data
#create the structure to hold information about the list
#including methods to append or remove a Node
class LinkedList:
def __init__(self,data):
self.head = Node(data, None)
def getHead(self):
return self.head
def append(self, data):
cur_node = self.head
while(cur_node.next_node is not None):
cur_node = cur_node.next_node
cur_node.next_node = Node(data)
def remove(self, value):
if self.head.data == value:
self.head = self.head.next_node
return
prev_node = self.head
cur_node = self.head.next_node
while(True):
if (cur_node.data == value):
prev_node.next_node = cur_node.next_node
if (cur_node.next_node == None):
break
prev_node = cur_node
cur_node = cur_node.next_node
return None
def printList(self):
cur_node = self.head
while(cur_node.next_node):
print cur_node.data
cur_node = cur_node.next_node
print cur_node.data
def findNode(self, value):
cur_node = self.head
while(True):
if (cur_node.data == value):
return cur_node
if (cur_node.next_node == None):
break
cur_node = cur_node.next_node
return None
if __name__ == "__main__":
print '-> first test with data "information"'
data = "information"
#pass in data for "head" Node
linked_list = LinkedList(data)
head = linked_list.getHead()
print head.getData()
print '-> one more Node added with data "more information"'
moredata = "more information"
linked_list.append(moredata)
linked_list.printList()
print '-> another test adding value "another piece of information"'
anotherpiece = "another piece of information"
linked_list.append(anotherpiece)
linked_list.printList()
print '-> return Node with specified value "another piece of information"'
found_node = linked_list.findNode("another piece of information")
print found_node.data
print '-> search for value that doesn\'t exist'
no_node = linked_list.findNode("not a value")
if no_node == None:
print 'Value searched for does not exist'
print '-> remove "more information" value'
linked_list.remove("more information")
linked_list.printList()
print '-> remove "information" value'
linked_list.remove("information")
linked_list.printList()
| true |
3d289735bca17f15a1e100fdaa01b4a86b871a25 | emuyuu/design_pattern | /3_behavioral_design_patterns/iterator_pattern.py | 1,704 | 4.59375 | 5 | # iterate = 繰り返す
# Iterator:
# > Anything that is iterable can be iterated,
# > including dictionaries, lists, tuples, strings, streams, generators, and classes
# > for which you implement iterator syntax.
# 引用:http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
# -----------------------------------------
# object.__getitem__(self, key):
# self[key] の値評価 (evaluation) を実現するために呼び出される。
# class Test():
# def __getitem__(self, item):
# if item in ['apple', 'banana', 'orange']:
# return f'item is fruit'
#
# test = Test()
# print(test['apple'])
# -> item is fruit
# -----------------------------------------
class Numbers:
def __init__(self):
self.number_list = [num for num in range(0, 11)]
numbers = Numbers()
print('non iterable class object')
print(f'iterable?: {hasattr(numbers, "__iter__")}')
for i in numbers.number_list:
print(i)
class IterNumbers:
def __init__(self):
self.number_list = [num for num in range(0, 11)]
def __iter__(self):
return iter(self.number_list)
iter_numbers = IterNumbers()
print('iterable class object')
print(f'iterable?: {hasattr(iter_numbers, "__iter__")}')
for i in iter_numbers:
print(i)
# -> 同じ出力だけれど、for文を書く時の量が少ない
class IterNumbersSequenceProtocol:
def __getitem__(self, index):
if 0 <= index < 6:
return index
raise IndexError()
print('iterable class object using sequence protocol(=__getitem__())')
print(f'iterable?: {hasattr(IterNumbersSequenceProtocol(), "__iter__")}')
for num in IterNumbersSequenceProtocol():
print(num)
| true |
99a214e31f4f1251f04f6f66fb4c96ef57049873 | crashley1992/Alarm-Clock | /alarm.py | 2,189 | 4.28125 | 4 | import time
from datetime import datetime
import winsound
# gets current time
result = time.localtime()
# setting varable for hour, minute, seconds so it can be added to user input
current_hour = result.tm_hour
current_min = result.tm_min
current_sec = result.tm_sec
# test to make sure format is correct
print(f'{current_hour} : {current_min} : {current_sec}')
# asks for user input for alarm, all converted to int for time.sleep() in alarm function
hour_input = input('How many hours from now would you like the timer to be set: ')
hour_set = int(hour_input)
min_input = input('How many minutes from now would you like the timer to be set: ')
min_set = int(min_input)
sec_input = input('How many seconds from now would you like the timer to be set: ' )
sec_set = int(sec_input)
# alarm sound that goes off
def sound():
for i in range(2): # Number of repeats
for j in range(9): # Number of beeps
winsound.MessageBeep(-1) # Sound played
time.sleep(2) # How long between beeps
# displays time and uses time.sleep() to delay sound() by converting all input to seconds and inputing it into the time.sleep()
def alarm():
print(f'Current time is {current_hour}:{current_min}:{current_sec}')
# takes user input an added to time object
alarm_hour = current_hour + hour_set
alarm_min = current_min + min_set
alarm_sec = current_sec + sec_set
print(f'Alarm set for {alarm_hour}:{alarm_min}:{alarm_sec}')
# counter variable that will take in the amount of delay for time.sleep()
seconds_to_wait = 0
# converstons for user's time input
if hour_set > 0:
# times 60 twice to get converstion from hours to seconds
wait_time = (hour_set * 60) * 60
# adds variable to seconds to wait counter
seconds_to_wait += wait_time
elif min_set > 0:
# times 60 once to get converstion from minutes to seconds
wait_time = (min_set * 60)
seconds_to_wait += wait_time
elif sec_set > 0:
wait_time = sec_set
seconds_to_wait += wait_time
time.sleep(seconds_to_wait)
# wanted a visual indicator for those who may not hear
print('Beep!')
sound()
alarm() | true |
cf823ebcf1c564bef2ed6103588b2ff8ed1e86da | donrax/point-manipulation | /point_side_line.py | 623 | 4.34375 | 4 | import numpy as np
def point_side_line(p1, p2, p):
"""
Computes on which side of the line the point lies.
:param p1: [numpy ndarray] start of line segment
:param p2: [numpy ndarray] end of line segment
:param p: [numpy ndarray] point
:return: 1 = LEFT side, 0 = ON the line, -1 = RIGHT side
"""
# Get vector from p1 to p2
a = p2 - p1
# Get vector from p1 to q
b = p - p1
# The sign of the cross product determines point side
s = np.sign(np.cross(a,b))
# s>0 -> LEFT side of the line
# s=0 -> ON side of the line
# s<0 -> RIGHT side of the line
return s | true |
e562b59876199bf03b6aa533afe98f5f8d385fd5 | Meethlaksh/Python | /again.py | 1,899 | 4.1875 | 4 | #Write a python function to find the max of three numbers.
def m1(l):
d = max(l)
return d
l = [1,2,3,4,5]
print(m1(l))
#Write a python function to sum up all the items in a list
def s1(s):
e = sum(s)
return e
s = [1,2,3,4,5]
print(s1(s))
#multiply all the items in a list
import math
def mul1(x):
f = math.prod(x)
return f
x = [1,2,3,4]
print(mul1(x))
#function that checks whether a passed string is palindrome
def str4(str1):
str2 = ''.join(reversed(str1))
if str1 == str2:
return 'yes'
else:
return 'no'
str1 = 'racecar'
print(str4(str1))
#string is a pangram
def str6(str3):
alphabet = ["a","b","c","d"]
value = True
for x in alphabet:
if x not in str3:
value = False
return value
str3 = "The quick brown fox jumps over the lazy dog"
print(str6(str3))
#Python function to create and print a list where the values are square of numbers between 1 and 30 (both included)
def mk():
k = []
n = 1
while n < 30:
k.append(n)
n+=1
return k
def squ():
z = mk()
d2 = []
for y in z:
d1 = pow(y,2)
d2.append(d1)
return d2
print(squ())
#Python program to make a chain of function decorators (bold, italic, underline etc.) in Python.
"""
def make_bold(fn):
from __future__ import unicode_literals, print_function
h = '<b> fn </b>'
return h
fn = 'hello world'
print(make_bold(fn))"""
def make_bold(fn):
def wrapped():
return "<b>" +fn() + "</b>"
return wrapped
def make_italic(fn):
def wrapped():
return "<i>" +fn() + "</i>"
return wrapped
def make_underline(fn):
def wrapped():
return "<u>" +fn() + "</u>"
return wrapped
@make_bold
@make_italic
@make_underline
def name():
return "Hello World"
print(name())
#jinja templating python(flask, django)
| true |
baff5161fd319ce26fd9d5de0e68078885b9983e | Meethlaksh/Python | /studentclass.py | 985 | 4.125 | 4 | """Create a Student class and initialize it with name and roll number. Make methods to :
1. Display - It should display all informations of the student.
2. setAge - It should assign age to student
3. setMarks - It should assign marks to the student.
"""
"""
keywords:
parameter
methods
difference between functions and methods
self = represents the instance of that class
create a student mark and set his age to 20
create a student jane and set her marks as 25
"""
class Student:
def __init__(self, name, rollnumber):
self.name = name
self.rollnumber = rollnumber
self.age = int
self.marks = int
def display(self):
app = [self.name, self.rollnumber]
return app
def setage(self, age):
self.age = int(age)
return self.age
def setmarks(self, marks):
self.marks = int(marks)
return self.marks
mark = Student(mark, 15)
mark.setage(20)
jane = Student(jane, 18)
jane.setmarks(25) | true |
58a96988ee925d1c65148817e500a3dee2e0216d | kylastyles/Python1000-Practice-Activities | /PR1000_03/PR03_HexReaderWriter.py | 970 | 4.40625 | 4 | #!usr/bin/env python3
# Problem Domain: Integral Conversion
# Mission Summary: Convert String / Integral Formats
user_string = input("Please enter a string to encode in hexadecimal notation: ")
def hex_writer(user_string):
hex_string = ""
if user_string == "":
return None
for char in user_string:
hex_num = hex(ord(char))
hex_string += hex_num
return hex_string
def hex_reader(encoded_string):
if encoded_string:
hex_list = encoded_string.split("0x")
char_list = [chr(int(i, 16)) for i in hex_list if i != '']
glue = ""
decoded_string = glue.join(char_list)
return decoded_string
return None
def main(user_string):
encoded_string = hex_writer(user_string)
print("\nYour hex-encoded string is:")
print(encoded_string)
decoded_string = hex_reader(encoded_string)
print("\nYour decoded string is:")
print(decoded_string)
main(user_string) | true |
2e8fb160337f084912b9ed384f11891ab01fe63e | AwjTay/Python-book-practice | /ex4.py | 1,207 | 4.25 | 4 | # define the variable cars
cars = 100
# define the variable space_in_a_car
space_in_a_car = 4.0
# define the variable drivers
drivers = 30
# define the variable passengers
passengers = 90
# define the variable cars_not_driven
cars_not_driven = cars - drivers
# define the variable cars_driven as equal to drivers
cars_driven = drivers
# define the variable carpool_capacity
carpool_capacity = cars_driven * space_in_a_car
# define the variable average_passengers_in_a_car
average_passengers_in_a_car = passengers / cars_driven
# line 20 defines the variable carpool_capacity. average_passengers_in_a_car = car_pool_capacity / passenger
# would return an error becaus both the variables 'car_pool_capacity' and 'passenger' are not defined
# print the string "There are" and the value of the variable cars and the string "cars available"
print ("There are", (cars), "cars available" )
print ("There are only", (drivers), "drivers available")
print ("There will be", (cars_not_driven), "empty cars today.")
print ("We can transport", (carpool_capacity), "people today.")
print ("We have", (passengers), "to carpool today.")
print ("We need to put about", (average_passengers_in_a_car), "in each car.") | true |
72cb7e9d73041025ecd0e17490fb4cf1dcf1b508 | jw0711qt/Lab4camelcase | /Lab4_camelCase.py | 641 | 4.3125 | 4 | def camel_case(sentence):
if sentence.isnumeric(): #if statment handling empty and numeric number
return 'enter only words'
elif sentence=="":
return 'please enter your input'
else:
split_sentence=sentence.split() #for loop handling the camel case.
cap_sentence=[split_sentence[0].lower()]
for x in range (1, len(split_sentence)):
cap_sentence.append(split_sentence[x].capitalize())
return ''.join(cap_sentence)
def main():
sentence=input("enter your sentence")
camelCase=camel_case(sentence)
print(camelCase)
if __name__ == "__main__":
main()
| true |
2f5eeabbad6d9f7cc4a53e85da174af7ab891002 | tushushu/pads | /pads/sort/select_sort.py | 1,315 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
@Author: tushushu
@Date: 2018-09-10 22:23:11
@Last Modified by: tushushu
@Last Modified time: 2018-09-10 22:23:11
"""
def _select_sort_asc(nums):
"""Ascending select sort.
Arguments:
nums {list} -- 1d list with int or float.
Returns:
list -- List in ascending order.
"""
n = len(nums)
for i in range(n):
idx = i
for j in range(i + 1, n):
if nums[j] < nums[idx]:
idx = j
nums[i], nums[idx] = nums[idx], nums[i]
return nums
def _select_sort_desc(nums):
"""Descending select sort.
Arguments:
nums {list} -- 1d list with int or float.
Returns:
list -- List in descending order.
"""
n = len(nums)
for i in range(n):
idx = i
for j in range(i + 1, n):
if nums[j] > nums[idx]:
idx = j
nums[i], nums[idx] = nums[idx], nums[i]
return nums
def select_sort(nums, reverse=False):
"""Select sort.
Arguments:
nums {list} -- 1d list with int or float.
Keyword Arguments:
reverse {bool} -- The default is ascending sort. (default: {False})
Returns:
list -- List in order.
"""
return _select_sort_desc(nums) if reverse else _select_sort_asc(nums)
| true |
7fd24f06f3e47581d35635e1767bc230da26b20b | NortheastState/CITC1301 | /chapter10/Course1301.py | 1,507 | 4.1875 | 4 | # ===============================================================
#
# Name: David Blair
# Date: 04/14/2018
# Course: CITC 1301
# Section: A70
# Description: You can think of this Python file as a "driver"
# that tests the Student class. It can also be
# thought of as a container that hold a course
# full of Students.
#
# ===============================================================
from Student import Student
def main():
# create a Python list
courseCISP1301 = []
# create a few new Student objects from the class template
student1 = Student("Foo", "Bar", "A1")
student2 = Student("Bo", "Cephus", "A2")
student3 = Student("Curtis", "Loew", "A3")
# add students to the list
courseCISP1301.append(student1)
courseCISP1301.append(student2)
courseCISP1301.append(student3)
while True:
sID = input("Enter the student ID you want to add a grade: ")
# now add a few grades for Student with ID of 90012345
for student in courseCISP1301:
if student.getStudentID() == sID:
gradeItem = int(input("Enter a grade: "))
student.addAGrade(gradeItem)
done = input("Type 'Y' to enter another grade? ")
if done != 'Y':
break
print()
# output all students
for student in courseCISP1301:
print(student.toString(), student.getGradeAverage(), student.getMaxGrade(), student.getMinGrade())
main()
| true |
475cee6f9b8424e9028087a90c96fc1c6c69a2e8 | NortheastState/CITC1301 | /chapter1/foobar.py | 964 | 4.21875 | 4 | # ===============================================================
#
# Name: David Blair
# Date: 01/01/2018
# Course: CITC 1301
# Section: A70
# Description: In the program we will examine simple output
# using a function definition with no parameters
# and a print statement.
# Note that Python does not require a main function,
# even though there is one behind the curtains you
# you can't see, but it is customary to use one anyway.
# Also, we will see later in the course that getting
# use to using one will be a good thing to do.
#
# ===============================================================
# define the main function that takes no parameters.
# functions are not called when the program executes, instead it
# called only by name underneath.
def main():
print("Hello Mr. Foobar!")
# make a call to the main() function above
main()
| true |
9bc5bf07fbc4a04940394c23bfd0d0116422749e | sahilg50/Python_DSA | /Array/reverse_array.py | 782 | 4.3125 | 4 | #Function to reverse the array
def reverse(array):
if(len(array)==0):
return ("The array is empty!")
L = 0
R = len(array)-1
while(L!=R and L<R):
array[R], array[L] = array[L], array[R]
L+=1
R-=1
return array
#Main Function
def main():
array = []
lenght = int(input('Enter the size of the array: '))
for i in range(lenght):
while(True):
try:
element = int(input('Enter the {} element: '.format(i+1)))
array.append(element)
break
except(ValueError):
print("Oops! Please enter a numebr.")
print(reverse(array))
if __name__ == "__main__":
main() | true |
8a962ec652a3d239af3a3b860cf7663ab173c070 | sahilg50/Python_DSA | /Array/Max_Min_in_Array.py | 1,463 | 4.28125 | 4 | # Find the maximum and minimum element in an array
def get_min_max(low, high, array):
"""
(Tournament Method) Recursive method to get min max.
Divide the array into two parts and compare the maximums and minimums of the two parts to get the maximum and the minimum of the whole array.
"""
# If array has only one element
if(low == high):
array_min = array[low]
array_max = array[high]
return(array_min, array_max)
# If array has only two elements
elif(high == low+1):
a = array[low]
b = array[high]
if(a > b):
array_max = a
array_min = b
else:
array_max = b
array_min = a
return (array_max, array_min)
else:
mid = int((low + high) / 2)
arr_max1, arr_min1 = get_min_max(low, mid, array)
arr_max2, arr_min2 = get_min_max(mid + 1, high, array)
return (max(arr_max1, arr_max2), min(arr_min1, arr_min2))
def main():
# Create an array
array = []
try:
while True:
array.append(int(input("Enter the element: ")))
except ValueError:
print(array)
if(len(array) == 0):
print('The array is empty!')
return
low = 0
high = len(array) - 1
arr_max, arr_min = get_min_max(low, high, array)
print('Minimum element is ', arr_min)
print('nMaximum element is ', arr_max)
if __name__ == "__main__":
main()
| true |
7b62197a3a0395b563b62d68bc34066d8fa2643f | Libbybacon/Python_Projects | /myDB.db.py | 1,068 | 4.125 | 4 | # This script creates a new database and adds certain files from a given list into it.
import sqlite3
conn = sqlite3.connect('filesDB.db')
fileList = ('information.docx','Hello.txt','myImage.png', \
'myMovie.mpg','World.txt','data.pdf','myPhoto.jpg')
# Create a new table with two fields in filesDB database
with conn:
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS fileNames(\
ID INTEGER PRIMARY KEY AUTOINCREMENT, \
fileName STRING \
)")
conn.commit()
conn.close()
# Iterates through fileList to find files that end in '.txt'
# Then it adds those files to the fileNames table in dB
# and prints names of .txt files to console
conn = sqlite3.connect('filesDB.db')
for file in fileList:
if file.endswith('.txt'):
with conn:
cur = conn.cursor()
cur.execute("INSERT INTO fileNames(fileName) VALUES (?)", (file,))
conn.commit()
print("The following file has the '.txt' extenstion: {}".format(file))
conn.close()
| true |
8f1507a5140d329d2234f13fe0987291a7ff4df5 | Libbybacon/Python_Projects | /buildingClass2.py | 2,665 | 4.25 | 4 |
# Parent class Building
class Building:
# Define attributes:
numberSides = 4
numberLevels = 1
architectureType = 'unknown'
primaryUse = 'unknown'
energyEfficient = True
def getBuildingDetails(self):
numberSides = input("How many sides does the building have?\n>>> ")
numberLevels = input("How many levels are in the building?\n>>> ")
architectureType = input("What is the architecture style of the building?\n>>> ")
primaryUse = input("What is the primary use of the building?\n>>> ")
return numberSides,numberLevels,architectureType,primaryUse
def addLevel(self):
moreLevels = input("How many levels would you like to add to the building?\n>>> ")
numberLevels += moreLevels
return numberLevels
# Child class House
class Home(Building):
homeType: 'unknown'
age = 0
hasGarage = True
locationType = 'unknown'
lastSaleValue = 0
# Same method as parent class except it asks for homeType and locationType
# and not primaryUse
def getBuildingDetails(self):
numberSides = input("How many sides does the building have?\n>>> ")
numberLevels = input("How many levels are in the building?\n>>> ")
architectureType = input("What is the architecture style of the building?\n>>> ")
homeType = input("Is this home a house, an apartment, or a condominium?\n>>> ")
locationType = input("Is this home in a city, town, or rural area?\n>>> ")
return numberSides,numberLevels,architectureType,homeType,locationType
# Child class Business
class Business(Building):
businessType = 'unkown'
numberEmployees = 0
totalAnnualProfits = 0
squareFootage = 0
# Same method as parent class except it asks for businessType and squareFootage
# and not primaryUse
def getBuildingDetails(self):
numberSides = input("How many sides does the building have?\n>>> ")
numberLevels = input("How many levels are in the building?\n>>> ")
architectureType = input("What is the architecture style of the building?\n>>> ")
businessType = input("What type of business is in this building?\n>>> ")
squareFootage = input("What is the square footage of the building?\n>>> ")
return numberSides,numberLevels,architectureType,businessType,squareFootage
# Code to invoke getBuildingDetails method in each class
if __name__ == "__main__":
buildingOwner = Building()
buildingOwner.getBuildingDetails()
homeOwner = Home()
homeOwner.getBuildingDetails
businessOwner = Business()
businessOwner = getBuildingDetails()
| true |
3f2884d5da68f9fc7f684e63ed5a8a2144f0f39f | agrepravin/algorithms | /Sorting/MergeSort.py | 1,193 | 4.15625 | 4 | # Merge sort follows divide-conquer method to achieve sorting
# As it divides array into half until one item is left these is done in O(log n) time complexity
# While merging it linear compare items and merge in order which is achieved in O(n) time complexity
# Total time complexity for MergeSort is O(n log n) in all three cases
from Sorting.Sorting import Sorting
class MergeSort(Sorting):
def sort(self):
if len(self.arr) > 1:
mid = len(self.arr)//2
left = self.arr[:mid]
right = self.arr[mid:]
L = MergeSort(left)
L.sort()
R = MergeSort(right)
R.sort()
i=j=k=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
self.arr[k] = left[i]
i += 1
else:
self.arr[k] = right[j]
j += 1
k += 1
while i < len(left):
self.arr[k] = left[i]
i += 1
k += 1
while j < len(right):
self.arr[k] = right[j]
j += 1
k += 1
| true |
612e527762f60567874da66187cdaecf1063874e | khch1997/hw-python | /timing.py | 462 | 4.125 | 4 | import time
def calculate_time(func):
"""
Calculate and print the time to run a function in seconds.
Parameters
----------
func : function
The function to run
Examples
--------
def func():
time.sleep(2)
>>> calculate_time(func)
2.0001738937
"""
def wrapper():
current = time.time()
func()
end = time.time()
print(f'Total time {end - current}')
return wrapper | true |
6c0d5375fda176642668a007e65f8ae9f4c21e4a | josgard94/CaesarCipher | /CesarEncryption.py | 1,915 | 4.53125 | 5 | """
Author: Edgard Diaz
Date: 18th March 2020
In this class, the methods of encrypting and decrypting the plain
text file using modular arithmetic are implemented to move the original
message n times and thus make it unreadable in the case of encryption,
the same process is performed for decryption using the file containing the
encrypted text and scrolled n times to retrieve the original text.
In the alphabet the use of lowercase and capital letters is considered as
well as the numbers from zero to nine.
"""
import string
class Encryption:
def EncrypText(self, PlaneText, n):
EncrypT = "";
EncrypTxt = self.TextToNumber(PlaneText)
i = 0;
while i < len(EncrypTxt):
aux = EncrypTxt[i]
try:
x = int(EncrypTxt[i])
if x >= 0 or x <= 60:
E_n = ((x - n) % 61)
#print(E_n)
letter = self.NumberToText(E_n)
EncrypT += letter
i += 1;
except ValueError:
#i += 1;
EncrypT += aux
i += 1;
return EncrypT
def DecrypText(self, EncrypTxt, n):
Text = ""
StringNumber = self.TextToNumber(EncrypTxt)
i = 0;
while i < len(StringNumber):
aux = StringNumber[i]
try:
x = int(StringNumber[i])
if x >= 0 or x <= 60:
D_n = ((x + n) % 61)
letter = self.NumberToText(D_n)
Text += letter
i += 1;
except ValueError:
#i += 1;
Text += aux
i += 1;
return Text
def NumberToText(self,Number):
letter = 'abcdefghijklmnopqrstuvwxyzABCDFGHIJKLMNOPQRSTUVWXYZ0123456789'
return letter[Number]
def TextToNumber(self,Text):
NumberString = []
letter = 'abcdefghijklmnopqrstuvwxyzABCDFGHIJKLMNOPQRSTUVWXYZ0123456789'
i = 0
for c in Text:
#c = Text[i]
if c in letter:
#NumberString[i] = str(letter.index(c))
NumberString.append(str(letter.index(c)))
else:
NumberString.append(c);
i += 1;
return NumberString
| true |
f9b109cc9d356431ae79bf53b635889cd56465f3 | Kertich/Linked-List | /linkedList.py | 777 | 4.15625 | 4 | # Node class
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.start = None
# Inserting in the Linked List
def insert(self, value):
if self.start == None:
self.start = Node(value)
current = self.start
while current.next is not None:
current = current.next
current.next = Node(value)
# Traversing Linked List
def print(self):
current = self.start
while current is not None:
print(current.value)
current = current.next
linkedlist = LinkedList()
linkedlist.insert(10)
linkedlist.insert(20)
linkedlist.insert(30)
linkedlist.insert(40)
linkedlist.insert(50)
| true |
47321ae0df841cdc0c790d1692b65d9411aa8f7d | Croxy/The-Modern-Python-Bootcamp | /Section 10: Loops/examples/whileExample1.py | 332 | 4.28125 | 4 |
# Use a while loop to check user input matches a specific value.
msg = input("what is the secret password?")
while msg != "bananas":
print("WRONG!")
msg = input("what is the secret password?")
print("CORRECT!")
# Use a while loop to create for loop functionality.
num = 1
while num < 11:
print(num)
num += 1
| true |
ba30a449793ff270e61284e1d4598629647f5681 | pradeepraja2097/Python | /python basic programs/arguments.py | 543 | 4.1875 | 4 | '''
create a function for adding two variables. It will be needed to calculate p=y+z
'''
def calculateP( y , z ) :
return int( y ) + int( z )
'''
create a function for multiplying two variables. It will be needed to calculate p=y+z
'''
def calculateResult( x, p ) :
return int( x ) * int( p )
#Now this is the beginning of main program
x = input('x: ')
y = input('y: ')
z = input('z: ')
#Now Calculate p
p = calculateP ( y , z )
#Now calculate the result;
result = calculateResult( x , p )
#Print the result
print(result)
| true |
23f95e08d2678366d97400ade96b85453ce265e5 | EdwinaWilliams/MachineLearningCourseScripts | /Python/Dice Game.py | 484 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 22:18:01 2019
@author: edwinaw
"""
import random
#variable declaration
min = 1
max = 6
roll = "yes"
while roll == "yes" or roll == "y":
print("Rolling the dices...")
dice = random.randint(min, max)
#Printing the random number generated
print("You rolled.. " + str(dice))
#Asking the user if they want to roll the dice again
roll = input("Do you want to roll the dice again? \n")
| true |
69237dabe784446234868c8f59c6e1b0173c8df5 | hfu3/codingbat | /logic-1/date_fashion.py | 719 | 4.28125 | 4 | """
You and your date are trying to get a table at a restaurant.
The parameter "you" is the stylishness of your clothes,
in the range 0..10, and "date" is the stylishness of your
date's clothes. The result getting the table is encoded
as an int value with 0=no, 1=maybe, 2=yes. If either of
you is very stylish, 8 or more, then the result is 2
(yes). With the exception that if either of you has
style of 2 or less, then the result is 0 (no). Otherwise
the result is 1 (maybe).
"""
def date_fashion(you, date):
if you <= 2 or date <=2:
return 0
elif you >=8 or date >=8:
return 2
else:
return 1
date_fashion(5, 10)
date_fashion(5, 2)
date_fashion(5, 5) | true |
4505f8a1fe1c9cc5b04a326896c1648ec5415fee | jmockbee/While-Blocks | /blocks.py | 390 | 4.1875 | 4 | blocks = int(input("Enter the number of blocks: "))
height = 0
rows = 1
while rows <= blocks:
height += 1
# is the height +1
blocks -= rows
#blocks - rows
if blocks <= rows:
break
# while the rows are less than the blocks keep going.
# if the rows become greater than the blocks stop
rows += 1
print("The height of the pyramid:", height) | true |
e9bb62ab1fceeb98599946ef6a0c00650baa5d29 | ioannispol/Py_projects | /maths/main.py | 2,337 | 4.34375 | 4 | """
Ioannis Polymenis
Main script to calculate the Area of shapes
There are six different shapes:
- square
- rectangle
- triangle
- circle
- rhombus
- trapezoid
"""
import os
import class_area as ca
def main():
while True:
os.system('cls')
print("*" * 30)
print("Welcome to Area Calculator ")
print("Options:")
print("s = Square")
print("r = Rectangle")
print("tri = Triangle")
print("c = Circle")
print("rh = Rhombus")
print("trap = Trapezoid")
print("q = Quit")
print("*" * 30)
userInput = input("Enter the shape command: ")
if userInput == 's':
width = int(input("Enter the width of square: "))
height = int(input("Enter the height of the square: "))
square = ca.Area(width, height)
print("Square area: %d" % (square.square_area()))
elif userInput == 'r':
width = int(input("Enter the width of square: "))
height = int(input("Enter the height of the square: "))
rectangle = ca.Area(width, height)
print("Rectangle area: %d" % (square.rectangle_area()))
elif userInput == 'tri':
base = int(input("Enter base of the triangle: "))
tri_height = int(input("Enter height of the triangle: "))
tri = ca.Triangle(base, tri_height)
print("Triangle Area: %d" % (tri.area()))
elif userInput == 'c':
radius = int(input("Enter circle radius: "))
cir = ca.Circle(radius)
print("Circle area: %d" % cir.area())
elif userInput == 'rh':
width = int(input("Enter the width of rhombus: "))
height = int(input("Enter the height of the rhombus: "))
rh = ca.Rhombus(width, height)
print("Rhombus area: %d" % (rh.area()))
elif userInput == 'trap':
base = int(input("Enter the base of the trapezoid: "))
base2 = int(input("Enter the 2nd base of the trapezoid: "))
height = int(input("Enter the height of the trapezoid: "))
trap = ca.Trapezoid(base, base2, height)
print("Trapezoid area: %d" % (trap.area()))
elif userInput == 'q':
break
if __name__ == '__main__':
main()
| true |
e467818f8fe5e8099aaa6fb3a9c10853ff92b00b | wiznikvibe/python_mk0 | /tip_calci.py | 610 | 4.25 | 4 | print("Welcome to Tip Calculator")
total_bill = input("What is the total bill?\nRs. ")
tip_percent = input("What percent tip would you like to give? 10, 12, 15?\n ")
per_head = input("How many people to split the bill?\n")
total_bill1 = float(total_bill)
(total_bill)
tip_percent1 = int(tip_percent)
per_head1 = int(per_head)
total_tip = total_bill1 * (tip_percent1/100)
total_amount = total_bill1 + total_tip
tip_pperson = total_tip / per_head1
each_person = total_amount / per_head1
each_person1 = round(each_person,3)
message = f"Each person has to pay: Rs.{each_person1} "
print(message)
| true |
0e4cf1b1837a858cfb92830fa38c93879980b80c | sifisom12/level-0-coding-challenges | /level_0_coding_task05.py | 447 | 4.34375 | 4 | import math
def area_of_a_triangle (side1, side2, side3):
"""
Calculating the area of a triangle using the semiperimeter method
"""
semiperimeter = 1/2 * (side1 + side2 + side3)
area = math.sqrt(semiperimeter* ((semiperimeter - side1) * (semiperimeter - side2) * (semiperimeter - side3)))
return area
area = area_of_a_triangle (7, 9, 11)
print("Area is equal to " + "{:.2f}".format(area) + " square units")
| true |
110ca5d0377417a8046664b114cfd28140827ed4 | christinalycoris/Python | /arithmetic_loop.py | 1,741 | 4.34375 | 4 | import math
print ("This program will compute addition, subtraction,\n"
"multiplication, or division. The user will\n"
"provide two inputs. The inputs could be any real\n"
"numbers. This program will not compute complex\n"
"numbers. The program will run until the user\n"
"chooses to terminate the program. The user can\n"
"do this by selecting the appropriate option when\n"
"prompted to do so.\n\n")
ans = input("Do you want to continue? Y/N ")
while ans == 'Y' or ans == 'y' or ans == 'Yes' or ans == 'yes' or ans == 'YES':
print ("\nSelect one operation: ")
print ("\t1. Addition ")
print ("\t2. Subtraction (A from B) ")
print ("\t3. Subtraction (B from A) ")
print ("\t4. Multiplication ")
print ("\t5. Division (A into B) ")
print ("\t6. Division (B into A) ")
print ("\t7. EXIT ")
sel = int(input("Your selection is: "))
while sel < 1 or sel > 6:
if sel == 7:
print ("Okay. Goodbye. \n")
exit()
else:
print ("Invalid.\n")
sel = int(input("Your selection is: "))
print ("\n")
x = float(input("Input a (all real numbers): "))
y = float(input("Input b (all real numbers): "))
print ("\n")
if sel == 1:
print ("1. Addition \n\t",x,"+",y,"=",x+y)
elif sel == 2:
print ("2. Subtraction (A from B) \n\t",y,"-",x,"=",y-x)
elif sel == 3:
print ("3. Subtraction (B from A) \n\t",x,"-",y,"=",x-y)
elif sel == 4:
print ("4. Multiplication \n\t",x,"×",y,"=",x*y)
elif sel == 5:
print ("5. Division (A into B) \n\t",y,"÷",x,"=",y/x)
elif sel == 6:
print ("6. Division (B into A) \n\t",x,"÷",y,"=",x/y)
else:
print ("Hmm. I don't seem to know that one.\n")
if ans == 'N' or ans == 'n' or ans == 'No' or ans == 'no' or ans == 'NO':
print ("\nOkay. Goodbye. \n")
exit()
| true |
224d9fa0622c1b7509f205fa3579a4b42a8a73a6 | MurasatoNaoya/Python-Fundamentals- | /Python Object and Data Structure Basics/Print Formatting.py | 1,397 | 4.59375 | 5 | # Print Formatting ( String Interpolation ) -
# .format method -
print('This is a string {}'.format('okay.')) # The curly braces are placeholders for the variables that you want to input.
# Unless specified otherwise, the string will be formatted in the order you put them in your .format function.
print('This is a {}, not a {}; or a {}'.format('string', 'dictionary', 'tuple'))
#A solution to this, is using indexing.
print(" The world is {2}, {0} and {1}".format("lean", "mean.", "cruel")) # The variable(s) that you input, can also be in a list too.
#The assigning of objects to letters is also possible.
print('The {f} {b} {q}'.format(f='fox', b='brown', q='quick')) # Using letters is easier than index position, just do to it being hard to count the spaces.
# Float Formatting -
result = 100/777
print('The result was {r}'.format(r = result))
# Value:Width:Precision. (Mainly dealing with 'Precision'), as the width value only adds white space.
print('The result was {r:1.3}'.format(r = result)) # Variable inserted to three decimal places, with a width of one.
#fstrings method, alternative to the .format method.
name = 'Andrew'
age = 18
weight = 100.5
print(f'Hello my name is {name}') # This works with multiple variables (strings, integers, floats.)
print(f'{name} is {age} years old; and can deadlift {weight} kilograms') | true |
f62dd5c65eb6c397c7aa0d0557192b8a53768591 | lxmambo/caleb-curry-python | /60-sets.py | 557 | 4.15625 | 4 | items = {"sword","rubber duck", "slice of pizza"}
#a set cannot have duplicates
items.add("sword")
print(items)
#what we want to put in the set must be hashable, lists are not
conjunctions = {"for","and","nor","but","or","yet","so"}
seen = set()
copletely_original_poem = """yet more two more times
i feel nor but or but or, so get me for and 2 or and
times yet to know but i know you nor i get more for but
"""
data = copletely_original_poem.split()
for word in data:
if str.lower(word) in conjunctions:
seen.add(str.lower(word))
print(seen) | true |
390e46a938f9b7f819a9e59f517a9de9848b387e | lxmambo/caleb-curry-python | /25-reverse-list-w-slice.py | 308 | 4.15625 | 4 | data = ["a","b","c","d","e","f","g","h"]
#prints every 2 items
print(data[::2])
#prints reversed
print(data[::-1])
data_reversed = data
data[:] = data[::-1]
print(data)
print(id(data))
print(id(data_reversed))
#doint the slice like this changes only the content of the list
#but doesn't change de list... | true |
02d504e4b5a9658e643c3d10a5dc13b7a2e427f5 | yennanliu/CS_basics | /leetcode_python/Hash_table/group-shifted-strings.py | 2,917 | 4.21875 | 4 | """
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Return:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
Note: For the return value, each inner list's elements must follow the lexicographic order.
"""
# V0
# V1
# https://www.jiuzhang.com/solution/group-shifted-strings/#tag-highlight-lang-python
class Solution:
"""
@param strings: a string array
@return: return a list of string array
"""
def groupStrings(self, strings):
# write your code here
ans, mp = [], {}
for str in strings:
x = ord(str[0]) - ord('a')
tmp = ""
for c in str:
c = chr(ord(c) - x)
if(c < 'a'):
c = chr(ord(c) + 26)
tmp += c
if(mp.get(tmp) == None):
mp[tmp] = []
mp[tmp].append(str)
for x in mp:
ans.append(mp[x])
return ans
# V1'
# http://www.voidcn.com/article/p-znzuctot-qp.html
class Solution(object):
def groupStrings(self, strings):
"""
:type strings: List[str]
:rtype: List[List[str]]
"""
dic = {}
for s in strings:
hash = self.shiftHash(s)
if hash not in dic:
dic[hash] = [s]
else:
self.insertStr(dic[hash], s)
return dic.values()
def shiftHash(self, astring):
hashlist = [(ord(i) - ord(astring[0])) % 26 for i in astring]
return tuple(hashlist)
def insertStr(self, alist, astring):
i = 0
while i < len(alist) and ord(astring[0]) > ord(alist[i][0]):
i += 1
if i == len(alist):
alist.append(astring)
else:
alist[:] = alist[0:i] + [astring] + alist[i:]
# V2
# Time: O(nlogn)
# Space: O(n)
import collections
class Solution(object):
# @param {string[]} strings
# @return {string[][]}
def groupStrings(self, strings):
groups = collections.defaultdict(list)
for s in strings: # Grouping.
groups[self.hashStr(s)].append(s)
result = []
for key, val in groups.iteritems():
result.append(sorted(val))
return result
def hashStr(self, s):
base = ord(s[0])
hashcode = ""
for i in range(len(s)):
if ord(s[i]) - base >= 0:
hashcode += unichr(ord('a') + ord(s[i]) - base)
else:
hashcode += unichr(ord('a') + ord(s[i]) - base + 26)
return hashcode
| true |
4e2a77b9611c8885a882a290dc99070f53655c49 | yennanliu/CS_basics | /leetcode_python/Dynamic_Programming/best-time-to-buy-and-sell-stock-iii.py | 2,900 | 4.15625 | 4 | """
123. Best Time to Buy and Sell Stock III
Hard
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 105
"""
# V0
# V1
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/solution/
# IDEA : Bidirectional Dynamic Programming
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) <= 1:
return 0
left_min = prices[0]
right_max = prices[-1]
length = len(prices)
left_profits = [0] * length
# pad the right DP array with an additional zero for convenience.
right_profits = [0] * (length + 1)
# construct the bidirectional DP array
for l in range(1, length):
left_profits[l] = max(left_profits[l-1], prices[l] - left_min)
left_min = min(left_min, prices[l])
r = length - 1 - l
right_profits[r] = max(right_profits[r+1], right_max - prices[r])
right_max = max(right_max, prices[r])
max_profit = 0
for i in range(0, length):
max_profit = max(max_profit, left_profits[i] + right_profits[i+1])
return max_profit
# V1'
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/solution/
# IDEA : One-pass Simulation
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
t1_cost, t2_cost = float('inf'), float('inf')
t1_profit, t2_profit = 0, 0
for price in prices:
# the maximum profit if only one transaction is allowed
t1_cost = min(t1_cost, price)
t1_profit = max(t1_profit, price - t1_cost)
# reinvest the gained profit in the second transaction
t2_cost = min(t2_cost, price - t1_profit)
t2_profit = max(t2_profit, price - t2_cost)
return t2_profit
# V2 | true |
e21178720f6c4a17fd9efa5a90062082a6c94655 | Guimez/SecsConverter | /SecondsConverter.py | 1,067 | 4.46875 | 4 | print()
print("===============================================================================")
print("This program converts a value in seconds to days, hours, minutes and seconds.")
print("===============================================================================")
print()
Input = int(input("Please, enter a value that you want to convert, in seconds: "))
### Explains what the program do, then, asks and stores the value given by the user.
Days = Input // 86400 # How many integer days there is.
Hours = (Input % 86400) // 3600 # The rest of the above division divided by 3600 (correspondent value of 1 hour in seconds).
Minutes = ((Input % 86400) % 3600) // 60 # The rest of the above division divided by 60 (correspondent value of 1 minute in seconds).
Seconds = (((Input % 86400) % 3600) % 60) # The rest of the above division.
### Calculates the values.
print("*****************************************************************************")
print(Days, "days,", Hours, "hours,", Minutes, "minutes and", Seconds, "seconds.")
## Shows the results.
| true |
b18737a279e3b4511d708ae94bd53bc59a2be024 | datastarteu/python-edh | /Lecture 1/Lecture.py | 2,367 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 18:00:20 2017
@author: Pablo Maldonado
"""
# The "compulsory" Hello world program
print("Hello World")
###########################
### Data types
###########################
## What kind of stuff can we work with?
# First tipe: Boolean
x = True
y = 100 < 10
y
x*y
x+y
# Numeric data (integers and floats)
a = 1
b = 2
a+b
a*b
a/b
c, d = 2.5, 10.0
c
d
# Complex numbers
z = complex(1,2)
z
# Strings
x = "I am a string"
y = "... and I am a string too"
# Tells us the type of the object
type(x)
x+y
x*2
'test '*2
"test "*2
###########################
### Containers
###########################
# These are objects that contain other objects.
# List
x = [1,'a',2.0]
x
x[0]
x[2]
x[-1]
x[-2]
x[0] = 'pablo'
x # The new list is now modified
# Tuple
y = (1,'a',2.0)
y
type(y)
y[0]
y[0] = 'something' # Error! You can not overwrite tuples
# Unpacking: Storing the information of an object in different parts
names = ('Juan', 'Pablo','Maldonado')
first_name, second_name, last_name = names
first_name
# Parse a string into a list
single_line = 'pablo,maldonado,zizkov'
my_data = single_line.split(',')
my_data
# put it again together
new_single_line = ','.join(my_data)
new_single_line
# Dictionaries
d = {'name':'Pablo', 'last_name':'M'}
type(d)
d['name']
d['last_name']
d['address']
###########################
### Loops and list comprehension
###########################
x_vals = [1,2,3,4,5]
for x in x_vals:
print(x*x)
# Sum of squares
x_vals
total = 0
for x in x_vals:
total = total + x*x
total
# The Python way: Using list comprehension!
sum([x*x for x in x_vals])
# List comprehension is a very useful way of doing loops "faster"
[x*x for x in x_vals]
# Ranges of numbers:
my_vals = range(1,20)
# Run the following. What does it print?
for i in my_vals:
print(i)
my_vals
# Calculating squares in two different ways
sum([x*x for x in my_vals])
sum([x**2 for x in my_vals])
# Example: Calculate the distance between two vectors
####
from math import sqrt
x = [3,0]
y = [0,4]
dist = 0
for i in range(len(x)):
dist += (x[i]-y[i])**2
dist = sqrt(dist)
dist
# How can we re-write this?
def my_dist(x,y):
dist2 = sum([(x[i]-y[i])**2 for i in range(len(x))])
dist = sqrt(dist2)
return dist
| true |
e2bb2d975de5ede39c8393da03e9ad7f48a19b7f | TenzinJam/pythonPractice | /freeCodeCamp1/try_except.py | 1,080 | 4.5 | 4 | #try-except block
# it's pretty similar to try catch in javascript
# this can also help with some mathematical operations that's not valid. such as 10/3. It will go through the except code and print invalid input. The input was valid because it was a number, but mathematically it was not possible to compute that number. Except will catch that as well.
# we can except specific kind of error in this try except block. In the example below we are using built in keywords such as ZeroDivisionError and ValueError. Depending on what kind of error it is, it will display the message accordingly.
# you can also name the error and print that error, like we did in the case of ZeroDivisionError, where we named it as "err" and then print it out. This err message returned in "integer division or modulo by zero" as specified by python, and not by the developer.
# therefore, it is not a good practice to do an umbrella except.
try:
number = int(input("Enter a number:" ))
print(number)
except ZeroDivisionError as err:
print(err)
except ValueError:
print("Invalid input")
| true |
c1c368937073a6f68e60d72a72d5c5f36f0243c1 | kristinnk18/NEW | /Project_1/Project_1_uppkast_1.py | 1,481 | 4.25 | 4 |
balance = input("Input the cost of the item in $: ")
balance = float(balance)
x = 2500
monthly_payment_rate = input("Input the monthly payment in $: ")
monthly_payment_rate = float(monthly_payment_rate)
monthly_payment = monthly_payment_rate
while balance < x:
if balance <= 1000:
for month in range(1, 13):
monthly_interest_rate = 0.015
monthly_payment = monthly_payment_rate
interest_paid = balance * monthly_interest_rate
balance = (balance - monthly_payment) + (balance * monthly_interest_rate)
if balance <= 50:
monthly_interest_rate = 0.015
monthly_payment = balance
interest_paid = balance * monthly_interest_rate
balance = (balance - monthly_payment)
print("Month: ", month, "Payment: ", round(monthly_payment, 2), "Interest paid: ", round(interest_paid,2), "Remaining debt: ", round(balance,2))
break
else:
for month in range(1, 13):
monthly_interest_rate = 0.02
monthly_payment = monthly_payment_rate
interest_paid = balance * monthly_interest_rate
balance = (balance - monthly_payment) + (balance * monthly_interest_rate)
print("Month: ", month, "payment: ", round(monthly_payment, 2), "Interest paid: ", round(interest_paid,2), "Remaining balance: ", round(balance,2))
break
| true |
06119d936bbe22687f7b163aee7cda895eae7957 | kristinnk18/NEW | /Skipanir/whileLoops/Timi_3_2.py | 327 | 4.1875 | 4 | #Write a program using a while statement, that given the number n as input, prints the first n odd numbers starting from 1.
#For example if the input is
#4
#The output will be:
#1
#3
#5
#7
num = int(input("Input an int: "))
count = 0
odd_number = 1
while count < num:
print(odd_number)
odd_number += 2
count += 1 | true |
5bb9558126505e69beda2cfb5e076e33a7cffa48 | kristinnk18/NEW | /Skipanir/whileLoops/Timi_3_6.py | 426 | 4.125 | 4 | #Write a program using a while statement, that prints out the two-digit number such that when you square it,
# the resulting three-digit number has its rightmost two digits the same as the original two-digit number.
# That is, for a number in the form AB:
# AB * AB = CAB, for some C.
count = 10
while count <= 100:
total = count * count
if total % 100 == count:
print(count)
break
count +=1 | true |
8d51a0547e26c0a4944ff04866cc37fd83c2ad35 | kristinnk18/NEW | /Skipanir/Lists/pascalsTriangle.py | 444 | 4.1875 | 4 | def make_new_row(x):
new_list = []
if x == []:
return [1]
elif x == [1]:
return [1,1]
new_list.append(1)
for i in range(len(x)-1):
new_list.append(x[i]+x[i+1])
new_list.append(1)
return new_list
# Main program starts here - DO NOT CHANGE
height = int(input("Height of Pascal's triangle (n>=1): "))
new_row = []
for i in range(height):
new_row = make_new_row(new_row)
print(new_row)
| true |
26f7474ef39d8d92a78e605b92bdb46e73b77e45 | Bioluwatifemi/Assignment | /assignment.py | 345 | 4.15625 | 4 | my_dict = {}
length = int(input('Enter a number: '))
for num in range(1, length+1):
my_dict.update({num:num*num})
print(my_dict)
numbers = {2:4, 3:9, 4:16}
numbers2 = {}
your_num = int(input('Enter a number: '))
for key,value in numbers.items():
numbers2.update({key*your_num:value*your_num})
print (numbers2) | true |
7028471a2d611b32767fb9d62a2acaab98edb281 | free4hny/network_security | /encryption.py | 2,243 | 4.5625 | 5 | #Key Generation
print("Please enter the Caesar Cipher key that you would like to use. Please enter a number between 1 and 25 (both inclusive).")
key = int(input())
while key < 1 or key > 25:
print(" Unfortunately, you have entered an invalid key. Please enter a number between 1 and 25 (both inclusive) only.")
key = int(input())
print(" Thanks for selecting the Caesar Cipher key. The Key selected by you is " + str(key))
#The plain text message
#Allow the user to enter the plaintext message through the console
plain_text = str(input("Please enter the plain text message that you would like the Caesar Cipher Encryption Algorithm to encrypt for you."))
cipher_text = ""
print(" Thanks for entering the plain text message. You have entered the following plain text message.")
print(" " + plain_text)
#The Caesar Cipher Encryption algorithm
for letter in plain_text:
if letter.isalpha():
val = ord(letter)
val = val + key
if letter.isupper():
if val > ord('Z'):
val -= 26
elif val < ord('A'):
val += 26
elif letter.islower():
if val > ord('z'):
val -= 26
elif val < ord('a'):
val += 26
new_letter = chr(val)
cipher_text += new_letter
else:
cipher_text += letter
print(" Cipher Text -----> " + cipher_text)
######################################################
# #The Caesar Cipher Decryption algorithm
# key1 = key
# key1 = -key1
# plain_text = ""
# print(" Cipher Text -----> " + cipher_text)
# for letter in cipher_text:
# if letter.isalpha():
# val = ord(letter)
# val = val + key1
# if letter.isupper():
# if val > ord('Z'):
# val -= 26
# elif val < ord('A'):
# val += 26
# elif letter.islower():
# if val > ord('z'):
# val -= 26
# elif val < ord('a'):
# val += 26
# new_letter = chr(val)
# plain_text += new_letter
# else:
# plain_text += letter
# print(" Plain Text -----> " + plain_text) | true |
aacace9f445f6f26d1f1e12c1e38802cb4d58c69 | Kiara-Marie/ProjectEuler | /4 (palindrome 3digit product).py | 706 | 4.34375 | 4 | def isPalindrome(x):
"Produces true if the given number is a palindrome"
sx = str(x) # a string version of the given number
lx = len(sx) # the number of digits in the given number
n = lx - 1
m = 0
while 5 == 5:
if sx[m] != sx[n] :
return (False)
break
elif m >= n:
return (True)
break
else:
n -= 1
m += 1
#Program to find biggest palindrome made by multiplying 2 3-digit numbers
n = 100
m = 100
rsf = -1
x = -1
for n in range(999):
for m in range(999):
if (m * n) > x and isPalindrome(m * n):
rsf += 1
x = m * n
print(rsf,x)
| true |
a09f7b9417baef1b2635f3ba4245b503f493f14d | AaqibAhamed/Python-from-Begining | /ifpyth.py | 419 | 4.25 | 4 | responds= input('Do You Like Python ?(yes/no):')
if responds == "yes" or responds == "YES" or responds == "Yes" or responds== "Y" or responds== "y" :
print("you are on the right course")
elif responds == "no" or responds == "NO" or responds == "No" or responds == "N" or responds == "n" :
print(" you might change your mind ")
else :
print(" I did not understand ")
| true |
8dd72e83e364d450cafab02d2d099a4c3190d5ae | Maker-Mark/python_demo | /example.py | 831 | 4.15625 | 4 |
grocery_list = ["Juice", "Apples", "Potatoes"]
f = 1
for i in grocery_list:
print( "Dont forget to buy " + i + '!')
##Demo on how to look though characters in a string
for x in "diapers":
print(x)
#Conditional loop with a if statment
desktop_app_list = ["OBS", "VMware", "Atom", "QR Generator", "Potatoe AI"]
for x in desktop_app_list:
print(x)
if x == "Atom":
print("Ladies and Gents, we got it! \nThe rest of your desktop apps are:")
## function demo
def my_function():
print("This text is coming from a function")
#To call the fucntion just call the funchion with the parameters
my_function()
# fucntion with parameters Demo
def function_with_params(name):
print("Hello, my name is " + name + " and I am a fucntion")
#Calling paramatized function
function_with_params("Bob")
| true |
ffc172de327a528fe0b4b6266080d16d0012f23c | sentientbyproxy/Python | /JSON_Data.py | 638 | 4.21875 | 4 | # A program to parse JSON data, written in Python 2.7.12.
import urllib
import json
# Prompt for a URL.
# The URL to be used is: http://python-data.dr-chuck.net/comments_312354.json
url = raw_input("Please enter the url: ")
print "Retrieving", url
# Read the JSON data from the URL using urllib.
uh = urllib.urlopen(url)
data = uh.read()
# Parse and extract the comment counts from the JSON data.
js = json.loads(str(data))
# Set starting point of sum.
sum = 0
comments = js["comments"]
# Compute the sum of the numbers in the file.
for item in js["comments"]:
sum += item["count"]
# Enter the sum below:
print "Sum: ", sum
| true |
cc12ace41f10bfc03fd6fda0bfa7d3d95694768c | Ontefetse-Ditsele/Intro_python | /week_3/cupcake.py | 1,744 | 4.125 | 4 | #Ontefetse Ditsele
#
#19 May 2020
print("Welcome to the 30 second expect rule game--------------------")
print("Answer the following questions by selection from among the options")
ans = input("Did anyone see you(yes/no)\n")
if ans == "yes":
ans = input("Was it a boss/lover/parent?(yes/no)\n")
if ans == "no":
print("Eat It")
else:
ans = input("Was it expensive(yes/no)\n")
if ans == "yes":
ans = input("Can you cut of the part that touched the floor?(yes/no): \n")
if ans == "yes":
print("Eat it")
else:
print("Your call")
else:
ans = input("is it chocolate?(yes/no)\n")
if ans == "yes":
print("Eat it")
else:
print("Don't eat it")
else:
ans = input("Was it sticky?(yes/no)\n")
if ans == "yes":
ans = input("Is it a raw steak?(yes/no)\n")
if ans == "yes":
ans = input("Are you a puma?(yes/no)\n")
if ans == "yes":
print("Eat it")
else:
print("Don't eat it")
else:
ans = input("Did the cat lick it?(yes/no)\n")
if ans == "no":
print("Eat it")
else:
ans = input("Is it a healthy cat?(yes/no)\n")
if ans == "yes":
print("Eat it")
else:
print("Your call")
else:
ans = input("Is it an emausaurus(yes/no)\n")
if ans == "yes":
ans = input("Are you a megalosaurus(yes/no)\n")
if ans == "yes":
print("Eat it")
else:
print("Don't eat it")
else:
ans = input("Did the cat lick it?(yes/no)\n")
if ans == "no":
print("Eat it")
else:
ans = input("Is your cat healthy?(yes/no)\n")
if ans == "yes":
print("Eat it")
else:
print("Your call")
| true |
d09b3c2711d9df4ea00c917aabfe2c0f191055ee | Ontefetse-Ditsele/Intro_python | /week_3/pi.py | 356 | 4.28125 | 4 | #Ontefetse Ditsele
#
#21 May 2020
from math import sqrt
denominator = sqrt(2)
next_term = 2/denominator
pi = 2 * 2/denominator
while next_term > 1:
denominator = sqrt(2 + denominator)
next_term = 2/denominator
pi *= next_term
print("Approximation of PI is",round(pi,3))
radius = float(input("Enter the radius:\n"))
print("Area:",round(pi * (radius**2),3))
| true |
a61ad782abbf9a3c0f2b76a561c1c190474264e0 | rohini-nubolab/Python-Learning | /dictionary.py | 551 | 4.28125 | 4 | # Create a new dictionary
d = dict() # or d = {}
# Add a key - value pairs to dictionary
d['xyz'] = 123
d['abc'] = 345
# print the whole dictionary
print d
# print only the keys
print d.keys()
# print only values
print d.values()
# iterate over dictionary
for i in d :
print "%s %d" %(i, d[i])
# another method of iteration
for index, key in enumerate(d):
print index, key, d[key]
# check if key exist
print 'xyz' in d
# delete the key-value pair
del d['xyz']
# check again
print "xyz" in d
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.