blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
eba680e70f99c565a0b95c2d230061034bf24291 | tdominic1186/Python_Crash_Course | /Ch_3_Lists/seeing_the_world_3-5.py | 833 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 8 20:56:36 2018
@author: Tony_MBP
"""
places = ['new zealand', 'canada', 'uk', 'australia', 'japan']
print(places)
#use sorted to to print list alphabetically w/o modifying list
print(sorted(places))
#show list is still in same original order
print(places)
#use sorted to print list in reverse alpha w/o modifying list
print(sorted(places, reverse = True))
#show list is still in same order
print(places)
#use reverse to to change order of list and print
places.reverse()
print(places)
#use reverse to change order back
places.reverse()
print(places)
#use sort to change list to alpha and print to show changed order
places.sort()
print(places)
#use sort to change list to reverse alpha and print to show changed order
places.sort(reverse = True)
print(places) | true |
7e9f1fe1a143bd90aea5e8478c703ec8bc980a59 | tdominic1186/Python_Crash_Course | /Ch_9_Classes/number_served.py | 2,193 | 4.5 | 4 | '''
Start with your program from Exercise 9-1 (page 166).
Add an attribute called number_served with a default value of 0. x
Create an instance called restaurant from this class. x
Print the number of customers the restaurant has served, and then change this value and print it again. x
Add a method called set_number_served() that lets you set the number of customers that have been served. Call this method with a new number and print the value again. x
Add a method called increment_number_served() that lets you increment
the number of customers who’ve been served. Call this method with any number you like that could represent how many customers were served in, say, a day of business. x
p171
'''
class Restaurant():
"""A simple model for a restaurant"""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize name and cuisine type attributes"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""Describes the restaurant's name and cuisine type."""
print("\nThe restaurant's name is " + self.restaurant_name.title() + " and the cuisine type is " + self.cuisine_type.title() + ".")
def open_restaurant(self):
"""Inidcates if the restaurant is open."""
print(self.restaurant_name.title() + " is open!")
def set_number_served(self, customer_number):
"""Set number of customers that have been served."""
self.number_served = customer_number
def increment_number_served(self, additional_customers):
"""Add the given amount of customers to the Number Served"""
self.number_served += additional_customers
restaurant = Restaurant("the cheesesteak house", "american")
restaurant.describe_restaurant()
restaurant.open_restaurant()
print("\nNumber Served: " + str(restaurant.number_served))
restaurant.number_served = 25
print("\nNumber Served: " + str(restaurant.number_served))
restaurant.set_number_served(30)
print("\nNumber Served: " + str(restaurant.number_served))
restaurant.increment_number_served(55)
print("\nNumber Served: " + str(restaurant.number_served))
| true |
fe45487f19bd0c0e402cd04b572741b9087d54ab | tdominic1186/Python_Crash_Course | /Ch_9_Classes/login_attempts.py | 2,013 | 4.125 | 4 | """
9-5. Login Attempts:
Add an attribute called login_attempts to your User class from Exercise 9-3 (page 166). x
Write a method called increment_login_attempts() that increments the value of login_attempts by 1. x
Write another method called reset_login_attempts() that resets the value of login_attempts to 0.x
Make an instance of the User class and call increment_login_attempts()
several times. x
Print the value of login_attempts to make sure it was incremented properly, and then call reset_login_attempts(). x
Print login_attempts again to make sure it was reset to 0.x
p171
"""
class User():
def __init__(self, first_name, last_name, age, favorite_color, favorite_band):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.favorite_color = favorite_color
self.favorite_band = favorite_band
self.login_attempts = 0
def describe_user(self):
"""Describes user's attributes."""
print(self.first_name.title() + " " + self.last_name.title() + "'s age is " + str(self.age) + ". Their favorite color is " + self.favorite_color + " and their favorite band is " + self.favorite_band.title() + ".")
def greet_user(self):
"""Greets user by formatted first and last name."""
print("Hello, " + self.first_name.title() + " " + self.last_name.title() + "!")
def increment_login_attempts(self):
"""Increments login_attempts from the user by 1"""
self.login_attempts += 1
def reset_login_attempts(self):
"""Resets the value of login_attempts to 0."""
self.login_attempts = 0
jc = User("jessica", "colliver", 29, "purple", "nsync")
jc.increment_login_attempts()
jc.increment_login_attempts()
jc.increment_login_attempts()
jc.increment_login_attempts()
print("\nThe number of times user has attempted to log in: " + str(jc.login_attempts))
jc.reset_login_attempts()
print("\nThe number of times user has attempted to log in: " + str(jc.login_attempts)) | true |
153b1a2153121b5d00b452484b9f88d344b73ed6 | tdominic1186/Python_Crash_Course | /Ch_8_Functions/unchanged_magicians_8-11.py | 1,514 | 4.53125 | 5 | """
5/21/18
8-11. Unchanged Magicians: Start with your work from Exercise 8-10. Call the
function make_great() with a copy of the list of magicians’ names. Because the
original list will be unchanged, return the new list and store it in a separate list.
Call show_magicians() with each list to show that you have one list of the original
names and one list with 'the Great' added to each magician’s name.
p150
"""
def show_magicians(magician_names):
"""
Prints the formatted names of a list of magicians
"""
while magician_names:
for magician_name in magician_names:
magician_name = magician_names.pop()
print(magician_name.title())
def copy_list(magician_names):
"""
Makes a copy of list 'magician_names'
"""
clone = magician_names[:]
return clone
def make_great(magician_names):
"""
Creates a new list to hold each magician that has been made 'great'
Appends 'the Great' to each magician's name
Returns the modified names to the 'magician_names' list
"""
# great_names = []
while magician_names:
name = magician_names.pop()
great_name = name + ' the Great'
great_names.append(great_name)
# for great_name in great_names:
# magician_names.append(great_name)
# return magician_names
magician_names = ['houdini', 'david copperfield', 'david blaine']
great_names = copy_list(magician_names)
#make_great(great_names)
print(magician_names)
print(great_names)
| true |
d7d65a0c5695274842767e20e5a337db4640d113 | tdominic1186/Python_Crash_Course | /Ch_5_if_Statements/stages_of_life_5-6.py | 522 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 18 11:58:03 2018
5-6 Stages of life - Write an if-elif-else chain that determines a person's
stage of life.
@author: Tony_MBP
"""
age = 65
if age < 2:
print("You're a baby.")
elif age >= 2 and age < 4:
print("You're a toddler.")
elif age >= 4 and age < 13:
print("You're a kid.")
elif age >= 13 and age < 20:
print("You're a teenager.")
elif age >= 20 and age < 65:
print("You're an adult.")
else:
print("You're an elder.")
| true |
cbc38a58be400e83c18324be9acba86971729545 | vladn90/Data_Structures | /heaps/heap_sort_naive.py | 797 | 4.15625 | 4 | """ Naive implementation of heap sort algorithm using Min Heap data structure.
"""
import random
from min_heap_class import MinHeap
def heap_sort_naive(array):
""" Sorts an array in non-descending order using heap. Doesn't return anything.
Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(array).
"""
heap = MinHeap()
for element in array: # put all array elements into heap
heap.insert(element)
for i in range(len(array)): # extract min element from the heap, update array
array[i] = heap.pop_min()
if __name__ == "__main__":
array = [random.randrange(-10, 10) for i in range(10)]
print(f"original array: {array}")
heap_sort_naive(array)
assert array == sorted(array) # self-check
print(f"sorted array: {array}")
| true |
7c1249777a1cdf09f1da6fb492cc70e85d092ac0 | AnjanaPradeepcs/guessmyno-game | /guessmyno.py | 541 | 4.28125 | 4 | import random
number=random.randrange(1,10)
guess=int(input("guess a number between 1 and 10))
while guess!= number:
if guess>number:
print("guess a lesser number.Try again")
guess=int(input("guess a number between 1 and 10))
else:
print("guess a higher number.Try again")
guess=int(input("guess a number between 1 and 10))
print("your guess is correct and You won the game") | true |
8aee1e37b8d65fb372d200a9fd173abc719d6443 | gloriasalas/GWC-Summer-Immersion-Program | /TextAdventure.py | 1,549 | 4.1875 | 4 | start = '''You wake up one morning and find yourself in a big crisis.
Trouble has arised and your worst fears have come true. Zoom is out to destroy
the world for good. However, a castrophe has happened and now the love of
your life is in danger. Which do you decide to save today?'''
print(start)
done = False
print(" Type 'Flash to save the world' or 'Flash to save the love of his life' ")
user_input = input()
while not done:
if user_input == "world":
print (" Flash has to fight zoom to save the world. ")
done = True
print("Should Flash use lightening to attack Zoom or read his mind?")
user_input = input()
if user_input == "lightening":
print("Flash defeats Zoom and saves the world!")
done = True
elif user_input == "mind":
print("Flash might be able to defeat Zoom, but is still a disadvantage. ")
done = True
print("Flash is able to save the world.")
elif user_input == "love":
print ("In order to save the love of his life, Flash has to choose between two options. ")
done = True
print("Should Flash give up his power or his life in order to save the love of his life?")
user_input = input()
if user_input == "power":
print("The Flash's speed is gone. But he is given the love of his life back into his hands. ")
done = True
elif user_input == "life":
print("The Flash will die, but he sees that the love of his life is no longer in danger.")
done = True
print("No matter the circumstances, Flash is still alive. ") | true |
58578e34604e68fc5b8fd9315959316a62a94c21 | lward27/Python_Programs | /echo.py | 240 | 4.125 | 4 | #prec: someString is a string
#times is a integer
#postc:
#prints someString times times to the screen
#if times <=0, nothing prints.
def repeat(someString, times):
if times <= 0:
return
print someString
repeat(someString, times - 1)
| true |
f6c9d0c94a80bbaa9db1e9bedc041baf70c2f6fd | jjulch/cti110 | /P4HW3_NestedLoops_JeremyJulch.py | 356 | 4.3125 | 4 | # Making Nested Loops
# 10-17-2019
# CTI-110 PH4HW3-Nested Loops
# Jeremy Julch
#
# Making the first loop
for row in range(6):
print('#', end='', sep='')
# Making the nested loop to create the spaces between the #
for spaces in range(row):
print( ' ', end='', sep='')
# Making the second #
print('#', sep='')
| true |
e37676e882c196756d7af562c25b8fcb53643f0b | cliffjsgit/chapter-10 | /exercise108.py | 795 | 4.15625 | 4 | #!/usr/bin/env python3
__author__ = "Your Name"
###############################################################################
#
# Exercise 10.8
#
#
# Grading Guidelines:
# - Variable "answer" should be the answer to question 1: If there are 23
# students in your class, what are the chances that two of you have the
# same birthday?.
#
# This exercise pertains to the so-called Birthday Paradox, which you can read
# about at http://en.wikipedia.org/wiki/Birthday_paradox .
#
# 1. If there are 23 students in your class, what are the chances that two of you
# have the same birthday? You can estimate this probability by generating random
# samples of 23 birthdays and checking for matches.
#
# Hint: you can generate random birthdays with the randint function in the
# random module.
#
| true |
b06a2e53ae982a0d013b38968b99d0406aaaffc0 | MrSameerKhan/Machine_Learning | /practice/reverse_list.py | 1,288 | 4.40625 | 4 |
def reverse_a_list():
my_list = [1,2,3,566,6,7,8]
original_list = my_list.copy()
list_length = 0
for i in my_list:
list_length += 1
for i in range(int(list_length/2)):
main_value = my_list[i]
mirror_value = my_list[list_length-i-1]
my_list[i] = mirror_value
my_list[list_length-i-1] = main_value
print(f"Before reversing {original_list} After revesring {my_list}")
def remove_multiple():
# Python program to remove multiple
# elements from a list
# creating a list
list1 = [11, 5, 17, 18, 23, 50]
# Iterate each element in list
# and add them in variale total
for ele in list1:
if ele % 2 == 0:
list1.remove(ele)
# printing modified list
print("New list after removing all even numbers: ", list1)
def count_occurence():
# Python code to count the number of occurrences
def countX(lst, x):
count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
# Driver Code
lst = [8, 6, 8, 10, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x, countX(lst, x)))
if __name__ == "__main__":
# reverse_a_list()
# remove_multiple()
count_occurence() | true |
2a18cc8fd70105eee7c47def0f4c4b8d1202fd04 | weiiiiweiiii/AP-statistic-graphs | /Sources-For-Reference/Programs/Poisson.py | 1,155 | 4.4375 | 4 | # -*- coding: utf-8 -*-
from scipy.stats import poisson
import numpy as np
import matplotlib.pyplot as plt
import mpld3
#print "Welcome!"
#print "This is a program that can help you plot graphs for poisson distributions"
#Using poisson.pmf to create a list
#rate = raw_input("Please enter the rate(rate should be an integer), rate = " )
#o = raw_input("Please enter the maximum number of incidents(o should be an integer), o = ")
rate = int(5)
o = int(500)
n = np.arange(0,o+1)
y = poisson.pmf(n, rate)
#Plotting the poisson distribution for users
plt.plot(n,y, 'o-')
plt.title('Poisson: rate=%i' %(rate), fontsize = 20)
plt.xlabel('Number of incidents', fontsize = 15)
plt.ylabel('Probability of happenning', fontsize = 15)
poisim = poisson.rvs(rate, loc = 0, size = 1000)
print ("Mean: %g" % np.mean(poisim))
print ("SD: %g" % np.std(poisim, ddof=1))
#plt.figure()
plt.hist(poisim,bins = 9, normed = True)
plt.xlim(0,10)
plt.xlabel("Number of incidents")
plt.ylabel("density")
plt.show()
#fig = plt.figure(1, figsize=(9, 6))
#fig.savefig('Poisson.png', bbox_inches='tight')
fig = plt.figure(1, figsize=(9, 6))
print(mpld3.fig_to_html(fig))
| true |
3118d09cf3963b943a81b04a96e9729cece878f6 | ProfessorJas/Learn_Numpy | /ndarray_shape.py | 302 | 4.46875 | 4 | import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
print()
# This resize the array
a = np.array([[1, 2, 3], [4, 5, 6]])
a.shape = (3, 2)
print(a)
print()
# Numpy also provides a reshape function to resize an array
a = np.array([[1, 2, 3], [4, 5, 6]])
b = a.reshape(3, 2)
print(b) | true |
4e3b1fbdfe12194e77d28b3dcebd47fae42e44c8 | dongheelee1/oop | /polymorphism.py | 592 | 4.4375 | 4 |
#Polymorphism:
#Example of Method Overriding
class Animal(object):
def __init__(self, name):
self.name = name
def talk(self):
pass
class Dog(Animal):
def talk(self):
print("Woof")
class Cat(Animal):
def talk(self):
print("Meow")
cat = Cat('KIT')
cat.talk()
dog = Dog('EDDY')
dog.talk()
#Example of method overloading
def add(typ, *args):
if typ == 'int':
result = 0
if typ == 'str':
result = ''
for i in args:
result += i
return result
add('int', 1, 2, 3)
add('str', 'i', 'love', 'python')
| true |
ad56dc7b368603b7d2592573ed26503dcce41e4b | moncefelmouden/python-project-ui-2018 | /dbDemo.py | 1,594 | 4.21875 | 4 | import sqlite3
import os.path
def initDatabase():
db=sqlite3.connect('dbDemo.db')
sql="create table travel(name text primary key,country text)"
db.execute(sql)
sql="insert into travel(name,country) values('Korea Ski-ing Winter Tour','Korea')"
db.execute(sql)
db.commit()
db.close()
def readData():
db=sqlite3.connect('dbDemo.db')
sql="select * from travel"
db.row_factory = sqlite3.Row
rows=db.execute(sql)
for data in rows:
print(data['name']+" -- "+data['country'])
db.close()
def insertData(name,country):
db=sqlite3.connect('dbDemo.db')
sql="insert into travel(name,country) values(?,?)"
db.execute(sql,(name,country))
db.commit()
db.close()
#Exercise...
def deleteData(name):
print("Delete...")
db=sqlite3.connect('dbDemo.db')
sql="delete from travel where name=?"
db.execute(sql,(name,))
db.commit()
db.close()
#create a database when it does not exist
if not os.path.exists("dbDemo.db"): #cannot find file dbDemo.db
initDatabase()
userInput=""
while userInput!="Q":
userInput=input("Enter R to display Data or I to insert Data or D to delete Data or Q to quit")
userInput = userInput.upper()
if userInput=="R":
readData()
elif userInput=="I":
name=input("Enter the name of travel package:")
country=input("Enter the Country:")
insertData(name,country)
elif userInput=="D":
name=input("Enter the name of tour package to Delete")
deleteData(name)
| true |
52008b5181e886e0656108dab34c19823d1caa07 | brandonbloch/cisc327 | /bCommands.py | 2,983 | 4.21875 | 4 |
def find_account(number, accounts):
"""
This function takes in a account number and the master accounts list
to check if the specified account number is in the master accounts list.
"""
for i in range(len(accounts)):
if accounts[i][0] == number:
return i+1
return 0
def withdraw(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
If the transaction is not valid the program will terminate
"""
num = find_account(transaction[2], accounts)
if not num:
raise RuntimeError
elif int(accounts[num-1][1]) - int(transaction[3]) < 0:
raise RuntimeError
else:
accounts[num-1][1] = str(int(accounts[num-1][1]) - int(transaction[3]))
return accounts
def deposit(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
"""
num = find_account(transaction[1], accounts)
if not num:
raise RuntimeError
else:
accounts[num-1][1] = str(int(accounts[num-1][1]) + int(transaction[3]))
return accounts
def transfer(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
"""
num1 = find_account(transaction[1], accounts)
num2 = find_account(transaction[2], accounts)
if not (num1 and num2):
raise RuntimeError
elif int(accounts[num2-1][1]) - int(transaction[3]) < 0:
raise RuntimeError
else:
accounts[num1-1][1] = str(int(accounts[num1-1][1]) + int(transaction[3]))
accounts[num2-1][1] = str(int(accounts[num2-1][1]) - int(transaction[3]))
return accounts
def create(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
"""
num = find_account(transaction[1], accounts)
if num:
raise RuntimeError
else:
transaction = [transaction[1], '000', transaction[4]]
accounts.append(transaction)
return accounts
def delete(transaction, accounts):
"""
This function takes in the merged transaction summary file and the master
accounts list and updates the master accounts list with the specified transaction.
"""
num = find_account(transaction[1], accounts)
if not num:
raise RuntimeError
elif int(accounts[num-1][1]) != 0:
raise RuntimeError
elif transaction[4] != accounts[num+1][2]:
raise RuntimeError
else:
accounts.remove([accounts[num-1][0], accounts[num-1][1], accounts[num+1][2]])
return accounts
| true |
77cee1eae648b4d90ce87bfd203332c8f49fd0c8 | Mb01/Code-Samples | /algorithms/sorting/heapsort.py | 1,886 | 4.25 | 4 | #!/usr/bin/env python
import random
LENGTH = 100
data = [random.randint(0,100) for _ in range(LENGTH)]
def heapsort(lst):
def swap(lst, a, b):
"""given a list, swap elements at 'a' and 'b'"""
temp = lst[a]
lst[a] = lst[b]
lst[b] = temp
def siftdown(lst, start, end):
"""move an element to proper position"""
root = start
while root * 2 + 1 <= end:
left_child = root * 2 + 1
cand = root
# is left_child a candidate for swapping?
if lst[cand] < lst[left_child]:
cand = left_child
# given that swap is max(left_child, root),
# is right_child a candidate for swapping?
if left_child + 1 <= end and lst[cand] < lst[left_child + 1]:
cand = left_child +1
# set root to value to be swapped (or do nothing if same)
if cand != root:
swap(lst, root, cand)
root = cand
else:
break
def heapify(lst):
"""call siftdown on non-leaf elements"""
size = len(lst)
# begin at rightmost non-leaf element
start = size/2 -1
# call siftdown and move left (start -= 1)
while start >= 0:
siftdown(lst, start, size - 1)
start -= 1
def heapsort(lst):
# create heap
heapify(lst)
last = len(lst) - 1
# while there is a heap under consideration
while last > 0:
# zeroeth element is largest, move to last position
swap(lst, last, 0)
# shrink heap
last = last - 1
# first element altered, move to proper position
siftdown(lst, 0, last)
heapsort(lst)
print "initial", data
heapsort(data)
print "sorted", data
| true |
1c676ba9bb43be453458060ce539fa12e31e645b | brianaguirre/CS3240 | /lab3/lab3_part1.py | 1,642 | 4.28125 | 4 | __author__ = 'BrianAguirre'
#USER CREATION
user_name = ""
password = ""
data = {}
print("This program takes in usernames and password.")
print("If at any point you wish to quit, enter an empty string.")
user_name = input("Please enter the first user name:")
password = input("Enter a password for " + user_name + ":")
condition = True
if (user_name == ""):
condition = False
elif (password == ""):
condition = False
while(condition):
data[user_name] = password
user_name = input("Please enter another username:")
password = input("Please enter another password for " + user_name + ":")
if (user_name == ""):
condition = False
elif (password == ""):
condition = False
#VERIFY USER LOGIN
print("")
print("Please login by enter a username and password.")
print("Enter an empty string to stop.")
check_user = input("Please enter the first user name:")
check_pass = input("Enter a password for " + check_user + ":")
condition2 = True
if (check_user == ""):
condition2 = False
elif (check_pass == ""):
condition2 = False
while(condition2):
if (check_user in data):
pass_on_file = data[check_user]
if (check_pass == pass_on_file):
print("Login success!")
else:
print("Login failed. Wrong Password.")
else:
print("Username not found.")
check_user = input("Please enter another username:")
check_pass = input("Please enter another password for " + check_user + ":")
if (check_user == ""):
condition2 = False
elif (check_pass == ""):
condition2 = False
if __name__ == "__main__":
pass | true |
58d8e5da962370d21564be1b4e891a64abfb26da | underwaterlongs/codestorage | /Project_Euler/P3_LargestPrimeFactor.py | 1,362 | 4.15625 | 4 | """
The prime factors of 13,195 are 5,7,13,29.
What is the largest prime factor of a given number ?
We can utilize Sieve of Eratosthenes to find the prime factors for N up to ~10mil or so efficiently.
General pseudocode for sieve:
initialize an array of Boolean values indexed by 2 to N, set to True
i = 2
for i to sqrt(n) do
if(arr[i]==True):
for j = i^2, i^2+i, i^2+2i.... to n do
a[j] = False
p^2: 2^2, 3^2, 4^2 -> for this p in 2 to sqroot(num), we mark this as the non prime factors by switching it to False. Thus remaining numbers in the range are prime and remain True
We can modify this concept to find factors instead.
"""
import math
import sys
def find_largest_prime_factor(num):
largest_prime_factor = 0
# check for divisibility by 2, if so -> divide till only 1 or some other non-2 factors are left
while(num%2 == 0):
num //= 2
largest_prime_factor=2
for i in range(3,int(math.sqrt(num)+1),2):
while (num%i==0):
num //= i
largest_prime_factor = int(i)
if(num>=2):
largest_prime_factor = int(num)
print(largest_prime_factor)
if __name__ == "__main__":
# number of testcases, t
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
find_largest_prime_factor(n) | true |
1044ae5fa1dcff182100ef9f352d2985e2ee924a | Roy-Chandan/Roy-world | /Range1.py | 685 | 4.15625 | 4 | def user_choice():
choice = 'Wrong'
accept_range = range(0,10)
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input ("Enter a number between 1-10: ")
if choice.isdigit() == False:
print ("Please enter a number not string")
if choice.isdigit() == True:
if int(choice) in accept_range:
within_range = True
else:
print ("Number is not between 1-10")
within_range = False
return int(choice)
result = user_choice()
print (result)
| true |
2cd2cee48549e357234920cd03528ecad6b1c5ba | kvega/potentialsim | /src/potentialsim.py | 1,020 | 4.28125 | 4 | #!/usr/bin/python3
import pylab
import random
"""
Generates a text file of values representing the coordinates of n particles in a
potential.
"""
# Create the Particle Class
class Particle(object):
"""
Representation of a simple, non-interacting, massive particle
(assumes point-like, does not model charge).
"""
def __init__(self, position, velocity, mass=1.0):
"""
TODO: define attributes
"""
self.mass = mass
self.position = position
self.velocity = velocity
# Get the current position and velocity of the particle
def get_position(self):
return self.position
def get_velocity(self):
return self.velocity
# Set the new position and velocity of the particle
def set_position(self, position):
self.position = position
def set_velocity(self, velocity):
self.velocity = velocity
# TODO: Implement the equations of motion for a given potential
# TODO: Create function to generate particles | true |
861a99afac2f93a6163847d6a9bdc57b21136b19 | jflow415/mycode | /dict01/marvelchar01.py | 1,290 | 4.21875 | 4 | #!/usrbin/env python3
marvelchars = {
"Starlord":
{"real name": "peter quill",
"powers": "dance moves",
"archenemy": "Thanos"},
"Mystique":
{"real name": "raven darkholme",
"powers": "shape shifter",
"archenemy": "Professor X"},
"She-Hulk":{
"real name": "jennifer walters",
"powers": "super strength & intelligence",
"archenemy": "Titania"}
}
char_name = input("Which character do you want to know about? (starlord, mystique, she-hulk)").title()
char_stat = input("What statistic do you want to know about? (real name, powers, archenemy)").lower()
#print(marvelchars, sep= ", ")
print(char_name,"s", char_stat, "is:", marvelchars[char_name][char_stat])
# notice that when you put the cursor over the last parens, it doesn't highlight the FIRST one next to print at the beginning of the line
# shows that you're missing an ending parenthesis at the end of line 21 :)
#would the get method give the current power of the chosen character?
# as written, no I don't believe so... the first argument is the key being "get"ted, the second argument is what gets returned if no key is found.
#Ok. I'll do some more digging . Ok cool! Let me know if you need any help!
| true |
7830f2711cd16350747357b1639b0f72d2974a68 | RasikKane/problem_solving | /python/00_hackerrank/python/08_list_comprehension.py | 631 | 4.375 | 4 | """
Let's learn about list comprehensions!
You are given three integers x, y and z representing the dimensions of a cuboid along with an integer n.
Print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum of i+j+k is not equal to n.
Here, 0 <= i <=x , 0 <=j <=y, 0 <= k <=z. Please use list comprehensions rather than multiple loops, as a learning exercise.
"""
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print([[i,j,k] for i in list(range(x+1)) for j in list(range(y+1)) for k in list(range(z+1)) if not int(i+j+k) == n]) | true |
51ac5fba05dea57ebbc98fc66092876f2e867b82 | NoraIlisics/FirstRep | /for.py | 924 | 4.34375 | 4 | #Write a program which sums the integers from 1 to 10 using a for loop
# (and prints the total at the end).
total = 0
for i in range(1,11):
total += i
print(total)
#Can you think of a way to do this without using a loop?
total2 = sum(range(1,11))
print(total2)
#Write a program which finds the factorial of a given number.
# E.g. 3 factorial, or 3! is equal to 3 x 2 x 1; 5! is equal to 5 x 4 x 3 x 2 x 1, etc..
# Your program should only contain a single loop.
number = int(input("Choose a number: "))
num_fact = 123412313241234123412341234
for i in range(1, number+1):
num_fact *= i
print(num_fact)
#Write a program which prompts the user for 10 floating-point numbers and calculates their sum,
# product and average. Your program should only contain a single loop.
#Rewrite the previous program so that it has two loops
# – one which collects and stores the numbers, and one which processes them.
| true |
57ddd657bd402e1b4666223f51ad8efcc17a070f | Nevashka/Project-Euler | /palindrome.py | 591 | 4.1875 | 4 | #Problem 4: Find the largest palindrome made from the product of two 3-digit numbers.
def largest(digits):
''' (int) -> int
return the largest palindrome from the product of the numbers with
the given number of digits
palindrome(2) -> 9009 '''
first = 10**(digits-1)
last = (10**digits)-1
palindrome = [0]
for i in range(last, first, -1):
for x in range(last, first, -1):
product = i * x
if str(product) == str(product)[::-1] and palindrome[0] < product:
palindrome[0] = product
return palindrome[0]
| true |
b6de5d4434c5d21dbbafe799879b02b43278c2ec | davidlbyrne/cybersecurity | /assignment2/des_cbc.py | 2,882 | 4.15625 | 4 | #!/usr/local/bin/python3
# Assignment2 - Assignment 2, due November 7, 2018: Problem 6.1
# in the lecture notes. You may import the following packages from
# Python libraries:
import sys
import binascii
from Crypto.Cipher import DES
from Crypto import Random
def checkpad(plaintext):
length= len(plaintext)
if ((length % 8) != 0):
rem = length%8
# Pad indicates how many characters we have to add to the end of the file
pad = 8 - rem
# the first meaningless number in binary is (10000000) which is equal to 128
for i in range (pad):
plaintext= plaintext + chr (0)
return (plaintext)
# xor function
def xor(lft, rht):
# set up 8 char arrays with none elements
lft_ba = [None,None,None,None,None,None,None,None]
rht_ba = [None]*8
# print(lft_ba)
# print(lft, rht)
# step through each letter and conv to integer and store
for i in range(0,8):
# print(i)
lft_ba[i] = ord(lft[i])
rht_ba[i] = ord(rht[i])
# finally the result of xor
xor_res = [None] * 8
for i in range(0, 8):
xor_res[i] = lft_ba[i] ^ rht_ba[i]
# convert the bits into char again
ret=""
# print('xor_result:',xor_res)
return bytes(bytearray(xor_res))
#Encrypt function
def des_cbc_encrypt(plaintext,key,iv) :
ciphertext=b''
previous=""
#des first round
obj = DES.new(key,DES.MODE_ECB)
plaintext = checkpad(plaintext)
pte = plaintext[:8]
plaintext = plaintext[8:]
# print("pte:",pte)
pte = xor(iv,pte)
# print(len(pte))
previous = obj.encrypt(pte)
# print(len(previous), previous)
ciphertext = ciphertext + previous
# begin remaining rounds
for i in range (0,int((len(plaintext)/8))) :
pte = checkpad(plaintext[:8])
plaintext = plaintext[8:]
# print("encrypting ",len(pte),"bytes :\'",pte,"\'")
previous = ''.join([chr(s) for s in bytearray(previous)])
# print("previous :",previous)
pte = xor(previous,pte)
# print(pte,"END")
# print(len(pte), "pte",pte)
previous = obj.encrypt(pte)
# print(len(previous), previous)
ciphertext = ciphertext + previous
return ciphertext
#Decrypt Function
#des first round
#remaining rounds
if __name__ == '__main__':
key = sys.argv[1]
# print("Encrypting :",sys.argv[2])
file = open(sys.argv[2],'r')
plaintext=file.read()
file.close()
iv = '00000000'
ciphertext=des_cbc_encrypt(plaintext,key,iv)
print(ciphertext)
#print
'''
$ more test.txt
Hello, World!
$ python des-cbc.py 12345678 test.txt | xxd -b
00000000: 11100000 01011001 00110010 11110100 00101101 10100110 .Y2.-.
00000006: 11111011 01101011 00001000 00100001 10011100 01011100 .k.!.\
0000000c: 11000111 10110010 11001000 01001010 00001010 ...J.
'''
| true |
72e11ac47280c2ff079353f3e92a744fb16de490 | sabasharf123/word-frequency | /word-frequency-starter.py | 2,824 | 4.21875 | 4 | #set up a regular expression that can detect any punctuation
import re
punctuation_regex = re.compile('[\W]')
#open a story that's in this folder, read each line, and split each line into words
#that we add to our list of storyWords
storyFile = open('short-story.txt', 'r') #replace 'short-story.txt' with 'long-story.txt' if you want!
storyWords = []
for line in storyFile:
lineWords = line.split(' ') #separate out each word by breaking the line at each space " "
for word in lineWords:
cleanedWord = word.strip().lower() #strip off leading and trailing whitespace, and lowercase it
cleanedWord = punctuation_regex.sub('', cleanedWord) #remove all the punctuation
#(literally, replace all punctuation with nothing)
storyWords.append(cleanedWord) #add this clean word to our list
#set up an empty dictionary to hold words and their frequencies
#keys in this dictionary are words
#the value that goes with each key is the number of times that word appears in the dictionary
#Example: a key might be 'cat', and frequency_table['cat'] might be 5 if the word 'cat'
#appears 5 times in the storyWords list
frequency_table = {}
#ALL OF OUR CODE GOES HERE
for word in storyWords:
#if I have not seen any words of this type before, add a new entry
#1 is referring to how many times you've seen it before
if word not in frequency_table:
frequency_table[word] = 1
#if I have seen it before, add 1 to its current count
else:
frequency_table[word] = 1 + frequency_table[word]
print(frequency_table)
#this is a function that finds the most frequent word
def find_max_frequency():
#at the start, I haven't seen any words
#but I want to keep track of the most frequent word I've seen so far
max_freq = 0
max_word = ' '
#look through ALL words in the frequency table
for word in frequency_table:
#if the word I'm looking at now has appeared more than any
#words I've seen so far, update my max
if frequency_table[word] > max_freq:
max_freq = frequency_table[word]
max_word = word
#at the end of the for loop, we've looked through all entries and max_word has the most frequent word in it
return max_word
best_word = find_max_frequency()
print("The most frequent word is: " + best_word)
#make a fucntion to find the top 10
#CHALLENGE: modify this so it takes the top N
def top_twenty():
#take the most frequent word out of the frequency table 10 times
for count in range(20):
top_word = find_max_frequency()
print(top_word + " appears " + str(frequency_table[top_word]))
del(frequency_table[top_word]) #take that entry out of the table
#call the top ten function
top_twenty()
| true |
aec85ea6f687ec7516c577d5ddd58ed90f72e18f | tigerjoy/SwayamPython | /old_programs/cw_17_06_20/year.py | 471 | 4.15625 | 4 | year=int(input("enter year :"))
if year%100==0:
print("it is a centennial year")
if year%400==0:
print("it is a leap year")
else:
print("it is not a leap year")
elif year%4==0:
print("it is a leap year")
else:
print("it is not a leap year")
# Alternative
# if (year % 100 == 0) and (year % 400 == 0):
# print("it is a leap year")
# elif (year % 100 != 0) and (year % 4 == 0):
# print("it is a leap year")
# else:
# print("it is not a leap year") | true |
571a5322ed3b18be4a319ffa3a14a9541b6f08d3 | tigerjoy/SwayamPython | /old_programs/cw_2021_01_16/dictionary_exercise.py | 639 | 4.1875 | 4 | dict_users={}
for i in range(1,11):
# Enter username of user 1:
username=input("Enter username of user {}:".format(i))
password=input("Enter password of user {}:".format(i))
dict_users[username]=password
print("Enter log in details:")
username=input("Enter username of user :")
password=input("Enter password of user :")
# If the username is present in the dictionary
if(username in dict_users):
# If the entered password is of the username
if(dict_users[username] == password):
print("Welcome",username,"you are now logged in")
else:
print("Password is invalid")
else:
print(username,"is not a valid user")
| true |
3b51f2f0f0267366f5c1b246267ca3c10105cf9b | tigerjoy/SwayamPython | /old_programs/cw_2021_01_16/list_exercise.py | 623 | 4.15625 | 4 | list1 = []
list2 = []
size1 = int(input("Enter the size of list 1: "))
print("Enter elements in list 1")
for i in range(size1):
item = int(input("Enter element {}: ".format(i + 1)))
list1.append(item)
size2 = int(input("Enter the size of list 2: "))
print("Enter elements in list 2")
for i in range(size2):
item = int(input("Enter element {}: ".format(i + 1)))
list2.append(item)
# Q3 (Page 95) (List Exercise)
is_subset = True
for e in list1:
if e not in list2:
print("No, list1 notasubset of list2")
is_susbet = False
break
if is_subset == True:
print("Yes, list 1 is a subset of list 2")
| true |
12d9d1eb684dad8946f5c66c30eb5faec45c3f72 | tigerjoy/SwayamPython | /old_programs/cw_2020_10_22/list_q15.py | 264 | 4.34375 | 4 | size=int(input("Enter size of a list:"))
arr=[]
for i in range(0,size):
item=int(input("Enter element {}:".format(i+1)))
arr.append(item)
largest=arr[0]
for i in range(1,size):
if(arr[i]>largest):
largest=arr[i]
print("Largest element is:",largest) | true |
2cc2a7b4d5e441bdd774cdd94d14d54257b2c91e | tigerjoy/SwayamPython | /old_programs/cw_2020_10_22/list_q16.py | 269 | 4.25 | 4 | size=int(input("Enter size of a list:"))
arr=[]
for i in range(0,size):
item=int(input("Enter element {}:".format(i+1)))
arr.append(item)
smallest=arr[0]
for i in range(1,size):
if(arr[i]<smallest):
smallest=arr[i]
print("smallest element is:",smallest) | true |
8c8c861daf4fb6f0c70eb776d8563907dda10f35 | Yuchen-Yan/UNSW_2017_s2_COMP9021_principle_of_programming | /labs/lab_1/my_answer/celsius_to_fahrenheit.py | 435 | 4.1875 | 4 | # Written by Yuchen Yan for comp9021 lab 1 question1
'''
Prints out a conversion table of temperatures from Celsius to Fahrenheit degrees,
with the former ranging from 0 to 100 in steps of 10.
'''
min_temperature = 0
max_temperature = 100
step = 10
print('Celsius\tFahrenheit')
for celsius in range(min_temperature, max_temperature + step, step):
fahrenheit = celsius * 9 / 5 +32
print(f'{celsius:7d}\t{int(fahrenheit):10d}')
| true |
20e61a14ba04a69c1095840c5b33ff936f6a8d3b | vpiyush/SandBox | /python-samples/rangeOp.py | 330 | 4.15625 | 4 |
# sequnce of numbers 0 to 8
for temp in range(9):
print(temp)
# sequnce of numbers 0 to 8
# range (start, stop)
for temp in range(5, 9):
print(temp)
# sequnce of numbers 0 to 8
# range (start, stop, step)
for temp in range(1, 9, 2):
print(temp)
#typecasting to list
oddlist = list(range(1, 19, 2))
print(oddlist)
| true |
27a48c5d309c06a6730df859139245bec6106a37 | sureshanandcse/Python | /listex.py | 693 | 4.34375 | 4 | # Creating a List with the use of multiple values
l= ["Sairam", "Engineering", "College"]
print("\nList containing multiple values: ")
print(l[0])
print(l[2])
s=l[1]
print("s= ",s)
print("s[2] =" ,s[2])
print(len(l))
"""
list = [ 'abcd', 786 , 2.23, 'john', 70.26 ]
list[0]='suresh' # list is mutable
print(list)
print (list[0]) # Prints first element of the list
print (list[1:3]) # 1,2 # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print(list)
print (list[-1] ) # prints last element in list
print (list[-5]) # prints first element in list
print(list[0:10])
"""
| true |
125c4341943e9781fc9ee60b35e6beb13717c4aa | peggybarley/Ch.03_Input_Output | /3.0_Jedi_Training.py | 1,568 | 4.375 | 4 | # Sign your name: Peggy Barley
# 1.) Write a program that asks someone for their name and then prints their name to the screen?
print()
name = str(input("What is your name?"))
print("Hello,", name,"!")
print()
# 2. Write a a program where a user enters a base and height and you print the area of a triangle.
print()
print("Welcome to the triangle area calculator!")
base = float(input("What is the base of your triangle?"))
height = float(input("What is the height o your triangle?"))
area = 0.5*(base*height)
print()
print("The area of your triangle is", area)
print()
# 3. Write a line of code that will ask the user for the radius of a circle and then prints the circumference.
print()
print ("Welcome to the circumference calculator!")
r = float(input("What is the radius of your circle?"))
cir = 3.14*(r*2)
print()
print("The circumference of your circle is", r)
print()
# 4. Ask a user for an integer and then print the square root.
print()
print ("Welcome to the square root calculator!")
inte = int(input("Type an integer!"))
sr = inte**0.5
print()
print("The square root of", inte, "is", sr)
print()
# 5. Good Star Wars joke: "May the mass times acceleration be with you!" because F=ma.
# Ask the user for mass and acceleration and then print out the Force on one line and "Get it?" on the next.
print()
print("Welcome to the force calculator!")
m = float(input("What is the mass?"))
a = float(input("what is the acceleration?"))
f = m*a
print()
print("The force is", f)
print("May the mass times acceleration be with you!")
print("Get it?")
print() | true |
7ee6a48e8387a0d45ea82cf44b3e7b679dfcc503 | kongxilong/python | /mine/chaptr3/readfile.py | 341 | 4.3125 | 4 | #!/usr/bin/python3
'readTextFile.py--read and display text file'
#get file name
fname = input('please input the file to read:')
try:
fobj = open(fname,'r')
except:
print("*** file open error" ,e)
else:
#display the contents of the file to the screen.
for eachline in fobj:
print(eachline,)
fobj.close()
| true |
6c9b1f856e9c1abb350336b26b76f48a87a9f1bb | antwork/pynote | /source/str.py | 1,872 | 4.25 | 4 | # encoding:utf-8
# len(str)
s = 'hello China'
print(len(s))
#
# capitalize
# Return a capitalized version of S, i.e. make the first character
# have upper case and the rest lower case.
print('big city'.capitalize()) # Big city
#encode:utf-8
#
# casefold
# out: **********************value***********************
print('value'.center(50, '*'))
# out: value*********************************************
print('value'.ljust(50, '*'))
# out: *********************************************value
print('value'.rjust(50, '*'))
# out: 2
print('big city'.count('i')) # 2
#
# encode
# out: True
print('hello'.endswith('lo'))
# out:False
print('hello'.startswith('e'))
# print('^ one ^'.expandtabs(32))
#
# expandtabs
#
# find
print('CHINA'.find('I')) # Found: return index:2
print('China'.find('I')) # Not Found: return -1
print('CHINA'.index('I'))
try:
print('China'.index('I'))
except ValueError as e:
print(e) # substring not found
#
# format
#
# format_map
# isalnum
print('abc'.isalnum()) # True
print('12ab'.isalnum()) # True
print('+'.isalnum()) # False
#
# isalpha
print('abc'.isalpha()) # True
print('123'.isalpha()) # False
# isdecimal
# Return True if there are only decimal characters in S, False otherwise.
# >>> print('0123456789'.isdecimal())
# True
# >>> print('0123456789a'.isdecimal())
# False
# isdigit
#
# isidentifier
#
# islower
#
# isnumeric
#
# isprintable
#
# isspace
#
# istitle
#
# isupper
#
# Out:apple.banana.orange
arr = ['apple', 'banana', 'orange']
print('.'.join(arr))
#
# ljust
#
# lower
#
# lstrip
#
# maketrans
#
# partition
#
# Out: banana is delicious!
src = "orange is delicious!"
print(src.replace('orange', 'banana'))
#
# rfind
#
# rindex
#
# rjust'#
# rpartition'#
# rsplit'#
# rstrip'#
# split'#
# splitlines'#
# startswith'#
# strip'#
# swapcase'#
# title'#
# translate'#
# upper'#
# zfill'
| true |
8416779fee766e6ad1dbbf23bc88cdd02c7a7706 | n0execution/prometheus-python | /lab5_3.py | 635 | 4.40625 | 4 | """
function for calculating superfibonacci numbers
it is a list of whole numbers with the property that,
every n term is the sum of m previous terms
super_fibonacci(2, 1) returns 1
super_fibonacci(3, 5) returns 1
super_fibonacci(8, 2) returns 21
super_fibonacci(9, 3) returns 57
"""
def super_fibonacci(n, m) :
#checking for some special cases
if n <= m or m == 1 :
return 1
#making list of [1, 1, 1...] with length of m
new_list = [1 for x in range(m)]
for i in range(m, n) :
length = len(new_list)
#appending the sum of m last elements to list
new_list.append(sum(new_list[length - m :]))
return new_list[n - 1]
| true |
5cf0406aa64a6679f4aea84a4662d819dad13d4a | TaylorKolasinski/hackerrank_solutions | /strings/pangrams.py | 1,122 | 4.3125 | 4 | # Difficulty - Easy
# Problem Statement
# Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly because it is a pangram. ( pangrams are sentences constructed by using every letter of the alphabet at least once. )
# After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.
# Given a sentence s, tell Roy if it is a pangram or not.
# Input Format
# Input consists of a line containing s.
# Constraints
# Length of s can be atmost 103 (1≤|s|≤103) and it may contain spaces, lowercase and uppercase letters. Lowercase and uppercase instances of a letter are considered same.
# Output Format
# Output a line containing pangram if s is a pangram, otherwise output not pangram.
def findPanagram(s):
alpha = []
for char in s:
if char not in alpha:
alpha.append(char)
if len(alpha) == 26:
print "pangram"
else:
print "not pangram"
if __name__ == '__main__':
# Hanlde inputs
s = raw_input().replace(" ", "").lower()
findPanagram(s) | true |
8c31f4a29804ccecb16daedd837a65ea8fd375bb | JAT117/Notes | /CSCE4910/PythonExamples/TexBoxWidget.py | 827 | 4.25 | 4 | #!/usr/bin/env python3
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("Python GUI")
#Handles Button Clicked
def clickMe():
#When clicked, change name of button.
myButton.configure(text='Hello ' + name.get())
#Lable INSIDE our win (Window)
ttk.Label(win, text="Enter a name:").grid(column=0, row=0)
#String Variable
name = tk.StringVar()
#Box for INPUT inside win of width 12 and value stored on Var name
inputBox = ttk.Entry(win, width = 12, textvariable = name)
inputBox.grid(column = 0, row = 1) #Possition
#Adding a Button
myButton = ttk.Button(win, text="Click Me!", command=clickMe)
myButton.grid(column=1, row=1) #Possition
win.mainloop()
| true |
674c75a565efdf149d612db8fead1899d1e5336e | vedk21/python-playground | /Intermediate/OOP/Abstraction/abstraction.py | 710 | 4.1875 | 4 | # Abstraction (hiding the details of operation but availabling the interface open)
class Car:
def __init__(self, name, color, year):
self.name = name
self.color = color
self._year = year # _ represents it understood as private member
def drive(self):
print('driving {self.name} a car of color {self.color}')
def _get_year(self):
return self._year
def show_year(self):
print(f'This car is manufactured in {self._get_year()}')
mustang = Car('Mustang GT', 'grey', 1970)
print(mustang.show_year())
# There is no way in python, that we can limit the member access using public or private key words,
# But it is a common practice to use '_' as representation of private members
| true |
104cc6f2a2c4044a905c748603f3998535f84b0f | taylorak/python-demo | /03-if-statement/if_statement.py | 767 | 4.1875 | 4 | '''
Working with if-then statements
'''
def if_else(correct):
"Checks if correct is true or not"
if correct:
print("true statement")
else:
print("false statement")
if_else(True)
if_else(False)
def check_nums(num1, num2):
'''
Checks which number is greater
'''
if num1 > num2:
print("{} is greater than {}".format(num1, num2))
elif num2 > num1:
print("{} is greater than {}".format(num2, num1))
else:
print("{} is equal to {}".format(num1, num2))
check_nums(1, 2)
check_nums(2, 1)
check_nums(2, 2)
def ternary_if(correct):
"Checks if correct is true or not"
statement = "true statment" if correct else "false statment"
print(statement)
ternary_if(True)
ternary_if(False)
| true |
2e1e275dd7191f8b18fe73af0a8d7cde49c95289 | gaurangalat/SI506 | /Gaurang_DYU2.py | 1,163 | 4.3125 | 4 | #Week 2 Demonstrate your understanding
print "Do you want a demo of this week's DYU?\nA. Yes B. Not again\n"
inp = raw_input("Please enter your option: ") #Take input from user
if (inp =="B" or inp =="b"):
print "Oh well nevermind"
elif(inp == "A" or inp =="a"): #Check Option
print "\nHere are a few comic book characters"
d={"Batman" : "Robin", "Asterix": "Obelix", "Tintin" :"Snowy"} #Dictionary Initialization
print d.keys() #Print keys of the dictionary
x= raw_input("\nDo you want to know their sidekicks?\nA. Yes B. No\n")
if (x == "A" or x =="a"): #Check for User Option
y = raw_input("Which character's sidekick would you like to know about? ") #Take input
c=0
for ele in d.keys():
if (y.upper()==ele.upper()): #Compare input and key of ditcionary
print d[ele], "is the sidekick of", y, "\n"
else:
c+=1
if(c==3): #Invalid Input checker
print "Please Check Again"
elif(inp =="B" or inp =="b"):
print "\nOh well nevermind"
else:
print "\nNevermind. Sorry to waste your time :)"
else: #Invalid input checker
print ("\nSorry, wrong option. Run again")
| true |
8db034fea3cc39b02329ea5246f5a526caa3f88d | Ktulu1/Learning_Python3_The_Hard_Way | /ex20-1.py | 1,555 | 4.15625 | 4 | # import argv from library sys
from sys import argv
# setup variables for argv
script, input_file = argv
# define a function that prints the entire contents of the file
def print_all(f):
print(f.read())
# define a function that seeks to the begining of the file
def rewind(f):
f.seek(0)
# define a fuction that prints a specific line in the file
def print_a_line(line_count, f):
print(line_count, f.readline())
# set the a variable for the open file
current_file = open(input_file)
# echo this text to the screen
print("First let's print the whole file:\n")
# call the function print_all
print_all(current_file)
# echo this text to the screen
print("Now let's rewind, kind of like a tape.")
# call the function rewind
rewind(current_file)
# echo this text to the screen
print("Let's print three lines:\n")
# set a variable for line number
current_line = 1
print(f"Current line is {current_line}")
# call the function print_a_line and pass the line number and file object variables
print_a_line(current_line, current_file)
# take the variable for line number and increment it by 1
current_line += current_line
print(f"current line is {current_line}")
# call the function print_a_line and pass the line number and file object variables
print_a_line(current_line, current_file)
# take the variable for line number and increment it by 1
current_line = current_line + 1
print(f"Current line is {current_line}")
# call the function print_a_line and pass the line number and file object variables
print_a_line(current_line, current_file) | true |
9f04f14496b13a8a9b851f6758bf9b0dfb62c46a | Ktulu1/Learning_Python3_The_Hard_Way | /ex16.py | 1,209 | 4.28125 | 4 | # load argv from the sys library
from sys import argv
# define variables for argv
script, filename = argv
# echo some text with a varaible in it
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you want that, hit RETURN.")
# set the prompt
input("?")
# echo some text about what's going on
print("Opening the file...")
# open the file as file object "target" in write mode
target = open(filename, 'w')
# more echoed text
print("Truncating the file. Goodbye!")
# use the truncate command on the file object "target"
target.truncate()
# echo some instructions
print("Now we're goign to ask you for three lines.")
# input 3 strings named line1...
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
# more status updates echoed to the screen
print("I'm going to write these to the file.")
# use the write command to write the imput from above to the file object "target" and write a new line - 3 times
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
# more status echoed
print("And finally, we close it.")
# close the file object "target"
target.close() | true |
fdaae9577fa0821a143ca185cc1019d03bcf5202 | Nathnos/probabilistic_battleships | /game/board_setup.py | 1,920 | 4.1875 | 4 | """
Main game functions
"""
import numpy as np
from game.game_tools import (
get_direction,
get_boat_size,
get_random_direction,
get_random_position,
)
def can_place(grid, boat, position, direction):
"""
grid : numpy array
boats : represented by an integer
position : tuple (x, y)
direction : left, right, top or bottom
"""
x_dir, y_dir = get_direction(direction)
boat_size = get_boat_size(boat)
x, y = position
for i in range(boat_size):
x_i = x + i * x_dir
y_i = y + i * y_dir
if x_i >= 10 or x_i < 0 or y_i >= 10 or y_i < 0 or grid[y_i, x_i]:
return False
return True
def place(grid, boat, position, direction, append=False):
"""
Returns where or not the boat has been placed.
"""
if not can_place(grid, boat, position, direction) and not append:
return False
x_dir, y_dir = get_direction(direction)
boat_size = get_boat_size(boat)
x, y = position
if append:
for i in range(boat_size):
grid[y + i * y_dir, x + i * x_dir] += 1
else:
for i in range(boat_size):
grid[y + i * y_dir, x + i * x_dir] = boat
return True
def generate_random_grid(boat_list=range(1, 6)):
"""
Generate a random grid, making sure boats don't share same position.
"""
grid = get_empty_grid()
for boat in boat_list:
random_placement(grid, boat)
return grid
def get_empty_grid():
return np.zeros((10, 10), dtype=np.uint8)
def random_placement(grid, boat):
"""
Try a random location, until it's possible (no other boats there).
"""
placed = False
while not placed:
direction = get_random_direction()
position = get_random_position()
placed = place(grid, boat, position, direction)
def show(grid):
print(grid)
def eq(grid1, grid2):
return (grid1 == grid2).all()
| true |
221c0daa1d412fc285fd01b8386202029931e2d0 | arnab-arnab/Python-Course | /06.Chapter 6/Question 4.py | 211 | 4.15625 | 4 | text=input("Enter the text:\n")
a=len(text)
print("Length is:",a)
if(a<10):
print("The length is less than 10")
if(a>10):
print("The length is greater than 10")
if(a is 10):
print("The length is 10") | true |
f1e5cca8210d307dbe84e01717b19d11ee7298f9 | arnab-arnab/Python-Course | /04.Chapter 4/Question_3.py | 403 | 4.25 | 4 | print("Enter three elements to be stored in tuple")
a1=input("Enter the 1st element: ")
a2=input("Enter the 2nd element: ")
a3=input("Enter the 3rd element: ")
tupl=(a1,a2,a3)
print(tupl)
print("Which of the element of the tuple would you try to change\n")
print("0\t1\t2\n")
a4=input("Enter the index value from the above:")
a5=input("Enter the new element:")
tupl[a4]=a5 # <-- Error
print(tupl)
| true |
6002071aa47b871e3cfb4121562fcc334392ebf3 | arnab-arnab/Python-Course | /05.Chapter 5/02_Dictionary_Methods.py | 1,239 | 4.375 | 4 | myDict={
"Fast":"In a quick manner",
"Arnab":"A coder",
"Marks":[1,2,5],
"Li":(3,44,6),
"Number": 5,
"anotherDict":{"Devesh":"Doggy",
"Sneha":"Bitch",
"Deborshi":"Cow",
"Sex_Position":69
}
}
# DICTIONARY METHODS
print(tuple(myDict.keys())) # We can convert the keys of the dictionary to a tuple
print(list(myDict.keys())) # We can convert the keys of a dictionary to a list
print(myDict.values()) # Prints the values inside the dictionary
print(myDict.keys()) # Prints all the keys of the dictionary
print(myDict.items()) # Prints all the keys, values for all items of the dictionary
print(myDict)
updateDict={
"Devesh":"Friend", # Here devesh is not updated because it is inside nested dictionary
56:69,
"Arnab":"A programmer" # Here it also updates arnab from a coder to a programmer
}
myDict.update(updateDict) # Updates the dictionary with the new keys and values
print(myDict)
print(myDict.get("Devesh")) # It searches for a key
print(myDict["Devesh"])
print(myDict.get("Devesh2")) # It does not throw error
# print(myDict.grt("Devesh2")) <-- It throws error | true |
f7ed51b9039ee4b5488431c519be8027e383b5e6 | markkampstra/examples | /Python/fizzbuzz.py | 1,620 | 4.25 | 4 | #!/usr/bin/python
# FizzBuzz by Mark Kampstra
#
# Write a program that prints the numbers from 1 to 100.
# But for multiples of 3 print "Fizz" instead of the number and for the multiples of five print "Buzz".
# For numbers which are multiple of both 3 and 5, print "FizzBuzz".
#
import string
class FizzBuzz:
'''The FizzBuzz class'''
def __init__(self):
self.result = ""
def do_fizz_buzz(self):
# return the FizzBuzz sequence in a string
# create an array with numbers 1 to 100
numbers = range(1,101)
# loop though the array of numbers and check whether to print 'Fizz', 'Buzz', 'FizzBuzz' or just the number
for n in numbers:
if n % 3 == 0:
self.fizz()
if n % 5 == 0:
self.buzz()
if (n % 3 != 0) and (n % 5 != 0):
self.result += "%d" % (n)
# add a space
self.result += ' '
return self.result[:-1] # remove trailing space and return
def fizz(self):
self.result += "Fizz"
def buzz(self):
self.result += "Buzz"
def fizz_buzz_oneliner(self):
# FizzBuzz in one line
return string.join(["FizzBuzz" if x%15 == 0 else "Fizz" if x%3 == 0 else "Buzz" if x % 5 == 0 else str(x) for x in range(1,101)])
def main():
fizz_buzz = FizzBuzz()
result1 = fizz_buzz.do_fizz_buzz()
result2 = fizz_buzz.fizz_buzz_oneliner()
print 'FizzBuzz'
print
print 'do_fizz_buzz() result:'
print result1
print
print 'fizz_buzz_oneliner result:'
print result2
if result1 == result2:
print 'Both results are the same! \o/'
else:
print 'Oops, something is not right :\'('
if __name__ == "__main__":
main() | true |
ea3cd26f2804b5ac8850ea448d8dcb23f9e1cca9 | dbozic/useful-functions-exploration | /column_unique_values.py | 1,252 | 4.71875 | 5 | def column_unique_values(data, exclusions):
"""
This function goes through each column of a dataframe
and prints how many unique values are in that column.
It will also show what those unique values are. The
function is particularly useful in exploratory data
analysis for quick understanding of column content
within the dataframe. Assumes that pandas has
been imported.
INPUTS:
data: dataframe to be analyzed.
exclusions: a list of columns as strings to be excluded, e.g. exclusions = ['column1', 'column2']
If no exclusions, then input 'exclusions = []'.
OUTPUT:
print statements
"""
# First, we select only those columns that are implicitly included
selection = data.drop(exclusions, axis = 1)
# Then we parse through every column of the dataframe
for column in selection.columns.values:
print('Column {x} has {y} unique values.').format(x = column, y = len(data[column].unique()))
print('')
print('Those unique values are:')
print('')
print(data[column].unique())
print('')
print('- - - - - - - - - - - - - - - - - -')
print('')
| true |
45af716bb44964e643e8bf989626a735719dbdca | judyohjo/Python-exercises | /Python exercise 12 - List.py | 396 | 4.3125 | 4 | '''
Exercise 12 - Get the smallest number from each list and create a new list and print that new list.
'''
list1 = [1, 3, 5, 0, 2, 3]
list2 = [3, 5, 3, 56, 7, 22]
list3 = [67, 34, 24, 15, 88, 99]
newlist = []
smallest1 = min(list1)
smallest2 = min(list2)
smallest3 = min(list3)
newlist.append(smallest1)
newlist.append(smallest2)
newlist.append(smallest3)
print(newlist)
| true |
fbaf080f19aea0424908dfa870cf4213753b719a | judyohjo/Python-exercises | /Python exercise 11 - Input.py | 209 | 4.21875 | 4 | '''
Exercise 11 - Input a number and print the number of times of "X" (eg. if number is 3, print...
X
XX
XXX)
'''
num = int(input("Input a number: "))
for i in range(1, num+1):
print(i*"X")
| true |
a05605bc741df904178fa79706fc90b7bedd50bf | schappidi0526/IntroToPython | /20_IterateOnDictionary.py | 811 | 4.65625 | 5 | grades={'Math': 100,
'Science': 80,
'History': 60,
'English': 50}
grades['Biology']=70
#To print just keys
for key in grades:
print(key)
#To print keys along with their values
for key in grades:
print(key,grades[key])
for key in grades.keys():
print(key,grades[key])
#To print values from a dictionary
for value in grades.values():
print (value)
#keys and values are dynamic objects and read only. When the dict changes these will change
values=grades.values()
keys=grades.keys()
print (sorted(keys))
print (sorted(values))
#to make changes to the keys
"""though keys structure appear to be as lists but those
are not lists, we need to convert to list to make changes"""
keys_l=list(keys)
keys_l.append('Zoology')
print(keys_l)
| true |
eb63068b4b356aa525322e418921c6b23f681c6b | schappidi0526/IntroToPython | /22_Update&DeleteDictionary.py | 1,088 | 4.3125 | 4 | #Merge/Update dictionary
dict1={'Math':99,
'science':98,
'history':33}
dict2={'telugu':88,
'hindi':77,
'english':99,
'Math':69}#If you have same keys in both dictionaries,values will be updated
dict1.update(dict2)
print (dict1)
dict2.update(dict1)
print(sorted(dict2.keys()))
print(sorted(dict2.values()))
#Delete keys in dictionary based on the keys
del dict1["hindi"]
print (dict1)
dict1.pop('english')
print (dict1)
#if you try to pop a key that doesn't exist, it will throw keyerror
# dict1.pop('hindi')
# print (dict1)
#clear all elements
dict1.clear()
print (dict1)
#get function
print (dict1.get('hindi'))
"""By default above will print 'None'. If a key doesn't exist and if you want to specify a
value other than 'None'"""
print (dict1.get('hindi','Not found'))
#Add lists to dictionary
L1=[1,2,3,4,5]
count=['count1','count2','count3','count4','count5']
dict2={"l1":L1,
"count":count}
print (dict2)
#Another way
d1=dict(zip(L1,count))
print (d1)
print (help()) | true |
9a403dad3118c5410b09b4969f8e2ff2f7fb41f1 | problems-forked/Dynamic-Programming | /0_1 Knapsack/Programmes/main(14).py | 1,149 | 4.15625 | 4 |
def find_target_subsets(num, s):
totalSum = sum(num)
# if 's + totalSum' is odd, we can't find a subset with sum equal to '(s + totalSum) / 2'
if totalSum < s or (s + totalSum) % 2 == 1:
return 0
return count_subsets(num, int((s + totalSum) / 2))
# this function is exactly similar to what we have in 'Count of Subset Sum' problem.
def count_subsets(num, s):
n = len(num)
dp = [[0 for x in range(s+1)] for y in range(n)]
# populate the sum = 0 columns, as we will always have an empty set for zero sum
for i in range(0, n):
dp[i][0] = 1
# with only one number, we can form a subset only when the required sum is
# equal to the number
for s in range(1, s+1):
dp[0][s] = 1 if num[0] == s else 0
# process all subsets for all sums
for i in range(1, n):
for s in range(1, s+1):
dp[i][s] = dp[i - 1][s]
if s >= num[i]:
dp[i][s] += dp[i - 1][s - num[i]]
# the bottom-right corner will have our answer.
return dp[n - 1][s]
def main():
print("Total ways: " + str(find_target_subsets([1, 1, 2, 3], 1)))
print("Total ways: " + str(find_target_subsets([1, 2, 7, 1], 9)))
main() | true |
6e6b8dbcdd7d5cbfef4c7ae9005cbd2639671f18 | fanliu1991/LeetCodeProblems | /38_Count_and_Say.py | 1,473 | 4.21875 | 4 | '''
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the n-th term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
'''
import sys, optparse, os
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
integer = "1"
for _ in range(n-1):
digit = integer[0]
digit_count = 0
output = ""
for num in integer:
if num == digit:
digit_count += 1
else:
output = output + str(digit_count) + digit
digit = num
digit_count = 1
integer = output + str(digit_count) + digit
return integer
# n = 5
# solution = Solution()
# result = solution.countAndSay(n)
# print result
solution = Solution()
for n in range(1,6):
result = solution.countAndSay(n)
print(n, result)
'''
Complexity Analysis
Time complexity : O(logn).
Binary search solution.
Space complexity : O(1).
No extra space is used. Only two extra variables left and right are needed.
''' | true |
da22091944898edbfca31ed8919e568a6802d8ec | fanliu1991/LeetCodeProblems | /75_Sort_Colors.py | 2,115 | 4.28125 | 4 | '''
Given an array with n objects colored red, white or blue,
sort them in-place so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2
to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's,
then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
'''
import sys, optparse, os
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
'''
Initially, we set the frist 1 and first 2 at position 0,
For every number in the nums, we set it as 2,
if it is 2, then we done,
else if it is 0 or 1, then we set the value at first 2 position as 1 and mover forward the first 2 position,
if it is 1, then we done,
else if it is 0, then we set the value at first 1 position as 0 and mover forward the first 1 position.
hence, [0, first_one), [first_one, first_two), [first_two, k) are 0s, 1s and 2s sorted in place for [0,k).
'''
first_one, first_two = 0, 0
for i in range(len(nums)):
value = nums[i]
nums[i] = 2
if value < 2:
nums[first_two] = 1
first_two += 1
if value == 0:
nums[first_one] = 0
first_one += 1
nums = [2,0,2,1,1,0]
solution = Solution()
result = solution.sortColors(nums)
print result
'''
Complexity Analysis
Time complexity : O(n).
We are doing one pass through the nums.
Space complexity : O(1).
Nums are sorted in place and no extra space is used. Only extra variables are needed.
'''
| true |
0cd58414e3ad8e23d1532ba3509d4e005d9f5cf0 | fanliu1991/LeetCodeProblems | /89_Gray_Code.py | 1,833 | 4.25 | 4 | '''
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code,
print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
'''
import sys, optparse, os
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
"""
n = 0, 0 = 0
n = 1, 0 = 0
1 = 1
n = 2, 00 = 0
01 = 1
11 = 3
10 = 2
n = 3, 000 = 0
001 = 1
011 = 3
010 = 2
110 = 6
111 = 7
101 = 5
100 = 4
for n bits sequence,
add 2^(n-1) to each value in the reversed sequence of n-1 bits,
i.e. replace the first bit of n-bit number from 0 to 1,
will generate the sequence of n bits
"""
if n == 0:
return [0]
# spical case, which should be [], but accepted answer is [0]
result = [0]
for i in range(n):
result = result + [value + 2**i for value in reversed(result)]
return result
n = 4
solution = Solution()
result = solution.grayCode(n)
print result
'''
Complexity Analysis
Time complexity : O(2^n).
We are doing one pass through each of the list
with length 2, 4, 8, ..., 2^(n-1).
Space complexity : O(2^n).
Extra space is used to store 2^n values of n bits sequence.
'''
| true |
5a81227b5affe10bfea4b5acabb0dcea57f9ec68 | fanliu1991/LeetCodeProblems | /125_Valid_Palindrome.py | 1,278 | 4.1875 | 4 | '''
Given a string, determine if it is a palindrome,
considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
import sys, optparse, os
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
s = s.lower()
left = 0
right = len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if s[left] != s[right]:
return False
else:
left += 1
right -= 1
return True
s = "A man, a plan, a canal: Panama"
solution = Solution()
result = solution.isPalindrome(s)
print result
'''
Complexity Analysis
Time complexity: O(n).
We are doing a single pass through the string, hence n steps,
where n is the length of price array.
Space complexity : O(1).
No extra space is used. Only extra variables are needed.
'''
| true |
97de3552794dbc0e04be28659349f09d415702ba | fanliu1991/LeetCodeProblems | /101_Symmetric_Tree.py | 2,889 | 4.25 | 4 | '''
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Example 1:
input: binary tree [1,2,2,3,4,4,3]
output: True
1
/ \
2 2
/ \ / \
3 4 4 3
Example 2:
input: binary tree [1,2,2,null,3,null,3]
output: False
1
/ \
2 2
\ \
3 3
'''
import sys, optparse, os
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# recursive solution
def isMirror(left_subtree, right_subtree):
if left_subtree == None and right_subtree == None:
return True
elif left_subtree == None or right_subtree == None:
return False
if left_subtree.val != right_subtree.val:
return False
else:
ans = isMirror(left_subtree.left, right_subtree.right) and \
isMirror(left_subtree.right, right_subtree.left)
return ans
if root == None:
return True
else:
res = isMirror(root.left, root.right)
return res
# iterative solution
'''
stack = []
if root == None:
return True
stack.append((root.left, root.right))
while stack:
subtrees = stack.pop()
left_subtree = subtrees[0]
right_subtree = subtrees[1]
if left_subtree == None and right_subtree == None:
continue
elif left_subtree == None or right_subtree == None:
return False
if left_subtree.val != right_subtree.val:
return False
else:
stack.append((left_subtree.left, right_subtree.right))
stack.append((left_subtree.right, right_subtree.left))
return True
'''
root = [1,2,2,3,4,4,3]
solution = Solution()
result = solution.isSymmetric(root)
print result
'''
Complexity Analysis
Time complexity : O(n).
We traverse the entire input tree once, the total run time is O(n),
where n is the total number of nodes in the tree.
Space complexity :
recursive method: O(logN).
The number of recursive calls is bound by the height of the tree.
But in the worst case, the tree is linear, i.e. each node has only one child.
Therefore, the height of tree is in O(n),
space complexity due to recursive calls on the stack is O(n) in the worst case.
iterative method: O(n).
There is additional space required for the search queue.
In the worst case, we have to insert O(n) nodes in the queue.
Therefore, space complexity is O(n).
'''
| true |
5c4c4b8c30d09c8a7163d24ff3030fa4b3e0ce34 | Shehu-Muhammad/Python_College_Stuff | /Problem4_CupcakeRequest.py | 459 | 4.125 | 4 | # Shehu Muhammad
# Problem 4 -Requests the number of cupcakes ordered and displays the total cost
# May 7, 2018
orders = int(input("What are the total number of cupcake orders? "))
cost = 0
small = 0.75
large = 0.70
if(orders <= 99 and orders>=1):
cost = cost + (orders*small)
elif(orders >= 100):
cost = cost + (orders*large)
else:
print("No cupcakes were ordered.")
print("The total cost for the cupcakes ordered is $",format(cost,'.2f'),".",sep="")
| true |
05228bb597c8d13f1e2e6427a2a307e0abf2ee02 | Shehu-Muhammad/Python_College_Stuff | /Python Stuff/Guess.py | 1,156 | 4.125 | 4 | # Guess my number
# Shehu Muhammad
import random
import math
random.seed()
randomNumber = math.floor(random.random() * 100) + 1 # generates a random number between 1 and 100
guess = 0 # initializes guess to zero
count = 0 # initializes count to 0
while (randomNumber != guess): # loops until guess is equal to random number
count = count+1 # increments count by 1 when guess is wrong
guess = int(input("Guess my number: ")) # askes user for a guess
if (guess < randomNumber): # checks if guess is lower than random number
print("Higher!") # prompts user for a higher guess
elif(guess > randomNumber): # checks if guess is higher than random number
print("Lower!") # prompts user for a lower guess
print("Correct! " + str(count) + " tries.") # Prints "Correct" and number of tries counted until the user guessed the random number
| true |
5a1e50c525e772ece7944a9c7609ac8cb5ad79bb | CoderDojoNavan/python | /basics/4_inputs.py | 985 | 4.125 | 4 | """4: Inputs"""
# Sometimes you might want to ask the user a question. To do that, we use
# a special function called `input`. Functions are covered in `5-functions.py`.
# You can ignore the # pylint comment, it is there to tell tools which analyze
# the code that in fact everything is OK with this line.
days = 365 # pylint: disable=C0103
print('there are ' + str(days) + 'in a normal year')
days = int(input('How many days in a leap year? ')) # pylint: disable=C0103
if days == 366:
print('Well Done!')
else:
print('(Its one more than every other year)')
# Try running the above code, and type in your answer.
# What happens if you try to type a letter instead of a number? Try it now and
# come back
# You should get an ValueError saying that you gave an invalid literal for
# int() This is because we use a thing which is called a cast. By default,
# input gives us a string, but we cannot compare string to an int, so we need
# to convert it to an a number - int.
| true |
78b7f69d1513f3d252d07e30f3970be2beec094b | benjaminhuanghuang/dl-study | /keras_first_network.py | 2,038 | 4.78125 | 5 | '''
Develop Your First Neural Network in Python With Keras Step-By-Step
https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
The steps you are going to cover in this tutorial are as follows:
Load Data.
Define Model.
Compile Model.
Fit Model.
Evaluate Model.
Tie It All Together.
'''
from keras.models import Sequential
from keras.layers import Dense
import numpy
# fix random seed for reproducibility
numpy.random.seed(7)
# load pima indians dataset
dataset = numpy.loadtxt("data/pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]
# create model
'''
Models in Keras are defined as a sequence of layers.
We create a Sequential model and add layers one at a time until we are happy with our network topology.
We use a fully-connected network structure with three layers.
Fully connected layers are defined using the Dense class
'''
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu')) #input_dim=8 means 8 input variables
model.add(Dense(8, activation='relu')) # 8 neurons in the laryer,
model.add(Dense(1, activation='sigmoid'))
'''
initialize the network weights to a small random number generated from a uniform distribution (‘uniform‘),
in this case between 0 and 0.05 because that is the default uniform weight initialization in Keras.
'''
'''
Compiling the model uses backend library such as Theano or TensorFlow.
The backend automatically chooses the best way to represent the network for training
'''
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
'''
Fit the model
nepochs is the number of iterations
batch_size is the number of instances that are evaluated before a weight update in the network is performed
'''
model.fit(X, Y, epochs=150, batch_size=10)
'''
Evaluate Model
'''
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100)) | true |
2265d032ca4fc7148a6ff610e6fdd3d095484c5f | charukiewicz/Numerical-Methods | /convergence.py | 1,501 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Christian Charukiewicz (netid: charuki1)
This compares the rates of convergence between the Newton and Secant methods.
The program will print output values and display a plot in matplotlib.
More info:
- http://en.wikipedia.org/wiki/Newton's_method
- http://en.wikipedia.org/wiki/Secant_method
"""
import numpy as np
import matplotlib.pyplot as plt
import math as mth
def f(x):
return float((5-x)*mth.exp(x)-5)
def fd(x):
return float(-1*mth.exp(x)*(x-4))
secx = []
secy = []
newx = []
newy = []
def secant(func, oldx, x):
oldf, f = func(oldx), func(x)
if (abs(f) > abs(oldf)):
oldx, x = x, oldx
oldf, f = f, oldf
xk = 0
while 1:
dx = f * (x - oldx) / float(f - oldf)
if abs(dx) < 10e-8 * (1 + abs(x)):
return x - dx
oldx, x = x, x - dx
oldf, f = f, func(x)
xk = xk + 1
secx.append(xk)
secy.append(mth.log(x))
def newton(f, fd, x):
f_temp = f(x)
fd_temp = fd(x)
xk = 0
while 1:
dx = f_temp / float(fd_temp)
if abs(dx) < 10e-8 * (1 + abs(x)):
return x - dx
x = x - dx
f_temp = f(x)
fd_temp = fd(x)
xk = xk + 1
newx.append(xk)
newy.append(mth.log(x))
print "NEWTON's METHOD:" , newton(f, fd, 5)
print "SECANT METHOD:" , secant(f, 5, 10)
plt.plot(newx,newy,'r--',secx,secy,'b--')
plt.show() | true |
de96cc585410c8356590a971bd86505045a03f9e | azrlzhao/password-safty-check- | /check_password.py | 1,724 | 4.125 | 4 |
#Password security check code
#
# Low-level password requirements:
# 1. The password is composed of simple numbers or letters
# 2. The password length is less than or equal to 8 digits
#
# Intermediate password requirements:
# 1. The password must consist of numbers, letters or special characters (only: ~!@#$%^&*()_=-/,.?<>;:[]{}|\) any two combinations
# 2. The password length cannot be less than 8 digits
#
# Advanced password requirements:
# 1. The password must consist of three combinations of numbers, letters and special characters (only: ~!@#$%^&*()_=-/,.?<>;:[]{}|\)
# 2. The password can only start with a letter
# 3. The password length cannot be less than 16 digits
# apply all the possible letter symbol letters in the array and use for compare
word=r'''~!@#$%^&*()_=-/,.?<>;:[]{}\|'''
number='0123456789'
letter='abcdefghijklmnopqrstuvwxyz'
passward =input("please input your password:")
safty=0
count=0
#check the password should not be zero
while passward.isspace() or len(passward)==0:
passward =input("passward should not be empty")
#meet the low requirment and set a flag
if len(passward) <=7:
safty=1
#second set flag
elif 7<=len(passward)<=15:
safty=2
elif len(passward)>15:
safty=3
#check if the password has multple combination
for each in passward:
if each in number:
count+=1
break
for each in passward:
if each in word:
count+=1
break
for each in passward:
if each in letter:
count+=1
break
# print state
if safty==1 and count==1:
print('low safty ')
elif safty ==3 and count == 3:
print('high safty')
else:
print('median safty')
| true |
ab7b5ff8e907d45ef3cfbec2bb611ada3b68058d | daninick/test | /word_count.py | 1,318 | 4.375 | 4 | import re
filename = input('''
This program returns the words in a .txt file and their count in it.
Enter a .txt file name: ''')
f = open(filename, 'r')
# Read the file and convert it to a string
text = f.read()
# Ignore the empty lines
text = text.replace('\n', ' ')
# All words in the text are separated by space now.
# Make a list of all words in the text using regular expressions.
words = re.findall(r'\w+',text,re.I)
# Create an empty dictionary
d = {}
# For every word in the list of words check if the word exists in the dictionary.
# If it doesn't exist -> add it as a key and set a count of 1 as a value.
# If the word exists in the dictionary -> simply increase the count with 1.
for word in words:
word = word.lower()
# finds the items that contain a digit and do not put them in the dictionary.
# I presume the words has only word characters and no numbers
match = re.search(r'\d',word)
if match:
pass
else:
if word not in d.keys():
d[word] = 1
else:
d[word] = d[word] + 1
# Prints on the terminal all words and their count even the count of the keywords, alphabetically sorted.
print('''
The words in the file are: ''')
for key in sorted(d.keys()):
print(f"{key}: {d[key]}")
print(f'''
Total unique words used: {len(d)}''') | true |
c38e0d609c3414396e23f7ae50b2bf4695477eb6 | rrotilio/MBA539Python | /p20.py | 482 | 4.15625 | 4 | validInt = False
def doRepeat (str1,int1):
i = 0
while (i < int1):
print(str1)
i = i + 1
print("I like to repeat things.")
varStr = str(input("What do you want me to repeat?: "))
while not validInt:
try:
varInt = int(input("How many times should I repeat it?: "))
if(varInt < 0):
print("I can't repeat something negative times! Choose a positve number")
else:
validInt = True
except:
print("Whole numbers only please. Try again.")
doRepeat(varStr,varInt) | true |
856f36bd79f0866552aa760bd9cea652ee4cfdbb | dwzukowski/PythonDojo | /funwithfunctions.py | 2,051 | 4.625 | 5 | def multiply(list, num):
newList = []
for val in list:
newList.append(val*num)
return newList
#we declare a function called layered_multiples which takes one parameter arr
def layered_multiples(arr):
#we declare a variable called new_array which is an empty list
new_array = []
#we instantiate a for loop which iterates through all values in arr
for val in arr:
#we append a list of 1s equal to val in each coresponding index of new_arr
new_array.append([1]*val)
print new_array
layered_multiples(multiply([2,4,5],3))
"""
Hacker Challenge:
Write a function that takes the multiply function call as an argument. Your new function should return the multiplied list as a two-dimensional list. Each internal list should contain the number of 1's as the number in the original list. Here's an example:
def layered_multiples(arr)
# your code here
return new_array
x = layered_multiples(multiply([2,4,5],3))
print x
# output
>>>[[1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
Create a series of functions based on the below descriptions.
Create a function called 'multiply' that iterates through each value in a list (e.g. a = [2, 4, 10, 16]) and returns a list where each value has been multiplied by 5.
The function should multiply each value in the list by the second argument. For example, let's say:
#We declare a function called odd_even that takes no parameters
def odd_even():
#We instantiate a for loop beginning at 1 and ending after 2000
for i in range(1,2001):
#Using the condition expression if, we check if the number is even or odd
if i % 2 == 0:
print "The number is " +str(i) + ". This is an even number"
else:
print "The number is " +str(i) + ". This is an odd number"
odd_even()
Odd/Even:
Create a function called odd_even that counts from 1 to 2000. As your loop executes have your program print the number of that iteration and specify whether it's an odd or even number.
""" | true |
a03dbd25a62938ef0ed68df80d0df1df9983125e | dwzukowski/PythonDojo | /comparingArrays.py | 1,379 | 4.3125 | 4 | #we declare a function called compareArrays which takes two parameters, list one and list two
def compareArrays(list_one, list_two):
#we delcare a variable answer which is string
answer = ""
#we compare the lengths of teh two lists; if they are not equal the list cannot be the same
if len(list_one) != len(list_two):
answer= "The lists are not the same"
else:
#we instantiate a for loop begining at zero and ending at the end of the list
for i in range (0,len(list_one)):
#we compare the value at each index of the list; we exit the loop the first time two indexes are not equal
if list_one[i] != list_two[i]:
answer= "The lists are not the same"
break
else:
answer= "The lists are the same"
print answer
list_one = ['celery','carrots','bread']
list_two = ['celery','carrots','bread',]
compareArrays(list_one, list_two)
"""
Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
Your program should be able to accept and compare two lists: list_one and list_two. If both lists are identical print "The lists are the same". If they are not identical print "The lists are not the same." Try the following test cases for lists one and two:
list_one = [1,2,5,6,2]
list_two = [1,2,5,6,2]
""" | true |
d1f1d9a4d2a03bab8643fb8c00c5dcccf7b1462a | dwzukowski/PythonDojo | /classesIntroBike.py | 2,318 | 4.75 | 5 | #we declare a class called bike
class Bike(object):
#we set some instance variables; the miles variable will start at zero for every instance of this class
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
#we declare a method called displayInfo that, when called, displays that instance's price, speed, and total miles traveled
def displayInfo(self):
print "${}".format(self.price)
print self.max_speed
print "{} miles".format(self.miles)
#we declare a method called ride which increments total miles by 10; we return self to allow method chaining
def ride(self):
print "Riding"
self.miles+= 10
return self
#we declare a method called reverse which decrements the instance's total miles by 5; we return self to allow method chaining
def reverse(self):
print "Reversing"
self.miles-= 5
if self.miles < 0:
self.miles = 0
return self
bike1 = Bike(200, "25 MPH")
bike2 = Bike(250, "26 MPH")
bike3 = Bike(200, "25 MPH")
#example of method chaining; ride three times, reverse twice, and display
bike2.ride().ride().ride().reverse().reverse().displayInfo()
"""
Create a new class called Bike with the following properties/attributes:
price
max_speed
miles
Create 3 instances of the Bike class.
Use the __init__() function to specify the price and max_speed of each instance (e.g. bike1 = Bike(200, "25mph"); In the __init__() also write the code so that the initial miles is set to be 0 whenever a new instance is created.
Add the following functions to this class:
displayInfo() - have this method display the bike's price, maximum speed, and the total miles.
ride() - have it display "Riding" on the screen and increase the total miles ridden by 10
reverse() - have it display "Reversing" on the screen and decrease the total miles ridden by 5...
Have the first instance ride three times, reverse once and have it displayInfo(). Have the second instance ride twice, reverse twice and have it displayInfo(). Have the third instance reverse three times and displayInfo().
What would you do to prevent the instance from having negative miles?
Which methods can return self in order to allow chaining methods?
""" | true |
7654c068f8136a957fd0f17a00f00c130c0af639 | dwzukowski/PythonDojo | /typeList.py | 1,091 | 4.34375 | 4 | #we declare a function called typeList that takes one paramater, list
def typeList(list):
newStr = ""
sum = 0
#instantiate a for loop
for i in range(0,len(list)):
if isinstance(list[i], int):
sum+=list[i]
elif isinstance(list[i], float):
sum+=list[i]
elif isinstance(list[i], str):
newStr+= (list[i])+" "
print sum
print newStr
x= ['magical unicorns',19,'hello',98.98,'world']
typeList(x)
"""
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.
Here are a couple of test cases. Think of some of your own, too. What kind of unexpected input could you get?
""" | true |
8e662865c92c45a66ab05eb834ac525f87863c30 | 19h61a0507/python-programming-lab | /strpalindrome1.py | 205 | 4.375 | 4 | def palindrome(string):
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")
string=input("enter the string")
palindrome(string)
| true |
bdb456492eb7c89a11f0528f2fa631e76f353031 | peiyong-addwater/2018SM2 | /2018SM2Y1/COMP90038/quizFiveSort.py | 2,748 | 4.28125 | 4 | def insertionSort(arr):
assignment = 0
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
assignment = assignment +1
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
assignment = assignment+1
j -= 1
arr[j+1] = key
assignment = assignment +1
print(arr, assignment)
def shellSort(arr):
# Start with a big gap, then reduce the gap
n = len(arr)
gap = n/2
# Do a gapped insertion sort for this gap size.
# The first gap elements a[0..gap-1] are already in gapped
# order keep adding one more element until the entire array
# is gap sorted
while gap > 0:
for i in range(gap,n):
# add a[i] to the elements that have been gap sorted
# save a[i] in temp and make a hole at position i
temp = arr[i]
# shift earlier gap-sorted elements up until the correct
# location for a[i] is found
j = i
while j >= gap and arr[j-gap] >temp:
arr[j] = arr[j-gap]
j -= gap
# put temp (the original a[i]) in its correct location
arr[j] = temp
gap /= 2
array = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
insertionSort(array)
import math
print(math.log2(3355431+1))
# Python program to implement interpolation search
# If x is present in arr[0..n-1], then returns
# index of it, else returns -1
'''def interpolationSearch(arr, n, x):
# Find indexs of two corners
lo = 0
hi = (n - 1)
# Since array is sorted, an element present
# in array must be in range defined by corner
while lo <= hi and x >= arr[lo] and x <= arr[hi]:
# Probing the position with keeping
# uniform distribution in mind.
pos = lo + int(((float(hi - lo) /
( arr[hi] - arr[lo])) * ( x - arr[lo])))
# Condition of target found
if arr[pos] == x:
return pos
# If x is larger, x is in upper part
if arr[pos] < x:
lo = pos + 1;
# If x is smaller, x is in lower part
else:
hi = pos - 1;
return -1
# Driver Code
# Array of items oin which search will be conducted
arr = [10, 10, 10, 10, 11, 10, 10, 10, \
22, 23, 24, 33, 35, 42, 10]
n = len(arr)
x = 18 # Element to be searched
index = interpolationSearch(arr, n, x)
if index != -1:
print "Element found at index",index
else:
print "Element not found"
# This code is contributed by Harshit Agrawal'''
| true |
9b1f7b2a6b5cf52bd6406563714300f1e32d1f3d | crazywiden/Leetcode_daily_submit | /Widen/LC543_Diameter_of Binary_Tree.py | 1,564 | 4.25 | 4 | """
543. Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
"""
# actually took me a while
# Runtime: 44 ms, faster than 67.62% of Python3 online submissions for Diameter of Binary Tree.
# Memory Usage: 14.5 MB, less than 100.00% of Python3 online submissions for Diameter of Binary Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if root == None:
return 0
left_depth, left_span = self.maxDepth(root.left)
right_depth, right_span = self.maxDepth(root.right)
return max(left_depth + right_depth, left_span, right_span)
def maxDepth(self, root):
if root == None:
return 0, 0
left_depth, left_span = self.maxDepth(root.left)
right_depth, right_span = self.maxDepth(root.right)
depth = 1 + max(left_depth, right_depth)
span = max(left_depth + right_depth, left_span, right_span)
return depth, span | true |
83163acd94774048c6ed331b41da1d5bb8a904ca | crazywiden/Leetcode_daily_submit | /Widen/LC376_Wiggle_Subsequence.py | 1,871 | 4.25 | 4 | """
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Example 1:
Input: [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence.
Example 2:
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Example 3:
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
"""
# two array dp
# Time complexity -- 0(N)
# Space complexity -- O(1)
# Runtime: 40 ms, faster than 70.83% of Python3 online submissions for Wiggle Subsequence.
# Memory Usage: 13.8 MB, less than 10.00% of Python3 online submissions for Wiggle Subsequence.
# I should learn to use two arraries in dp
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
n = len(nums)
if n <= 1:
return n
inc, dec = 1, 1
for x in range(1, n):
if nums[x] > nums[x - 1]:
inc = dec + 1
elif nums[x] < nums[x - 1]:
dec = inc + 1
return max(inc, dec) | true |
628f8ab619e1460c897cdacfb238dd69b0cb94eb | crazywiden/Leetcode_daily_submit | /Widen/LC394_Decode_String.py | 1,811 | 4.15625 | 4 | """
394. Decode String
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
"""
# stack
# time complexity -- O(N)
# Runtime: 24 ms, faster than 94.38% of Python3 online submissions for Decode String.
# Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Decode String.
class Solution:
def decodeString(self, s: str) -> str:
if len(s) == 0:
return ""
stack = []
idx = 0
while idx < len(s):
if s[idx].isnumeric():
multiplier = []
while s[idx].isnumeric():
multiplier.append(s[idx])
idx += 1
stack.append("".join(multiplier))
elif s[idx].isalpha():
stack.append(s[idx])
idx += 1
elif s[idx] == "[":
idx += 1
elif s[idx] == "]":
new_str = []
while stack[-1].isalpha():
new_str.insert(0, stack.pop())
multiplier = int(stack.pop())
new_str = "".join(new_str)
stack.append(new_str*multiplier)
idx += 1
return "".join(stack) | true |
a953d20e0094da3a509afd7ae9a8cda33aeee6cf | crazywiden/Leetcode_daily_submit | /Widen/LC408_Valid_Word_Abbreviation.py | 2,325 | 4.1875 | 4 | """
408. Valid Word Abbreviation
Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.
A string such as "word" contains only the following valid abbreviations:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word".
Note:
Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.
Example 1:
Given s = "internationalization", abbr = "i12iz4n":
Return true.
Example 2:
Given s = "apple", abbr = "a2e":
Return false.
"""
# easy question is always very annoying...
# Runtime: 28 ms, faster than 98.80% of Python3 online submissions for Valid Word Abbreviation.
# Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Valid Word Abbreviation.
import re
class Solution:
def validWordAbbreviation(self, word: str, abbr: str) -> bool:
abbr_char = re.findall("[a-z]+", abbr)
abbr_digit = re.findall("[0-9]+", abbr)
if abbr[0] >= "0" and abbr[0] <= "9":
if int(abbr_digit[0]) > len(word):
return False
if abbr[0][0] == "0":
return False
return self.compare(word[int(abbr_digit[0]):], abbr_char, abbr_digit[1:])
else:
return self.compare(word, abbr_char, abbr_digit)
def compare(self, word, abbr_char, abbr_digit):
start = 0
if len(abbr_char) == 0 and len(word) != 0:
return False
while start < len(word):
if len(abbr_char) != 0:
tmp_seg = abbr_char.pop(0)
if word[start:start+len(tmp_seg)] != tmp_seg:
return False
start = start + len(tmp_seg)
if len(abbr_digit) != 0:
tmp_abbr = abbr_digit.pop(0)
if tmp_abbr[0] == "0":
return False
start += int(tmp_abbr)
if len(abbr_char) == 0 and len(abbr_digit) == 0:
break
if len(abbr_char) == 0 and len(abbr_digit) == 0 and start == len(word):
return True
else:
return False
| true |
7b98a0b5d9e81cc2d8fc1aca7e1e6e26dd164eae | crazywiden/Leetcode_daily_submit | /Widen/LC71_Simplify_Path.py | 1,287 | 4.28125 | 4 | """
71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix
Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.
"""
# actually simple
# but need to figure out what does canonical path means
# Runtime: 24 ms, faster than 95.52% of Python3 online submissions for Simplify Path.
# Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Simplify Path.
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
elements = path.split("/")
for ele in elements:
if ele == "..":
if stack:
stack.pop()
elif ele == "." or ele == "":
continue
else:
stack.append(ele)
return "/" + "/".join(stack) | true |
94ddc5ac813e101d378660e725d8cf258418e701 | elle-johnnie/Arduino_Py | /PythonCrashCourse/fizzbuzz.py | 762 | 4.1875 | 4 | # fizzbuzz in Python 2.7
##
# I just heard about this at a local meetup - thought I'd give it a go.
# The rules:
# Write a program that prints the numbers from
# 1 to 100. But for multiples of three print Fizz instead of the number and for the multiples of five print
# Buzz. For numbers which are multiples of both three and five print FizzBuzz
# create empty list
nums = []
# append 1-100 as items in num list
for i in range(1, 101):
nums.append(i)
# print unaltered list
print nums
print ('Begin fizzbuzz test... \n')
for i in nums:
if i % 3 == 0 and i % 5 == 0:
print ('fizzbuzz')
elif i % 3 == 0:
print ('fizz')
elif i % 5 == 0:
print ('buzz')
else:
print i
print ('fizzbuzz testing complete.')
| true |
6a26ef4cc53b955a98306b03c895c19e94264020 | elle-johnnie/Arduino_Py | /edX_CS_exercises/number_guess_bisect.py | 988 | 4.3125 | 4 | # The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive).
# The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection
# search, the computer will guess the user's secret number!
# edX wk 2 Algorithms
# solution attempt 01/31/2018 @LJohnson
low = 0
high = 100
number = False
print('Think of a number between 0 and 100.')
while not number:
mid = (high + low)//2
print('Is your number %d ?' % mid)
userinput = input('''Enter 'h' to indicate the guess is too high.
Enter 'l' to indicate the guess is too low.
Enter 'c' to indicate I guessed correctly.''')
if userinput == 'l':
low = mid
elif userinput == 'h':
high = mid
elif userinput == 'c':
print('Awesome I guessed your number correctly!')
number = True
else:
print('Sorry I did not understand your response.')
| true |
2ae130d5f467c00cd8c54b05409bbf4839b8579a | shaunn/projecteuler | /Problem1/py/p1.py | 1,730 | 4.21875 | 4 | # divisors of 3 and 5
#
# Problem 1
# If we list all the natural numbers below 10 that are divisors of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these divisors is 23.
#
# Find the sum of all the divisors of 3 or 5 below 1000.
# Strategies
#
# 1. `remainder = dividend - divisor * quotient` and `remainder=0`
# 2. Using the built-in modulo function
# 3. Using the built-in remainder function
# Packages! tbd...
# Constants and variables!
# Set the upper limit
upper_limit = 1000
# Set the list of divisors to test against
divisors = [3, 5]
# Define the 'summer' containing the running of sums
summer = 0
# Functions!
def test_if_multiple(test_number, test_divisor):
if test_number < test_divisor:
return False
if test_zero_using_modulo_function(test_number, test_divisor):
return True
else:
return False
def test_zero_using_modulo_function(test_number, test_divisor):
# 2. Using the built-in modulo function
test = test_number % test_divisor
if test == 0:
return True
else:
return False
def main():
global summer
# Note that the range function is the total number of elements starting at 0.
# Conveniently this satisfies the "below 1000" requirement out of the box!
for number in range(upper_limit):
# Rules state 'Find the sum of all the divisors of 3 or 5'
# Once a match is found for the multiple, don't perform further processing
multiple = False
for divisor in divisors:
if not multiple:
if test_if_multiple(number, divisor):
multiple = True
summer = summer + number
print(str(summer))
if __name__ == "__main__":
main()
| true |
ab403bbb4698cc504ca55c83af4067710a785ae6 | ziyadalvi/PythonBook | /6The Dynamic Typing Interlude/3GarbageCollection.py | 1,251 | 4.28125 | 4 | #when we reassign a variable, what happens to the value it was
#previously referencing? For example, after the following statements, what happens to
#the object 3?
"""The answer is that in Python, whenever a name is assigned to a new object, the space
held by the prior object is reclaimed if it is not referenced by any other name or object.
This automatic reclamation of objects’ space is known as garbage collection"""
x = 42
x = 'shrubbery' # Reclaim 42 now (unless referenced elsewhere)
x = 3.1415 # Reclaim 'shrubbery' now
x = [1, 2, 3] # Reclaim 3.1415 now
#notice that x is set to a different type of object each time. Again, though this is
#not really the case, the effect looks like that the type of x is changing over time.
#Each time x is
#assigned to a new object, Python reclaims the prior object’s space. For instance, when
#it is assigned the string 'shrubbery', the object 42 is immediately reclaimed (assuming
#it is not referenced anywhere else)
#Internally, Python accomplishes this feat by keeping a counter in every object that keeps
#track of the number of references currently pointing to that object. As soon as (and
#exactly when) this counter drops to zero, the object’s memory space is automatically
#reclaimed
| true |
655c7e3810af8e5c502f65f2a95892598a45e1b9 | anila-a/CEN-206-Data-Structures | /lab04/mainPolygon.py | 1,306 | 4.5625 | 5 | '''
Program: mainPolygon.py
Author: Anila Hoxha
Last date modified: 03/21/2020
Design a class named Polygon to represent a regular polygon. In regular
polygon, all the sides have the same length. The class contains:
Constructor: Instance Variable: n – number of sides with default value 3,
side – length of the side with default value 1.
Methods:
• Getters and Setters methods for all instance variables
• getPerimeter() that returns the perimeter of the polygon.
• getArea() that returns the area of the polygon.
Use the following test program mainPolygon.py that creates two Polygon objects - one
with no-arg constructor and the other with Polygon(8, 5).
'''
from polygon import * # Import Polygon class from polygon.py file
# Create objects
poly1 = Polygon()
poly2 = Polygon(8, 5)
print("Polygon 1: ")
print(" # of sides: ", poly1.getN())
print(" length of a side: ", poly1.getSide())
print(" Area: %.2f" %poly1.getArea())
print(" Perimeter: ", poly1.getPerimeter())
print("Polygon 2: ")
print(" # of sides: ", poly2.getN())
print(" length of a side: ", poly2.getSide())
print(" Area: %.2f" %poly2.getArea())
print(" Perimeter: ", poly2.getPerimeter())
| true |
84f6fd7694a4f63abc9c445f7a2d0a6c13ab57a8 | anila-a/CEN-206-Data-Structures | /hw01/hw1_2.py | 868 | 4.125 | 4 | '''
Program: hw1_2.py
Author: Anila Hoxha
Last date modified: 04/2/2020
Consider the Fibonacci function, F(n), which I defined such that
𝐹(1) = 1, 𝐹(2) = 2, 𝑎𝑛𝑑 𝐹(𝑛) = 𝐹(𝑛 − 2) + 𝐹(𝑛 − 1) 𝑓𝑜𝑟 𝑛 > 2.
Describe an efficient algorithm for determining first n Fibonacci numbers. What is the running time of
your algorithm, “Big-Oh”?
'''
def fibonacci(n):
a = 0 # O(1)
b = 1 # O(1)
if n == 1: # O(1)
print(a)
elif n == 2: # O(1)
print(a)
print(b)
else: # O(1)
print(a)
print(b)
for i in range(3, n+1): # O(n)
c = a + b # O(n)
print(c) # O(n)
# Exchange values for incrementation
a = b # O(n)
b = c # O(n)
n = int(input("Enter the value of n: ")) # O(1)
fibonacci(n) | true |
500e415d59727e99428a28bb85835e81a35eb836 | anila-a/CEN-206-Data-Structures | /midterm/Q1/main_Q1.py | 439 | 4.25 | 4 | '''
Program: main_Q1.py
Author: Anila Hoxha
Last date modified: 05/14/2020
Implement a program that can input an expression in postfix notation (see
Exercise C-6.22) and output its value.
'''
from postfix import *
''' Test the program with sample input: 52+83-*4/ '''
exp = str(input("Enter the expression: ")) # Read the user input
print("Postfix evaluation:", postfix(exp)) # Print the postfix evaluation of the expression
| true |
ac14eab101249ad1f9e19f01f9add32ad7e01e7a | anila-a/CEN-206-Data-Structures | /lab04/mainFlight.py | 1,761 | 4.5 | 4 | '''
Program: mainFlight.py
Author: Anila Hoxha
Last date modified: 03/21/2020
Design then implement a class to represent a Flight. A Flight has a flight
number, a source, a destination and a number of available seats. The class should have:
• A constructor to initialize the 4 instance variables. You must shorten the name of
the source and the destination by calling the method
shortAndCapital(name).
• Accessor/getters methods for each one of the 4 instance variables.
• Mutator/setters methods for each one of the 4 instance variables except the
flight number instance variable.
• A method reserve(numberOfSeats) to reserve seats on the flight.
(NOTE: You must check that there is enough number of seats to reserve)
• A function cancel(numberOfSeats) to cancel one or more reservations.
• A toString method to easily return the flight information as follows:
A method equal to compare 2 flights.
(NOTE: 2 Flights considered being equal if they have the same flight number,
flg1.equal(flg2))
• A method shortAndCapital(name) to shorten the name of the source and
destination to 3 characters only if it is longer than 3 characters.
'''
from flight import * # Import Flight class from flight.py file
# Create objects
flg1 = Flight(flightNr = 5432, source = "Tirana", destination = "Vienna", seatsNr = 100)
flg2 = Flight(flightNr = 2345, source = "Vienna", destination = "Munich", seatsNr = 100)
# Reserve
nrR = int(input("Enter the number of seats you want to reserve: "))
flg1.reverse(nrR)
# Cancel
nrC = int(input("Enter the number of seats you want to cancel: "))
flg1.cancel(nrC)
# Print flight information
print("Your flight information: ")
flg1.toString()
# Compare two flights
Flight.compare(flg1, flg2)
| true |
3d4cbfbfc5da19abbc3fd2b8c9e99d4192f48e4c | anila-a/CEN-206-Data-Structures | /midterm/Q2/B/singlyQueue.py | 2,276 | 4.1875 | 4 | '''
Program: singlyQueue.py
Author: Anila Hoxha
Last date modified: 05/16/2020
Write a singlyQueue class, using a singly linked list as storage. Test your class in testing.py
by adding, removing several elements. Submit, singlyQueue.py and testing.py.
'''
class SinglyQueue:
# FIFO queue implementation using a singly linked list for storage
class _Node:
__slots__ = '_element', '_next'
def __init__(self, element, next): # Constructor
self._element = element # Value of the node
self._next = next # Reference to the next node
def __init__(self): # Constructor
# Create an empty queue
self._head = None # No initial value
self._tail = None # No initial value
self._size = 0
def __len__(self): # Find the length of the queue
return self._size # Return the number of elements in the queue
def is_empty(self): # Check if the queue is empty or not
return self._size == 0 # Return True if the queue is empty
def first(self):
# Return (but do not remove) the element at the front of the queue
if self.is_empty(): # If the queue is empty
return ('Queue is empty') # If so, return this statement
return self._head._element # If not, return the first element in the queue
def dequeue(self):
# Remove and return the first element of the queue
if self.is_empty(): # If the queue is empty
return ('Queue is empty') # If so, return this statement
ans = self._head._element
self._head = self._head._next
self._size -= 1 # Decrement size by 1
if self.is_empty(): # Special case as queue is empty
self._tail = None # Removed head had been the tail
return ans
def enqueue(self, e):
# Add an element to the back of queue
newest = self._Node(e, None) # Node will be new tail node
if self.is_empty(): # If the queue is empty
self._head = newest # Special case: previously empty
else:
self._tail._next = newest # Tail node references to the newest node
self._tail = newest # Update reference to tail node
self._size += 1 # Increment size with one
| true |
fd59412ce8e23b59d93543166848d4c9ff9f25b6 | urmidedhia/Unicode | /Task1Bonus.py | 1,543 | 4.28125 | 4 | number = int(input("Enter number of words : "))
words = []
print("Enter the words : ")
for i in range(number): # Taking input in a list words
element = input()
words.append(element)
dist = []
for word in words: # Adding distinct words to a list dist
if word not in dist:
dist.append(word)
distinct = len(dist) # Number of distinct words is length of list dist
print("Number of distinct words is", distinct)
occur = []
for word in dist: # Adding number of occurrences of each distinct word in a list occur
count = 0
for item in words:
if word == item:
count += 1
occur.append(count)
print(count) # Printing number of occurrences of each distinct word
for j in range(distinct): # Arranging both the lists in descending order of occurrences
for i in range(j + 1, distinct): # Since length of dist is same as length of occur
if occur[j] < occur[i]:
temp = dist[j] # Swapping in dist list
dist[j] = dist[i]
dist[i] = temp
temp = occur[j] # Swapping in occur list
occur[j] = occur[i]
occur[i] = temp
print("The input in descending order of occurrences is : ", dist)
print("The most repeated word is : ", dist[0])
print("The least repeated word is : ", dist[-1])
| true |
d161e2a732a5c0c15610d8145b428419b87bcd9a | Yaasirmb/Alarm-Clock | /alarm.py | 602 | 4.125 | 4 | from datetime import datetime
import time
from playsound import playsound
#Program that will act as an alarm clock.
print("Please enter your time in the following format: '07:30:PM \n")
def alarm (user = input("When would you like your alarm to ring? ")):
when_to_ring = datetime.strptime(user, '%I:%M:%p').time()
while True:
time.sleep(2)
current_time = datetime.now().time().strftime("%I:%M:%p")
if when_to_ring.strftime("%I:%M:%p") == current_time:
playsound('wake_up.mp3')
print('Current time ' + current_time)
alarm() | true |
5c4d4fd464c0fa9bbb58f4f34125cff05b1a3d57 | PauloHARocha/accentureChallenge | /classification_naiveBayes.py | 2,036 | 4.125 | 4 | import pandas as pd
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn import metrics
# Naive Bayes
# The objective of this module is to classify the data from the pre-processed dataset,
# based on the alignment of each hero (good or bad), using the Naive Bayes algorithm.
# Question 3:
# 1- The Naive Bayes algorithm is a classifier based on the Bayes' theorem,
# which is based on conditional probability. It is a probabilistic algorithm that
# returns the probability of each entry belonging to a class. Two assumptions are
# made by this algorithm, the first is that the features are independent, and the second
# is that all features have an equal effect on the classification. Because of this assumptions
# the algorithm is called 'Naive'.
#
# 2- Due to the large number of categorical variables and most of them having several categories,
# it was decided to reduce the number of categories and to transform each category into a column
# representing whether or not the hero has such a characteristic. Due to the same characteristics
# of the data set it was chosen to use the Multinomial Naive Bayes algorithm, which has a better
# performance with this type of data.
#
# 3- Accuracy is being used as a metric to evaluate the model result,
# Read pre-processsed dataset
df = pd.read_csv('datasets/info_power_processed.csv')
X = df.drop(columns=['name', 'Alignment'])
# Classifying in good or bad
y = df['Alignment']
# Split dataset into training set and test set # 70% training and 30% test
X_train, X_test, y_train, y_test = train_test_split(X, y.values.ravel(),
test_size=0.3,random_state=109)
# Initialize algorithm
clf = MultinomialNB()
# Training model
clf.fit(X_train, y_train)
# Predicting test cases
y_pred = clf.predict(X_test)
# Model Accuracy
print("Accuracy:",metrics.accuracy_score(y_test, y_pred)) | true |
770dc7e863343aabae12f23a99b7da024c5827d1 | ZakOpry/digital-crafts | /week1/day3/introToPython4.py | 271 | 4.15625 | 4 | # Conditionals
print("Welcome to this program")
firstName = input("What is your first name?")
length_of_first_name = len(firstName)
print(firstName)
if length_of_first_name <= 0:
print("Please enter at least one character")
else:
print(f"Hello {firstName}")
| true |
07b213e5a72caa2ce55966adfcdeb5ddf8b05362 | HughesSvynnr/prg1_homework | /hw4.py | 1,891 | 4.125 | 4 | '''
problem 1
Ask a user for a number. Depending on the number, respond with how many factors exist within that number
for example:
Enter a number
>15
15 has 4 factors, which are 1 3 5 15
'''
'''
problem 2
Write a program that will ask a user for a word. For that word, replace each letter with
the appropriate letter of the phonetic alphabet.
For instance
Enter a word
>balloon
Bravo Alpha Lima Lima Oscar Oscar November
'''
#problem 1
print("give me a whole number")
number = input("> ")
factors = []
for x in range(1, int(number)+1):
if(int(number)%x==0):
factors.append(x)
print(number, " has ",len(factors)," factors. ",factors)
#problem 2
print("Type a word")
word = input("> ")
word_split = word.split(" ")
for x in word:
if(x=="a"):
print("Alpha")
elif(x=="b"):
print("Bravo")
elif(x=="c"):
print("Charlie")
elif(x=="d"):
print("Delta")
elif(x=="e"):
print("Echo")
elif(x=="f"):
print("Foxtrot")
elif(x=="g"):
print("Golf")
elif(x=="h"):
print("Hotel")
elif(x=="i"):
print("Indigo")
elif(x=="j"):
print("Juliet")
elif(x=="k"):
print("Kilo")
elif(x=="l"):
print("Lima")
elif(x=="m"):
print("Mike")
elif(x=="n"):
print("November")
elif(x=="o"):
print("Oscar")
elif(x=="p"):
print("Papa")
elif(x=="q"):
print("Quatar")
elif(x=="r"):
print("Romeo")
elif(x=="s"):
print("Siera")
elif(x=="t"):
print("Tango")
elif(x=="u"):
print("Uniform")
elif(x=="v"):
print("Victor")
elif(x=="w"):
print("Whiskey")
elif(x=="x"):
print("X-ray")
elif(x=="y"):
print("Yankee")
elif(x=="z"):
print("Zulu")
else:
print("Not word try english again")
| true |
be0d9eb645a4aeadd0f5dc9e5c78336aba9d7527 | IvanKelber/plattsburgh-local-search | /Circles/circle.py | 2,119 | 4.15625 | 4 | # Created by Ivan Kelber, March 2017
import sys
import random
import math
def circles(points):
'''
- points is a list of n tuples (x,y) representing locations of n circles.
The point (x,y) at points[i] represents a circle whose center is at
(x,y) and whose radius is i.
This function returns the side of the smallest possible square that can
surround each of these circles such that no two circles are overlapping.
If two circles are found to be overlapping this function will return
sys.maxint.
'''
minX = sys.maxint
maxX = 0
minY = sys.maxint
maxY = 0
distance = [[1000 for i in range(len(points))] for j in range(len(points))]
for radius in range(len(points)):
point = points[radius]
#Update X
minX = min(minX,point[0]-radius)
maxX = max(maxX,point[0]+radius)
#Update Y
minY = min(minY,point[1]-radius)
maxY = max(maxY,point[1]+radius)
for radius2 in range(len(points)):
point2 = points[radius2]
if point is not point2:
distance[radius][radius2] = dist(point,point2,radius,radius2)
if(distance[radius][radius2] < 0):
# printDistance(distance)
return sys.maxint
# printDistance(distance)
return max(maxY-minY,maxX-minX)
def printDistance(distanceMatrix):
'''
Used to print out the distance matrix computed in the circles function;
primarily for debugging.
'''
for i in range(len(distanceMatrix)):
row = ""
for j in range(len(distanceMatrix)):
row += str(distanceMatrix[i][j]) + "\t"
print row
def dist(a,b,ra,rb):
'''
- a,b are centers of circles
- ra,rb are the respective radii of those two circles.
This function calculates the distance between the edges of two circles.
Note that this returns a negative value if two circles are overlapping.
'''
return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) - (ra + rb)
def main():
pass
if __name__ == '__main__':
main()
| true |
743606a3c25a96d1e7addb7ac6294bc04319f527 | NaughtyJim/learning-python | /2019-09-16/trees.py | 898 | 4.34375 | 4 | def main():
width = input('How wide should the tree be? ')
height = input('How tall should the tree be? ')
print("Here's your tree:")
print()
width = int(width)
height = int(height)
# this is the call if we omit the height
# print_tree(width, width // 2 + width % 2)
print_tree(width, height)
def print_tree(width, height):
# initialize i depending on whether the width is odd or even
i = 2 - width % 2
trunk_count = i
h = 0
# how often should we increment the number of leaves?
increment_step = int(2 * height / width)
while h < height:
print(' ' * ((width - i) // 2), '*' * i)
h += 1
if h % increment_step == 0 and i < width:
i += 2
print_trunk(width, trunk_count)
def print_trunk(width, count):
print(' ' * ((width - 1) // 2), '|' * count)
if __name__ == '__main__':
main()
| true |
a32ecf010adc0c1fde48a03a73def9282c101def | Pallavi2000/heraizen_internship | /internship/M_1/digit.py | 388 | 4.21875 | 4 | """program to accept a number from the user and determine the sum of digits of that number.
Repeat the operation until the sum gets to be a single digit number."""
n=int(input("Enter the value of n: "))
temp=n
digit=n
while digit>=10:
digit=0
while not n==0 :
r=n%10
digit+=r
n=n//10
n=digit
print(f"Given Number : {temp} Sum of Digits : {digit}")
| true |
82b7d80de1f353d744906bbe3203149cad2299e2 | Pallavi2000/heraizen_internship | /internship/armstrong.py | 291 | 4.375 | 4 | """Program to check whether a given number is armstrong number or not"""
n=int(input("Enter the value of n: "))
temp=n
sum=0
while not temp==0:
r=temp%10
sum+=r**3
temp=temp//10
if n==sum:
print(f"{n} is a armstrong number")
else:
print(f"{n} is not a armstrong number") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.