blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ea3ab35f3898ef36af6e484bafae5a243dabdf29 | kameshkotwani/python_assignment | /Assignment_1/grade.py | 1,138 | 4.34375 | 4 | '''
Exercise 1 Test Score Grades Problem Statement
Reboot Academy
This solution is created in python 3.6.4
CAUTION: MAY NOT WORK IN OLDER VERSION
Solved by: Kamesh Kotwani
'''
print("Welcome to Test Score Grade System! This System will help you find out your grade!")
#To take input from user about his test score
score =int(input("Please Enter your Test Score : "))
#To check if the score is above 90.
#No check is being is made if input is above 100 as not given in problem statement
if(score >=90):
print("Your grade is A! Congratulations!")
#To check if score is between 80 and 89
elif(score >=80 and score<=89):
print("You have got a B grade! Very Good!")
#To check if score is between 70 and 79
elif(score >=70 and score<=79):
print("You have got a C grade! Not so good....")
#To check if score is between 60 and 69
elif(score >=60 and score<=69):
print("You have got a D grade! you need to work hard....")
#To check if score is below 60
elif(score<60):
print("You have got an F, you are fail!")
#If input is not defined or any system error
else:
print("SYSTEM ERROR or INPUT ERROR!! Please TRY again.")
| true |
3e82ff08a0730088a2f7e6a172bc7aef913a021d | kameshkotwani/python_assignment | /Assignment_1/primes.py | 867 | 4.15625 | 4 | '''
Python Assignment 1 : Reboot Academy
To print the prime numbers in given range
Created using Python 3.6.4
CAUTION: MAY NOT WORK IN OLDER
Solved by: Kamesh Kotwani
'''
print("***Welcome to prime series!***")
n = int(input("Please enter upto which number primes should be displayed : "))
#Making sure if the user has entered a positive number or not
while(n<0):
n = int(input("Please enter upto which number primes should be displayed : "))
print(f"**List of prime numbers from 2 to {n}***")
for i in range(2,n + 1): #Counting from 2 through number
if(i > 1):
for j in range(2,i): #Another loop to find out divisibility
if (i%j== 0): #If divisible then breaking out of loop
break
else: #If not, then printing the number
print(f"{i}",end=" ")
| true |
3d755a8f1806e3d400fba196f694c5c9b08af718 | BradyBallmann/program-arcade-games | /Lab 04 - Camel/main_program.py | 2,558 | 4.25 | 4 | import random
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobie desert.")
print("The natives want their camel back and are chasing you down! Survive your")
print("desert trek and out run the natives.")
done = False
camel_thirst = 0
camel_tired = 0
miles_traveled = 0
distance_natives = -20
drinks_canteen = 3
random_oasis = random.randrange(1 , 21)
random_forward = random.randrange(10 , 21)
random_native = random.randrange(7 , 15)
random_tiredness = random.randrange(1 , 4)
random_moderate = random.randrange(5, 13)
while not done:
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
print()
user_answer = input("Your choice? ")
if user_answer.upper() == "Q":
done = True
elif user_answer.upper() == "E":
print("Miles traveled:", miles_traveled)
print("Drinks in canteen: ", drinks_canteen)
print("The natives are", str(distance_natives) + " miles behind you")
elif user_answer.upper() == "D":
camel_tired = 0
print("The camel is happy :D")
distance_natives = distance_natives + random_native
elif user_answer.upper() == "C":
miles_traveled = miles_traveled + random_forward
print("You traveled", str(miles_traveled) + " miles.")
camel_thirst = camel_thirst + 1
camel_tired = camel_tired + random_tiredness
distance_natives = distance_natives + random_native
elif user_answer.upper() == "B":
print("You traveled", str(random_moderate) + " miles.")
camel_thirst = camel_thirst + 1
camel_tired = camel_tired + 1
distance_natives = distance_natives + random_native
elif user_answer.upper() == "A":
drinks_canteen = drinks_canteen - 1
camel_thirst = 0
elif not done and camel_thirst < 4:
print("You are thirsty")
elif not done and camel_thirst < 6:
print("You died")
done = True
elif camel_tired > 5:
print("Your camel is getting tired")
elif camel_tired > 8:
print("Your camel is dead")
done = True
elif distance_natives >= miles_traveled:
print("The natives have caught you")
done = True
elif miles_traveled >= 200:
print("YOU WON!")
elif random_oasis == 10:
print("You found an oasis")
drink_canteen = 3
camel_thirst = 0
camel_tired = 0
| true |
eb4fa5d36aac209cfb4dab7657a2d63a2f336999 | BradyBallmann/program-arcade-games | /Lab 03 - Create a Quiz/main_program.py | 1,411 | 4.28125 | 4 | #!/usr/bin/env python3
# Creating a quiz
# Brady Ballmann
# 11/03/2017
percentage = 0
print('Ready for a quiz? :)')
question_one = input('Who won the 2017 World Series? ')
if question_one.lower() == "astros":
print("Correct!")
percentage += 1
else:
print('Incorrect!')
question_two = int(input("What is 5 * 432 / 4? "))
if question_two == 540:
print("Correct!")
percentage += 1
else:
print("Incorrect!")
print("What is the most common male name in the US?")
print("1. James")
print("2. Robert")
print("3. David")
print("4. Michael")
print("TIP! Enter the number not the name")
question_three = int(input('? '))
if question_three == 1:
print('Correct!')
percentage += 1
else:
print("Incorrect!")
question_four = int(input("What is 10 to the power of 3? "))
if question_four == 1000:
print("Correct!")
percentage += 1
else:
print("Incorrect!")
print('If an apple weighs about 3 and 1/2 ounces. What is the radius of the sun? ')
print("1. 432,288 mi")
print("2. 542,421 mi")
print("3. 674,321 mi")
print("4. 132,424 mi")
print("TIP! Enter the number not the name.")
question_five = int(input('? '))
if question_five == 1:
print('Correct!')
percentage += 1
else:
print("Incorrect!")
percent = percentage * 20
print("You got" , percentage, "out of 5")
print(percent, "percent! Congrats!")
| false |
b6cc6853e89b552fcf879332a2cf2384b2675738 | mikelopez/experimental-labs | /algorithms/heapsort/Python/heapsort_verbose.py | 2,536 | 4.1875 | 4 | """
Heapsort implementation
Timing complexity Best/worse/average: O(n log n)
Each parent node is greater than its child
Given n as the index number in question, find the left/right children
using the following:
- left: 2n + 1
- right: 2n + 2
Check to see if an element is greater than its children.
If not, the values of the element and child are swapped.
Continue to check this until the element is in a position where
it is greater than its children.
"""
def heapsort( aList ):
# convert aList to heap
length = len( aList ) - 1
print '- length is at %s' % length
leastParent = length / 2
print '- leastParent is at %s' % leastParent
for i in range ( leastParent, -1, -1 ):
print 'for %s in range %s, -1, -1' % (i, leastParent)
moveDown( aList, i, length )
print "\n----------FLATTENING ARRAY\n----------------\n\n"
# flatten heap into sorted array
for i in range ( length, 0, -1 ):
print "for %s in range(%s, 0, -1)" % (i, length)
print "\tA[0] = %s, A[i] = %s" % (aList[0], aList[i])
print "\tif A[0] > A[i]"
if aList[0] > aList[i]:
print "\t----Swapping(A, 0, %s)" % i
swap( aList, 0, i )
print "\t----A[0] = %s, A[i] = %s" % (aList[0], aList[i])
print "\tCalling movedown(A, 0, %s - 1)........" % (i)
moveDown( aList, 0, i - 1 )
def moveDown( aList, first, last ):
print '\t- movedown(A, %s, %s) ' % (first, last)
largest = 2 * first + 1
print '\t- largest = %s' % largest
print '\t- while %s <= %s' % (largest, last)
while largest <= last:
# right child exists and is larger than left child
print "\t\tif Largest < Last and A[%s] < A[%s + 1]" % (largest, largest)
if ( largest < last ) and ( aList[largest] < aList[largest + 1] ):
largest += 1
print "\t\tIncrementing largest + 1"
else:
print "\t\t-- !skip %s" % (largest+1)
# right child is larger than parent
print "\t\tA[%s], A[%s] = %s, %s" % (largest, first, aList[largest], aList[first])
print "\t\tif A[%s] > A[%s]" % (largest, first)
if aList[largest] > aList[first]:
print "\t\tSwapping (A, %s, %s) " % (largest, first)
swap( aList, largest, first )
print "\t\tAfter swapping, largest, first = %s, %s" % (largest, first)
# move down to largest child
first = largest;
largest = 2 * first + 1
print "\t\tSet first to %s" % first
print "\t\tSet largest to N*2+1 = %s" % (largest)
else:
return # force exit
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
| true |
e7572d9c14c53c4ea50d2d2206d4710819de753a | jjerry-k/learning_data_structure | /Tree/Priority_queue.py | 1,961 | 4.28125 | 4 | # Priority queue
# Abstract data type
# Using heap
def swap(tree, index_1, index_2):
temp = tree[index_1]
tree[index_1] = tree[index_2]
tree[index_2] = temp
def heapify(tree, index, tree_size):
left_child_index = 2 * index
right_child_index = 2 * index + 1
largest = index
if (0 < left_child_index < tree_size) and tree[index] < tree[left_child_index]:
largest = left_child_index
if (0 < right_child_index < tree_size) and tree[largest] < tree[right_child_index]:
largest = right_child_index
if largest != index:
swap(tree, index, largest)
heapify(tree, largest, tree_size)
def reverse_heapify(tree, index):
parent_index = index // 2
if 0 < parent_index < len(tree) and tree[index] > tree[parent_index]:
swap(tree, index, parent_index)
reverse_heapify(tree, parent_index)
class PriorityQueue:
def __init__(self):
self.heap = [None]
def insert(self, data):
# 1. insert data at last index
# 2. compare with parent node
# 3. swap or not
self.heap.append(data)
reverse_heapify(self.heap, len(self.heap)-1)
def extract_max(self):
root = 1
tail = len(self.heap)-1
swap(self.heap, root, tail)
val = self.heap.pop()
heapify(self.heap, root, len(self.heap))
return val
def __str__(self):
return str(self.heap)
# 실행 코드
priority_queue = PriorityQueue()
priority_queue.insert(6)
priority_queue.insert(9)
priority_queue.insert(1)
priority_queue.insert(3)
priority_queue.insert(10)
priority_queue.insert(11)
priority_queue.insert(13)
print(priority_queue)
print(priority_queue.extract_max())
print(priority_queue.extract_max())
print(priority_queue.extract_max())
print(priority_queue.extract_max())
print(priority_queue.extract_max())
print(priority_queue.extract_max())
print(priority_queue.extract_max()) | true |
6ddc98e49f12be54ad29d6ef0a70a6a9d4e75b49 | Minal2179/NLP-programs | /src/utils.py | 1,567 | 4.1875 | 4 | import sqlite3
# initialize the connection to the database
def db_connection():
connection = sqlite3.connect('chatdata.sqlite')
cursor = connection.cursor()
# create the tables needed by the program
create_table_request_list = [
'CREATE TABLE words(word TEXT UNIQUE)',
'CREATE TABLE sentences(sentence TEXT UNIQUE, used INT NOT NULL DEFAULT 0)',
'CREATE TABLE associations (word_id INT NOT NULL, sentence_id INT NOT NULL, weight REAL NOT NULL)',
]
for create_table_request in create_table_request_list:
try:
cursor.execute(create_table_request)
except:
pass
return connection
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
The "answer" return value is True for "yes" or False for "no".
- a Cut-and-Paste piece of code from Stack Overflow
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n") | true |
5ccff8703e594071092bf05fb3f7a2055e06f4b8 | mr-c/george_murray | /python_tutorials/sentdex_introduction/dna_complement.py | 328 | 4.15625 | 4 | sequenceInput = input("Find the reverse complement of this sequence: ")
def reverseComplement(sequenceInput):
complement = {'A':'T', 'C':'G', 'G':'C', 'T':'A'}
reverseComplement = []
for in sequenceInput:
reverseComplement = complement[base] + t
return reverseComplement:
print(reverseComplement)
| true |
c767575b68cbebef0b28f58d1eb202cead6b5248 | subiksharaman1/Rock-Paper-Scissors-Python | /Rock Paper Scissors.py | 1,127 | 4.1875 | 4 | import random
yourCount, computerCount = 0, 0
while True:
userin = input("Rock, paper or scissors? ").upper()
randNum = random.randint(0,2) #to generate computer's play
myList = ["ROCK", "PAPER", "SCISSORS"]
if userin == "ROCK":
uservalue = 0
elif userin == "PAPER":
uservalue = 1
elif userin == "SCISSORS":
uservalue = 2
elif userin == "END":
print("GAME OVER.")
break
else:
print("Please enter a valid input. END to stop the game.")
continue
#3 cases exist given that input is valid:
if (uservalue - randNum) == 1 or (uservalue - randNum) == -2:
print("Computer played " + myList[randNum] + ", YOU WIN!")
yourCount += 1
if (uservalue - randNum) == -1 or (uservalue - randNum) == 2:
print("Computer played " + myList[randNum] + ", YOU LOSE!")
computerCount += 1
if uservalue == randNum:
print("Computer played " + myList[randNum] + ", it's a draw.")
print("Your score: " + str(yourCount) + " Computer's score: " + str(computerCount))
| true |
929b51ad32bcbd56b6a330abea6076ccead0fbda | rumen89/programming_101_python | /week_1/sum_numbers.py | 639 | 4.125 | 4 | # Implement a Python script, called sum_numbers.py that takes one argument - a
# filename which has integers, separated by " ".
#
# The script should print the sum of all integers in that file.
import sys
def sum_numbers(string):
result = 0
number = '0'
for char in string:
if '0' <= char <= '9':
number += char
else:
result += int(number)
number = '0'
return result
def main():
filename = sys.argv[1]
with open(filename) as file:
file_to_string = file.read()
return sum_numbers(file_to_string)
if __name__ == '__main__':
print(main())
| true |
1fc8d328c2c6a67ca1098d958deb9f2320ed5ac1 | oliiiiiiiiiiiii/HowToFixPythonErrors | /Examples/RecursionErrorSolve.py | 568 | 4.15625 | 4 | # So lets create a function
def func(x):
return func(x)
# this would immediately raise RecursionError since calling this function will go on forever and ever
# you can see the maximum recurstion limit by printing sys.getrecursionlimit() like this
import sys
print(sys.getrecursionlimit())
# to fix a recursion error, add a base case.
def f(x):
if x == 5:
return x
z = x + 1
return f(z)
# the "if x == 5" in the above example is called a base case so we dont reach the max recursion limit
# now calling the function "f" will return 5
f(1)
| true |
87aa8ea053bb765dfeeaf9c0bf29c1b9928cd355 | LinnierGames/Core-Data-Structures | /source/search.py | 2,760 | 4.28125 | 4 | #!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return linear_search_recursive(array, item)
# return linear_search_recursive(array, item)
def linear_search_iterative(array, item):
# loop over all array values until item is found
for index, value in enumerate(array):
if item == value:
return index # found
return None # not found
def linear_search_recursive(array, item, index=0):
# if item is found
if array[index] == item:
return index
else:
# not found and has reached the end of the array
if index == len(array) -1:
return None
else:
# call recursively
return linear_search_recursive(array, item, index +1)
def binary_search(array, item):
"""return the index of item in sorted array or None if item is not found"""
# implement binary_search_iterative and binary_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return binary_search_iterative(array, item)
# return binary_search_recursive(array, item)
def binary_search_iterative(array, item):
length = len(array)
left = 0
right = length -1
# split array until left bound and right bound are equal
while left != right:
length = right - left +1
midpoint = length // 2 +left
# is item after/before midpoint
if item >= array[midpoint]:
# discard left half
left = midpoint
else:
# discard right half
right = midpoint -1
# does split array, of one, equal item?
if array[left] == item:
return left
else:
return None
def binary_search_recursive(array, item, left=None, right=None):
# setup left and right bounds
if left is not None:
length = right - left + 1
midpoint = length // 2 + left
else:
length = len(array)
left = 0
right = length -1
midpoint = length // 2
# does left and right equal the item
if length == 1:
if item != array[left]:
# not found, does not exist
return None
else:
# found
return left
# is item after/before midpoint
if item >= array[midpoint]:
# discard left
return binary_search_recursive(array, item, midpoint, right)
else:
# discard right
return binary_search_recursive(array, item, left, midpoint -1)
| true |
772e631557fd8381e2201e98ea0008b55d82dcb3 | jjack94/python-code-samples | /day-calc-jj.py | 422 | 4.375 | 4 | # James Jack
# 1/28/21
# this program takes the starting weekday/number of days gone and gives the weekday of the return
start = input("what day of the week did you leave? please input between 0-6 (0=sunday/6=saturday")
start = int(start)
days_gone = input(" how many days were you gone for?")
days_gone = int(days_gone)
end_day = (start + days_gone) % 7
print("the day of the week of your return is", end_day)
| true |
3b8d44aa019ceb6ef2fc545ffde159c57d6ed00b | SL-0305/Assignment-1 | /Assignment1_7.py | 334 | 4.25 | 4 | # Write a program which contains one function that accept one number from user and returns true
# if number is divisible by 5 otherwise return false.
def num(x):
if(x%5 ==0):
print("Number is divisible by 5")
else:
print("Number is not divisible by 5")
x=(int(input("Enter the number")))
num(x) | true |
20e3b3cf9239e32b7a4783dad33830ddd09c28b9 | lraynes/cheat_sheets | /5.5-Saturday/comprehension.py | 1,633 | 4.25 | 4 | prices= ["24", "13", "16000", "1400"]
#convert string to integer within all of list by looping through
price_nums = [int(price) for price in prices]
print(prices)
print(price_nums)
dog = "poodle"
letters = [letter for letter in dog]
print(letters)
print(f"we iterate over a string into a list: {letters}")
#capitalize by looping through each letter
capital_letters = [letter.upper() for letter in letters]
print(capital_letters)
#OR
capital_letters = []
for letter in letters:
capital_letters.append(letter.upper())
#eliminate a letter
no_o = [letter for letter in letters if letter != "o"]
print(no_o)
#or
no_o = []
for letter in letters:
if letter != "o":
no_o.append(letter)
june_temperature = [72,65,59,87]
july_temperature = [87,85,92,72]
august_temperature = [88,77,66,100]
temperature = [june_temperature,july_temperature,august_temperature]
low_temp = [min(temp) for temp in temperature]
print(low_temp)
#OR longhand
low_temp = []
for temp in temperature:
low_temp.append(min(temp))
#average
print(sum(low_temp)/len(low_temp))
print(low_temp[0])
print(low_temp[1])
print(low_temp[2])
max_temp = max(temp for temp in temperature)
print(max_temp)
#difference btn defining a function and calling a function
def name(parameter):
return "Hello " + parameter
print(name("Laura"))
#create average; sum function only works with list
def average(data):
return sum(data)/len(data)
print(average([1,2,3,4,5]))
#can have conditional in a function as long as only one return can happen at a time, no overlap
def mutiple3(a):
if(a % 3 == 0):
return True
else:
return False | true |
66c5876716099ac5bc870032a5f4a98815b43717 | lraynes/cheat_sheets | /5.1-Tuesday/basic_variables.py | 351 | 4.15625 | 4 | my_name = input("What is your name?")
neighbor_name = input("what is your neighbor's name?")
my_coding = int(input("How many months have you been coding?"))
neighbor_coding = int(input("How many months has your neighbor been coding?"))
print(my_name + ", " + str(my_coding) + " months")
print (neighbor_name + ", " + str(neighbor_coding) + " months") | true |
9a75cb732c37aec181ec1b3573ed9ae46d55b9ed | Dheerajkg/py-4-everybody | /wk03/Assign 3.1.py | 676 | 4.21875 | 4 | #3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly.
sh = input("Enter Hours:")
sr=input("enter rate")
fh = float(sh)
fr=float(sr)
if fh > 40:
reg=float(fr*(fh-5))
otp=(fh-40.0)*(fr*1.5)
xp=reg+otp
else:
xp=float(fh*fr)
print (xp) | true |
edf13334d1dbccb818dcd8714d52456ec91d8a0f | unblest/python | /ex35-2.py | 536 | 4.15625 | 4 | # a little 'what happens if' scenario
# basically, what happens if I have an 'if' function with an elif, but no else and something happens not covered by the 'if' function?
# turns out that nothing at all happens
# like actually nothing, so if you're expecting the if to return something (value, variable, function kick-off, list or whatever), thou art fucked without an else
response = raw_input("Choose 1 or 2: ")
if response == "1":
print "You selected 1! Good job!"
elif response == "2":
print "You selected 2! Good job!"
| true |
43f8d2211cf92bdf6f63f1644987ac57a3fa8ab4 | unblest/python | /ex4.py | 1,116 | 4.25 | 4 | # variable test file
# defines number of cars
cars = 100
# defines available space in a car
space_in_a_car = 4.0
# defines number of drivers
drivers = 30
# defines number of passengers
passengers = 90
# defines cars_not_driven as the number of cars minus the number of drivers lets see what happens if we scoot past this thingy
cars_not_driven = cars - drivers
# defines cars_driven as equal to the number of drivers
cars_driven = drivers
# defines the carpool_capacity as number of cars_driven multiplied by the space_in_a_car
carpool_capacity = cars_driven * space_in_a_car
# defines the average_passengers_per_car as equal to the number of passengers divided by the number of cars driven
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars avaialble."
print "There are only", drivers, "drivers avaialble."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
print "Hey %s there." % "you"
| true |
d8a8d80cb0aa64c09cfb783dfcf78f8a41151a12 | anderfernandes/COSC1315 | /chapter3/Fernandes_Chapter_3_3.py | 556 | 4.15625 | 4 | # Name: Anderson Fernandes
# Date: September 13, 2017
# Description: Exercise 3, Chapter 3
grade = input("Enter a grade: ")
try:
grade = float(grade)
# Check if grade is out of range
if (grade < 0.0 or grade > 1.0):
print("Bad score")
else:
# Find letter grade
if (grade >= 0.9):
print("A")
elif (grade >= 0.8):
print("B")
elif (grade >= 0.7):
print("C")
elif (grade >= 0.6):
print("D")
else:
print("F")
except:
print("Bad score")
| true |
17a7e013bb93ed7e5f1694dc21d72abcb6cdc445 | bmk15897/Prerequisite-Assignments | /frequencyApp.py | 1,236 | 4.25 | 4 | '''
Assignment 2 - Write a program to find frequency of each distinct word in a given text file ‘input.txt’. Your Output
should be stored in a different file named ‘output.txt’ in alphanumeric order. Each line should
contain the word and its frequency separated by a comma. (if numeric values are present in file
they should be at the start of output file). You can take any text file as your input file.
'''
import re
#frequency calculation function
def frequencyCalculation(inputFileName,outputFileName):
inputFile = open(inputFileName,'r')
fileContents = inputFile.read()
inputFile.close()
wordList = fileContents.split()
uniqueWordList = set(wordList)
convert = lambda text: int(text) if text.isdigit() else text
alphanumKey = lambda key: [convert(c) for c in re.split('([0-9]+)', key.strip())]
sortedWordList = sorted(uniqueWordList, key = alphanumKey)
frequencyCount = {i:0 for i in sortedWordList}
for i in wordList:
frequencyCount[i]+=1
outputFile = open(outputFileName,'w+')
for i in sortedWordList:
outputFile.write(i+","+str(frequencyCount[i])+"\n")
outputFile.close()
if __name__=='__main__':
frequencyCalculation('input.txt','output.txt')
| true |
e63d5be51fa356483a51acc355914e8450f46c19 | RhysLewingdon/COM404 | /2-Decisions/beeppainting.py | 573 | 4.21875 | 4 | def directioncode():
direction = input("Which direction should I paint in? ")
if direction == "up":
print("I am painting in the upward direction!")
elif direction =="down":
print("I am painting in the downward direction!")
elif direction =="left":
print("I am painting in the left direction!")
elif direction =="right":
print("I am painting in the right direction!")
else:
print("Please enter a valid direction (up, down, left, or right).")
directioncode()
directioncode()
print("Painting complete!") | true |
907c4b7450d11eeccc3a5a356faf5a3ddb4a46f9 | RhysLewingdon/COM404 | /2-Decisions/NestedDecisions.py | 750 | 4.125 | 4 | firstlook = input("Where should I look? ")
if firstlook == "in the bedroom":
secondlook = input("Where in the bedroom should I look? ")
if secondlook == "in the cupboard":
print("Found some mess but no battery.")
else:
print("---------")
elif firstlook == "in the bathroom":
secondlook = input("Where in the bathroom should I look? ")
if secondlook == "in the bathtub":
print("Found a rubber duck but no battery.")
else:
print("---------")
elif firstlook == "in the lab":
secondlook = input("Where in the lab should I look? ")
if secondlook == "on the table":
print("Yes! I found my battery!")
else:
print("---------")
else:
print("---------")
print("Finished.") | true |
b1476310b78859982e2c1c2f3c45f6aacd958a20 | PallabPandaOwn/python101 | /variables/venv/src/Assignment-6/assignment-6-solution-2.py | 981 | 4.46875 | 4 | # Assignment 6
# Create a function that takes in two parameters: rows, and columns, both of which are integers.
# The function should then proceed to draw a playing board (as in the examples from the lectures) the same number of rows and columns as specified.
# After drawing the board, your function should return True.
import shutil
maxcol = shutil.get_terminal_size()[0]
maxrow = shutil.get_terminal_size()[1]
print("Max column size : {0} and Max row size : {1} are available in current terminal".format(maxcol, maxrow))
def create_board(cols, rows):
if cols <= maxcol and rows <= maxrow:
for r in range(rows):
for s in range(cols):
print("|_", end="")
print("|")
return True
else:
print("specified rows and cols are bigger than terminal max row and col size")
return False
if create_board(10, 100):
print("Board has been created successfully")
else:
print("Failed to create board")
| true |
fb40d5c8310767bfde315a33f45a355a9ee19703 | pitzcritter/CodingDojo--Python | /16 Dictionary in, tuples out.py | 802 | 4.21875 | 4 | #Assignment: Dictionary in, tuples out
#Write a function that takes in a dictionary and returns a list of tuples where the first tuple item is the key and the second is the value. Here's an example:
### function input
#my_dict = {
# "Speros": "(555) 555-5555",
## "Michael": "(999) 999-9999",
## "Jay": "(777) 777-7777"
#}
#function output
#[("Speros", "(555) 555-5555"), ("Michael", "(999) 999-9999"), ("Jay", "(777) 777-7777")]
myDict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
def toTuple(dic):
order = ['Speros','Michael', 'Jay']
print tuple([myDict[field] for field in order])
print [(k, v) for k, v in myDict.iteritems()]
this = []
for k,v in myDict.items():
this.append((k,v))
print this
toTuple(myDict) | true |
93a79d4b7a6e850940f4273dd7acf56f1f9eeb0b | mattalhamilton-zz/Python-and-Bash-Scripts | /Mod02Tutorial.py | 2,562 | 4.21875 | 4 | ##Matthew Hamilton
##Mod 02 Tutorial
import random
def rando_insert(thing_being_inserted):
position = random.randint(0,9)
my_list.insert(position, thing_being_inserted)
counter = 0
my_list = []
while counter < 10:
list_item = input('Please enter a word or a number: ')
my_list.append(list_item)
counter += 1
ints_only = []
print('\nTask 1 - Check the length of the list\n')
print('This list has 10 items. ' + str(len(my_list) == 10 ))
print('\nTask 2 - Print the list\n')
print(my_list)
print('\nTask 3 - Swapping first item with the last item in the list then print the list.\n')
first_thing = my_list[0]
my_list[0] = my_list[-1]
my_list[-1] = first_thing
print(my_list)
print('\nTask 4 - Print the first 3 items in the list and the last three in the list.\n')
print(my_list[0:3], my_list[-3:])
print('\nTask 5 - Loop through and print all the items in the list.\n')
for i in my_list:
print(i)
print('\nTask 6 - Use an IF statement to check to see if the word "cat" is \nin the list and let the user know.')
if 'cat' in my_list:
print('\nThere is a cat in my list')
else:
print('There is no cat in my list')
print('\nTask 7 - Get the name of a Marvel character from the user and pass that \nto a function that randomly inserts the name into the list (import random).')
another_item = input('\nPlease insert the name of a Marvel character: ')
rando_insert(another_item)
print('\nTask 8 - Get the index for the Marvel character and print it out so \nthat it looks nice.')
print(another_item + ' is at index ' + str(my_list.index(another_item)))
print('\nTask 9 - Copy all the integers in the original list to a new list, then sort and print out that list.')
for matt in my_list:
try:
int(matt)
ints_only.append(int(matt))
except:
continue
ints_only.sort()
print ('\nThese are the integers from the list')
print (ints_only)
print('\nTask 10 - Convert the original list to a tuple and print the tuple.\n')
my_tuple = tuple(my_list)
print(my_tuple)
print('\nTask 11 - Try and change the first item in the tuple to "cat", but catch the error and print out Tuples are immutable!\n')
try:
my_tuple[0] = 'cat'
except:
print('Tuples are immutable!')
print('\nTask 12 - Copt this new list in the text box into your script.\n')
list_in_list = [[1,2,3],['a','b','c']]
for i in list_in_list:
for j in i:
print(j)
print()
print('press enter to end the script')
input()
| true |
e45f96adbf1b1e13f47a1038100542f5089c3174 | minhld99/Data-Structure-and-Algorithms-in-Python | /SelectionSort/SelectionSort.py | 626 | 4.15625 | 4 | # Selection Sort
def selectionSort(array):
for i in range(len(array)):
index = i
for j in range(i+1, len(array)):
if array[j] < array[index]: # Ascending Order
index = j # Find smallest element
if index != i: swap(array, index, i) # Swap with left most element
return array
def swap(arr, x, y):
temp = arr[x]
arr[x] = arr[y]
arr[y] = temp
# ---------------- Testing --------------------
if __name__ == '__main__':
array = [9,6,69,10,100,96,26,4]
print("Unsorted array: ", array)
print(selectionSort(array)) | true |
db311282123ef6391f78de33be38a30fcf1ae0ac | piyush09/LeetCode | /Valid Parentheses.py | 1,672 | 4.15625 | 4 | """
Algo: An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
An empty string is also considered valid.
If opening bracket, push it onto the stack
If closing bracket, then check the element on top of the stack. If the element at the top of the stack is an opening bracket of the same type, then pop it off the stack and continue processing. Else, this implies an invalid expression.
T.C. - O(n), as, traverse the given string one character at a time and push and pop operations on a stack take O(1)O(1) time.
S.C. - O(n), as pushing all opening brackets onto the stack and in the worst case, all the brackets will be pushed onto the stack.
"""
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
# Initializing parantheses dictionary
parantheses_dict = {"]": "[", "}": "{", ")": "("}
for character in s: # Iterating over each character in string s
if character in parantheses_dict.values():
stack.append(character)
elif character in parantheses_dict.keys():
if stack == [] or parantheses_dict[character] != stack.pop():
# If the stack is empty or no matching parantheses
return False
else:
# If another character is encountered apart from parantheses
return False
# As empty string is also a valid string
return stack == []
str = "()[]{}"
test = Solution()
print (test.isValid(str)) | true |
a62d37fd43ffb0159ed660d559dfbaa900b25328 | piyush09/LeetCode | /Climbing Stairs.py | 636 | 4.15625 | 4 | """
Algo: Use concept of Fibonacci number
Fib(N) = Fib(N-1) + Fib(N-2)
Find nth number of the fibonacci series with Fib(1)=1 and Fib(2)=2.
T.C. - O(N) - Single loop upto n to calculate nth fibonacci number.
S.C.- O(1) - Constant space is used.
"""
def climbStairs(n):
if (n == 1):
return 1
first = 1 # Initialize first as ways to climb 1 stair to 1
second = 2 # Initialize second as ways to climb 2 stairs to 2
# Iterate till number 'n'
for i in range(3, (n + 1)):
third = first + second
first = second
second = third
return second
# n = 2
n = 4
print (climbStairs(n)) | true |
7d6f74a667a6d43df0f8cbb77f11279ac64056ee | piyush09/LeetCode | /Invert Binary Tree.py | 1,566 | 4.21875 | 4 | """
Algo: Call invert of left subtree, call invert of right subtree.
Swap left and right subtrees.
Time and Space complexities similar to Tree traversal time and space complexities.
T.C. - O(N) - 'N' is the number of nodes as calculated by Master theorem.
S.C. - O(N) - Explained below - When tree is completely skewed
Auxiliary Space: If size of stack for function calls is not considered, then O(1), otherwise O(N)
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def InorderTraversal(node):
if node is None:
return
# first recur on left child
InorderTraversal(node.left)
# then print the data of node
print (node.val),
# now recur on right child
InorderTraversal(node.right)
class Solution:
def invertTree(self, root):
# Inverting left and right subtrees and swapping them.
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
def main():
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(7)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(6)
root.right.right = TreeNode(9)
print("Inorder Traversal of input binary tree: ")
InorderTraversal(root)
print ("\n Inverting binary tree:")
Solution().invertTree(root)
print("Inorder Traversal of Inverted binary tree: ")
InorderTraversal(root)
main() | true |
3cc47b4b74284b03e3fee038af7a71adb3ade386 | piyush09/LeetCode | /Product of Array Except Self.py | 1,008 | 4.53125 | 5 | """
Algo: Initialise output array corresponding to each element.
Calculate the product of numbers to the left of each array element
Calculate the product of numbers to right of each array element
T.C. - O(N), 'N' number of items in nums list, as two for loops to iterate through the numbers
S.C. - O(N), Output array is the only array used for it.
"""
def productExceptSelf(nums):
output = [1] * len(nums) # Output array values intialised to 1 with length equal to length of nums
prod = 1 # Initialise product to 1
for i in range(len(nums)): # Calculating the product of numbers to the left of each array element
output[i] = output[i] * prod
prod = prod * nums[i]
prod = 1 # Again making product value as 1
for i in range(len(nums) - 1, -1, -1): # Calculating the product of numbers to right of each array element
output[i] = output[i] * prod
prod = prod * nums[i]
return output
nums = [1,2,3,4]
print (productExceptSelf(nums)) | true |
b83d7216748e58b73d8b344a8f29f3b1ff39ac82 | vtphan/Graph | /example.py | 872 | 4.25 | 4 | from graph import Graph, DGraph
print("Example of unweighted undirected graph")
G = Graph()
G.add(2,3) # add edge (2,3); (3,2) is automatically addeded.
G.add(3,5) # add edge (3,5); (5,3) is automatically addeded.
G.add(3,10) # add edge (3,10); (10,3) is automatically addeded.
print( (3,5) in G ) # True
print( (5,3) in G ) # True
print( (10,5) in G ) # False
for v in G.Vertices:
print("vertex", v)
for e in G.Edges:
print("edge", e)
print("Neighbors of vertex 3:")
for v in G.Neighbors[3]:
print("\t", v)
print("\nExample of weighted directed graph")
D = DGraph()
D.add(2,3,10)
D.add(2,5,20)
D.add(3,5,30)
for e in D.Edges:
print("Edge", e, "has weight", D[e])
print("Vertices that vertex 3 points to")
for v in D.Out[3]:
print("\t", v)
print("Vertices that point to vertex 5.")
for v in D.In[5]:
print("\t", v)
| true |
185ed6725b9da7a6f3e3b0d3a1448378d688d835 | rramosaveros/CursoPythonCisco | /Ejercicios/EjemploIfElseElif.py | 251 | 4.1875 | 4 | n = input("Ingres el nombre: ")
if n == "Espatifilo":
print("Si, ¡El Espatifilo es la mejor planta de todos los tiempos!")
elif n == "pelargonio":
print("!Espatifilo! ¡No pelargonio!")
else:
print("No, ¡quiero un gran Espatifilo!") | false |
f8a266e34c14259927ddc819901b9043f1630559 | lamwilton/DSCI-553-Data-Mining | /HW4/test.py | 2,359 | 4.34375 | 4 | # Python3 Program to print BFS traversal
# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict
import networkx as nx
import matplotlib.pyplot as plt
# This class represents a directed graph
# using adjacency list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
# Function to print a BFS of graph
def BFS(self, s):
tree = defaultdict(dict) # Use list for unweighted graph
levels = defaultdict(int)
# Mark all the vertices as not visited
visited = defaultdict(bool)
# Create a queue for BFS
queue = []
# Mark the source node as
# visited and enqueue it
queue.append(s)
levels[s] = 0
visited[s] = True
while queue:
# Dequeue a vertex from
# queue and print it
s = queue.pop(0)
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent
# has not been visited, then mark it
# visited and enqueue it
for i in self.graph[s]:
if not visited[i]:
queue.append(i)
tree[s][i] = 0
levels[i] = levels[s] + 1
visited[i] = True
else:
# If visited, add edge only if they are at lower levels
if levels[i] > levels[s]:
tree[s][i] = 0
return tree, levels
# Driver code
# Create a graph given in
# the above diagram
g = Graph()
g.addEdge(1, 2)
g.addEdge(1, 3)
g.addEdge(2, 3)
g.addEdge(2, 4)
g.addEdge(4, 5)
g.addEdge(4, 6)
g.addEdge(4, 7)
g.addEdge(5, 6)
g.addEdge(6, 7)
tree5, levels5 = g.BFS(3)
# https://stackoverflow.com/questions/52763876/create-a-weighted-networkx-digraph-from-python-dict-of-dicts-descripton
for k, d in tree5.items():
for ik in d:
#d[ik] = {'weight': 6}
pass
nxgraph = nx.DiGraph(tree5)
nx.draw_planar(nxgraph, with_labels=True)
# nx.draw_networkx_edge_labels(nxgraph, pos=nx.spring_layout(nxgraph))
plt.show()
print() | true |
d71078dc702fc51e10036779ab14e796e5af64bf | arnav13081994/python-deepdive | /python-problems/main.py | 1,540 | 4.40625 | 4 | # Implement a class Rectangle
class Rectangle:
def __init__(self, height, width):
""" Initialises an instance of the Rectangle Class"""
# _width and _height are internal (private) Rectangle Instance's attributes. This is something
# We keep to ourselves to make sure the User can't just update these attrs randomly and also
# so that the code has backward compatibility.
self._width = None
self._height = None
# Lets now use the SETTER Method the width and height of the newly initialised Rectangle Class
self.width = width
self.height = height
@property
def width(self):
""" Gets the width"""
return self._width
@property
def height(self):
""" Gets the height"""
return self._height
@width.setter
def width(self, width):
""" Sets the Width"""
if width <= 0:
raise ValueError("Width should be Positive")
self._width = width
@height.setter
def height(self, height):
""" Sets the Height"""
if height <= 0:
raise ValueError("Height should be Positive")
self._height = height
def area(self):
""" Returns the Area of the Rectangle"""
return self.width * self.height
def perimeter(self):
""" Returns the Perimeter of the Rectangle"""
return 2 * (self.width + self.height)
def __le__(self, other):
""" Implements the Less than or Equal to Operator"""
if not isinstance(other, Rectangle):
raise NotImplementedError("Please use an object of class <Rectangle> only")
return (self.width == other.width and self.height == other.height) or (self.area() < other.area())
| true |
a97cad540333cf0c7095454117b8453fa5ff3e63 | srikanthpragada/PYTHON_17_JUN_2021 | /demo/oop/sum_of_numbers.py | 299 | 4.15625 | 4 | # Accept 5 numbers and display total
# Make sure invalid numbers are ignored
total = 0
count = 1
while count <= 5:
try:
num = int(input(f"Enter Number {count} :"))
total += num
count += 1
except ValueError:
print("Invalid Number!")
print("Total :", total)
| true |
c8ef8ba64d8eaf418bb2964df54e47defe394860 | gdeep141/Small-projects | /recursion.py | 1,162 | 4.1875 | 4 | """
""" Solve a maze using recursive backtracking
"""
string = """\
#################
# ### ##
# #### #### ## ##
# #### ## ##
# ############ ##
# * ## # #
#### #### ##
#################
"""
# get height and width of maze
height = 0
width = 0
for i in string:
if i == "\n":
break
else:
width += 1
for j in string:
if j == "\n":
height += 1
# create maze
maze = []
for i in range(height):
row = []
for j in range(width):
col = ' '
row.append(col)
maze.append(row)
# set values in maze to string
row = 0
col = 0
for i in string:
if i == '\n':
row += 1
col = 0
else:
maze[row][col] = i
col += 1
# solve maze
def solve(row, col):
maze[row][col] = '.'
# check values surrounding current location
for i, j in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
if maze[row + i][col + j] == '*':
print("solution found")
print_maze()
input("Continue?")
elif maze[row + i][col + j] == ' ':
solve(row + i, col + j)
maze[row + i][col + j] = ' '
return False
def print_maze():
for row in maze:
for col in row:
print(col, end = '')
print()
solve(1, 1)
print("No more solutions found")
| false |
78918e02e1d80ecb19c4956e4f81a992f828204a | krishnasairam/sairam | /cspp1-assignments/m22/assignment1/read_input.py | 288 | 4.34375 | 4 | '''
Write a python program to read multiple lines of text input and store the input into a string.
'''
def main():
'''printing string'''
int_input = int(input())
for _ in range(int_input):
string = input()
print(string)
if __name__ == '__main__':
main()
| true |
eba393633d02982f36662cf070b6cb8ccff695be | krishnasairam/sairam | /cspp1-assignments/m7/Functions - Assignment-1/assignment1.py | 859 | 4.1875 | 4 | '''credit card company each month.'''
def paying_debtoff(previous_balance, annual_interest, monthly_payment_rate):
'''updated_balance'''
monthly_interest = (annual_interest) / 12.0
updated_balance = previous_balance
i_temp = 1
while i_temp <= 12:
monthly_payment = monthly_payment_rate * updated_balance
monthly_unpaid_balance = updated_balance - monthly_payment
updated_balance = monthly_unpaid_balance + (monthly_interest * monthly_unpaid_balance)
x_out = round(updated_balance, 2)
i_temp += 1
return x_out
def main():
'''enter previous_balance, annual_interest, monthly_payment_rate'''
data = input()
data = data.split(' ')
data = list(map(float, data))
print("Remaining balance: " + str(paying_debtoff(data[0], data[1], data[2])))
if __name__ == "__main__":
main()
| true |
628f709ae0400b44a40d7d62f362f8f13a5c7f3f | Abhinav-Bala/ICS3U | /problem_set_1/hypotenuse_calculator.py | 892 | 4.4375 | 4 | # Abhinav Balasubramanian
# Feb. 18, 2021
# ICS3UO-C
# This program will output the length of the hypotenuse given the two other sides of a triangle
import math # imports the math library
print('Hello, this program will calculate the legnth of the hypotenuse of a right-triangle.') # prints welcome message
# INPUT
side_a = float(input('Enter the length of the first side: ')) # variable for inputted side a casted as a float
side_b = float(input('Enter the length of the second side: ')) # variable for inputted side b casted as a float
# PROCESSING
side_c = math.sqrt((side_a * side_a) + (side_b * side_b)) # determines the length of side c using the pythagorean theorem
side_c = round(side_c, 1) # rounding the length of side c to 1 decimal place
# OUTPUT
print('The length of the hypotenuse is: ' + str(side_c) + ' cm') # outputs text and concatenates the casted string side c
| true |
d99a4e06de6a02d7862be368a3e16e4872ef5aee | Abhinav-Bala/ICS3U | /problem_set_2/leap_year_checker.py | 815 | 4.1875 | 4 | # Abhinav Balasubramanian
# March 1, 2021
# ICS3UO-C
# This program will check whether an inputted year is a leap year or not
#INPUT
print("This program will check to see whether a given year is a leap year.") # displays welcome message
year = int(input("Please enter a year: ")) # gets user input for year and then casts it as an int
#PROCESSING AND OUTPUT
if year % 4 == 0: # checks if the year is divisible by 4
if year % 100 == 0: # checks if the year is divisible by 100
if year % 400 == 0: # checks if the year is divisible by 400
print(str(year) + " is a leap year.")
else:
print(str(year) + " is not a leap year.")
else:
print(str(year) + " is a leap year.")
else:
print(str(year) + " is not a leap year.") # concatenates the year and prints the answer | true |
857bd453c9a11176d797fd4f288ca4300869782a | Abhinav-Bala/ICS3U | /problem_set_2/integer_classifier.py | 1,275 | 4.21875 | 4 | # Abhinav Balasubramanian
# March 1, 2021
# ICS3UO-C
# This program will check whether an inputted integer is even or odd and positive, negative or zero
#INPUT
print("This program will determine whether an integer is even or odd.\nIt will also determine if the integer is positive, negative or zero") # displays welcome message
user_int = int(input("Enter your integer: ")) # gets user input, casts it as a float and then assings it to the variable user_int
#PROCESSING AND OUTPUT
# checks if user_int is positive or negative
if user_int % 2 == 0: # if the remainder is zero that means it is divisible by two
print(str(user_int) + " is an even integer.") # concatenates user_int and prints that the integer is even
else:
print(str(user_int) + " is an odd integer.") # concatenates user_int and prints that the integer is odd
# checks if user_int is positive, negative or 0
if user_int == 0: # checks if user_int is the integer 0
print("This integer is also 0 (not positive or negative).") # concatenates user_int and prints that the integer is 0
elif user_int > 0: # checks if user_int is greater than 0
print("This integer is also positive.") # prints that the integer is positive
else:
print("This integer is also negative.") # prints that the integer is negative
| true |
c1f8ff78272f8ed6b31bcc67d213abc124aba27d | patchen/battleship | /src/queue.py | 1,063 | 4.15625 | 4 | class EmptyQueueError(Exception):
'''Raised when pop is called on an empty Queue.'''
pass
class Queue(object):
'''A First-in, first-out (FIFO) Queue of items'''
def __init__(self):
'''(Queue) -> None
A new empty Queue.
'''
self.contents = []
def __str__(self):
return str(self.contents)
def enqueue(self, v):
'''(Queue, object) -> None
Adds v to the end of the line.
'''
self.contents.append(v)
def dequeue(self):
'''(queue) -> object
Remove and return the first item of the queue. Also adjusts front position.
'''
if self.is_empty():
raise EmptyQueueError
return self.contents.pop(0)
def is_empty(self):
'''(Queue) -> bool
Return whether this Queue is empty.
'''
return not self.contents
def queue_del(self):
'''(Queue) -> None
Deletes everything from the Queue.
'''
self.contents = []
| true |
3f408c1c2d8d338e47358196c085d7cdfcb83d4c | TimLatham/Udacity_Projects | /Intro_to_Programming/Stage2/productList.py | 666 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 08 11:42:46 2017
@author: tim.latham
"""
# Define a procedure, product_list,
# that takes as input a list of numbers,
# and returns a number that is
# the result of multiplying all
# those numbers together.
def product_list(list_of_numbers):
product = 1
count = 0
if len(list_of_numbers) == 0:
return product
else:
while count < len(list_of_numbers):
product = product * list_of_numbers[count]
count += 1
return product
print product_list([9])
#>>> 9
print product_list([1,2,3,4])
#>>> 24
print product_list([])
#>>> 1 | true |
10049e0cc0a8c73474b69b91920513ba703c77d2 | KeeReal/cpsmi_python | /task01.py | 512 | 4.125 | 4 | # coding=utf-8
# Введенную с клавиатуры строку вывести на экран наоборот (использовать цикл).
def reverse_string(string):
result = ""
length = len(string)
for i in range(length):
result += string[length - i - 1]
return result
if __name__ == '__main__':
print 'type q to quit'
string = ''
while string != 'exit':
string = raw_input("any string: ")
print 'reverse: %s' % reverse_string(string)
| false |
b0968020e5522d050502bbce3e560f89daaa8c84 | shiningflash/Competitive-Programming-Resources | /Sorting-Algorithms/insertion_sort.py | 578 | 4.1875 | 4 | """
Insertion Sort
Time Complexity
1. Best case: O(N)
2. Avg. case: O(N^2)
3. Worst case: O(N^2)
Space Complexity: O(1)
Stable: Yes
Useage:
1. small array
2. few elements left unsorted
"""
def insertion_sort(arr):
for i in range(len(arr)):
for j in range(i, 0, -1):
if arr[j] < arr[j-1]:
arr[j-1], arr[j] = arr[j], arr[j-1]
else:
break
return arr
if __name__ == '__main__':
arr = [5, 1, 423, 12, -1, -1231, 9, 0, -1]
print('before: ', arr)
insertion_sort(arr)
print('after: ', arr)
| false |
232ff848d0862b4b0a3565c34e1d22bf16428806 | MRichardN/Palindromes | /palindrome.py | 807 | 4.15625 | 4 | #string = input("Please enter a word:")
#string = [n for n in input('Enter numbers: ').split()]
#def palin(word1):
def palindrome(word):
word = input("Please enter a word:")
word = word.lower().replace(' ', '')
if not word.isalpha():
return '{} is not a string. Enter srings only'.format(word)
if list(word) == list(reversed(word)):
return "{} is a palidrome".format(word)
return "{} is not a palidrome".format(word)
print(palindrome(word))
word = input("Please enter a word:")
word = word.lower().replace(' ', '')
if not word.isalpha():
print '{} is not a string. Enter srings only'.format(word)
if list(word) == list(reversed(word)):
print "{} is a palidrome".format(word)
print "{} is not a palidrome".format(word)
#print(palindrome(word)) | false |
480c91a41ef1908fa06bea190e258477d28ca7d7 | SuperMartinYang/learning_algorithm | /leetcode/easy/Balanced_Binary_Tree.py | 1,215 | 4.15625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
if (self.maxDepth(root.left) - self.maxDepth(root.right) > 1) or (
self.maxDepth(root.right) - self.maxDepth(root.left) > 1):
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
def maxDepth(self, root):
"""
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1 | true |
155032d5e5c60b31d7c9ee313a3d27161cbb5f6e | lindaduong25/PythonChooseYourOwnAdventureGame | /FirstGame.py | 1,667 | 4.1875 | 4 | print("Welcome to Random Guessing!")
name = input("What is your name? ")
age = int(input("What is your age? "))
points = 20
if age >= 15:
print("You are old enough to play!")
wants_to_play = input("Do you want to play? ").lower()
if wants_to_play == "yes":
print("Let's begin then!")
print("Let's start you off with 20 points, but beware, the decisions you make may cost you.... mwahahahah")
red_or_green = input("First choice... Red or Green (red/green)? ").lower()
if red_or_green == "red":
ans = input("Correct! You chose the correct answer, now you come to a stop sign, do you turn left or right (left/right)? ").lower()
if ans == "right":
print("You have reached a dead end! You will have to be re-set on your track and therefore will lose 10 points.")
points -= 10
elif ans == "left":
print("Awesome, you have made it across the road.")
ans = input("You come to a fruit tree, do you pick the apple or the orange (apple/orange)? ").lower()
if ans == "apple":
print("You were poisoned by the apple, whoopsie. You lose 10 points.")
points -= 10
if points <=0:
print("You have no more points to use and have lost the game.")
else:
print("You win!")
else:
print("Wrong choice, you have lost!")
else:
print("Wrong! You lose, sorry...")
else:
print("Goodbye!")
else:
print("You are not old enough to play...")
| true |
902571ea8243955347359783adc96ff2a611c83d | pildurr/indexing | /indexing.py | 316 | 4.34375 | 4 | """Given a string of any length named s.
Extract and then print the first and last characters of the string (with one space between them).
For example, given s = 'abcdef'
the output will be
a f"""
s = input("Input a string: ")
s_first = s[0]
s_last = s[-1]
s_modified = s_first + " " + s_last
print(s_modified) | true |
a859edb41cd4e5781e9e677f9a083eb38d802483 | giosermon/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-append_write.py | 400 | 4.40625 | 4 | #!/usr/bin/python3
""" Append to a file """
def append_write(filename="", text=""):
"""Function to append a text in a file
Args:
filename (str): Name of the file to append to.
text (str): Text to append to the file.
Return:
The numbers of characters written.
"""
with open(filename, 'a', encoding="utf-8") as file:
return (file.write(text))
| true |
dafb603481281b3abbbe04ee96a308dfccce51c8 | gbmikhail/pyalg | /lesson_2/task_3.py | 481 | 4.15625 | 4 | # 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
# Например, если введено число 3486, надо вывести 6843.
n = int(input("Введите число: "))
m = 0
while n > 0:
m = (m * 10) + (n % 10)
n = n // 10
print(f"Обратное по порядку входящих в него цифр число: {m}")
| false |
f6c81a96ef98a1d413ba85ab89209ef920b894bf | MaunikQ/Sample | /Assesment Python/Q14.py | 229 | 4.125 | 4 | def power_of_two(n):
if(n==1):
return True
if(n%2==0):
return power_of_two(n/2)
else:
return False
if __name__ == '__main__':
num = int(input('Enter the number to be checked: '))
power = power_of_two(num)
print power | true |
6ebd58bb8157899588ca6376671ac33f40919007 | sunil2982/python_core | /story.py | 1,299 | 4.375 | 4 | #initializing variables
girlname = " "
boyname = " "
girl_desc = " "
boy_desc = " "
walk_desc = " "
animal = " "
gift = " "
answer = " "
#taking input from user
girlname=input("enter a girl name")
girlname=girlname.capitalize()
boyname = input("input a boy name")
boyname = boyname.capitalize()
girl_desc= input("enter name of flower")
girl_desc =girl_desc.lower()
boy_desc = input("enter the type of boy")
boy_desc = boy_desc.lower()
walk_desc = input("enter how you dance ")
walk_desc =walk_desc.lower()
animal =input("enter the name of animal you have ride on")
animal = animal.lower()
answer = input("what would you say to some one who gives you car??")
answer = answer.lower()
gift = input("what you want most")
gift = gift.lower()
# print("once upone a time ")
# print("their is a girl whos name was {}".format(girlname)
#story printing
print("\nOnce upon a time,")
print("there was a girl named " + girlname + ".")
print("One day, " + girlname + " was walking like doing" + walk_desc + " down the street.")
print("Then she met a " + boy_desc + " boy named " + boyname + ".")
print("He said, 'You are really beautiful like a" + girl_desc + "!'")
print("She said '" + answer + ", " + boyname + ".'")
print("Then they both rode away on a " + animal + " and lived happily ever after.") | true |
71171fbe056a8efc0134caee636e0abcb1a86e5c | sunil2982/python_core | /forloop_turtle.py | 279 | 4.15625 | 4 | import turtle
numsides = int(input("how many sides you want ??"))
tut=turtle.Turtle()
for step in range(numsides):
tut.forward(step+100)
tut.right(360/numsides)
for step in range(numsides):
tut.forward(step+70)
tut.right(360/numsides)
turtle.done() | true |
32d5718ae55bee81b9617efb2a96506c28280ecd | WangYangLau/learnpython | /dict.py | 509 | 4.125 | 4 | # -*- coding:utf-8 -*-
#dict
index = False
print('dict')
d = {'Michael':80,'Lisa':95,'Jack':72,'Bart':0}
d['Bart'] = 98
while index==False:
print('enter the name you find:')
name = input()
index = name in d
if index==False:
print('Without this guy,Do you want to insert one?(yes/no)')
a = input()
if a=='yes':
d.setdefault(name,0)
print(d)
else:
pass
else:
pass
print('Have this guy,enter his score:')
score = input()
d[name] = score
print(d)
print('Lisa' in d) #返回True or False
| true |
7b33c4306d1b85d58244af8db01481bac45cd763 | ceirius/teaching-python | /rectangle 1.py | 738 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
write a program to compute area of a rectangle
"""
class Rectangle:
length = 0
breadth = 0
def __init__(self, length, breadth):
self.breadth = breadth
self.length = length
# print(self.length, self.breadth)
def getArea(self):
area = self.length * self.breadth
print("the area of the rectangle is: ", area)
def getPerimeter(self):
perimeter = 2 * (self.length + self.breadth)
print ("the perimeter of the rectangle is: :", perimeter)
s = Rectangle(1,3)
s.getArea()
s.getPerimeter()
t = Rectangle(3.5, 35.7)
t.getArea()
t.getPerimeter() | true |
097c4751288031f243ddbabb730d0320f900fddb | ALittleRunaway/Data_Visualisation | /Random walk/random_walk.py | 1,403 | 4.3125 | 4 | """random walk"""
from random import choice
class RandomWalk():
"""Класс для генерирования случайных блужданий"""
def __init__(self, num_points=5000):
"""Инициализирует атрибуты блуждания"""
self.num_points = num_points
# Все блуждающиеся точки начинаются с (0, 0)
self.x_values = [0]
self.y_values = [0]
@staticmethod
def get_step():
"""Finds a step"""
step = choice([1, -1]) * choice([0, 1, 2, 3, 4]) # [-4, 4]
return step
def fill_walk(self):
"""Вычисляет все точки блуждания"""
# Шаги генерируютя до достижения нужной длины
while len(self.x_values) < self.num_points:
# Определение направления и длины перемещения
x_step = self.get_step()
y_step = self.get_step()
# Отклонение нулевых перемещений
if x_step == 0 and y_step == 0:
continue
# Вычисление следущих значений x и y
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
| false |
ac23cdb1ea2110040c84fdccbc435fef2a27becf | carlosalbertoestrela/Lista-de-exercios-Python | /01 Estrutura_Sequencial/07.py | 272 | 4.15625 | 4 | # 7) Faça um Programa que calcule a área de um quadrado,
# em seguida mostre o dobro desta área para o usuário.
lado = float(input('Digite um lado do quadrado: '))
area = lado**2
print(f'A area do quadrado de {lado}x{lado} é {area:.2f} eseu dobor é {area*2:.2f}')
| false |
49056292713787d81f6fc41c3a5b82743a3ad38f | carlosalbertoestrela/Lista-de-exercios-Python | /02 Estrutura_de_Decisão/07.py | 479 | 4.15625 | 4 | """
07) Faça um Programa que leia três números e mostre o maior e o menor deles.
"""
num1 = int(input('Digite o primeiro número: '))
menor = maior = num1
num2 = int(input('Digite o segundo número: '))
if num2 < menor:
menor = num2
if num2 > maior:
maior = num2
num3 = int(input('Digite o terceito número: '))
if num3 < menor:
menor = num3
if num3 > maior:
maior = num3
print(f'O meior número digitado foi: {maior}\nO menor número digitado foi: {menor}')
| false |
f091044a71ad01668f3f49011c42e6e0662e2a20 | carlosalbertoestrela/Lista-de-exercios-Python | /03 Estrutura_de_repetição/13.py | 437 | 4.1875 | 4 | """
13) Faça um programa que peça dois números, base e expoente, calcule e mostre o primeiro número
elevado ao segundo número. Não utilize a função de potência da linguagem
"""
base = int(input('Digite a BASE: '))
expo = int(input('Digite o EXPOENTE: '))
result = int()
for n in range(1, expo):
if n == 1:
result = base * base
else:
result *= base
print(f"{base} elevado a {expo} é igual a {result}")
| false |
f798ed52493f88698c93a21d0fc352b4b9494a9a | carlosalbertoestrela/Lista-de-exercios-Python | /02 Estrutura_de_Decisão/04.py | 287 | 4.21875 | 4 | """
04) Faça um Programa que verifique se uma letra digitada é vogal ou consoante.
"""
letra = str(input('Digite uma letra: ')).strip().upper()[0]
if letra in 'AÀÁÂÃEÈÉÊIÌÍÎOÒÓÔÕUÚÙÛ':
print(f'{letra} é uma VOGAL!')
else:
print(f'{letra} é uma CONSOANTE!')
| false |
9cc5fdb85ad8fe2e4e78b09c3fd7a08e44d581b1 | carlosalbertoestrela/Lista-de-exercios-Python | /05 Funções/02.py | 411 | 4.125 | 4 | """
02) Faça um programa para imprimir:
1
1 2
1 2 3
.....
1 2 3 ... n
para um n informado pelo usuário. Use uma função que receba um valor n inteiro imprima até a n-ésima linha.
"""
def print_cont_seq(num):
for n in range(num+1):
for i in range(1, n+1):
print(f'{i} ', end='')
print()
print_cont_seq(int(input('Digite um número: ')))
| false |
305a69c20bddb73dc4e8c13f162a251c065e0c2e | carlosalbertoestrela/Lista-de-exercios-Python | /03 Estrutura_de_repetição/18.py | 555 | 4.15625 | 4 | """
18) Faça um programa que, dado um conjunto de N números, determine o menor valor, o maior valor e a soma dos valores.
"""
maior = menor = soma = cont = 0
while True:
num = int(input('Digite um número: (0 para parar) '))
if soma == 0:
maior = menor = num
if num == 0:
break
elif num > maior:
maior = num
elif num < menor:
menor = num
soma += num
print(f'O MAIOR número digitado foi {maior}\n'
f'O MENOR número digitado foi {menor}\n'
f'A SOMA dos números digitados é {soma}')
| false |
a584d51da5e3146246ab96cbb8c46dd1c6e54cad | lisboaxd/exercicios-python-brasil | /estrutura-sequencial/ex06.py | 224 | 4.125 | 4 | #Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
from math import pi
raio = float(input(u"Insira o raio do círculo: "))
area = pi*(raio**2)
print("A área do cícurlo é : {0}".format(area))
| false |
1e2e1fec71c9fc5657d9b4931d0d825741280711 | joselufb/Sudoku_Solver | /200914_Sudoku_Solver.py | 1,877 | 4.15625 | 4 | '''
Python array Sudoku solver
References:
https://towardsdatascience.com/solve-sudokus-automatically-4032b2203b64
'''
# Example of sudoky board
# Gaps are represented with number 0
board_test = [
[0, 0, 9, 8, 0, 0, 7, 6, 0],
[5, 0, 3, 6, 0, 7, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 3, 0, 5],
[2, 5, 0, 0, 8, 0, 6, 0, 0],
[0, 9, 7, 0, 6, 5, 0, 0, 4],
[8, 0, 0, 0, 4, 2, 0, 0, 3],
[0, 3, 8, 0, 2, 6, 0, 0, 7],
[0, 7, 0, 0, 0, 8, 5, 0, 0],
[6, 0, 0, 0, 7, 0, 0, 0, 0],
]
def print_board(board):
# Print the soduku in a visual way with its grid
for i in range(len(board)):
line = " "
if i == 3 or i == 6:
print("-----------------------")
for j in range(len(board[i])):
if j == 3 or j == 6:
line += "| "
line += str(board[i][j]) + " "
print(line)
def find_empty(board):
# Find the next empty position (indicated by 0)
# and return a tupple
for x in range(9):
for y in range(9):
if board[x][y] == 0:
return x, y
return -1,-1
def valid(board, i, j, num):
# Check if num is contained in the row
check_row = True
for x in range(9):
if num == board[i][x]:
check_row = False
# Check if num is contained in the column
check_column = True
if check_row:
for x in range(9):
if num == board[x][j]:
check_column = False
# Check if num is contained in the box 3x3
if check_column:
box_x = 3*(i // 3)
box_y = 3*(j // 3)
for x in range(box_x, box_x + 3):
for y in range(box_y, box_y + 3):
if board[x][y] == num:
return False
return True
return False
def solve(board, i=0, j=0):
i, j = find_empty(board)
if i == -1:
return True
for num in range(1, 10):
if valid(board, i, j, num):
board[i][j] = num
if solve(board, i, j):
return True
board[i][j] = 0
return False
print_board(board_test)
solve(board_test)
print("\nThe solution is:\n")
print_board(board_test)
| true |
715347f5a6fb822fda4119b97d948b99d0976a06 | akadi/TDD | /romain_numerals.py | 1,550 | 4.25 | 4 | # -*- coding: utf-8 -*-
# Author: Abdelhalim Kadi <kadi.halim@gmail.com>
# Convert arabic numbers into roman numbers.
# Constst
DICT_NUMS = { 1: u'I',
2: u'II',
3: u'III',
4: u'IV',
5: u'V',
6: u'VI',
7: u'VII',
8: u'VIII',
9: u'IX',
10: u'X',
50: u'L',
500: u'D',
1000: u'M'
}
def get_romain_numerals(number):
u"""
This function is used for convert an arabic numbers into romain numbers.
number - an arabic number.
return - a romain representation for this number.
Example: get_romain_numerals(1) --> u'I'.
"""
repr_romain = u""
keys = sorted(DICT_NUMS.iterkeys())
if number in keys:
return u"{0}{1}".format(repr_romain, DICT_NUMS.get(number, ''))
else:
# Look for the element in keys who is the closest to our number
# We return Concatinating value of element \
# and value of (number - key) if number-element in DICT_NUMS.keys()
# else we recall get_romain_numerals with (number - key) argument.
# (recursive function )
i = 0
j = 1
while number not in xrange(keys[i], keys[j]):
i += 1
j += 1
repr_romain = "{0}{1}{2}".format(
repr_romain,
DICT_NUMS[keys[i]],
get_romain_numerals(number - keys[i]))
return repr_romain
| false |
5365eb7c3d8b6e9bef15361f0006c2b80405795a | luanquanghuy/Python-Projects | /bai2/list.py | 894 | 4.15625 | 4 | numbers = [1, 2, 3, 4, 5]
names = ['Quang', 'Huy', 'Luan']
print('nhap: ')
# index = int(input())
# print(type(index))
# print(numbers[1])
# try:
# print('dung', numbers[index])
# except IndexError:
# print('Nhap sai')
print(3 in numbers)
print(2 not in numbers)
print('huy' in names)
print('Huy' in names)
print(numbers[2:4])
del numbers[2]
print(numbers)
del numbers[1:3]
print(numbers)
print(numbers + names)
numbers.append(10)
print(numbers)
numbers.pop(2) #Lay phan tu cuoi cung ra khoi mang va tra ve gia tri phan tu cuoi cung do
print(numbers)
"""Day la multi-line comment"""
bo = True
bo = 3.14
print(str(bo))
str1 = "Quang"
str2 = "Huy"
print("Ten toi %s la %s" % (str1, str2))
from datetime import datetime
now = datetime.now()
print(now)
print(now.time())
choices = ['pizza', 'pasta', 'salad', 'nachos']
for index, item in enumerate(choices):
print(index + 1, item) | false |
cd64ee861ad81f45fad453c188e83e46fad005b7 | soberoy1112/Lintcode | /my_answer/454.py | 787 | 4.125 | 4 | #/usr/bin/env python3
# -*- coding: utf-8 -*-
class Rectangle(object):
def __init__(self, width, height):
self.__width = width
self.__height = height
def setArea(self, width, height):
if width > 0 and height > 0:
self.__width = width
self.__height = height
else:
print('Sorry, we don\'t accept minus and zero!')
self.__width = 0
self.__height = 0
def getArea(self):
return self.__width * self.__height
area = Rectangle(1, 1)
print("""The initial square is 1 x 1.
So the area of initial square is 1.
Now, please give the width and height of your square:""")
x = int(input('The width = '))
y = int(input('The height = '))
area.setArea(x, y)
z = area.getArea()
if z > 0:
print('The area of your square is: %d' % z)
else:
print('')
| true |
e6e31b042637bc7745abd2b269e09ad83f57adab | tarcisiovale/Pyquest | /envExemplo/Lista01/Lista01Ex07.py | 541 | 4.125 | 4 | """
Escreva um programam que calcule o índice de massa corpórea (IMC) de uma pessoa,
sendo o peso e a altura fornecidos pelo teclado. Apresentar na tela o peso, a altura
e o IMC calculado.
Exemplo: Valores fornecidos pelo teclado: Peso = 60kg e Altura = 1,67m
Cálculo do IMC = 60 / (1,67)² = 60 / 2,78 = 21,5
"""
peso= float(input('Digite seu peso:'))
altura= float(input('Digite sua altura:'))
imc= (peso / (altura**2))
print('Valores fornecidos, Peso= {:.2f}kg, Altura {:.2f}m, cálculo do imc é de {:.2f}'.format(peso, altura, imc))
| false |
77c3c90343834f3bf77f54d5951e385f985da7b9 | tarcisiovale/Pyquest | /envExemplo/Lista04/Lista04Ex07.py | 228 | 4.25 | 4 | # Programa para converter temperatura de Fahrenheit para Celsius
temp_celsius = lambda f: (5/9) * (f - 32)
f = float(input('Entre com a temperatura em Fahrenheit:'))
print(f'A temperatura em Celsius é: {temp_celsius(f):0.2f}')
| false |
78c45bfb60be63747dcbed7872731067edf76d4f | ravenusmc/flask_weather | /basic.py | 1,718 | 4.15625 | 4 | #This file will contain information to display basic information.
import pandas as pd
import numpy as np
#This class will be used to pull weather information for me
class Weather():
#I was using this method to set up the initial attribute but I needed
#to reset the attribute each time I used it.
# def __init__(self):
# pass
#self.__data = pd.read_csv('weather.csv')
#This method will get the average mean temperature per day.
def get_mean_temp(self):
self.__data = pd.read_csv('weather.csv')
self.__data = self.__data[[1]]
mean = self.__data['actual_mean_temp'].mean()
return mean
#This method will get the average mean high temperature per day.
def get_mean_high_temp(self):
self.__data = pd.read_csv('weather.csv')
self.__data = self.__data[[3]]
high_mean = self.__data['actual_max_temp'].mean()
return high_mean
#This method will get the average mean low temperature per day.
def get_mean_low_temp(self):
self.__data = pd.read_csv('weather.csv')
self.__data = self.__data[[2]]
low_mean = self.__data['actual_min_temp'].mean()
return low_mean
#This method will get the average mean rain per day.
def get_mean_rain(self):
self.__data = pd.read_csv('weather.csv')
self.__data = self.__data[[10]]
rain_mean = self.__data['actual_precipitation'].mean()
return rain_mean
#### Practice code here ######
#Code ideas that I tried out.
# weather = Weather()
# weather.get_mean_rain()
# print(data._Weather__age)
#print(weather._Weather__data.get_mean_temp())
# print(weather.get_mean_high_temp())
#print(weather.get_mean_temp())
| true |
f8b40ee65abf9adb5187079836a9e5cd6b3be4d3 | sudonitin/dsa | /sorting/algorithms/selection_sort.py | 1,316 | 4.21875 | 4 | ''' selection_sort.py
############### NOTES ###############
=> From GFG
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
** Time Complexity: O(n2) as there are two nested loops.
** Auxiliary Space: O(1)
The good thing about selection sort is it never makes more than O(n) swaps and can be useful when memory write is a costly operation.
=> My Note
- No need to maintain different arrays, this can be done in-place
- Simply swap the minimum number with current index
'''
def selection_sort(arr):
for i in range(len(arr)):
temp = arr[i]
for j in range(i, len(arr)):
temp = arr[j] if temp > arr[j] else temp
if temp != arr[i]:
tempIndex = arr.index(temp)
arr[i], arr[tempIndex] = arr[tempIndex], arr[i]
print(arr)
return 1
def main():
arr = list(map(int, input().split(' ')))
selection_sort(arr)
main()
# input examples
# 64 25 12 22 11 | true |
1e77ca5042a4c3093dfe60ed40777c1fbab53b98 | branhoff/automation_class | /1.FilenamesAndFilepaths/rename_files.py | 1,464 | 4.25 | 4 | # import modules we'll need
import datetime
import os
def get_curr_month_name():
"""
Pulls current month as long form name i.e. "January"
"""
today = datetime.date.today()
curr_month = today.strftime("%B")
return curr_month
# Function to rename multiple files
def main():
print(os.getcwd())
for filename in os.listdir("1.FilenamesAndFilepaths\\work_files"):
print(filename)
# What we have:
# We can currently iterate through a list of filenames, but we still need to change
# the names of the "filename" variable. We should remember that strings are immutable
# so we can't just tell python to cut out the "October" in the filename and replace it with November.
# REMEMBER YOU CAN GOOGLE
# Steps to think about:
# 1. Need to convert the "filename" into something that is mutable (an object that can be changed) i.e. a list
# 2. Change the part of the mutable that represents "October" to "November"
# 3. Convert that mutable back to a normal string like before, but now with the correct name
# 4. Change the current ACTUAL name of the file to our new name
# TRY GOOGLING "how to change string to list in python"
# "how to create new folder in python"
# "how to copy files in python"
# "how to rename files in python"
# Driver Code
if __name__ == '__main__':
# Calling main() function
main() | true |
9f8bf1d75c990ffe082f866e9284e66ec70face2 | blakexcosta/Unit3_Python_Chapter10 | /main.py | 557 | 4.15625 | 4 | import turtle
# defining a method and default value
def add_list_numbers(list_name=[1, 2]):
total = 0
for number in list_name:
total = total + number
return total
# palindrome checker
def is_palindrome(orig_string):
letters_list = list(orig_string)
letters_list.reverse()
rev_string = ''.join(letters_list)
return orig_string == rev_string
def main():
some_list = [2, 4, 4]
print(add_list_numbers(some_list))
print("hello")
print(is_palindrome("tacocat"))
if __name__ == "__main__":
main()
| true |
26308787dd7f1c240868fbc8d93f3886a2c320f0 | parthcode/PythonMorningBatch | /caseAndOperators.py | 847 | 4.15625 | 4 | """
1.If else statement
These are the case statement in python which executes a block of code based on a condition
2.operators
comp : > , < , == , !=, >= , <=
"""
# x = 90
# y = 10
# print("sum", x + y)
# print("difference", x - y)
# print("product", x * y)
# print("Divide", x/y)
# print("reminder", x % y)
"""
check if a number is odd or even
"""
# input_number = int(input("Enter a number"))
#
# if input_number % 2 == 0:
# print("Even")
# elif input_number > 30:
# print("greater than 30")
# else:
# print("odd")
# user_name = ['alex', 'lexi', 'ramu kaka', 'lala land']
# name = input("Enter the name")
# if name in user_name:
# print(True)
# else:
# print(False)
user_details = {'Name': 'alex', 'age': 21, 'address': 'mumbai' }
name = input("Enter the name")
if name in user_details:
print(True)
else:
print(False) | true |
5e5017d97146b53314768b0e266c0ec145148956 | luiscssza/LeWa | /Pre_Work/LeWa_4_OOP.py | 2,346 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 13 10:18:39 2021
@author: luis
"""
# REAL PYTHON_OOP in Python 3
##############################################################################
# class Dog():
# # Class atribute
# species = "Canis familiaris"
# # DUNDER METHODS
# #INIT
# def __init__(self, name, age): # Instance atributes: name, age
# self.name = name
# self.age = age
# def __str__(self):
# return f"{self.name} is {self.age} years old"
# # INSTANCE METHODS
# def speak(self, sound):
# return f"{self.name} says {sound}"
##############################################################################
# class Car():
# def __init__(self, color, mileage):
# self.color = color
# self.mileage = mileage
# def __str__(self):
# return f"The {self.color} car has {self.mileage} miles."
# TO PRINT
# for car in (blue_car, red_car):
# print(f"The {car.color} car has {car.mileage:,} miles.")
##############################################################################
# INHERANCE
# class Dog():
# # Class atribute
# species = "Canis familiaris"
# # DUNDER METHODS
# #INIT
# def __init__(self, name, age, breed): # Instance atributes: name, age
# self.name = name
# self.age = age
# self.breed = breed
# def __str__(self):
# return f"{self.name} is {self.age} years old"
# # INSTANCE METHODS
# def speak(self, sound):
# return f"{self.name} says {sound}"
# class JackRussellTerrier(Dog):
# pass
# class Car():
# def __init__(self, brand, color):
# self.brand = brand
# self.color = color
# self.engine_started = False
# def start_engine(self):
# self.engine_started = True
# def stop_engine(self):
# self.engine_started = False
# def change_color(self, new_color):
# self.color =new_color
###############################################################################
# OOP LECTURES
###############################################################################
# CS50-OOP and AI
# Python OOP for Beginners (Tim)
# APIs basics
# I have added some stuff here to try to understand a pull-request
| false |
dee38444d6f8a2f8c2aa551cb4eea9bdaa497743 | nathanvanderleest/python | /while.py | 314 | 4.1875 | 4 |
# while loops
#use Ctrl+C to terminate the program.
import random
num1 = random.randint(1,6)
print("Guess the number:", end=" ")
guess = int(input())
count = 1
while guess != num1:
guess = int(input("Guess again: "))
count += 1
print("Your Right! It took you", count, "guesses")
| true |
25b43575af8086bb90db7271aecf7476668771af | nyy7/supermarket_register | /scripts/register.py | 904 | 4.125 | 4 | #!/usr/bin/python
#########
# author: Yanyan Ni
# date: 12/15/17
# description: a function to run calculator and print proper output
#########
from calculator import Calculator
import sys, os
def run(sku):
register = Calculator(sku)
if register.input_validation():
total_price = register.price_calculator()
#print('Total amount of sale: %s' %total_price)
price_with_tax = register.add_tax(total_price)
#print('Taxes: %s' %(register.tax))
#print('Final cost: %s' %(price_with_tax))
print('%s' %(price_with_tax))
return True
else:
print("input is not valid")
return False
if __name__=='__main__':
if len(sys.argv) == 1:
if 'SKU' in os.environ:
sku = os.environ['SKU']
else:
print 'please set SKU in environmental variable'
sys.exit()
elif len(sys.argv) == 2:
sku = sys.argv[1]
else:
print 'Wrong parameters, please input SKU of the product'
sys.exit()
run(sku)
| true |
c71c06e09a7ceae228dc30158aef6f5af69c504a | Jokerzhai/python-files | /module_exercise/directionary.py | 791 | 4.4375 | 4 | """
字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。
列表是有序的对象集合,字典是无序的对象集合。
两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典用"{ }"标识。字典由索引(key)和它对应的值value组成。
字典的输出是无序的
键与值分离
"""
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name':'joker','code':
'6734','dept':'sales'} #这里的:是用来分开键与值
print dict['one'] #输出键为'one'的值
print dict[2] #输出键为2的值
print tinydict #输出完整的字典
print tinydict.keys() #输出所有键
print tinydict.values() #输出所有值 | false |
d4e829315440537e1934c6650fe835b8d9216555 | srane96/Data-Structure-and-Algorithms-Using-Cpp-and-Python | /Python/linked_list.py | 2,976 | 4.28125 | 4 | class Element(object):
""" Element object represents each element in the linked list."""
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinkedList(object):
""" Linked list manages all the Element objects. """
def __init__(self, head=None):
self.head = head
def print_list(self):
""" Print values of the linkedList elements. """
current = self.head
lst = []
while current:
lst.append(current.value)
current = current.next
print lst
def append(self, new_element):
""" Append new element to the current Linked list. """
current_element = self.head
if current_element:
while current_element.next:
current_element = current_element.next
current_element.next = new_element
else:
self.head = new_element
def get_position(self, position):
""" Get element from a perticular position. Position starts from 0.
Return None if no element is present at the given position. """
count = 0
current = self.head
if position < 0:
return None
while current and count <= position:
if count == position:
return current
else:
current = current.next
count += 1
return None
def insert(self, new_element, position):
""" Insert a new element at the given position. """
if position < 0:
print("Invalid position")
return None
if position == 0:
new_element.next = self.head
self.head = new_element
else:
count = 0
current_element = self.head
while current_element and count <= position - 1:
if count == position - 1:
new_element.next = current_element.next
current_element.next = new_element
count += 1
current_element = current_element.next
def delete(self, value):
""" Delement element with given value"""
previous = None
current = self.head
while current.next and not current.value == value:
previous = current
current = current.next
if current.value == value:
if previous:
previous.next = current.next
else:
self.head = current.next
# Test DS
# initialize Elements
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
# Create a LinkedList
ll = LinkedList(e1)
ll.append(e2)
ll.append(e3)
ll.append(e4)
ll.print_list()
# get_position test
print ll.get_position(2).value
e5 = Element(5)
# insert test
ll.insert(e5,3)
ll.print_list()
print ll.get_position(3).value
# delete test
ll.delete(4)
ll.print_list()
print ll.get_position(0).value
print ll.get_position(1).value
| true |
8fad61fa51fa6835a34e3abc8f3d0cba86b90229 | srane96/Data-Structure-and-Algorithms-Using-Cpp-and-Python | /Python/selection_sort.py | 583 | 4.1875 | 4 | def selection_sort(input_array):
""" Get the smallest element and put it in the front. """
for i in range(len(input_array)):
smallest = input_array[i]
smallest_ind = i
for j in range(i+1,len(input_array)):
if input_array[j] < smallest:
smallest = input_array[j]
smallest_ind = j
if not smallest_ind == i:
temp = input_array[i]
input_array[i] = smallest
input_array[smallest_ind]= temp
# Test selection sort
l = [9,8,12,6,55,5,4,3,2,1]
selection_sort(l)
print(l)
| true |
adf32b219f9121da3445ad7e34316fae972d79d3 | illusionist99/Python_BootCamp_42 | /module00/ex01/exec.py | 365 | 4.15625 | 4 | import sys
args = sys.argv[1:]
args.reverse()
displayed = ""
for word in args:
for letter in word[::-1]:
if letter.islower():
displayed += letter.upper()
elif letter.isupper():
displayed += letter.lower()
else:
displayed += letter
if word != args[-1]:
displayed += ' '
print(displayed)
| true |
6888d2e97d55e36f5483bac4682ba1231c4a29c3 | isaackrementsov/led-circuit | /Blinking_LED.py | 1,307 | 4.1875 | 4 | # Isaac Krementsov
# 3/8/2020
# Introduction to Systems Engineering
# Blinking LED - Controls two blinking LED lights
import RPi.GPIO as GPIO
import time
# GPIO pin numbers where the red and yellow LED circuits are connected
RED_PIN = 18
YELLOW_PIN = 24
# Set the GPIO header board to Broadcom Model setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Setup the two pins, connected to the red and yellow LEDs, for output
GPIO.setup(RED_PIN, GPIO.OUT)
GPIO.setup(YELLOW_PIN, GPIO.OUT)
# Blink the two LEDs for a period of time in an alternating pattern
def blink_LED(red_pin, yellow_pin, blink_time):
# Set the power output to high for the red LED circuit and low for the yellow
GPIO.output(red_pin, GPIO.HIGH)
GPIO.output(yellow_pin, GPIO.LOW)
# Force the program to wait before switching the lights
time.sleep(blink_time)
# Switch the power settings for the red and yellow circuits
GPIO.output(red_pin, GPIO.LOW)
GPIO.output(yellow_pin, GPIO.HIGH)
# Wait before running the method again
time.sleep(blink_time)
# Blink the LEDs 20 times
for _ in range(20):
# Run the blink_LED function to blink the lights for 2 seconds
blink_LED(RED_PIN, YELLOW_PIN, 2)
# Shut off the yellow light, since it would still be on otherwise
GPIO.output(YELLOW_PIN, GPIO.LOW)
| true |
514acdf2ac68d64a26b1f913e4e5bbed05b6a495 | cpm205/ML_algorithm | /python/data_normalization/data_normalization.py | 1,182 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 12:23:07 2019
@author: derekh
"""
"""
It is a technique we use in Machine Learning and Deep Learning is to normalize our data.
It often leads to a better performance because gradient descent converges faster after normalization.
"""
"""
Implement normalizeRows() to normalize the rows of a matrix.
After applying this function to an input matrix x, each row of x should be a vector of unit length (meaning length 1).
"""
import numpy as np
def normalizeRows(x):
"""
Implement a function that normalizes each row of the matrix x (to have unit length).
Argument:
x -- A numpy matrix of shape (n, m)
Returns:
x -- The normalized (by row) numpy matrix. You are allowed to modify x.
"""
### START CODE HERE ### (≈ 2 lines of code)
# Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)
x_norm = np.linalg.norm(x, axis=1, keepdims = True)
# Divide x by its norm.
x = x/x_norm
### END CODE HERE ###
return x
x = np.array([
[0, 3, 4],
[1, 6, 4]])
print("normalizeRows(x) = " + str(normalizeRows(x))) | true |
b2785d0c67d2de85f4674cb5263b3e0599505a07 | rahulshivsharan/LearnPython01 | /ex27.py | 879 | 4.28125 | 4 |
def fun01():
nList = [2,4,3,7]
print("Original List ",nList) # printing original list
# looping through list 'nList' and multiple each element by 2
newList = [x*2 for x in nList]
print("Mulitply each element by 2")
print("Product of 2 ",newList)
nList = [12,45,15,67,28,19]
print("Original List ",nList) # printing original list
# filtering only even numbers
newList = [num for num in nList if num%2 == 0]
print("Even Number list ",newList)
# looping through and applying lambda expression
nList = [23,42,64,18,24,67,23,89]
print("Original List ",nList) # printing original list
# filter function
def fn(num):
return (num%3 == 0)
filterFn = filter(fn,nList) # get the filter refenrence
newList = list(filterFn)
print("Number divisible by three ",newList)
fun01()
| true |
05078c86bcc8680eef50048f60759c3052f33617 | acirederf/freddie-learns-python | /ex3.py | 1,283 | 4.5 | 4 | # This will print the thing it says.
print "I will now count my chickens:"
# This will print "Hens" and then calculate 25 plus 30 divided by 6
print "Hens", 25 + 30 / 6
# This will print "Roosters" and calculate the remainder of 100 minus the remainder of 75 divided by 4, which is 3.
print "Roosters", 100 - 25 * 3 % 4
# This will print the thing it says.
print "Now I will count the eggs:"
# This will calculate 3 plus 2 plus 1 minus 5 + 0 (the remainder of 4 divided by 2) - 0 (1 divided by 4 with the fractional bit dropped) plus 6
# That is, 3 + 2 + 1 - 5 + 0 - 0 + 6, which is 7
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Printy printy.
print "Is it true that 3 + 2 < 5 - 7?"
# This will evaluate the inequality below.
print 3 + 2 < 5 - 7
# This will print the string, then calculate the sum of 3 and 2.
print "What is 3 + 2?", 3 + 2
# This will print the string, then calculate 5 minus 7.
print "What is 5 - 7?", 5 - 7
# This will print this string.
print "Oh, that's why it's False."
# And again.
print "How about some more."
#These will all print the indicated string and then calculate the inequality after the comma, and return a value "True" or "False"
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
| true |
0431197032b26c56e24d73e5ea7d48cce4cff33f | FrancescoSRende/Year9DesignCS-PythonFR | /AbusiveSovietCalculator.py | 1,244 | 4.3125 | 4 | import math
import os
os.system("say -v Milena Привет! I do addition for you, yes?")
input("Привет! I do addition for you, yes? ")
os.system("say -v Milena Too late, I do anyway!")
print("Too late, I do anyway!")
os.system("say -v Milena Give me number")
add_1 = input("Give me number: ")
os.system("say -v Milena One more, пожалуйста")
add_2 = input("One more, пожалуйста: ")
add_1 = float(add_1)
add_2 = float(add_2)
sum = add_1 + add_2
print("Addition of",add_1," and",add_2," is "+str(sum)+".")
os.system("say -v Milena Addition of your numbers equal"+str(sum))
os.system("say -v Milena Now I do multiplication of 3 numbers! Give me first one")
times_1 = input("Now I do multiplication of 3 numbers! Give me first one: ")
os.system("say -v Milena Another")
times_2 = input("Another: ")
os.system("say -v Milena Last one, пожалуйста")
times_3 = input("Last one, пожалуйста: ")
times_1 = float(times_1)
times_2 = float(times_2)
times_3 = float(times_3)
product = times_1 * times_2 * times_3
print("Your answer of multiplication is "+str(product)+".")
os.system("say -v Milena Your answer of multiplication is "+str(product))
os.system("say -v Milena PROGRAM IS END")
print("PROGRAM IS END") | true |
40a107b297d30796397f97d0a4613944a69fca23 | gup-abhi/translation | /translator.py | 2,013 | 4.15625 | 4 | # importing all from tkinter
from tkinter import *
# importing Translator from googletrans
from googletrans import Translator
# creating window
win = Tk()
# giving title to the window
win.title('translator')
# specifying size of our window
win.geometry('500x100')
select = ""
# creating a function to get language
def selection():
global select
# getting the language to be converted too
select = str(radio.get())
# creating a function to translate user given text
def translation():
# dictionary with keys for specific languages
lang = {"Spanish" : "es", "English" : "en", "French" : "fr", "German" : "de"}
# getting text from entry field
word = entry.get()
# creating object of Translator
translator = Translator(service_urls =['translate.google.com'])
# translating the text to language specified by the user
translation1 = translator.translate(word, dest = lang[select])
# creating label to display the translated text
label1 = Label(win, text = f'Translated In {select} : {translation1.text}', bg = 'yellow')
label1.grid(row = 3)
# creating entry field
entry = Entry(win)
entry.grid(row = 1, column = 1)
# creating a radio variable to get radio button response
radio = StringVar(None, "English")
# creating button to call our translator function
button = Button(win, text = 'Translate', command = translation)
button.grid(row = 1, column = 2)
# creating radio button for spanish language
R1 = Radiobutton(win, text="Spanish", variable=radio, value="Spanish", command=selection)
R1.grid(row = 2, column = 0)
R1.grid_anchor(anchor=W)
# creating radio button for french language
R2 = Radiobutton(win, text="French", variable=radio, value="French", command=selection)
R2.grid(row = 2, column = 1)
R2.grid_anchor(anchor=W)
# creating radio button for german language
R3 = Radiobutton(win, text="German", variable=radio, value="German", command=selection)
R3.grid(row = 2, column = 2)
R3.grid_anchor(anchor=W)
# creating window loop
win.mainloop()
| true |
e3766dac92febd9712b1dc2c3712502064e4075b | cindylopez662/Mad-Libs | /mad_libs.py | 2,391 | 4.1875 | 4 | #creating a mad libs game - ask for words and add them to the correct places - use append???
'''
Strings
Variables
Concatenation
Print
'''
if __name__ == '__main__':
adjective1 = input("Tell me an adjective ")
adjective2 = input("Tell me an another adjective ")
adjective3 = input("Tell me an another adjective ")
adjective4 = input("Tell me an another adjective ")
adjective5 = input("Tell me an another adjective ")
adjective6 = input("Tell me an another adjective ")
noun1 = input("Tell me a noun ")
noun2 = input("Tell me a another noun ")
plural_noun1 = input("Tell me a plural noun ")
plural_noun2 = input("Tell me a another plural noun ")
plural_noun3 = input("Tell me a another plural noun ")
plural_noun4 = input("Tell me a another plural noun ")
person_in_room_female = input("Tell me a name of a female ")
article_of_clothing = input("Tell me an article of clothing ")
a_place = input("Tell me a place ")
a_city = input("Tell me a city ")
part_of_the_body = input("Tell me a part of the body ")
letter_of_the_alphabet = input("Tell me a letter of the alphabet ")
verb = input("Tell me a verb ")
number = input("Tell me a number ")
celebrity = input("Tell me a celebrity ")
mad_lib_template = f'''There are many {adjective1} ways to choose a/an {noun1} to read.
First, you could ask for recommendations from your friends and {plural_noun1}.
Just don’t ask Aunt {person_in_room_female} - she only reads {adjective2} books with {article_of_clothing}-ripping goddesses on the cover.
If your friends and family are no help, try checking out the {noun2} Review in The {a_city} Times.
If the {plural_noun2} featured there are too {adjective3} for your taste, try something a little more low-{part_of_the_body}, like {letter_of_the_alphabet}: The {celebrity} Magazine, or {plural_noun3} Magazine.
You could also choose a book the {adjective4}-fashioned way Head to your local library or {a_place} and browse the shelves until something catches your {part_of_the_body}.
Or you could save yourself a whole lot of {adjective5} trouble and log on to www.bookish.com, the {adjective6} new website to {verb} for books! With all the time you’ll save not having to search for {plural_noun4}, you can read {number} more books!
'''
print(mad_lib_template) | false |
db38d88c3a38e9322d95f87fc18333af881a3f74 | akkharin1/6230405347-oop-labs | /6230405347-oop-lab03 (1)/lab3_extra.py | 1,813 | 4.1875 | 4 | def lab3_special():
while True:
try:
first_number = check_quit("Enter the first number:")
second_number = check_quit("Enter the second number:")
operator = str(input("Enter the operator"))
except ValueError:
break
if operator == "+":
print(f"{first_number} + {second_number} = {first_number + second_number}")
elif operator == "-":
print(f"{first_number} - {second_number} = {first_number - second_number}")
elif operator == "*":
print(f"{first_number} * {second_number} = {first_number * second_number}")
elif operator == "/":
if first_number == 0 or second_number == 0:
print("Cannot divide a number by 0")
else:
print(f"{first_number} / {second_number} = {first_number / second_number}")
elif operator == "quit":
break
else:
print("Unknow operator")
return
if _name_ == '_main_':
while True:
n = int(input("Select problem 1 - 11, print 0 is end:"))
if n > 11 or n < 0:
print("Select problem again!!")
if n != 0 and n < 12:
print(f">>> now running lab03 problem {n} <<<")
if n == 1:
lab3_p1()
if n == 2:
lab3_p2()
if n == 3:
lab3_p3()
if n == 4:
lab3_p4()
if n == 5:
lab3_p5()
if n == 6:
lab3_p6()
if n == 7:
lab3_p7()
if n == 8:
lab3_p8()
if n == 9:
lab3_p9()
if n == 10:
lab3_p10()
if n == 11:
lab3_special()
if n == 0:
break | true |
a3826ef86713d169b853922a0ae98fffd80043cb | akkharin1/6230405347-oop-labs | /6230405347-oop-lab2/list_tuble.py | 450 | 4.15625 | 4 | tuple_1 = 1
tuple_2 = (2, 2)
tuple_3 = (3, 3, 3)
list_a = [tuple_1, tuple_2, tuple_3]
second_element_a = list_a[1]
second_sequence_a = second_element_a[1]
list_1 = list(range(0, 10))
list_2 = list(range(10, 20))
list_3 = list(range(20, 30))
list_4 = list(range(30, 40))
list_b = [list_1, list_2, list_3, list_4]
first_element_b = list_b[0]
last_two_elements = first_element_b[-2:]
print(second_sequence_a)
print(last_two_elements)
| false |
a34b5049b40d1707a784aa4635f1a68ce9256642 | AbdulMalik-Marikar/COMP-1405 | /Guntha-Board.py | 1,775 | 4.28125 | 4 | #Abdul-Malik Marikar
#101042166
#Key Reference: Starting out with python 3rd edition
#---next 2 lines from Abdul Siddiqui. used to clear screen
import os
os.system("cls")
#one guntha is equal to 101.7 square meters
guntha = 101.17
#one board is equal to 0.007742 square meters
board = 0.007742
#function concept from generator-for-A1.py
#printing selection menu
def startscreen():
print("Select an option from below")
print("")
print("Type 1 to convert Guntha's to Board's")
print ("Type 2 to convert Board's to Guntha's")
print ("Type 3 to Quit")
#Taking the values inputed by the user and converting it
def selections():
#user inputs values here
selectionvalue = int(input(">>>>"))
#enters the corresponding selection when the correct value is inputed
if selectionvalue == 1:
#to convert gunthas to boards
gunthavalue = int(input("How many Guntha's would you like to convert?\n"))
x= ((gunthavalue*guntha)/board)
print("")
print(gunthavalue,"Guntha's are equivalent to",x ,"Board's\n")
else:
#enters the corresponding selection when the correct value is inputed
if selectionvalue == 2:
#to covert boards to gunthas
boardvalue = int(input("How many boards's would you like to convert?\n"))
y= ((boardvalue*board)/guntha)
print("")
print(boardvalue, "Board's are equivilent to",y ,"Guntha's\n")
#This is used to exit the program
else:
if selectionvalue == 3:
os.system("cls")
return
#create a variable to control the loop
again = 'y'
#the actual program with a while loop so the user can convert more than once
while again == 'y':
startscreen()
selections()
#built in loop with an exit
print("Do you want to calculate again? Type 'y' for yes and 'n' for no\n")
again=input(">>>>")
os.system("cls")
| true |
2e28bb64b19882bb513ed62667bbadd3aa459c5f | K9Wan/oldcodes | /prog-py3-start/factorial.py | 336 | 4.125 | 4 | def factorial_recur(n):
if(n<=0):
return 1
else:
return n*factorial_recur(n-1)
def factorial_iter(n):
if(n<=0):
return 1
else:
x=1
while(n>0):
x*=n
n-=1
return x
n=float(input('''number
'''))
print(factorial_iter(n))
print(factorial_recur(n)) | false |
731e965139d80cde23cf1a3dc9f95f6995d1a566 | li-poltorak/code_guild_labs | /dec_11/cars/car.py | 1,061 | 4.28125 | 4 | # Create a Car class with some attributes typical of automobiles, then use it to
# create some instances of different cars.
#
# Create a new directory called cars
# Create the following 2 files inside the cars directory: main.py and car.py
# In car.py, create a class called Car with the following characteristics:
# A shared property called number_of_wheels set to the value 4
# The following instance properties that get set upon initialization:
# color
# number_of_doors
# A honk method that, when called, prints out the word honk
# In main.py, import your Car class and create 2 or 3 instances of cars with different
# characteristics; when you run main.py it should print out the characteristics of your Car instances
class Car:
def __init__(self, color, number_of_doors):
self.color = color
self.number_of_doors = number_of_doors
self.number_of_wheels = 4
def honk(self):
print('HONK!')
if __name__ == '__main__':
car1 = Car('blue','4')
print(car1.color)
car1.honk()
print(car1.number_of_wheels)
| true |
bc65b9eb05b8e1eefb7be206cee4d664a3e0ef8a | glock3/Learning- | /Misha/Numbers/fast_exponentation.py | 360 | 4.375 | 4 | def pow(value, power):
result=1
if power != 0:
for index in range(power):
result *= value
return result
if __name__=="__main__":
print('This program requires two integers and returns value in power\n')
value=int(input('Enter value: '))
power=int(input('Enter power: '))
print('Result: '+str(pow(value,power)))
| true |
44b78ad97be4843b6ad8b1078a86271b1ffcc536 | zabimaru1000/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/9-print_last_digit.py | 242 | 4.125 | 4 | #!/usr/bin/python3
def print_last_digit(number):
if number >= 0:
result = number % 10
elif number < 0:
result = number % -10
if result < 0:
result = result * -1
print(result, end="")
return result
| false |
35d1e730a7dd63f902a154a8b8e49e656610cdc3 | pawarspeaks/HacktoberFest_2021 | /python/Phone-Directory/main.py | 2,160 | 4.40625 | 4 | # Python program to implement a phone directory using arrays
# Array to store Contacts
directory = []
# To create a contact
def create_contact():
contact = []
name = input("Enter Name: ")
phone = int(input("Enter phone number: "))
contact.append(name)
contact.append(phone)
directory.append(contact)
# To delete a contact
def delete_contact():
delete_number = int(input("Enter the mobile number whose contact has to be deleted: "))
for i in range(0, len(directory)):
if directory[i][1] == delete_number:
directory.pop(i)
# To search a contact
def search_contact():
search_name = input("Enter Name to search for: ")
for j in range(0, len(directory)):
if directory[j][0] == search_name:
print("Name: ", directory[j][0], "Contact Number: ", directory[j][1])
# To update a contact
def update_contact():
update_number = int(input("Enter the number which you wanted to edit: "))
for k in range(0, len(directory)):
if directory[k][1] == update_number:
a = input("Do you wnat to edit number? (y/n) ")
if a == 'y' or a == 'Y':
new_number = int(input("Enter new number: "))
directory[k][1] = new_number
b = input("Do you want to edit name? (y/n) ")
if b == 'y' or b == 'Y':
new_name = input("Enter new name: ")
directory[k][0] = new_name
print("Updated Contact", directory[k])
break
# To show Directory
def show_directory():
print(directory)
# Main
cont = "y" or "Y"
while cont.lower() == "y" or cont.upper() == "Y":
choice = int(input("Choose option: \n1. Add Contact \n2. Delete Contact \n3. Search Contact \n4. update Contact \n5. Show Directory \n"))
if choice == 1:
create_contact()
elif choice == 2:
delete_contact()
elif choice == 3:
search_contact()
elif choice == 4:
update_contact()
elif choice == 5:
show_directory()
else:
print("Choose correct option")
cont = input("Do you want to continue? (y/n)")
if cont == "n":
break | true |
586872568e78be78907e1d761c90af565d494b7c | pawarspeaks/HacktoberFest_2021 | /python/Python-cipher-program/cipher.py | 2,932 | 4.15625 | 4 | #program with different cipher algorithms
import base64
def rot13():
ch='y'
while ch=='y' or ch=='Y':
print("Menu:") #menu for asking choice
print("1.Cipher a message")
print("2.Decipher a message")
choice=int(input("Enter your choice: "))
if choice==1:
string=input("Enter the string: ")
k=13
print("Creating cipher")
code=""
for x in string:
code=code+chr(ord(x)+k)
print("The code is ",code)
elif choice==2:
string=input("Enter the string: ")
k=13
print("Deciphering code")
message=""
for x in string:
message=message+chr(ord(x)-k)
print("The message is ",message)
else:
print("Wrong choice")
ch=input("Do you wish to continue?(y/n):") #asking to continue or not
def caesar():
ch='y'
while ch=='y' or ch=='Y':
print("Menu:") #menu for asking choice
print("1.Cipher a message")
print("2.Decipher a message")
choice=int(input("Enter your choice: "))
if choice==1:
string=input("Enter the string: ")
k=int(input("Enter the key for ciphering: "))
print("Creating cipher")
code=""
for x in string:
code=code+chr(ord(x)+k)
print("The code is ",code)
elif choice==2:
string=input("Enter the string: ")
k=int(input("Enter the key for deciphering: "))
print("Deciphering code")
message=""
for x in string:
message=message+chr(ord(x)-k)
print("The message is ",message)
else:
print("Wrong choice")
ch=input("Do you wish to continue?(y/n):") #asking to continue or not
def base64enc():
ch='y'
while ch=='y' or ch=='Y':
print("Menu:") #menu for asking choice
print("1.Cipher a message")
print("2.Decipher a message")
choice=int(input("Enter your choice: "))
if choice==1:
msg=input("Enter the string: ")
encoded_msg=base64.b64encode(msg.encode('utf-8'))
print("Encoded msg is ", encoded_msg)
elif choice==2:
msg=input("Enter the string: ")
decoded_msg=base64.b64decode(msg)
print("Decoded message is",decoded_msg.decode('utf-8'))
else:
print("Wrong choice")
ch=input("Do you wish to continue?(y/n):") #asking to continue or not
print("Menu:")
print("1.Caesar cipher")
print("2.ROT13")
print("3.Base64encoding")
option=int(input("Enter your choice (1 or 2): "))
if option==1:
caesar()
elif option==2:
rot13()
elif option==3:
base64enc()
| true |
5f205ba2255ff3f19a1b39dc92b2365a73a6267d | pawarspeaks/HacktoberFest_2021 | /python/insertion_sort.py | 796 | 4.4375 | 4 | # A program to implement insertion sort
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1 # j = index no of sorted element
while j >=0 and key < arr[j] : # if element of unsorted list is less than sorted one, it will swap
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
n = int(input('enter number of elements : '))
arr = []
for i in range(0,n):
# to take input n no of times
element = int(input())
# to add the elements to the list
arr.append(element)
# to display the list to the user given by him/her
print(f'list you entered is {arr}')
# function is called
insertionSort(arr)
# to print the array
print ("Sorted array is:")
for i in range(len(arr)):
print (arr[i]) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.