blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3b3012a175b7e66ea1d9d57b493b6df098ae68f3 | peterhchen/runBookAuto | /code/example/01_Intro/03_UnitConv.py | 449 | 4.28125 | 4 | #!/usr/bin/python3
# Problem: Receive miles and convert to kilometers
# kilometers = miles * 1.6
# Enter Miles 10.
# 10 Miles euqls to 16 kilometer.
# ask the user to input miles and assign it to the mile variable.
mile = input ('Enter Mile: ')
# Convert the string to integer.
mile = int (mile)
# Perform multiplication 1.6
kilometer = mile * 1.6034
# print result using format.
print ("{} mile equals {} kilometer ".format (mile, kilometer))
| true |
c208d5ee251a4de8b5d953ad057143ab9ef49bb2 | peterhchen/runBookAuto | /code/example/01_Intro/04_Calculator.py | 655 | 4.40625 | 4 | #!/usr/bin/python3
# Enter Calculator: 3 * 6
# 3 * 6 = 18
# Store the user input of 2 number and operator.
num1, oper , num2 = input ('Enter Calculator: ').split()
# Conver the strings into integers
num1 = int (num1)
num2 = int (num2)
# if + then need to provide the output based on addition
# Print the result.
if oper == '+':
print ("{} + {} = {}".format(num1, num2, num1+num2))
elif oper == "-":
print ("{} - {} = {}".format(num1, num2, num1-num2))
elif oper == "*":
print ("{} * {} = {}".format(num1, num2, num1*num2))
elif oper == "/":
print ("{} / {} = {}".format(num1, num2, num1/num2))
else:
print ("Only support + - * .")
| true |
4a425f72e61d4dd08b5c413a2ecec116ec5c767e | jamariod/Day-5-Exercises | /WordSummary.py | 397 | 4.1875 | 4 | # Write a word_histogram program that asks the user for a sentence as its input, and prints a dictionary containing the tally of how many times each word in the alphabet was used in the text.
any_word = input(
"Enter any word to tally how many times each letter in the alphabet was used in the word: ")
word_split = any_word.split(' ')
i = {a: any_word.count(a) for a in word_split}
print(i)
| true |
641aae71ec1efa9634631c16e6b8faa5f4742706 | boringPpl/Crash-Course-on-Python | /Exercises on IDE/7 String/ex7_2_string.py | 614 | 4.375 | 4 | '''Question 7.2:
Using the format method, fill in the gaps in the convert_distance function
so that it returns the phrase "X miles equals Y km", with Y having only 1 decimal place.
For example, convert_distance(12) should return "12 miles equals 19.2 km".
'''
def convert_distance(km):
miles = km * 0.621 # 1km is equal to approximately 0.621 miles
result = "{} km equals {} miles"
return result
print(convert_distance(19.2)) # Should be: 19.2 km equals 11.92 miles
print(convert_distance(8.8)) # Should be: 8.8 km equals 5.46 miles
print(convert_distance(17.6)) # Should be: 17.6 km equals 10.92 miles
| true |
59155ff91c8651d8db1bd9273b46e12b9de074c1 | boringPpl/Crash-Course-on-Python | /Exercises on IDE/6 For Loops/ex6_2_for.py | 441 | 4.65625 | 5 | '''Question 6.2:
This function prints out a multiplication table
(where each number is the result of multiplying the first number
of its row by the number at the top of its column).
Fill in the blanks so that calling mul_table(1, 3) will print out:
1 2 3
2 4 6
3 6 9
'''
def mul_table(start, stop):
for x in ___:
for y in ___:
print(str(x*y), end=" ")
print()
mul_table(1, 3)
# Should print the multiplication table shown above | true |
2f0d5f695e42fb4e7027352362c147ba68a491be | boringPpl/Crash-Course-on-Python | /Exercises on IDE/3 Function/ex3_2_function.py | 994 | 4.65625 | 5 | ''' Question 3.2:
This function converts kilometers (km) to miles.
1. Complete the function. Your function receive the input kilometers, and return the value miles
2. Call the function to convert the trip distance from kilometers to miles
3. Fill in the blank to print the result of the conversion
4. Calculate the round-trip in miles by doubling the result, and fill in the blank to print the result
'''
# 1) Complete the function to return the result of the conversion
def convert_distance(km):
miles = km * 0.621 # 1km is equal to approximately 0.621 miles
return miles
trip_in_km = 50
# 2) Convert trip_in_km to miles by calling the function above
trip_in_miles = convert_distance(trip_in_km)
# 3) Fill in the blank to print the result of the conversion
print("The distance in miles is " + str(trip_in_miles))
# 4) Calculate the round-trip in miles by doubling the result,
# and fill in the blank to print the result
print("The round-trip in miles is " + str(trip_in_miles * 2))
| true |
3664bf0af663c33035ab8e699dd1f2d5f8af76cc | boringPpl/Crash-Course-on-Python | /Exercises on IDE/6 For Loops/ex6_3_for.py | 636 | 4.6875 | 5 | '''Question 6.3:
The display_even function returns a space-separated string
of all positive numbers that are divisible by 2, up to and
including the maximum number that's passed into the function.
For example, display_even(4) returns “2 4”. Fill in the blank to make this work.
'''
def display_even(max_num):
return_string = ""
for x in ___:
return_string += str(x) + " "
return return_string.strip()
print(display_even(6)) # Should be 2 4 6
print(display_even(10)) # Should be 2 4 6 8 10
print(display_even(1)) # No numbers displayed
print(display_even(3)) # Should be 2
print(display_even(0)) # No numbers displayed | true |
2cf55be5afac37d8737a9e4254ffccb2394ce111 | nigelginau/practicals_cp1404 | /prac_03/password_entry.py | 872 | 4.3125 | 4 | """" Nigel Ginau """
""""write a program that asks the user for a password, with error-checking to repeat if the password doesn't meet a minimum length set by a variable.
The program should then print asterisks as long as the password.
Example: if the user enters "Pythonista" (10 characters), the program should print "**********"."""""
minimum_length = 5
length_of_password = 0
while length_of_password < minimum_length:
password = input("Please input your password :")
length_of_password = len(password)
print("Password must be more than {0} characters and greater than {1} characters".format(minimum_length,
length_of_password))
print("Password is the correct length of {} characters".format(minimum_length))
asterisks = length_of_password * "*"
print(asterisks)
| true |
e00334f1474a2caa644d4f60498ffc3497570701 | Arslan0510/learn-basic-python | /3strings.py | 574 | 4.40625 | 4 | language = 'Python'
# print(len(language))
# Access each individual letter
# letter = language[3]
# letter = language[0:3] # first to third letter
# letter = language[1:] # skip first letter and show all the remaining part
letter = language[-1] # get reverse of string
# String Methods
languageString = 'Street of The Dead White Walkers RIP 1 EPISODE'
upper_language = languageString.upper()
lower_language = languageString.lower()
find_text = languageString.find("Dead")
replace_text = languageString.replace("White", "Black")
print(replace_text)
| true |
7866ce25883a04152b4587c683ff0be544a85ce5 | bigbillfighter/Python-Tutorial | /Part1/chap9_p2.py | 845 | 4.21875 | 4 | #the python library practise
from collections import OrderedDict
favourite_languages = OrderedDict()
favourite_languages['Lily'] = 'C'
favourite_languages['Max'] = 'Ruby'
favourite_languages['Lucas'] = 'Java'
favourite_languages['Peter'] = 'C'
for name, language in favourite_languages.items():
print(name.title()+"'s favourite language is "+language.title())
#random library includes the meethods that generate random numbers
#for example, randint(a, b) can return an integer that between a and b
from random import randint
num = list(range(1, 7))
for i in range(1,10000):
x = randint(1,6)
num[x-1]+=1
print(num)
#when we define classes, we let all the first letters capital instead of using '_'
#like what we do on functions
#for example: class MyFavouriteFood():
#def get_my_favourite_food(self): | true |
a2aaf99fcc1b5ce257d8506092ed273c1fd432a3 | amitsindoliya/datastructureandalgo | /selection_sort.py | 577 | 4.3125 | 4 | ## selection Sort ##
## In selection sort we find the minimum element or maximum element
# of the list and place it at the start
# continue this operation until we have an sorted array
# complexity O(N^2)/2
# unstable
def selection_sort(iterable):
for i in range(len(iterable)-1):
for j in range(i+1,len(iterable)):
if iterable[j] < iterable[i]:
iterable[i], iterable[j] = iterable[j], iterable[i]
return iterable
if __name__ == "__main__":
iterable = [ 4,2,5,2,-6,2,8,5,2,1,8]
print(selection_sort(iterable))
| true |
f65d0d677044624e03d82e2f43cb8c48a94f7226 | razmikmelikbekyan/ACA_2019_python_lectures | /homeworks/CapstoneProject/database/books.py | 1,422 | 4.28125 | 4 | from typing import Dict, List
BOOKS = "database/books.txt"
def create_books_data():
"""
Creates an empty txt file for storing books data. If the file already exists, it should
not do anything.
"""
pass
def get_all_books() -> List[Dict]:
"""Returns all books data in a list, where each item in a list is one book."""
pass
def find_book(code: str) -> Dict:
"""
Finds book by its code in library and returns it's data in the form of dict. If the book is not
in the library, return an empty dict.
For example:
{
'code': 'a1254',
'name': 'The Idiot',
'author': 'Fyodor Dostoyevsky',
'quantity': 4,
'available_quantity': 2
}
"""
pass
def add_book(code: str, name: str, author: str, quantity: int):
"""Adds given book to the database, which is a txt file, where each row is book."""
pass
def delete_book(code: str):
"""Deletes book from database."""
pass
def _interact_with_user(code: str, increase: bool):
"""
Helper function for interacting with user. It increases or decreases available_quantity by 1.
"""
pass
def give_book_to_user(code: str):
"""
Gives book to user from library: decreases book available_quantity by 1.
"""
pass
def get_book_from_user(code: str):
"""
Gets book from user back to library: increases book available_quantity by 1.
"""
pass
| true |
cc9f9dc9810af12141c6f005a9b951c25bffd1e0 | lowks/py-etlt | /etlt/cleaner/DateCleaner.py | 1,871 | 4.3125 | 4 | import re
class DateCleaner:
"""
Utility class for converting dates in miscellaneous formats to ISO-8601 (YYYY-MM-DD) format.
"""
# ------------------------------------------------------------------------------------------------------------------
@staticmethod
def clean(date):
"""
Converts a date in miscellaneous format to ISO-8601 (YYYY-MM-DD) format.
:param str date: The input date.
:rtype str:
"""
# Return empty input immediately.
if not date:
return date
parts = re.split('[\-/\. ]', date)
if len(parts) == 3 or (len(parts) == 4 and (parts[3] in ('00:00:00', '0:00:00'))):
if len(parts[0]) == 4 and len(parts[1]) <= 2 and len(parts[2]) <= 2:
# Assume date is in YYYY-MM-DD of YYYY-M-D format.
return parts[0] + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[2])[-2:]
if len(parts[0]) <= 2 and len(parts[1]) <= 2 and len(parts[2]) == 4:
# Assume date is in DD-MM-YYYY or D-M-YYYY format.
return parts[2] + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[0])[-2:]
if len(parts[0]) <= 2 and len(parts[1]) <= 2 and len(parts[2]) == 2:
# Assume date is in DD-MM-YY or D-M-YY format.
year = '19' + parts[2] if parts[2] >= '20' else '20' + parts[2];
return year + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[0])[-2:]
if len(parts) == 1 and len(date) == 8:
# Assume date is in YYYYMMDD format.
return date[0:4] + '-' + date[4:2] + '-' + date[6:2]
# Format not recognized. Just return the original string.
return date
# ----------------------------------------------------------------------------------------------------------------------
| true |
5f59166ef3478ece7bb0bed7ea6e3fc02ef1ca44 | sb17027/ORS-PA-18-Homework07 | /task4.py | 1,336 | 4.34375 | 4 | """
=================== TASK 4 ====================
* Name: Number of Appearances
*
* Write a function that will return which element
* of integer list has the greatest number of
* appearances in that list.
* In case that multiple elements have the same
* number of appearances return any.
*
* Note: You are not allowed to use built-in
* functions.
*
* Note: Please describe in details possible cases
* in which your solution might not work.
*
* Use main() function to test your solution.
===================================================
"""
# Write your function here
def mostOccurences(arr):
mostNumber = arr[0]
maxNumberOfOccurences = 1
currNumberOfOccurences = 0
currNumber = 0
i = 1
while i < len(arr):
currNumber = arr[i]
currNumberOfOccurences = 0
j = 0
while j < len(arr):
if(arr[j] == currNumber):
currNumberOfOccurences = currNumberOfOccurences + 1
j = j + 1
if currNumberOfOccurences > maxNumberOfOccurences:
maxNumberOfOccurences = currNumberOfOccurences
mostNumber = currNumber
i = i + 1
return mostNumber
def main():
arr = [1, 3, 4, 6, 1, 1, 12, 12, 12, 12, 12, 12, 12]
mostNumber = mostOccurences(arr)
print("Number with most occurences: ", mostNumber)
main()
| true |
115490da841034c40a2c2c3029adede809f4c499 | mali0728/cs107_Max_Li | /pair_programming/PP9/fibo.py | 1,017 | 4.25 | 4 | """
PP9
Collaborators: Max Li, Tale Lokvenec
"""
class Fibonacci: # An iterable b/c it has __iter__
def __init__(self, val):
self.val = val
def __iter__(self):
return FibonacciIterator(self.val) # Returns an instance of the iterator
class FibonacciIterator: # has __next__ and __iter__
def __init__(self, val):
self.index = 0
self.val = val
self.previous = 1
self.previous_previous = 0
def __next__(self):
if self.index < self.val:
next_value = self.previous + self.previous_previous
self.previous_previous = self.previous
self.previous = next_value
self.index += 1
return next_value
else:
raise StopIteration()
def __iter__(self):
return self # Allows iterators to be used where an iterable is expected
if __name__ == "__main__":
fib = Fibonacci(10)
print(list(iter(fib)))
fib2 = Fibonacci(2)
print(list(iter(fib2))) | true |
6a98a213ff9063964adc7731056f08df3ac755ae | gatisnolv/planet-wars | /train-ml-bot.py | 2,062 | 4.25 | 4 | """
Train a machine learning model for the classifier bot. We create a player, and watch it play games against itself.
Every observed state is converted to a feature vector and labeled with the eventual outcome
(-1.0: player 2 won, 1.0: player 1 won)
This is part of the second worksheet.
"""
from api import State, util
# This package contains various machine learning algorithms
import sys
import sklearn
import sklearn.linear_model
from sklearn.externals import joblib
from bots.rand import rand
# from bots.alphabeta import alphabeta
from bots.ml import ml
from bots.ml.ml import features
import matplotlib.pyplot as plt
# How many games to play
GAMES = 1000
# Number of planets in the field
NUM_PLANETS = 6
# Maximum number of turns to play
NUM_TURNS = 100
# Train for symmetric start states
SYM = True
# The player we'll observe
player = rand.Bot()
# player = alphabeta.Bot()
data = []
target = []
for g in range(GAMES):
state, id = State.generate(NUM_PLANETS, symmetric=SYM)
state_vectors = []
i = 0
while not state.finished() and i <= NUM_TURNS:
state_vectors.append(features(state))
move = player.get_move(state)
state = state.next(move)
i += 1
winner = state.winner()
for state_vector in state_vectors:
data.append(state_vector)
if winner == 1:
result = 'won'
elif winner == 2:
result = 'lost'
else:
result = 'draw'
target.append(result)
sys.stdout.write(".")
sys.stdout.flush()
if g % (GAMES/10) == 0:
print("")
print('game {} finished ({}%)'.format(g, (g/float(GAMES)*100)))
# Train a logistic regression model
learner = sklearn.linear_model.LogisticRegression()
model = learner.fit(data, target)
# Check for class imbalance
count = {}
for str in target:
if str not in count:
count[str] = 0
count[str] += 1
print('instances per class: {}'.format(count))
# Store the model in the ml directory
joblib.dump(model, './bots/ml/model.pkl')
print('Done')
| true |
41895c829a967c20cb731734748fe7f407b364a3 | bats64mgutsi/MyPython | /Programs/graph.py | 2,244 | 4.28125 | 4 | # A program that draws the curve of the function given by the user.
# Batandwa Mgutsi
# 02/05/2020
import math
def getPointIndex(x, y, pointsPerWidth, pointsPerHeight):
"""Returns the index of the given point in a poinsPerWidth*pointsPerHeight grid.
pointsPerWidth and pointsPerHeight should be odd numbers"""
# These calculations take the top left corner as the (0;0) point
# and both axes increase from that point.
originRow = int(pointsPerHeight/2)
originColumn = int(pointsPerWidth/2)
# A positive x value increases the column, and vice versa
# A positive y value decrease the row since the above calculations took the row as increasing
# when going downwards.
pointRow = originRow - y
pointColumn = originColumn + x
index = pointRow*pointsPerWidth+pointColumn
return index
def printGraph(graph, pointsPerWidth, pointsPerHeight):
for row in range(pointsPerHeight):
for column in range(pointsPerWidth):
print(graph[row*pointsPerWidth+column], end='')
print()
def drawCurve(function, graph, pointsPerWidth, pointsPerHeight, fill='o'):
output = list(graph)
halfOfXAxis = int(pointsPerWidth/2)
for x in range(-halfOfXAxis, halfOfXAxis+1):
try:
# Using a try/except will prevent the program from crashing in case an error occurs while
# evaluating the function at the current x value. For example, if the function is a hyperbola
# the try/except will prevent the program from crashing when x is an asymptote of the function.
y = eval(function)
except:
continue
y = round(y)
pointIndex = getPointIndex(x, y, pointsPerWidth, pointsPerHeight)
if pointIndex < 0 or pointIndex >= len(buffer):
continue
else:
output[pointIndex] = fill
return output
# Using a grid with [-10, 10] endpoints
buffer = list(''.rjust(21*21))
# Draw the axes
for y in range(-10, 11):
buffer[getPointIndex(0, y, 21, 21)] = '|'
buffer = drawCurve('0', buffer, 21, 21, '-')
buffer[getPointIndex(0, 0, 21, 21)] = '+'
function = input('Enter a function f(x):\n')
buffer = drawCurve(function, buffer, 21, 21)
printGraph(buffer, 21, 21)
| true |
768ffb93219b9d95d73ec3075fbb191ed00837a6 | Tobi-David/first-repository | /miniproject.py | 625 | 4.15625 | 4 |
## welcome message
print("\t\t\tWelcome to mini proj! \nThis application helps you to find the number and percentage of a letter in a message.")
## User message input
user_message = input("This is my message ")
## user letter input
user_letter = input("this is my letter ")
## count letter in message
letter_freq = user_message.count(user_letter)
## calculate percentage
total_chr = len(user_message)
percentage = int(letter_freq/total_chr*100)
# # print result
print ("the count of", user_letter, "is", letter_freq )
print (f"the percentage of '{user_letter}' in '{user_message}' is {percentage} percent" )
| true |
637267a96a001520af71a7c748f1a05109726f5e | Colosimorichard/Choose-your-own-adventure | /Textgame.py | 2,513 | 4.15625 | 4 | print("Welcome to my first game!")
name = input("What's your name? ")
print("Hello, ", name)
age = int(input("What is your age? "))
health = 10
if age >= 18:
print("You are old enough to play.")
wants_to_play = input("Do you want to play? (yes/no) ").lower()
if wants_to_play == "yes":
print("You are starting with", health, "health")
print("Lets Play!")
left_or_right = input("First choice....Left or Right? (left/right) ").lower()
if left_or_right == "left":
ans = input("Nice, you follow the path and reach a lake....do you swim across or go around? (across/around) ").lower()
if ans == "around":
print("You go around and reached the other side of the lake.")
elif ans == "across":
print("You managed to get across but were bit by a fish and lost 5 health")
health -= 5
print("Your health is at", health)
ans = input("You notice a house and a river. Which do you go to? (river/house) ").lower()
if ans == "house":
print("You've entered the house and are greeted by the owner... He doesn't like you.")
ans = input("Give him a gift or spit in his eye? (gift/spit) ").lower()
if ans == "spit":
print("He did not like that and hit you over the head with a cane. You lose 5 health.")
health -= 5
if health <= 0:
print("You now have 0 health and you lose the game...Sucks to suck,", name,)
else:
print("Well,",name, ", your health is", health, "and you're not dead and im over this so You Win. Congratulations or whatever.")
quit()
if ans == "gift":
print("He decided not to hit you with a cane. You have", health, "health left. You survived. I don't want to do this anymore, You win,", name,)
else:
print("You fell in the river and drowned. Sucks to suck.")
else:
print("You fell in that giant well directly to your right that literally anyone could see. Seriously, how did you miss that? Sucks to suck. Buh bye!")
else:
print("Geez, fine. Buh Bye")
else:
print("You are not old enough to play. I don't know why this is a question in the first place. See ya.")
| true |
d3f40012da083979a5c97407e2e2b6a43346ece0 | december-2018-python/adam_boyle | /01-python/02-python/01-required/07-functions_intermediate_2.py | 2,453 | 4.15625 | 4 | # 1. Given
x = [[5,2,3], [10,8,9]]
students = [
{'first_name' : 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Rooney']
}
z = [ {'x': 10, 'y': 20} ]
x[1][0] = 15 # Changes the value 10 in x to 15
students[0]['last_name'] = 'Bryant' # Changes the last_name of the first student from 'Jordan' to 'Bryant'
sports_directory['soccer'][0] = 'Andres' # Changes 'Messi' to 'Andres' in sports_directory
z[0]['y'] = 30 # Changes the value 20 to 30
# 2. Create a function that given a list of dictionaries, it loops through each dictionary in the list and prints each key and the associated value. For example, given the following list:
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
def names():
i = 0
while i < len(students):
print('first_name -', students[i]['first_name'] + ',','last_name -', students[i]['last_name'])
i += 1
names()
# 3. Create a function that given a list of dictionaries and a key name, it outputs the value stored in that key for each dictionary.
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
def names():
i = 0
while i < len(students):
print(students[i]['first_name'])
i += 1
names()
#4. Say that
dojo = {
'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'],
'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon']
}
# Create a function that prints the name of each location and also how many locations the Dojo currently has. Have the function also print the name of each instructor and how many instructors the Dojo currently has.
def coding():
i = 0
print(len(dojo['locations']),'LOCATIONS')
while i < len(dojo['locations']):
print(dojo['locations'][i])
i += 1
print('')
i = 0
print(len(dojo['instructors']), 'INSTRUCTORS')
while i < len(dojo['instructors'][i]):
print(dojo['instructors'][i])
i += 1
coding() | true |
34533f19a443b7063a4637c798b97233006acc02 | Seon2020/data-structures-and-algorithms | /python/code_challenges/ll_zip/ll_zip.py | 698 | 4.375 | 4 | def zipLists(list1, list2):
"""
This function takes in two linked lists and merges them together.
Input: Two linked lists
Output: Merged linked list the alternates between values of the original two linked lists.
"""
list1_current = list1.head
list2_current = list2.head
while list1_current and list2_current:
list1_next = list1_current.next
list2_next = list2_current.next
list1_current.next = list2_current
list2_current.next = list1_next
last_list1_current = list1_current.next
list1_current = list1_next
list2_current = list2_next
if not list1_current and list2_current:
last_list1_current.next = list2_current
return list1
| true |
04f7f3d62fe77d102c4bf88ef08621bb6b0b1740 | Seon2020/data-structures-and-algorithms | /python/code_challenges/reverse_linked_list.py | 351 | 4.28125 | 4 | def reverse_list(ll):
"""Reverses a linked list
Args:
ll: linked list
Returns:
linked list in reversed form
"""
prev = None
current = ll.head
while current is not None:
next = current.next
current.next = prev
prev = current
current = next
ll.head = prev
return ll
| true |
d70c86867376ccb77491b6d1e20c3f1a0b98bfe2 | concon121/project-euler | /problem4/answer.py | 688 | 4.3125 | 4 | # A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
ZERO = 0
MIN = 100
MAX = 999
def isPalindrome(number):
reverse = str(number)[::-1]
if (str(number) == str(reverse)):
return True
else:
return False
lhs = MAX
palindromes = []
while (lhs >= MIN):
rhs = MAX;
while (rhs >= MIN):
palindrome = isPalindrome(lhs * rhs)
if (palindrome):
palindromes.append(lhs * rhs)
rhs = rhs -1
lhs = lhs - 1
print("The largest palindrome is: ", max(palindromes))
| true |
7af9a74b13af5cc1c52a70970744b0a837bc52ca | cepGH1/dfesw3cep | /convTemps.py | 413 | 4.21875 | 4 | #°F = (°C × 9/5) + 32.
#C =(F -32)*(5/9)
myInput = input("please enter the temperature using either 'F' or 'C' at the end to show the scale: ")
theNumber = int(myInput[:-1])
theScale = myInput[-1]
print(theNumber)
print(theScale)
if theScale == "C":
fahrenheit = (theNumber*(9/5)) + 32
print(fahrenheit, "F")
if theScale == "F":
centigrade = (theNumber - 32)*(5/9)
print(centigrade, "C")
| true |
1cb7a726b1074a78252ba83a4b358821fd6f6385 | LeoBaz20/Netflix-Style-Recommender | /netflix-style-recommender-master/PythonNumpyWarmUp.py | 1,770 | 4.28125 | 4 |
# coding: utf-8
# In[25]:
# Handy for matrix manipulations, likE dot product and tranpose
from numpy import *
# In[26]:
# Declare and initialize a 2d numpy array (just call it a matrix, for simplicity)
# This how we will be organizing our data. very simple, and easy to manipulate.
data = array([[1, 2, 3], [1, 2, 3]])
print (data)
# In[27]:
# Get dimensions of matrix
data.shape
# In[28]:
# Declare and initialize a matrix of zeros
zeros_matrix = zeros((1,2))
print (zeros_matrix)
# In[29]:
# Declare and initialize a matrix of ones
ones_matrix = ones((1,2))
print (ones_matrix)
# In[30]:
# Declare and initialize a matrix of random integers from 0-10
rand_matrix = random.randint(10, size = (10, 5))
print (rand_matrix)
# In[31]:
# Declare and initialize a column vector
col_vector = random.randint(10, size = (10, 1))
print (col_vector)
# In[32]:
# Access and print the first element of the column vector
print (col_vector[0])
# In[33]:
# Change the first element of the column vector
col_vector[0] = 100
print (col_vector)
# In[34]:
# Access and print the first element of rand_matrix
print (rand_matrix[0, 0])
# In[35]:
# Access and print the all rows of first column of rand_matrix
print (rand_matrix[:, 0:1])
# In[36]:
# Access and print the all columns of first row of rand_matrix
print (rand_matrix[0:1, :])
# In[37]:
# Access the 2nd, 3rd and 5th columns fo the first row rand_matrix
# Get the result in a 2d numpy array
cols = array([[1,2,3]])
print (rand_matrix[0, cols])
# In[38]:
# Flatten a matrix
flattened = rand_matrix.T.flatten()
print (flattened)
# In[39]:
# Dot product
rand_matrix_2 = random.randint(10, size = (5,2))
dot_product = rand_matrix.dot(rand_matrix_2)
print (dot_product)
# In[ ]:
| true |
52b9c167b058db6092d8f6b5dc760a306cc9b608 | jdellithorpe/scripts | /percentify.py | 1,497 | 4.15625 | 4 | #!/usr/bin/env python
from __future__ import division, print_function
from sys import argv,exit
import re
def read_csv_into_list(filename, fs):
"""
Read a csv file of floats, concatenate them all into a flat list and return
them.
"""
numbers = []
for line in open(filename, 'r'):
parts = line.split()
numbers.append(parts)
return numbers
def percentify(filename, column, fs):
# Read the file into an array of numbers.
numbers = read_csv_into_list(filename, fs)
acc = 0
for row in numbers:
acc += float(row[column-1])
for row in numbers:
i = 0
for col in row:
if i == column-1:
print("%f " % (float(row[i])/acc), end='')
else:
print(row[i] + " ", end='')
i += 1
print()
def usage():
doc = """
Usage: ./percentify.py <input-file> <column> <field_separator>
Percentify the values in a given column in a csv file. Replaces values
with their relative weight in the sum of the values in the column.
Sample Input File:
8 1
10 14
12 29
14 34
16 23
18 4
./percentify.py input.txt 2 " "
Sample Output:
8 0.0095
10 0.1333
12 0.2762
14 0.3238
16 0.2190
18 0.0381
"""
print(doc)
exit(0)
if __name__ == '__main__':
if len(argv) < 4:
usage()
percentify(argv[1], int(argv[2]), argv[3])
| true |
a4bd50b4ac26814d745411ca815aa8115c058d0c | bettymakes/python_the_hard_way | /exercise_03/ex3.py | 2,343 | 4.5 | 4 | # Prints the string below to terminal
print "I will now count my chickens:"
# Prints the string "Hens" followed by the number 30
# 30 = (30/6) + 25
print "Hens", 25 + 30 / 6
# Prints the string "Roosters" followed by the number 97
# 97 = ((25*3) % 4) - 100
# NOTE % is the modulus operator. This returns the remainder (ex 6%2=0, 7%2=1)
print "Roosters", 100 - 25 * 3 % 4
# Prints the string below to terminal
print "Now I will count the eggs:"
# Prints 7 to the terminal
# 4%2=[0], 1/4=[0]
# 3 + 2 + 1 - 5 + [0] - [0] + 6
# NOTE 1/4 is 0 and not 0.25 because 1 & 4 are whole numbers, not floats
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
# Prints the string below to terminal
print "Is it true that 3 + 2 < 5 - 7?"
# Prints false to the screen
# 5 < -2 is false
# NOTE the < and > operators check whether something is truthy or falsey
print 3 + 2 < 5 - 7
# Prints the string below followed by the number 5
print "What is 3 + 2?", 3 + 2
# Prints the string below followed by the number -2
print "What is 5 - 7?", 5 - 7
# Prints the string below to terminal
print "Oh, that's why it's False."
# Prints the string below to terminal
print "How about some more."
# Prints the string below followed by 'true'
print "Is it greater?", 5 > -2
# Prints the string below followed by 'true'
print "Is it greater or equal?", 5 >= -2
# Prints the string below followed by 'false'
print "Is it less or equal?", 5 <= -2
# ================================
# ========= STUDY DRILLS =========
# ================================
#1 Above each line, use the # to write a comment to yourself explaining what the line does.
### DONE!
#2 Remember in Exercise 0 when you started Python? Start Python this way again and using the math operators, use Python as a calculator.
### DONE :)
#3 Find something you need to calculate and write a new .py file that does it.
### See calculator.py file
#4 Notice the math seems "wrong"? There are no fractions, only whole numbers. You need to use a "floating point" number, which is a number with a decimal point, as in 10.5, or 0.89, or even 3.0.
### Noted.
#5 Rewrite ex3.py to use floating point numbers so it's more accurate. 20.0 is floating point.
### Only rewrote line 20 because that's the only statement that would be affected by floating points.
### Rewrote calculator.py as well :). | true |
77ff1d18e2d88269716f2eda2e09270d78d39840 | eckoblack/cti110 | /M5HW1_TestGrades_EkowYawson.py | 1,650 | 4.25 | 4 | # A program that displays five test scores
# 28 June 2017
# CTI-110 M5HW1 - Test Average and Grade
# Ekow Yawson
#
#greeting
print('This program will get five test scores, display the letter grade for each,\
\nand the average of all five scores. \n')
#get five test scores
score1 = float(input('Enter test score 1: '))
score2 = float(input('Enter test score 2: '))
score3 = float(input('Enter test score 3: '))
score4 = float(input('Enter test score 4: '))
score5 = float(input('Enter test score 5: '))
#display a letter grade for each score
def determine_grade(score):
if score >= 90:
print('letter grade: A')
elif score >= 80:
print('letter grade: B')
elif score >= 70:
print('letter grade: C')
elif score >= 60:
print('letter grade: D')
else:
print('letter grade: E')
return score
#display average test score
def calc_average(score1, score2, score3, score4, score5):
average = (score1 + score2 + score3 + score4 + score5) / 5
print('The average is: ', average)
return average
#define main
def main():
print('-----------------------------------------------------------------------')
print('Test score 1')
determine_grade(score1)
print('Test score 2')
determine_grade(score2)
print('Test score 3')
determine_grade(score3)
print('Test score 4')
determine_grade(score4)
print('Test score 5')
determine_grade(score5)
print('-----------------------------------------------------------------------')
calc_average(score1, score2, score3, score4, score5)
#run main
main()
| true |
40867a0b45d2f9f37f5d4bcfe0027bd954c82c36 | eckoblack/cti110 | /M6T1_FileDisplay_EkowYawson.py | 451 | 4.1875 | 4 | # A program that displays a series of integers in a text file
# 5 July 2017
# CTI-110 M6T1 - File Display
# Ekow Yawson
#
#open file numbers.txt
def main():
print('This program will open a file named "numbers.txt" and display its contents.')
print()
readFile = open('numbers.txt', 'r')
fileContents = readFile.read()
#close file
readFile.close()
#display numbers in file
print(fileContents)
#call main
main()
| true |
4fdb7741fa84ad336c029825adf0994f174aaa2b | ocean20/Python_Exercises | /functions/globalLocal.py | 602 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 16:41:56 2019
@author: cawang
"""
x = 2
def fun1():
x = 1
print("Inside function x =", x)
fun1() # Inside function x = 1
print("Outside function x =", x) # Outside function x = 2
def fun2():
print("Inside function x =", x)
fun2() # Inside function x = 2
# the function did not declare a local variable x, so it looked for the global one
def fun3():
print("Inside function x =", x)
x = 3
print("Inside function x after change:", x)
fun3()
# error: local variable 'x' referenced before assignment
| true |
128039caec432553bb36875e92b86d6578175728 | AndreasGustafsson88/assignment_1 | /assignments/utils/assignment_1.py | 1,179 | 4.46875 | 4 | from functools import lru_cache
"""
Functions for running the assignments
"""
def sum_list(numbers: list) -> int:
"""Sums a list of ints with pythons built in sum() function"""
return sum(numbers)
def convert_int(n: int) -> str:
"""Converts an int to a string"""
return str(n)
def recursive_sum(item: list) -> int:
"""Calculates the sum of a nested list with recursion"""
return item if isinstance(item, int) else sum_list([recursive_sum(i) for i in item])
@lru_cache
def fibonacci(n: int) -> int:
"""
Calculate the nth number of the fibonacci sequence using recursion.
We could memoize this ourselves but I prefer to use lru_cache to keep the function clean.
"""
return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2)
def sum_integer(number: int) -> int:
"""Calculates the sum of integers in a number e.g 123 -> 6"""
return sum_list([int(i) for i in convert_int(number)])
def gcd(a: int, b: int) -> int:
"""
Calculated the GCD recursively according to the Euclidean algorithm gcd(a,b) = gcd(b, r).
Where r is the remainder of a divided by b.
"""
return a if not b else gcd(b, a % b)
| true |
fd50491b2f67bc3b76ff3b1b5391952b0bed92eb | JonSeijo/project-euler | /problems 1-9/problem_1.py | 825 | 4.34375 | 4 | #Problem 1
"""
If we list all the natural numbers below 10
that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of
all the multiples of 3 or 5 below 1000.
"""
MAXNUM = 1000
def findMultiples(number):
"""Return a list with the multiples of the number,
between 1 and MAXNUMBER"""
multiples = []
for n in range(1, MAXNUM):
#If remainder is zero, is multiple
if n % number == 0:
multiples.append(n)
return multiples
def main():
answer = 0
multiples = findMultiples(3) + findMultiples(5)
#Remove numbers multiples of both 3 and 5 using set
multiples = set(multiples)
#Sum all the multiples
for n in multiples:
answer += n
print answer
if __name__ == "__main__":
main() | true |
ec2a73d8147e75ab14f1453c16295bb50e52a58e | JonSeijo/project-euler | /problems 50-59/problem_57.py | 1,689 | 4.125 | 4 | # -*- coding: utf-8 -*-
# Square root convergents
# Problem 57
"""
It is possible to show that the square root of two
can be expressed as an infinite continued fraction.
√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408,
but the eighth expansion, 1393/985, is the first example
where the number of digits in the numerator exceeds
the number of digits in the denominator.
In the first one-thousand expansions,
how many fractions contain a numerator with more digits than denominator?
"""
def crearSucesiones():
"""
Jonathan Seijo
Las fracciones que quiero analizar son:
1+(1/2), 1+(2/5), 1+(5/12), 1+(12/29), 1+(29/70),..
considero an/bn = (1/2), (2/5), (5/12), (12/29), (29/70), ..
puedo definir esta sucesion por recurrencia como:
a1 = 1
b1 = 2
an = b(n-1)
bn = 2*b(n-1) + a(n-1)
--> 'an' contiene al numerador en la posicion n
--> 'bn' contiene al denominador en la posicion n
"""
an = [1]
bn = [2]
for n in range(1, 1001):
an.append(bn[n-1])
bn.append(2*bn[n-1] + an[n-1])
return an, bn
def main():
# Creo las suceciones de numeradores y denominadores
an, bn = crearSucesiones()
answer = 0
for n in range(0, 1000):
# 1 + (an/bn) = (bn + an)/bn
if len(str(bn[n] + an[n])) > len(str(bn[n])):
answer += 1
print "answer: " + str(answer)
if __name__ == "__main__":
main()
| true |
a09e6de32320dca2795f35f7218ec5bd4d4f85bb | brennobrenno/udemy-python-masterclass | /Section 11/spam.py | 1,525 | 4.15625 | 4 |
def spam1():
def spam2():
def spam3():
z = " even"
z += y
print("In spam3, locals are {}".format(locals()))
return z
y = " more " + x # y must exist before spam3() is called
y += spam3() # do not combine these assignments
print("In spam2, locals are {}".format(locals()))
return y
# x = "spam" + spam2() # breaks because spam2() tries to use the value of x when it is called, but x does not
x = "spam" # x must exist before spam2() is called
x += spam2() # do not combine these assignments
print("In spam1, locals are {}".format(locals())) # yet have a value
return x
print(spam1())
# wherever possible, try to write functions so that they only use local variables and parameters
# only access global and nonlocal variables when it is absolutely necessary
# no matter how trivial the change you make, test the program thoroughly to make sure nothing has been broken
# often simple changes will break code
# if you write unexpected code, make sure to write a comment so the next person who looks at the code understands it
# and doesn't mess it up
# at the module level, the local scope is the same as the global scope
print(locals())
print(globals())
# free variables are returned by locals() when it is called in function blocks, but not in class blocks
# order in which python searches for names: local -> enclosing (nonlocal or free) -> global -> built_ins (python stuff)
| true |
1f6689ff4d8990151ca329843ec12486157182b3 | brennobrenno/udemy-python-masterclass | /Section 7 & 8/43.py | 863 | 4.21875 | 4 | # list_1 = []
# list_2 = list()
#
# print("List 1: {}".format(list_1))
# print("List 2: {}".format(list_2))
#
# if list_1 == list_2:
# print("The lists are equal")
#
# print(list("The lists are equal"))
# even = [2, 4, 6, 8]
# another_even = even
#
# another_even = list(even) # New list
# another_even2 = sorted(even, reverse=True) # Also new list
#
# print(another_even is even) # Same variable/thing
# print(another_even == even) # Same content
#
# print("another_even 2")
# print(another_even2 is even) # Same variable/thing
# print(another_even2 == even) # Same content
#
# another_even.sort(reverse=True)
# print(even)
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = [even, odd] # A list containing two lists
print(numbers)
for number_set in numbers:
print(number_set)
for value in number_set:
print(value) | true |
7a4c6e46d471dee68f06f28956a964fd56559912 | wesbasinger/LPTHW | /ex22/interactive.py | 1,213 | 4.15625 | 4 | print "Let's just take a little quiz."
print "On this section, you were supposed to just review."
points = 0
def print_score():
print "So far you have %d points." % points
print_score()
print '''
Here's your first question. Which of the following
objects have we talked about so far?
a Strings
b Integers
b Functions
d All of the above
'''
answer = raw_input(">>> ")
if answer.lower() == "d":
print "Good job!"
points += 1
else:
print "Nope, sorry."
print_score()
print '''
Here's another question. T/F Strings can be enclosed by
double OR single quotes.
T
F
'''
answer = raw_input('>>> ')
if answer.upper() == "T":
print "Good job!"
points += 1
else:
print "Nope, sorry."
print_score()
print '''
Here's another question. Will this command read a file?
file = open('somefile.txt')
yes
no
'''
answer = raw_input('>>> ')
if answer.lower() == "no":
print "Good job!"
points += 1
else:
print "Nope, sorry."
print_score()
print '''
One last question. What keyword makes a function 'give
back' a value and is frequently used at the end of a function?
'''
answer = raw_input('>>> ')
if answer.lower() == "return":
print "Good job!"
points += 1
else:
print "Nope, sorry."
print_score()
| true |
edaff19fc7b3ea2a8ab87e1ab10ad6c029009841 | wesbasinger/LPTHW | /ex06/practice.py | 739 | 4.34375 | 4 | # I'll focus mostly on string concatenation.
# Honestly, I've never used the varied types of
# string formatting, although I'm sure they're useful.
# Make the console print the first line of Row, Row, Row Your Boat
# Do not make any new strings, only use concatenation
first_part =
second_part =
# should print 'Row, row, row your boat Gently down the stream."
# ***please note*** the space is added for you
print first_part + " " + second_part
main_char = "Mary"
space = " "
verb = "had"
indef_art = "a"
adjective = "little"
direct_object = "lamb"
# should print 'Mary had a little lamb'
print YOUR CODE GOES HERE
one = "one"
one_digit = "1"
# should print 'Takes 1 to know one."
print "Takes " + XXX + " to know " + XXX + "."
| true |
cf4a99e1a7c7562f04bb9d68cc91673f7d108309 | wesbasinger/LPTHW | /ex21/interactive.py | 1,924 | 4.28125 | 4 | from sys import exit
def multiply_by_two(number):
return number * 2
def subtract_by_10(number):
return number - 10
def compare_a_greater_than_b(first_num, second_num):
return first_num > second_num
print "So far, you've done only printing with function."
print "Actually, most of the time you will want your"
print "function to return something."
print "Instead of printing the value to the screen,"
print "you save the value to variable or pass it in"
print "somewhere else."
print "These functions have been defined already for you."
print '''
def multiply_by_two(number):
return number * 2
def subtract_by_10(number):
return number - 10
def compare_a_greater_than_b(first_num, second_num):
return first_num > second_num
'''
print "Let's do some math with those."
print "Give this command: multiply_by_two(40)"
prompt = raw_input('>>> ')
if prompt == "multiply_by_two(40)":
multiply_by_two(40)
print "See, nothing was printed."
else:
print "Not quite, try again."
exit(0)
print "This time let's print the value."
print "Give this command: print multiply_by_two(40)"
prompt = raw_input('>>> ')
if prompt == "print multiply_by_two(40)":
print multiply_by_two(40)
print "See, that worked."
else:
print "Not quite, try again."
exit(0)
print "Let's do some more."
print "Give this command: compare_a_greater_than_b(5,5)"
prompt = raw_input('>>> ')
if prompt == "compare_a_greater_than_b(5,5)":
compare_a_greater_than_b(5,5)
print "See, nothing was printed."
else:
print "Not quite, try again."
exit(0)
print "This time let's save the value to a variable."
print "Give this command: result = compare_a_greater_than_b(5,5)"
prompt = raw_input('>>> ')
if prompt == "result = compare_a_greater_than_b(5,5)":
result = compare_a_greater_than_b(5,5)
print "Your value is stored in result."
print "Now I will print 'result' for you."
print result
else:
print "Not quite, try again."
exit(0)
| true |
50f7a379886e1b687eafe0ae37ff11c2461ec95b | wesbasinger/LPTHW | /ex40/interactive.py | 2,919 | 4.40625 | 4 | from sys import exit
print "This is point where things take a turn."
print "You can write some really great scripts and"
print "do awesome stuff, you've learned just about"
print "every major data type and most common pieces"
print "of syntax."
print "But, if you want to be a real programmer,"
print "and write applications and programs beyond"
print "simple utility scripts, you'll need to dive"
print "into object-oriented programming."
print "Press Enter when you're ready to read more."
raw_input()
print "The first step of OOP is using modules, which"
print "really are just other files that have your"
print "code in them. This is a great way to keep"
print "things organized."
print "I'll try as best I can to show you this in an"
print "interactive session."
print """
Imagine you have a file in the same directory as where
you are running this imaginary prompt. The file is
called stairway_to_heaven.py
This is a variable inside that file.
first_line = 'Theres a lady who's sure'
There is also a function.
def sing_chorus():
print 'And as we wind on down the road'
Import the module by giving this command.
import stairway_to_heaven
"""
prompt = raw_input('>>> ')
if prompt == "import stairway_to_heaven":
print "Module successfully imported."
else:
print "Nope, try again."
exit(0)
print "Now let's call a property from the module."
print "Give this command: print stairway_to_heaven.first_line"
prompt = raw_input('>>> ')
if prompt == "print stairway_to_heaven.first_line":
print "There's a lady who's sure"
else:
print "Nope, not quite."
exit(0)
print "Now let's access a method in the same way."
print "Give this command: stairway_to_heaven.sing_chorus()"
prompt = raw_input('>>> ')
if prompt == "stairway_to_heaven.sing_chorus()":
print "And as we wind on down the road."
else:
print "Not quite, try again."
exit(0)
print "But object oriented programming goes beyond"
print "just modules. You can also do what are called classes."
print "Classes create objects."
class Candy(object):
def __init__(self, name):
self.name = name
def eat(self):
print "All gone. Yummy."
print """
This class has been defined for you.
class Candy(object):
def __init__(self, name):
self.name = name
def eat(self):
print "All gone. Yummy."
Let's create an instance of candy.
Give this command: snickers = Candy('snickers')"""
prompt = raw_input(">>> ")
if prompt == "snickers = Candy('snickers')":
print "Good job. Object instantiated."
snickers = Candy('snickers')
else:
print "Not quite, try again."
exit(0)
print "Let's call a method on snickers."
print "Give this command: snickers.eat()"
prompt = raw_input('>>> ')
if prompt == "snickers.eat()":
snickers.eat()
else:
print "Not quite, try again."
exit(0)
print "That should be enough to get your feet wet."
print "If you're like me, it might take a while for"
print "this to sink in. But, maybe you're smarter."
| true |
64bd98e9099267c2b5239a12c68a1c0108f4d92a | AmenehForouz/leetcode-1 | /python/problem-0832.py | 1,144 | 4.34375 | 4 | """
Problem 832 - Flipping an Image
Given a binary matrix A, we want to flip the image horizontally, then invert
it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.
For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced
by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].
"""
from typing import List
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
for i in A:
i.reverse()
for j in range(len(i)):
if i[j] == 0:
i[j] = 1
elif i[j] == 1:
i[j] = 0
return A
if __name__ == "__main__":
img1 = [[1, 1, 0], [1, 0, 1], [0, 0, 0]]
img2 = [[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]]
# Should return [[1, 0, 0], [0, 1, 0], [1, 1, 1]]
print(Solution().flipAndInvertImage(img1))
# Should return [[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]]
print(Solution().flipAndInvertImage(img2))
| true |
9f489fa5b55db295368c9ea6ff621fe59f2e37e9 | AmenehForouz/leetcode-1 | /python/problem-0088.py | 625 | 4.15625 | 4 | """
Problem 88 - Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1
as one sorted array.
"""
from typing import List
class Solution:
def merge(
self, nums1: List[int], m: int, nums2: List[int], n: int
) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
for i in range(n):
nums1[i + m] = nums2[i]
nums1.sort()
if __name__ == "__main__":
nums1 = [1, 2, 3, 0, 0, 0]
nums2 = [2, 5, 6]
# Should return [1, 2, 2, 3, 5, 6]
Solution().merge(nums1, 3, nums2, 3)
print(nums1)
| true |
1d79a965da3406b42c492b8a9aa2bfd6ae4c1bba | nathanielam0ah/homework | /exercise009.py | 230 | 4.21875 | 4 | #!/usr/bin/env python
def maxList(Li):
currentMax = Li[0]
for index in Li:
if index > currentMax:
currentMax = index
return currentMax
myList = ['3', '4', '6', '3', '-100']
print(maxList(myList))
| true |
da6106e6aa5268cc241d03472d3ff572f0a63e58 | ucsd-cse-spis-2020/spis20-lab03-Sidharth-Theodore | /lab3Letters_pair.py | 596 | 4.5625 | 5 | #Sidharth and Theodore
#1.the "anonymous turtle" is the default turtle used if none are created in Code, or the first created if multiple are created
#2."turtle" refers to the turtle library while "Turtle()" refers to the turtle class
#3.myTurtle.sety(100)
import turtle
def drawT(theTurtle, size):
'''Takes a turtle, uses it to draw letter T'''
theTurtle.pd()
theTurtle.forward(10*size)
theTurtle.right(180)
theTurtle.forward(5*size)
theTurtle.left(90)
theTurtle.forward(10*size)
bobRoss = turtle.Turtle()
myScreen = turtle.Screen()
myScreen.screensize(400,400)
drawT(bobRoss, 20) | true |
0c399de5188adb0418cef31a5896a2376afdf4bb | linzifan/python_courses | /misc-Stack.py | 1,487 | 4.40625 | 4 | """
Stack class
"""
class Stack:
"""
A simple implementation of a FILO stack.
"""
def __init__(self):
"""
Initialize the stack.
"""
self._items = []
def __len__(self):
"""
Return number of items in the stack.
"""
return len(self._items)
def __str__(self):
"""
Returns a string representation of the stack.
"""
return str(self._items)
def push(self, item):
"""
Push item onto the stack.
"""
self._items.append(item)
def pop(self):
"""
Pop an item off of the stack
"""
return self._items.pop()
def clear(self):
"""
Remove all items from the stack.
"""
self.items = []
############################
# test code for the stack
my_stack = Stack()
my_stack.push(72)
my_stack.push(59)
my_stack.push(33)
my_stack.pop()
my_stack.push(77)
my_stack.push(13)
my_stack.push(22)
my_stack.push(45)
my_stack.pop()
my_stack.pop()
my_stack.push(22)
my_stack.push(72)
my_stack.pop()
my_stack.push(90)
my_stack.push(67)
while len(my_stack) > 4:
my_stack.pop()
my_stack.push(32)
my_stack.push(14)
my_stack.pop()
my_stack.push(65)
my_stack.push(87)
my_stack.pop()
my_stack.pop()
my_stack.push(34)
my_stack.push(38)
my_stack.push(29)
my_stack.push(87)
my_stack.pop()
my_stack.pop()
my_stack.pop()
my_stack.pop()
my_stack.pop()
my_stack.pop()
print my_stack.pop() | true |
2384c7c82af5eccdb070c7522a11895f2c3f4aa6 | ldocao/utelly-s2ds15 | /clustering/utils.py | 674 | 4.25 | 4 | ###PURPOSE : some general purposes function
import pdb
def becomes_list(a):
"""Return the input as a list if it is not yet"""
if isinstance(a,list):
return a
else:
return [a]
def add_to_list(list1, new_element):
"""Concatenate new_element to a list
Parameters:
----------
list1: list
Must be a list
new_element : any
new element to be added at the end of list1
Output:
------
result: list
1D list
"""
return list1+becomes_list(new_element)
def is_type(a,type):
"""Test if each element of list is of a given type"""
return [isinstance(i,type) for i in a]
| true |
e68f7daf7a588470c36b131e13606b458298906d | sunnyyants/crackingPython | /Recursion_and_DP/P9_5.py | 1,169 | 4.21875 | 4 | __author__ = 'SunnyYan'
# Write a method to compute all the permutation of a string
def permutation(string):
if string == None:
return None
permutations = []
if(len(string) == 0):
permutations.append("")
return permutations
firstcharacter = string[0]
remainder = string[1:len(string)]
words = permutation(remainder)
for word in words:
for i in range(0,len(word)+1):
substring = insertCharAt(word, firstcharacter, i)
permutations.append(substring)
return permutations
def insertCharAt(word, firstc, i):
begin = word[0:i]
end = word[i:]
return (begin) + firstc + (end)
def permute2(s):
res = []
if len(s) == 1:
res = [s]
else:
for i, c in enumerate(s):
#print "i:" + str(i)
#print "c:" + str(c)
for perm in permute2(s[:i] + s[i+1:]):
res += [c + perm]
return res
# Testing Part...
print "All the permutation of set 'abc' will be showing as below:"
list = permutation("abc")
print list
print "All the permutation of set 'abcd' will be showing as below:"
print permute2("abcd")
| true |
70269b4f1997e6509e7323da0d8a7592355e0ef5 | sunnyyants/crackingPython | /Trees_and_Graph/P4_4.py | 850 | 4.1875 | 4 | __author__ = 'SunnyYan'
# Given a binary tree, design an algorithm which creates a linked list
# of all the nodes at each depth(e.g., if you have a tree with depth D,
# you'll have D linked lists
from Tree import BinarySearchTree
from P4_3 import miniHeightBST
def createLevelLinkedList(root, lists, level):
if(root == None):
return None
if(len(lists) == level):
linkedlist = []
lists.append(linkedlist)
else:
linkedlist = lists[level]
linkedlist.append(root.key)
createLevelLinkedList(root.leftChild,lists,level+1)
createLevelLinkedList(root.rightChild,lists,level+1)
return lists
T4 = BinarySearchTree();
i = [1,2,3,4,5,6]
T4.root = miniHeightBST(i,0,len(i) - 1)
T4.root.printSubtree(5)
lists = []
result = createLevelLinkedList(T4.root, lists, 0)
for i in result:
print i | true |
2db3135898b0a57ef68bc4005a12874954b4809f | sunnyyants/crackingPython | /strings_and_array/P1_7.py | 893 | 4.40625 | 4 | __author__ = 'SunnyYan'
#
# Write an algorithm such that if an element in an M*N matrix is 0,
# set the entire row and column to 0
#
def setMatrixtoZero(matrix):
rowlen = len(matrix)
columnlen = len(matrix[0])
row = [0]*rowlen
column = [0]*columnlen
for i in range(0, rowlen):
for j in range(0, columnlen):
if matrix[i][j] == 0:
row[i] = 1
column[j] = 1
for i in range(0, rowlen):
for j in range(0, columnlen):
if row[i] or column[j]:
matrix[i][j] = 0
return matrix
matrixrow = []
matrixcol = []
# initialized the matrix by using list
for row in range(0, 3):
for column in range(0, 4):
matrixcol.append(column+row)
matrixrow.append(matrixcol)
matrixcol=[]
print "Before setting"
print matrixrow
print "After setting"
print setMatrixtoZero(matrixrow)
| true |
cf53a1b7300099ea8ecbe596ac2cb6574642e05f | sainath-murugan/small-python-projects-and-exercise | /stone, paper, scissor game.py | 1,231 | 4.21875 | 4 | from random import randint
choice = ["stone","paper","scissor"]
computer_selection = choice[randint(0,2)]
c = True
while c == True:
player = input("what is your choice stone,paper or scissor:")
if player == computer_selection:
print("tie")
elif player == ("stone"):
if computer_selection == ("scissor"):
print("hey there you won, computer selects scissor.so,stone smaches scissor")
break
else:
print("hey there you lose,computer selects paper.so, paper covers stone")
break
elif player == ("paper"):
if computer_selection == ("scissor"):
print("hey there you lose, computer selects scissor.so, scissor cuts paper")
break
else:
print("hey there you won, computer selects stone.so, paper covers stone")
break
elif player ==("scissor"):
if computer_selection ==("stone"):
print("hey there you lose computer selects stone.so, stone smaches scissor")
break
else:
print("hey there you won,computer selects paper.so scissor cuts paper")
break
else:
print("enter a valid word!!!")
break
| true |
0bea4a359a651daeb78f174fe3fb539e118c39ad | asperaa/programming_problems | /linked_list/cll_create.py | 1,345 | 4.34375 | 4 | # class for Circular linked list node
class Node:
# function to initiate a new_node
def __init__(self, data):
self.data = data
self.next = None
# class for circular linked list
class CircularLinkedList:
# function to initialise the new_node
def __init__(self):
self.head = None
# function to push data in the front of circular linked list
def push(self, data):
# create a new node
new_node = Node(data)
# point next of new_node to head of CLL
new_node.next = self.head
# temp variable as a mover
temp = self.head
# CLL is not empty
if self.head is not None:
while(temp.next != self.head):
temp = temp.next
temp.next = new_node
else:
new_node.next = new_node
self.head = new_node
# function to print a circular linked list
def print_list(self):
temp = self.head
while(True):
print(temp.data, end=" ")
temp = temp.next
if temp == self.head:
break
print()
if __name__ == "__main__":
dll = CircularLinkedList()
dll.push(10)
dll.push(9)
dll.push(8)
dll.push(7)
dll.push(6)
dll.print_list()
| true |
316c16a74400b553599f007f61997e65a5ed0069 | asperaa/programming_problems | /linked_list/rev_group_ll.py | 1,889 | 4.25 | 4 | """ Reverse a group of linked list """
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# initialise the head of the linked list
def __init__(self):
self.head = None
# add a new node to the end of linked list
def add_node(self, data):
# create a new node
new_node = Node(data)
# check if the node is empty
if self.head is None:
self.head = new_node
return
# mover node
mover = self.head
while(mover.next):
mover = mover.next
mover.next = new_node
def reverse_k_group(self, temp_head, k):
current_node = temp_head
next = None
prev_node = None
count = 0
# break the loop on reaching the group limit
# and on end of ll
while(current_node is not None and count < k):
next = current_node.next
current_node.next = prev_node
prev_node = current_node
current_node = next
count += 1
# stop recursion on reaching the end of loop
if next is not None:
temp_head.next = self.reverse_k_group(next, k)
# keep the head of the linked list updated
self.head = prev_node
# prev_node is the new_head of the input list
return prev_node
def print_list(self):
temp = self.head
while(temp):
print(temp.data, end=" ")
temp = temp.next
print()
if __name__ == "__main__":
ll = LinkedList()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.add_node(4)
ll.add_node(5)
ll.add_node(6)
ll.add_node(7)
ll.add_node(8)
ll.print_list()
ll.reverse_k_group(ll.head, 3)
ll.print_list()
| true |
f7fa6a108c3a05c476fa48b679ec81b9dab0edd7 | asperaa/programming_problems | /linked_list/rev_ll.py | 1,383 | 4.25 | 4 | # Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# LinkedList class
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def reverse(self):
if self.head is None:
print("Empty ll")
return
# initialise the prev_node and current node as None and head of ll
prev_node = None
curr_node = self.head
while(curr_node is not None):
next_node = curr_node.next # save the next of curr_node in a next_node var
curr_node.next = prev_node # set the next of curr_node as prev_node
prev_node = curr_node # set the prev_node as curr_node
curr_node = next_node # set the curr_node as the next node that you saved earlier
self.head = prev_node # set the head of ll as the last node
def print_list(self):
temp = self.head
while(temp):
print(temp.data, end=" ")
temp = temp.next
print()
if __name__ == "__main__":
ll = LinkedList()
ll.push(8)
ll.push(7)
ll.push(4)
ll.push(90)
ll.push(10)
ll.print_list()
ll.reverse()
ll.print_list()
| true |
956495f4026844ed336b34512c87aceec11c0ef8 | asperaa/programming_problems | /linked_list/reverse_first_k.py | 2,093 | 4.375 | 4 | """Reverse the first k elements of the linked list"""
# Node class for each node of the linked list
class Node:
# initialise the node with the data and next pointer
def __init__(self, data):
self.data = data
self.next = None
# Linked list class
class LinkedList:
# initialise the head of the class
def __init__(self):
self.head = None
# add a node to the front of the linked list
def add_front(self, data):
# create a new node
new_node = Node(data)
# check if the linked list is empty
if self.head is None:
self.head = new_node
return
new_node.next = self.head
self.head = new_node
# function to reverse first k nodes of the linked list
def reverse_frist_k(self, k):
# check if the ll is empty
if self.head is None:
return
current_node = self.head
next_node = None
prev_node = None
count = 0
while(current_node and count < k):
next_node = current_node.next
current_node.next = prev_node
prev_node = current_node
current_node = next_node
count += 1
# point the next of the original first node
# to the first node of the un-reversed ll
self.head.next = next_node
# change the head of the linked list to
# point to the new node (first node of reversed part of ll)
self.head = prev_node
# print the linke the linked list
def print_list(self):
temp = self.head
while(temp):
print(temp.data, end=" ")
temp = temp.next
print()
if __name__ == "__main__":
ll = LinkedList()
ll.add_front(8)
ll.add_front(7)
ll.add_front(6)
ll.add_front(5)
ll.add_front(4)
ll.add_front(3)
ll.add_front(2)
ll.add_front(1)
# print the original linked list
ll.print_list()
# reverse the linked list
ll.reverse_frist_k(5)
# print the reversed linked list
ll.print_list()
| true |
9bd1ec0e8941bae713a60098d73bc0d7f996bf9c | eldimko/coffee-machine | /stage3.py | 1,047 | 4.34375 | 4 | water_per_cup = 200
milk_per_cup = 50
beans_per_cup = 15
water_stock = int(input("Write how many ml of water the coffee machine has:"))
milk_stock = int(input("Write how many ml of milk the coffee machine has:"))
beans_stock = int(input("Write how many grams of coffee beans the coffee machine has:"))
cups = int(input("Write how many cups of coffee you will need:"))
most_water_cups = water_stock // water_per_cup
most_milk_cups = milk_stock // milk_per_cup
most_beans_cups = beans_stock // beans_per_cup
# find the smallest amount of cups out of the list in order to find the most cups of coffee that are possible to be made
most_cups_list = [most_water_cups, most_milk_cups, most_beans_cups]
most_cups_list.sort()
most_cups = most_cups_list[0]
if most_cups == cups:
print("Yes, I can make that amount of coffee")
elif most_cups < cups:
print("No, I can make only {} cups of coffee".format(most_cups))
elif most_cups > cups:
print("Yes, I can make that amount of coffee (and even {} more than that)".format(most_cups - cups))
| true |
69a1845303537328dfd0db3c2379b2d094643633 | satya497/Python | /Python/storytelling.py | 1,340 | 4.15625 | 4 | storyFormat = """
Once upon a time, deep in an ancient jungle,
there lived a {animal}. This {animal}
liked to eat {food}, but the jungle had
very little {food} to offer. One day, an
explorer found the {animal} and discovered
it liked {food}. The explorer took the
{animal} back to {city}, where it could
eat as much {food} as it wanted. However,
the {animal} became homesick, so the
explorer brought it back to the jungle,
leaving a large supply of {food}.
The End
"""
def tellStory():
userPicks = dict()
addPick('animal', userPicks)
addPick('food', userPicks)
addPick('city', userPicks)
story = storyFormat.format(**userPicks)
print(story)
def addPick(cue, dictionary):
'''Prompt for a user response using the cue string,
and place the cue-response pair in the dictionary.
'''
prompt = 'Enter an example for ' + cue + ': '
response = input(prompt).strip() # 3.2 Windows bug fix
dictionary[cue] = response
tellStory()
input("Press Enter to end the program.") | true |
0f4005420c98c407a9d02e6f601c2fccbf536114 | satya497/Python | /Python/classes and objects.py | 775 | 4.46875 | 4 | # this program about objects and classes
# a class is like a object constructor
#The __init__() function is called automatically every time the class is being used to create a new object.
class classroom:
def __init__(self, name, age): # methods
self.name=name
self.age=age
def myfunc1(self):
print("my name is "+self.name)
print(self.name+" age is "+str(self.age))
p1=classroom("satya",23)
p2=classroom("ravi",21)
p3=classroom("akhil",24)
p1.age=22
p1.myfunc1()
p2.myfunc1()
p3.myfunc1()
class myclass:
def reversing(self,s):
return ' '.join(reversed(s.split()))
print(myclass().reversing('my name is'))
str1 = "how are you"
str2=str1.split(" ")
output = ' '.join(str2)
print(reversed(str2))
| true |
5b7f40cc69402346f9a029c07246da2286022c7f | Vk686/week4 | /hello.py | 212 | 4.28125 | 4 | tempName = "Hello <<UserName>>, How are you?"
username = input("Enter User Name: ")
if len(username) < 5:
print("User Name must have 5 characters.")
else:
print(tempName.replace("<<UserName>>",username))
| true |
1596d1d1e7ef22f858dad005741768c7887a5a0e | wardragon2096/Week-2 | /Ch.3 Project1.1.py | 296 | 4.28125 | 4 | side1=input("Enter the first side of the triangle: ")
side2=input("Enter the second side of the triangle: ")
side3=input("Enter the thrid side of the triangle: ")
if side1==side2==side3:
print("This is an equilateral triangle.")
else:
print("This is not an equilateral triangle.")
| true |
63bcca7240f1f8464135732d795e80b3e95ddd1f | RichardLitt/euler | /007.py | 565 | 4.125 | 4 | # What is the 10001st prime?
# Import library to read from terminal
import sys
# Find if a number is prime
def is_prime(num):
if (num == 2):
return True
for x in range(2, num/2+1):
if (num % x == 0):
return False
else:
return True
# List all primes in order
def list_primes(stop):
found = 0
current_num = 2
while (found != stop):
if (is_prime(current_num)):
found += 1
previous_num = current_num
current_num += 1
print previous_num
list_primes(int(sys.argv[1]))
| true |
2c91f734d48c6d0ab620b6b5a9715dc4f5e4ddb7 | smoke-hux/pyhton-codes | /2Dlistmatrixes.py | 1,044 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 05:54:12 2020
@author: root
"""
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1])
matrix[0][1] = 20
print(matrix[0][1])
#we can use nested loops to iterate over every item in the list
for row in matrix:#in each row it will contain one list one item
for item in row:#used to loop over eacch row that is a list items
print(item)
numbers = [5, 2, 1, 7, 4]
numbers.append(20)#append is used to add item to a list
print(numbers)
numbers.insert(0, 10)#used when one wants to insert a value to the where one desires and the first digit is the index and the second digits is the number you want to add
print(numbers)
numbers.remove(10)# if you want to remove an item in the list
print(numbers)
numbers.pop()#removes the last item on the list
print(numbers)
print(numbers.index(54))#is used tocheck the index of a given value in the list and also the existence of the given value
print(50 in numbers)
| true |
7f44a3ce1ebc5dc682fb9a71a62413640101ed46 | mdev-qn95/python-code40 | /challenge-counter-app.py | 642 | 4.15625 | 4 | # Basic Data Types Challenge 1: Letter Counter App
print("Welcome to the Letter Counter App")
# Get user input
name = input("\nWhat's your name: ").title().strip()
print("Hello, " + name + "!")
print("I'll count the number of times that a specific letter occurs in a message.")
message = input("\nPlease enter a message: ")
letter = input("Which letter would you like to count the occrrences of: ")
# Standardize
message = message.lower()
letter = letter.lower()
# Get the count and display results
letter_count = message.count(letter)
print("\n" + name + ", your message has " + str(letter_count) + " character '" + letter + "' in it.") | true |
e5162cfd848d2079cd0a2783413cdce62c365e39 | rajkamalthanikachalam/PythonLearningMaterial | /com/dev/pythonSessions/07Functions.py | 2,940 | 4.5625 | 5 | # Function: a piece of code to execute a repeated functions
# Recursion: A function calling itself
# Arguments : *arg is used to pass a single arguments
# Key words : **args is used to pass a multiple arguments in key & value format
# Lambda functions : Anonymous functions or function without name
# Function
def function(username):
print(username)
function(username="test1")
def function(username, password):
print(username, password)
function("user1", "test123") # You can pass arguments in both way
function(username="user1", password="test123") # You can pass arguments in both way
# Functions with no arguments
def function1(): # syntax to define a function
print("My First Function with no argument")
function1()
# Functions with single arguments
def function2(a):
print("Function with single argument : %d" % a)
return function2
function2(100)
# Functions with two arguments and return
def function3(a, b):
c = a+b
print("Function with two arguments : %d" % c)
return c
function3(10, 15)
# Functions with default/Optional parameter
def function4(name="None Selected"):
print(name)
function4()
function4("India")
function4("Australia")
# Functions with List
def function5(name):
for index in name:
print(index)
countryName = ["India", "Australia", "Africa", "America"]
function5(countryName)
# Functions with if- Else statement
def function6(country_name):
if country_name == "India":
print("Capital is New Delhi")
elif country_name == "Australia":
print("Capital is Melbourne")
elif country_name == "Africa":
print("Capital is Cape Town")
elif country_name == "America":
print("Capital is Washington DC")
else:
print("Not in the list")
function6("China")
# Recursion : Function calling itself , ie factorial of 5 (5*4*3*2*1)
def recursion(num):
if num > 1:
num = num * recursion(num-1)
return num
print(recursion(5))
# Arguments
print("********************************Arguments**************************************")
def arguments(*arg):
for x in arg:
print(x)
arguments(10, 12, 15, 18, 19)
arguments("Maths", "Science", "History", "English")
print("********************************Key word Arguments**************************************")
# **args is syntax
# for key, value in args.items(): is syntax
def arguments(**args):
for key, value in args.items():
print("%s == %s" % (key, value))
arguments(user1="test1", user2="test2", user3="test3")
arguments(xyz=10, abc=20, ijk=30)
# Lambda
# syntax lambda x: define the function after colon
print("********************************Lambda**************************************")
cube = lambda n: n*n*n
cubeX = cube(4)
print("Cube of C is %d" % cubeX)
total = lambda mark: mark+30
sumTotal = total(150)
print("Total mark earned is %d" % sumTotal)
| true |
3c83bcb69b992b68845482fbe0cf930bb0faaf22 | Japan199/PYTHON-PRACTICAL | /practical2_1.py | 257 | 4.21875 | 4 | number=int(input("enter the number:"))
if(number%2==0):
if(number%4==0):
print("number is a multiple of 2 and 4")
else:
print("number is multiple of only 2")
else:
print("number is odd")
| true |
98d91f20f106a8787e87e6e18bfb0388bb96a24e | Douglass-Jeffrey/Assignment-0-2B-Python | /Triangle_calculator.py | 499 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Douglass Jeffrey
# Created on: Oct 2019
# This program calculates area of triangles
def main():
# this function calculates the area of the triangles
# input
num1 = int(input("Input the base length of the triangle: "))
num2 = int(input("Input the height of the triangle: "))
# process
answer = (num1*num2)/2
# output
print("")
print("The area of the triangle is {} units^2".format(answer))
if __name__ == "__main__":
main()
| true |
73b8058f76913080f172dd81ab7b76b1889faa11 | ibrahimuslu/udacity-p2 | /problem_2.py | 2,115 | 4.15625 | 4 | import math
def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
def findPivot(input_list,start,end):
if start == end:
return start
if (end - start) == 1:
return end
if (start - end) == 1:
return start
mid = (start+ end)//2
if input_list[mid] > input_list[end]:
return findPivot(input_list,mid,end)
elif input_list[mid] < input_list[end]:
return findPivot(input_list,start,mid)
else:
return mid
pivot = findPivot(input_list,0,len(input_list)-1)
size = len(input_list)
# print(input_list[pivot])
def findNumber(input_list, number, pivot, start, end):
# print(input_list, number, pivot,start, end)
if number == input_list[pivot]:
return pivot
elif number >= input_list[pivot] and number <= input_list[end]:
return findNumber(input_list, number, math.ceil((end-pivot)/2)+pivot, pivot,end)
elif number >= input_list[0] and number <= input_list[pivot-1]:
return findNumber(input_list, number, math.ceil((pivot-start)/2), 0,pivot-1)
else:
return -1
return findNumber(input_list, number, pivot, 0, size-1)
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
a=linear_search(input_list, number)
b=rotated_array_search(input_list, number)
# print(a, b)
if (a == b):
print("Pass")
else:
print("Fail")
test_function([[6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20,21,22, 1, 2, 3, 4], 3])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10]) | true |
b2b27d69caeab17bc3150e1afe9c1e1de3ac5d9e | aniketchanana/python-exercise-files | /programmes/listMethods.py | 922 | 4.46875 | 4 | # methods are particular to a given class
# append insert & extend
first_list = [1,2,3,4,5]
# first_list.append([1,2,3])
# print(first_list)
# [1, 2, 3, 4, 5, [1, 2, 3]] simply pushes it inside the list
# no matter what is that <<append takes in only one arguement>>
# first_list.extend([1,2,3,4])
# print(first_list)
# first_list.insert(2,"hi")
# print(first_list)
# first_list.clear()
# print(first_list)
# print(first_list.pop(first_list.index(3)))
# print(first_list)
# first_list.remove(2)
# print(first_list)
#---------------------------------------------------------------#
# important functions related to list
# list.index(element)
# list.index(element,startIndex)
# list.index(element,startIndex,endIndex)
# list.count(element)
# first_list.reverse()
# print(first_list)
# first_list.sort()
# str = "a,n,i,k,e,t"
# print(str.split(","))
# join works with list of strings
# print(' .'.join(str)) | true |
5fbbfd843c662a09a20b1e5bad1861a2a82f53fa | aniketchanana/python-exercise-files | /programmes/bouncer.py | 270 | 4.125 | 4 | age = input("How old are you")
if age :
age = int(age)
if age >= 18 and age < 21 :
print("Need a wrist band")
elif age>=21 :
print("you can enter and drink")
else :
print("too little to enter")
else :
print("Input is empty")
| true |
3b582f75705736982841af1acc369baa26287f05 | ethomas1541/Treehouse-Python-Techdegree-Project-1 | /guessing_game.py | 2,919 | 4.15625 | 4 | """
Treehouse Python Techdegree
Project 1 - Number Guessing Game
Elijah Thomas
/2020
"""
"""
Tried to make my code a bit fancy. I have a bit of knowledge beyond what's been taught to me thus
far in the techdegree, and I plan to use it to streamline the program as much as I can.
"""
#Also, fair warning, I use a ton of \n newlines to make the output look better.
import random
def start_game():
guesses = 0 #Amount of user's guesses so far
feedback = "What is your guess?" #This variable will be what's printed when asking the user for their guess. It changes based on the user's answer and how it relates to the answer (lesser/greater)
plural = "guess" #This just determines whether "guess" or "guesses" is printed at the end of the game, just a grammatical fix.
guessed = [] #List containing any numbers the player has already guessed.
answer = random.choice(range(1, 11))
print("\nWelcome to my number guessing game!\nI'm going to pick a number between 1 and 10. Can you guess what it is?\n")
while True: #Main loop in which the entire game runs. Breaks when the user wins.
while True: #Loop to obtain acceptable input (integer 1-10). Will only break if this is achieved.
userInput = input(f"\n{feedback}\n\n")
try:
userInt = int(userInput)
if userInt < 1:
print("\nThat's too low!")
raise ValueError
elif userInt > 10:
print("\nThat's too high!")
raise ValueError
break
except ValueError:
print("\nPlease enter a whole number between 1 and 10.")
guesses += 1
if guesses > 1:
plural = "guesses"
if userInt == answer:
break #This will break the main loop, and the user will win the game.
elif userInt < answer:
feedback = "The answer's bigger!"
else:
feedback = "The answer's smaller!"
if userInt in guessed:
feedback += " You already guessed that!" #Adds a comment to the feedback variable if the user already guessed this number.
else:
guessed.append(userInt) #Adds the user's input into the list of guesses if it's not already there.
if input(f"\nCongratulations! You guessed it! The answer was {answer}! You got it in {guesses} {plural}!\n\nPlay again? (y/n)\n\n") in ("y", "Y", "yes", "Yes"): #This is a long line, but it basically announces that you won and asks if you want to play again, all in the same stroke.
start_game()
else:
exit()
start_game()
#I was going for the "exceeds expectations" requirements for this project, but chose to omit the high-score system. I thought it'd be a bit too tedious to implement it, so I'm good with just meeting the expectations.
| true |
7e8e5cd20755bc9967dc6800b3614fdc9c8cc8d3 | Sheax045/SWDV660 | /Week1/week-1-review-Sheax045/temp_converter.py | 371 | 4.375 | 4 | # Please modify the following program to now convert from input Fahrenheit
# to Celsius
def doConversion():
tempInFAsString = input('Enter the temperature in Fahrenheit: ')
tempInF = float( tempInFAsString )
tempInC = ( tempInF - 32 ) / 1.8
print('The temperature in Celsius is', tempInC, 'degrees')
for conversionCount in range( 3 ):
doConversion() | true |
f1c33d5a000f7f70691e10da2bad54de62fc9a8d | sugia/leetcode | /Integer Break.py | 648 | 4.125 | 4 | '''
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note: You may assume that n is not less than 2 and not larger than 58.
'''
class Solution:
def integerBreak(self, n: int) -> int:
if n == 2:
return 1
if n == 3:
return 2
res = 1
while n > 4:
res *= 3
n -= 3
res *= n
return res
| true |
a3fc906021f03ed53ad43fbc133d253f74e56daa | sugia/leetcode | /Valid Palindrome.py | 697 | 4.15625 | 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
'''
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
alpha = []
for c in s:
if c.isalnum():
alpha.append(c.lower())
for i in xrange(len(alpha) // 2):
if alpha[i] != alpha[len(alpha) - i - 1]:
return False
return True
| true |
396253f9798266c4b6b291f272aa7b79c6fa0a0a | sugia/leetcode | /Power of Two.py | 498 | 4.125 | 4 | '''
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Example 2:
Input: 16
Output: true
Example 3:
Input: 218
Output: false
'''
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
bit_count = 0
while n > 0:
bit_count += n & 1
n >>= 1
if bit_count == 1:
return True
return False
| true |
1c59ace51e212ef319a09a5703d88b878ca494e8 | sugia/leetcode | /Group Shifted Strings.py | 1,102 | 4.15625 | 4 | '''
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
Example:
Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Output:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
'''
class Solution(object):
def groupStrings(self, strings):
"""
:type strings: List[str]
:rtype: List[List[str]]
"""
dic = {}
for s in strings:
key = self.getKey(s)
if key in dic:
dic[key].append(s)
else:
dic[key] = [s]
return dic.values()
def getKey(self, s):
vec = [ord(c) for c in s]
tmp = vec[0]
for i in xrange(len(vec)):
vec[i] -= tmp
if vec[i] < 0:
vec[i] += 26
return ''.join([chr(x + ord('a')) for x in vec])
| true |
cd46ca9292716451523c2fb59813627274928af3 | sugia/leetcode | /Strobogrammatic Number II.py | 1,197 | 4.15625 | 4 | '''
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Find all strobogrammatic numbers that are of length = n.
Example:
Input: n = 2
Output: ["11","69","88","96"]
'''
class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
'''
1 = 1
6 = 9
8 = 8
9 = 6
0 = 0
'''
res = []
tmp = ['' for i in xrange(n)]
pairs = {1:1, 6:9, 8:8, 9:6, 0:0}
self.find(pairs, 0, n - 1, tmp, res)
return res
def find(self, pairs, start, end, tmp, res):
if start == end:
for i in [0, 1, 8]:
tmp[start] = i
res.append(''.join([str(x) for x in tmp]))
elif start > end:
res.append(''.join([str(x) for x in tmp]))
else:
for k, v in pairs.iteritems():
if start == 0 and k == 0:
continue
tmp[start] = k
tmp[end] = v
self.find(pairs, start + 1, end - 1, tmp, res)
| true |
e0e326f07a8f166d9e424ddd646e563b5e817da9 | sugia/leetcode | /Solve the Equation.py | 2,867 | 4.3125 | 4 | '''
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: "x=x"
Output: "Infinite solutions"
Example 3:
Input: "2x=x"
Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Example 5:
Input: "x=x+2"
Output: "No solution"
'''
class Solution(object):
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
equal_idx = equation.index('=')
if equal_idx == -1:
return 'Infinite solution'
left = self.get(equation[:equal_idx])
right = self.get(equation[equal_idx+1:])
variable = []
constant = []
for x in left:
if 'x' in x:
variable.append(x)
else:
constant.append(self.neg(x))
for x in right:
if 'x' in x:
variable.append(self.neg(x))
else:
constant.append(x)
v = self.solve(variable)
c = self.solve(constant)
if v == '0':
if c == '0':
return 'Infinite solutions'
else:
return 'No solution'
else:
a = v[:-1]
if a:
a = int(a)
else:
a = 1
return 'x=' + str(int(c) // a)
def get(self, s):
vec = []
start = 0
for end in xrange(1, len(s)):
if s[end] in '+-':
vec.append(s[start:end])
start = end
vec.append(s[start:])
return vec
def neg(self, x):
if x[0] == '+':
return '-' + x[1:]
if x[0] == '-':
return x[1:]
return '-' + x
def solve(self, vec):
if not vec:
return '0'
res = 0
sign = False
if 'x' in vec[0]:
sign = True
for x in vec:
if x[-1] == 'x':
y = x[:-1]
if y == '' or y == '+':
y = 1
elif y == '-':
y = -1
else:
y = int(x[:-1])
res += y
else:
res += int(x)
if sign:
if res == 0:
return '0'
elif res == 1:
return 'x'
else:
return str(res) + 'x'
else:
return str(res)
| true |
8c3ae2289cd214e6288ede5de4a2e296f5d3983b | sugia/leetcode | /Largest Triangle Area.py | 1,047 | 4.15625 | 4 | '''
You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.
Example:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2
Explanation:
The five points are show in the figure below. The red triangle is the largest.
Notes:
3 <= points.length <= 50.
No points will be duplicated.
-50 <= points[i][j] <= 50.
Answers within 10^-6 of the true value will be accepted as correct.
'''
class Solution(object):
def largestTriangleArea(self, points):
"""
:type points: List[List[int]]
:rtype: float
"""
res = 0
for i in xrange(len(points)):
for j in xrange(i+1, len(points)):
for k in xrange(j+1, len(points)):
res = max(res, self.getArea(points[i][0], points[i][1], points[j][0], points[j][1], points[k][0], points[k][1]))
return res
def getArea(self, x1, y1, x2, y2, x3, y3):
return abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0
| true |
55926ff3a2bebfaad166335cff41c9edc9aba9a6 | joseph-palermo/ICS3U-Assignment-02B-Python | /assignment_two.py | 527 | 4.34375 | 4 | #!/usr/bin/env python3
# Created by: Joseph Palermo
# Created on: October 2019
# This program calculates the area of a sector of a circle
import math
def main():
# This function calculates the area of a sector of a circle
# input
radius = int(input("Enter the radius: "))
angle_θ = int(input("Enter the angle θ: "))
# process
area = math.pi * radius ** 2 * angle_θ / 360
# output
print("")
print("The area is: {:,.2f}cm^2 "
.format(area))
if __name__ == "__main__":
main()
| true |
89a55032338f6872b581bbabdfa13670f9520666 | Derin-Wilson/Numerical-Methods | /bisection_.py | 998 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 4 19:12:56 2020
@author: esha
"""
# Python program for implementation
# of Bisection Method for
# solving equations
# An example function whose
# solution is determined using
# Bisection Method.
# The function is x^3 - x^2 + 2
def func(x):
return x**3 - x**2 + 2
# Prints root of func(x)
# with error of EPSILON
def bisection(a,b):
if (func(a) * func(b) >= 0):
print("You have not assumed right a and b\n")
c = a
while (((b-a))>= 0.01):
# Find middle point
c = (a+b)/2
# Check if middle point is root
if (func(c) == 0.0):
break
# Decide the side to repeat the steps
if (func(c)*func(a) < 0):
b = c
else:
a = c
print("The value of root is : ","%.4f"%c)
# Driver code
# Initial values assumed
a =-200
b = 300
bisection(a, b) | true |
b04dee090d6f39bb7ad5a6f31f8a1ad99ada9234 | clhking/lpthw | /ex4.py | 1,277 | 4.28125 | 4 | # Set a variable for the number of cars
cars = 100
# Set a variable (using a float) for space in each car
space_in_a_car = 4
# Set a variable with number of drivers
drivers = 30
# Set a variable with number of passengers
passengers = 90
# Set up the variable for cars not driven being # of cars minus number of drivers
cars_not_driven = cars - drivers
# set a variable cars = drivers # this could be wrong in the future, there should be a check for cars gte drivers
cars_driven = drivers
# setup carpool_capacity being space in cars multiplied by cars_driven
carpool_capacity = cars_driven * space_in_a_car
# setup avg_pass_per_car as being passengers divided by cars_driven
average_passengers_per_car = passengers / cars_driven
# print out number of cars
print "There are", cars, "cars available."
# print out number of drivers
print "There are only", drivers, "drivers available."
# print out number of cars not driven
print "There will be", cars_not_driven, "empty cars today."
# print out the carpool capacity
print "We can transport", carpool_capacity, "people today."
# print out number of passengers
print "We have", passengers, "to carpool today."
# print out avg # of passengers per car
print "We need to put about", average_passengers_per_car, "in each car."
| true |
e82a0d351645c38a97eb004714aae9ab377e13f4 | vaelentine/CoolClubProjects | /mags/codewars/get_middle_char.py | 1,231 | 4.3125 | 4 | """
Get the middle character
From codewars
https://www.codewars.com/kata/56747fd5cb988479af000028/train/python
You are going to be given a word. Your job is to return the middle character of the word.
If the word's length is odd, return the middle character.
If the word's length is even, return the middle 2 characters.
#Examples:
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("middle") should return "dd"
Kata.getMiddle("A") should return "A"
"""
# unit test case
import unittest
def get_middle(s):
# if length of word % 2 == 0, you'd return index 1 & 2
#middle character of dog, len 3, would be 1.
return s[len(s)/2-1:len(s)//2+1] if len(s) % 2 == 0 else s[len(s)/2]
class TestFunction(unittest.TestCase):
def test1(self):
self.assertEqual(get_middle("test"), "es")
def test2(self):
self.assertEqual(get_middle("testing"), "t")
def test3(self):
self.assertEqual(get_middle("middle"), "dd")
def test4(self):
self.assertEqual(get_middle("A"), "A")
def test5(self):
self.assertEqual(get_middle("of"), "of")
if __name__ == '__main__':
unittest.main()
| true |
51b06ab89a0b7a96d973ad14a2a75703697e5d2c | JMBarberio/Penn-Labs-Server-Challenge | /user.py | 2,532 | 4.15625 | 4 | class User():
"""
The user class that contains user information.
Attributes:
-----------
name : str
The name of the user.
clubs : list
The list of the clubs that the user is in
fav_list : list
The bool list of whether or not a club has been favorited
"""
def __init__(self, name, clubs):
self.__name = name
self.__clubs = clubs
self.__fav_list = []
for club in range(0, len(clubs)):
self.__fav_list.append(False)
def get_user_name(self):
"""
Getter for the club name
Returns:
--------
str
The club name
"""
return self.__name
def set_user_name(self, new_name):
"""
Setter for the club name
Arguements:
-----------
new_name : str
The new user name
"""
self.__name = new_name
def get_user_clubs(self):
"""
Getter for the list of clubs
Returns:
--------
list
The list of clubs
"""
return self.__clubs
def get_fav_list(self):
"""
Getter for the favorite list
Returns:
--------
list
The bool list of favorites
"""
return self.__fav_list
def add(self, new_club):
"""
Adds a new club to the club list
Arguements:
-----------
new_club : Club
The new club to be added
TODO: add throws for club not found
"""
self.__clubs.append(new_club)
self.__fav_list.append(false)
def remove(self, club):
"""
Removes a club from the club list if the club is in the current list
Pops the boolean from the bool list at the corresponding index
If the corresponding bool was True, the favorite count for that club is decreased
Arguments:
----------
club : Club
The club to be removed
Throws:
-------
"""
try:
index = self.__clubs.index(club)
if self.__fav_list[index] == True:
club.decrease()
self.__clubs.remove(club)
self.__fav_list.pop(index)
except ValueError:
raise e | true |
817d35dd6ee95282807850ca348a78528516beed | jhill57/Module-4-Lab-Activity- | /grading corrected.py | 1,553 | 4.4375 | 4 | # Calculating Grades (ok, let me think about this one)
# Write a program that will average 3 numeric exam grades, return an average test score, a corresponding letter grade, and a message stating whether the student is passing.
# Average Grade
# 90+ A
# 80-89 B
# 70-79 C
# 60-69 D
# 0-59 F
# Exams: 89, 90, 90
# Average: 90
# Grade: A
# Student is passing.
# Exams: 50, 51, 0
# Average: 33
# Grade: F
# Student iis failing.
# this code was edited by Jordan on 2/8/2020
exam_one = int(input("Input exam grade one: "))
exam_two = int(input("Input exam grade two: "))
exam_3 = int(input("Input exam grade three: "))
# for this list use [] and not paranthesis
# separate each with a comma..... the addition takes place is sum = sum + grade
grades = (exam_one + exam_two + exam_3)
sum = 0
# for grade in grades:
for grades in grades:
# sum = sum + grade
sum = sum , grades
# avg = sum / len(grades)
avg = grades/3
if avg >= 90:
letter_grade = "A"
elif avg >= 80 and avg < 90:
letter_grade = "B"
elif avg > 70 and avg < 80:
letter_grade = "C"
elif avg >= 60 and avg <= 70:
letter_grade = "D"
#this should be else: since it is the last condition and no need for comparing avg any more.
elif avg >= 50 and avg <= 59:
letter_grade = "F"
for grade in grades:
print("Exam: " + str(grade))
#the last two prints are not part of the loop -- remove indentation
print("Average: " + str(avg))
print("Grade: " + letter_grade)
if letter-grade == "F":
print ("Student is failing.")
else:
print ("Student is passing.")
| true |
1b48abeed7454fea2a67ed5afc2755932e093d32 | CTEC-121-Spring-2020/mod-6-programming-assignment-tylerjjohnson64 | /Prob-3/Prob-3.py | 521 | 4.125 | 4 | # Module 7
# Programming Assignment 10
# Prob-3.py
# <Tyler Johnson>
def main():
number = -1
while number <0.0:
x = float(input("Enter a positive number to begin program: "))
if x >= 0.0:
break
sum = 0.0
while True:
x = float(input("Enter a positive number to be added (negative to quit): "))
if x >= 0.0:
sum = sum + x
else:
break
print("This is the sum of numbers enterered: ",sum)
main() | true |
c9804338656ff356407de642e3241b44cc91d085 | leon0241/adv-higher-python | /Term 1/Book-1_task-6-1_2.py | 659 | 4.28125 | 4 | #What would be the linked list for..
#'brown', 'dog.', 'fox', 'jumps', 'lazy', 'over', 'quick', 'red', 'The', 'the'
#... to create the sentence...
#'The quick brown fox jumps over the lazy dog'
linkedList = [
["brown", 2], #0
["dog.", -1], #1
["fox", 3], #2
["jumps", 5], #3
["lazy", 7], #4
["over", 9], #5
["quick", 0], #6
["red", 1], #7
["The", 6], #8
["the", 4] #9
]
def print_linked_list(list, link):
while link != -1: #Loop until end
item, link = list[link] #Unpack the node
print(item, end = ' ') #Display the item
print()
start = 8
print_linked_list(linkedList, start)
| true |
b56a066a3e11ed1e8e3de30a9ed73c35975e8c2e | leon0241/adv-higher-python | /Pre-Summer/nat 5 tasks/task 6/task_6a.py | 218 | 4.1875 | 4 | name = input("what's your name? ")
age = int(input("what's your age? "))
if age >= 4 and age <= 11:
print("you should be in primary school")
elif age >= 12 and age <= 17:
print("you should be in high school")
| true |
67ef1b27449b3dd39629b8cc675e519ac462663e | RitaJain/Python-Programs | /greater2.py | 226 | 4.25 | 4 | # find greatest of two numbers using if else statment
a=int(input("enter a ?"))
b=int(input("enter b ?"))
if (a>b):
print("a is greater than b", a)
else:
print("b is greater than a",b)
| true |
1c1b6f7379b46515bab0e2bcddf0ed78bf527cc4 | vipulm124/Python-Basics | /LearningPython/LearningPython/StringLists.py | 355 | 4.40625 | 4 | string = input("Enter a string ")
#Method 1
reverse = ''
for i in range(len(string)):
reverse += string[len(string)-1-i]
if reverse==string:
print("String is a pallindrome. ")
else:
print("Not a pallindrome. ")
#Method 2
rvs = string[::-1]
if rvs == string:
print("String is a pallindrome. ")
else:
print("Not a pallindrome. ")
| true |
5c40d587eb5bea2adab8c6a6ae27c461ec45ed74 | bhattaraiprabhat/Core_CS_Concepts_Using_Python | /hash_maps/day_to_daynum_hash_map.py | 995 | 4.40625 | 4 | """
Built in python dictionary is used for hash_map problems
"""
def map_day_to_daynum():
"""
In this problem each day is mapped with a day number.
Sunday is considered as a first day.
"""
day_dayNum = {"Sunday":1, "Monday":2, "Tuesday":3, "Wednesday":4,
"Thursday":5, "Friday":6, "Saturday":7}
#Display method 1:
print (day_dayNum)
#Display method 2
for key, value in day_dayNum.items():
print (key, value)
#Display method 3
print (day_dayNum["Sunday"])
#Add elements:
day_dayNum["NewDay"]="Noday"
print (day_dayNum)
#Remove elements:
del day_dayNum["NewDay"]
print (day_dayNum)
#Remove with exception:
try:
del day_dayNum["Monday"]
except KeyError as ex:
print("No such key")
print (day_dayNum)
try:
del day_dayNum["Monday"]
except KeyError as ex:
print("No such key")
print (day_dayNum)
map_day_to_daynum()
| true |
1e6eb33a7057383f2ae698c219830b5408ba7ab5 | lilamcodes/creditcardvalidator | /ClassMaterials/parking lot/review.py | 1,563 | 4.34375 | 4 | # 1. Dictionary has copy(). What is it?
# DEEP
dict1 = {"apple": 4}
dict2 = dict1.copy()
dict1["apple"] = 3
# print("dict1", dict1)
# print("dict2", dict2)
# SHALLOW
dict1 = {"apple": [1,2,3]}
dict2 = dict1.copy()
copy = dict1
dict1["apple"].append(5)
# print("dict1", dict1)
# print("dict2", dict2)
# print("copy with equal sign", copy)
# 2. How to open a csv? How to open a text file?
# NOTE the string in the open() function is a path!!!! not just the name.
# If no path (such as .., or /) is in the string, it assumes the file is right next to it.
with open("example.txt") as examp:
# read() makes a string copy of the file.
exampString = examp.read()
# print(exampString)
# print(type(exampString))
import csv
with open("example.csv") as examp:
# WITH reader()
# exampCSV = csv.reader(examp)
# for row in exampCSV:
# print(row)
# WITH DictReader()
exampCSV = csv.DictReader(examp)
# for row in exampCSV:
# print("State",row["State"])
# 3. sorted()? What is it?
def add(number1, number2):
return number1 + number2
def func(number):
return number * -1
x = [3,2,4]
# y = sorted(x, key=func)
y = sorted(x)
# print("x",x)
# print("y",y)
# 4. append() vs insert()
exampleList = [1,2,3,4]
# Example with append()
# Adds the value to the end automatically! No choice!!
exampleList.append(5)
# print(exampleList)
# Example with insert
# Adds the value to the index position you say! Also, does not get rid of
# the value that is already at that index position.
exampleList.insert(0, 5)
print(exampleList)
| true |
f9ca56364b52e6da5cb52c00396872294c04e5eb | lilamcodes/creditcardvalidator | /ClassMaterials/day7/beginner_exercises.py | 1,701 | 4.59375 | 5 | # Beginner Exercises
# ### 1. Create these classes with the following attributes
# #### Dog
# - Two attributes:
# - name
# - age
# #### Person
# - Three Attributes:
# - name
# - age
# - birthday (as a datetime object)
# ### 2. For the Dog object, create a method that prints to the terminal the name and age of the dog.
# - i.e.:
# ```
# Dog.introduce() ===> "Hi I am Sparky and I am 5 years old."
# ```
# ### 3. Create a function that will RETURN the Person objects birthday day of the week this year.
# - i.e.:
# ```
# Bob.birthday() ===> "Thursday"
# ```
class Dog():
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return self.name + "" + str(self.age)
class Person():
def __init__(self,name, age, birthday):
self.name=name
self.age=age
self.birthday=birthday
def __st__(self):
return self.name + "" + str(self.birthday)
# d = Dog("Sparky",5)
# print("the dog's name is" + self.name
p1 = Person('Linda','11', today)
from datetime import datetime, date
today=date.today()
datetime_object = datetime.strptime('Sep 19 2017 1:33PM', '%b %d %Y %I:%M%p')
# print ("Bob's birthday is {:%b %d}".format(datetime_object) + ", which is thursday")
Kesha's Version
from datetime import datetime
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
class Person():
def __init__(self, name, birthday):
self.name = name
self.birthday = datetime.strptime(birthday,'%m %d %Y')
self.age = int(str(datetime.today())[:4])-int(str(self.birthday)[:4])
dave = Person('dave','12 03 1989')
print(dave.birthday)
print('Dave is {} years old!'.format(dave.age))
| true |
1b82d057d603672ef90d083bbc59dd34de075736 | saurabh-ironman/Python | /sorting/QuickSort/quicksort.py | 1,419 | 4.15625 | 4 | def partition(array, low, high): #[3, 2, 1] # [1, 2, 3]
# choose the rightmost element as pivot
pivot = array[high]
# pointer for greater element
i = low - 1
# traverse through all elements
# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# if element smaller than pivot is found
# swap it with the greater element pointed by i
i = i + 1
# swapping element at i with element at j
(array[i], array[j]) = (array[j], array[i])
# swap the pivot element with the greater element specified by i
(array[i + 1], array[high]) = (array[high], array[i + 1])
# return the position from where partition is done
return i + 1
def quicksort(array, start, end):
if start < end:
p = partition(array, start, end)
print(p)
quicksort(array, start, p - 1)
quicksort(array, p + 1, end)
def quicksort2(array):
if array == []:
return []
if len(array) == 1:
return array
pivot, *rest = array
smaller = [element for element in array if element < pivot]
bigger = [element for element in array if element > pivot]
return quicksort2(smaller) + [pivot] + quicksort2(bigger)
if __name__ == "__main__":
#array = [10, 2, 7, 8, 3, 1]
array = [1, 2]
# array = [8, 7, 2, 1, 0, 9, 6]
print(quicksort2(array))
| true |
ffc17a58e989094e5a31092826b501a6b22f2652 | JayWelborn/HackerRank-problems | /python/30_days_code/day24.py | 417 | 4.125 | 4 | def is_prime(x):
if x <=1:
return False
elif x <= 3:
return True
elif x%2==0 or x%3==0:
return False
for i in range(5, round(x**(1/2)) + 1):
if x%i==0:
return False
return True
cases = int(input())
for _ in range(cases):
case = int(input())
if is_prime(case):
print("Prime")
else:
print("Not prime") | true |
27a8884bada5af0cb7fea5b1fcc5d6e255188150 | jeetkhetan24/rep | /Assessment/q11.py | 755 | 4.28125 | 4 | """
Write a Python program to find whether it contains an additive sequence or not.
The additive sequence is a sequence of numbers where the sum of the first two numbers is equal to the third one.
Sample additive sequence: 6, 6, 12, 18, 30
In the above sequence 6 + 6 =12, 6 + 12 = 18, 12 + 18 = 30....
Also, you can split a number into one or more digits to create an additive sequence.
Sample additive sequence: 66121830
In the above sequence 6 + 6 =12, 6 + 12 = 18, 12 + 18 = 30....
Note : Numbers in the additive sequence cannot have leading zeros.
"""
a = [6,6,12,18,30]
i=1
for i in range(0,len(a)-3):
if(a[i]+a[i+1]==a[i+2]):
x=1
else:
x=0
break
if(x==1):
print("The sequence is additive")
else:
print("The sequence is not additive") | true |
6febde39059c62422f858e99718fa7471c7aa50b | Aternands/dev-challenge | /chapter2_exercises.py | 1,538 | 4.25 | 4 | # Exercises for chapter 2:
# Name: Steve Gallagher
# EXERCISE 2.1
# Python reads numbers whose first digit is 0 as base 8 numbers (with integers 0-7 allowed),
# and then displays their base 10 equivalents.
# EXERCISE 2.2
# 5---------------> displays the number 5
# x = 5-----------> assigns the value "5" to the variable "x". Does not display anything.
# x + 1-----------> displays the sum of 5 and 1------>6.
# The script evaluates x + 1, but does not display a result. Changing the last line to "print x + 1"
# makes the script display "6"
# EXERCISE 2.3
width = 17
height = 12.0
delimeter = '.'
#1. width/2 ---------> 8 (Floor Division-answer is an integer)
#2. width/2.0--------> 8.5 (Floating Point Division- answer is a float)
#3. 1 + 2 * 5--------> 11 (integer)
#4. delimeter * 5----> '.....' (string)
# EXERCISE 2.4
#1. (4/3.0)*(math.pi)*(5**3)------>523.5987755982989
#2. bookcount = 60
# shipping = 3 + (bookcount-1) * .75
# bookprice = 24.95 * .6
# totalbookprice = bookprice * bookcount
# totalbookprice + shipping-------------------->945.4499999999999 (round to $945.45)
#3 (8 * 60) + 15---------> 495 (easy pace in seconds per mile)
# 495 * 2---------------> 990 (total time in seconds at easy pace)
# (7 * 60) + (15)-------> 435 (tempo pace in seconds per mile)
# 435 * 3---------------> 1305 (total time in seconds at tempo pace)
# 1305 + 990------------> 2295 (total time in seconds)
# divmod (2295, 60)-----> (38, 15)---------> 38:15 (total time in minutes)
# 7:30:15 am
| true |
6362fb8b4b02d0ad66a13f68f59b233cdde2038b | jgarcia524/is210_lesson_06 | /task_01.py | 847 | 4.5625 | 5 | #!usr/bin/env python
# -*- coding: utf-8 -*-
"""Listing even and odd numbers"""
import data
from data import TASK_O1
def evens_and_odds(numbers, show_even=True):
"""Creates a list of even numbers and a list of odd numbers.
Args:
numbers (list): list of numbers
show_even (bool): determines whether the function returns list
of even or odd values; default set to True
Returns:
A list of either odd or even values from numbers list.
Examples:
>>> evens_and_odds([1,2,3,4,5],show_even=False)
[1, 3, 5]
>>> evens_and_odds([1,2,3,4,5])
[2, 4]
"""
even = [x for x in numbers if x % 2 is 0]
odd = [x for x in numbers if x % 2 is not 0]
if show_even is False:
return odd
else:
return even
| true |
d2e2b75a85e09aab40dca105c1cf1cabe404ea07 | ScottPartacz/Python-projects | /Pick_3_Lotto.py | 2,334 | 4.1875 | 4 | # Scott Partacz 1/25/2018 ITMD 413 Lab 3
import time
import random
def check (picked,wining_numbers) :
if(wining_numbers == picked) :
win_or_lose = True
elif(wining_numbers != picked) :
win_or_lose = False
return win_or_lose;
def fireball_check(fireball,picked,wining_numbers) :
count = 0;
temp1 = sorted([fireball,picked[1],picked[2]])
temp2 = sorted([fireball,picked[0],picked[2]])
temp3 = sorted([fireball,picked[0],picked[1]])
#checks to see if the fireball would make the numbers a match
if(temp1 == wining_numbers) :
count += 1
if(temp2 == wining_numbers) :
count += 1
if(temp3 == wining_numbers) :
count += 1
return count
fireball_wining = 0
fireball_flag = input("do you want to play fireball? (enter y/n) ")
list = sorted(random.sample(range(0, 10), 3))
fireball = random.randint(0,10)
#this is used to check the program is working
#print(list,fireball);
while(True) :
print("Plese enter your 3 numbers sperated by a space")
numbers = [int(x) for x in input().split()]
numbers.sort()
# checks if you entered 3 numbers
if(len(numbers) != 3) :
print("\nError: 3 numbers were not entered")
continue
# checks if the numbers pick are between 0-9
elif((numbers[0] > 9 or numbers[0] < 0) or (numbers[1] > 9 or numbers[1] < 0) or (numbers[2] > 9 or numbers[2] < 0)) :
print("\nError: one of the numebrs entered wasnt 0-9")
continue
break
if(fireball_flag == "y") :
fireball_wining = fireball_check(fireball,numbers,list)
flag = check(numbers,list)
# checks the lotto result
if ((flag == True) and fireball_wining > 0) :
print("\nyou won $100 dollar cash prize and firball won too so an extra $50 times ",fireball_wining)
elif ((flag == False) and fireball_wining > 0) :
print("\nyou lost but since you had fireball you win $50 times ",fireball_wining)
elif (flag == True) :
print("\nyou win $100 dollar cash prize will be sent your way soon")
elif (flag == False) :
print("\nNice try, better luck next time ")
print("\nThe wining numbers were: ",end =" ")
print(list)
print("\nThe Fireball number was: ",end =" ")
print(fireball)
print (" ")
print ("Scott Partacz")
print ("Date:",time.strftime("%x"))
print ("Current time:",time.strftime("%X"))
| true |
92cd0001b602a0cdea7e03d6170ba6bd500aca0f | bauglir-dev/dojo-cpp | /behrouz/ch01/pr_13.py | 227 | 4.46875 | 4 | # Algorithm that converts a temperature value in Farenheit to a value in Celsius
farenheit = float(input("Enter a temperature value in Farenheit: "))
celsius = (farenheit - 32) * (100/180)
print(str(celsius) + ' Celsius.'))
| true |
d5dde1216cb6e77f8b92a47de57268447c4189c3 | V4p1d/Assignment-1 | /Exercise_4.py | 406 | 4.40625 | 4 | # Write a program that receives three inputs from the terminal (using input()).
# These inputs needs to be integers. The program will print on the screen the sum of these three inputs.
# However, if two of the three inputs are equal, the program will print the product of these three inputs.
# Example 1: n = 1, m = 2, l = 3, output = 1 + 2 + 3 = 6
# Example 2: n = 1, m = 2, l = 2, output = 1 * 2 * 2 = 4
| true |
2af76dc77f4cebd7d13f517141f6ef633c073700 | prakhar-nitian/HackerRank----Python---Prakhar | /Sets/Set_.intersection()_Operation.py | 2,053 | 4.3125 | 4 | # Set .intersection() Operation
# .intersection()
# The .intersection() operator returns the intersection of a set and the set of elements in an iterable.
# Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set.
# The set is immutable to the .intersection() operation (or & operation).
# >>> s = set("Hacker")
# >>> print s.intersection("Rank")
# set(['a', 'k'])
# >>> print s.intersection(set(['R', 'a', 'n', 'k']))
# set(['a', 'k'])
# >>> print s.intersection(['R', 'a', 'n', 'k'])
# set(['a', 'k'])
# >>> print s.intersection(enumerate(['R', 'a', 'n', 'k']))
# set([])
# >>> print s.intersection({"Rank":1})
# set([])
# >>> s & set("Rank")
# set(['a', 'k'])
# Task
# The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English,
# some have subscribed only to French, and some have subscribed to both newspapers.
# You are given two sets of student roll numbers. One set has subscribed to the English newspaper, one set has subscribed to the French
# newspaper. Your task is to find the total number of students who have subscribed to both newspapers.
# Input Format
# The first line contains n, the number of students who have subscribed to the English newspaper.
# The second line contains n space separated roll numbers of those students.
# The third line contains b, the number of students who have subscribed to the French newspaper.
# The fourth line contains b space separated roll numbers of those students.
# Constraints
# 0 < Total number of students in college < 1000
# Output Format
# Output the total number of students who have subscriptions to both English and French newspapers.
# Enter your code here. Read input from STDIN. Print output to STDOUT
eng_num = int(raw_input())
eng_set = raw_input().split()
eng_set = set(map(int, eng_set))
fren_num = int(raw_input())
fren_set = raw_input().split()
fren_set = set(map(int, fren_set))
print len(eng_set.intersection(fren_set))
| true |
843ddcb5a7fd997179c284d6c18074282a70ab0a | KULDEEPMALIKM41/Practices | /Python/Python Basics/67.bug.py | 295 | 4.5625 | 5 | print('before loop')
for i in range(10,0,-1): # -1 is write perameter for reverse loop.
print(i)
print('after loop')
print('before loop')
for i in range(10,0): # if we are not give iteration in range function. it is by default work
print(i) # on positive direction.
print('after loop') | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.