blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
79f5435bbcf2bd7b757b6e2f1a0da40e4bf82836 | starmap0312/refactoring | /composing_method/introduce_explaining_variable.py | 930 | 4.4375 | 4 | # - if have a complicated expression that is hard to understand, put the result of the expression
# or parts of the expression in a temp variable with a name explaining its purpose
# - an alternative is to use extract method, but sometimes extract method is hard,
# because there are too many local temp variables then use introduce explaining variables
platform = 'MAC'
browser = 'IE'
# before: long expression
if platform.upper().index('MAC') > -1 and browser.upper().index('IE') > -1:
print 'MAC and IE'
# after: use temp variables to explain parts of the expression
isMac = platform.upper().index('MAC') > -1
isIE = browser.upper().index('IE') > -1
if isMac and isIE:
print 'MAC and IE'
# use extract method instead
def isMac(platform):
return platform.upper().index('MAC') > -1
def isIE(browser):
return browser.upper().index('IE') > -1
if isMac(platform) and isIE(browser):
print 'MAC and IE'
| true |
18164044687548ed741c2d8833149e564f708fa1 | shmishkat/PythonForEveryone | /Week05/forLoopDic.py | 436 | 4.21875 | 4 | #for loop in dictionaries.
countsofNames = {'sarowar': 1, 'hossain': 2, 'mishkat': 2, 'mishu': 2}
for key in countsofNames:
print(key,countsofNames[key])
#converting dictionary to list
nameList = list(countsofNames)
print(nameList)
print(countsofNames.keys())
print(countsofNames.values())
print(countsofNames.items())
#Cool thing!!
#Muiltiple iteration variables!!
for key,value in countsofNames.items():
print(key,value) | true |
4d29c7a19f10bd73b6c7a132e8024bf92e0de176 | tanmay2298/Expenditure_Management | /database.py | 1,715 | 4.3125 | 4 | import sqlite3
from datetime import date # get todays date
def create_table():
conn = sqlite3.connect("Expenditure.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Expenditure(ID INTEGER PRIMARY KEY, expenditure_date text, Item text, Cost real)")
conn.commit()
conn.close()
def insert_data(expenditure_date, item, cost):
conn = sqlite3.connect("Expenditure.db")
cur = conn.cursor()
cur.execute("INSERT INTO Expenditure VALUES (NULL, ?, ?, ?)", (expenditure_date, item, cost))
conn.commit()
conn.close()
def display_data():
conn = sqlite3.connect("Expenditure.db")
cur = conn.cursor()
cur.execute("SELECT * FROM Expenditure")
data = cur.fetchall()
conn.close()
for i in data:
print(i)
def prompt_database():
while True:
print()
print("1) Make an entry for today")
print("2) Any other date")
print()
n = int(input("Enter your choice: "))
if n == 1:
Expenditure_Date = str(date.today())
print(Expenditure_Date)
break
elif n == 2:
Expenditure_Date = input("Enter the date: ")
break
else:
print("Invalid Choice\n", "Retry")
return Expenditure_Date
def main_function():
create_table()
Expenditure_Date = prompt_database()
item = input("Expenditure on which Item: ")
cost = float(input("Cost of the Item: "))
print("Expenditure_Date: ", Expenditure_Date)
print("Item: ", item)
print("Cost: ", cost)
insert_data(Expenditure_Date, item, cost)
print()
print("CAUTION: PLEASE MAKE SURE THAT YOUR DATABASE IS NOT OPEN \nELSEWHERE IN SOME DB VIEWING APPLICATION")
print("....... Data Successfully Entered in Database ........")
print()
ch = input("Do you want to see the data: ")
if (ch == 'Y') or (ch == 'y'):
display_data()
| true |
d6944aa05f2adbb15f1eeeca1bc0713cb8e0000a | geoniju/PythonLearning | /Basics/DictEx1.py | 422 | 4.15625 | 4 |
""""
Write a program that reads words in words.txt and stores them as keys in a dictionary.
It doesnt matter what the values are.
Then you can use the in operator to check whether a string is in the dictionary.
"""
fhand = open('words.txt')
word_dict = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in word_dict.keys():
word_dict[word] = ''
print(word_dict)
| true |
df562ec851108571c9c64114e44b38088a5ca605 | lucas-deschamps/LearnPython-exercises | /ex6.py | 948 | 4.40625 | 4 | types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
print(f"I also said: '{y}'")
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {} {}"
print(joke_evaluation.format(types_of_people, do_not))
w = "This is the left side of..."
e = "a string with a right side."
print(w + e)
# types_of_people = 10 creates a variable named types_of_people
# and sets it = (equal) to 10.
# You can put that in any string with: {types_of_people}.
# You also see that I have to use a special type of string to "format";
# it's called an "f-string"
# Python also has another kind of formatting using the .format() syntax
# which you see on line 17.
# You'll see me use that sometimes
# when I want to apply a format to an already created string, such as in a loop.
| true |
6be6ef4eec51a80a29e1516c6c4e074ccb64f5f7 | lucas-deschamps/LearnPython-exercises | /ex38.py | 1,772 | 4.25 | 4 | ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("\nWait, there are not 10 things in that list. Let's fix that.\n")
# splits string into a list @ emptyspaces
stuff = ten_things.split(' ')
# 8 items in the list, but ten_things only needs 4 more
more_stuff = ['Day', 'Night', 'Song', 'Frisbee',
'Corn', 'Banana', 'Girl', 'Boy']
# while loop only adds enough until 10 by popping items of the other list
while len(stuff) != 10:
print(stuff)
print(more_stuff)
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(more_stuff)
print(f"There are {len(stuff)} items now.")
print(stuff)
print('\n')
print("There we go: ", stuff, '\n')
print("Let's do some things with stuff:\n")
print(stuff[1]) # prints item #1 in combined list
print(stuff[-1]) # prints last item in combined list
print(stuff.pop()) # pops last item in the list
print(' '.join(stuff)) # prints list by the way of joining them with empty spcs
print('#'.join(stuff[3:6])) # prints list from item 3 to 5 by the way of '#'
print(stuff, '\n')
##Study Drills
# Take each function that is called, and go through the steps for function calls
# to translate them to what Python does.
# For example, more_stuff.pop() is pop(more_stuff).
# Translate these two ways to view the function calls in English.
# For example, more_stuff.pop() reads as, "Call pop on more_stuff."
# Meanwhile, pop(more_stuff) means, "Call pop with argument more_stuff."
# Understand how they are really the same thing.
# Go read about "object-oriented programming" online. Confused?
# I was too. Do not worry.
# You will learn enough to be dangerous, and you can slowly learn more later.
| true |
bdeddd92cfaed29ffe474b9ce8130046597fcc82 | DhivyaKavidasan/python | /problemset_3/q7.py | 421 | 4.40625 | 4 | '''
function named uses_only that takes a word and a string of letters, and that returns True if the word contains only letters in the list
submitted by : dhivya.kavidasan
date: 05/12/2017
'''
def uses_only(word, only_letters):
i = 0
while i <len(word):
if word[i] in only_letters:
i+=1
else:
return False
return True
word='dhivya'
only_letters='xyz'
print uses_only(word,only_letters) | true |
cdefa6f65d75c76a213a108b0223122b72b30a2f | morrosquin/aleandelebake | /crypto/caesar.py | 385 | 4.125 | 4 |
from helpers import alphabet_position, rotate_char
def encrypt (text, rot):
encrypted_text = ""
for characters in text:
encrypted_text += rotate_char(characters, rot)
return encrypted_text
def main():
text = input('Enter your message: ')
rotation = int(input('Enter rotation: '))
print(encrypt(text, rotation))
if __name__ == "__main__":
main() | true |
89d25d50b13a4ee345ba2aeee3b4f4f2063e0947 | tiveritz/coding-campus-lessons-in-python | /src/dcv/oct/day09part01.py | 695 | 4.3125 | 4 | def bubble_sort(arr):
sorted = arr.copy()
to_swap = True
while to_swap:
to_swap = False
for i in range(1, len(arr)):
if (sorted[i - 1] > sorted[i]):
to_swap = True
sorted[i - 1], sorted[i] = sorted[i], sorted[i - 1]
return sorted
def hello_world_functions():
my_array = [6, 23, 78, 34, 89, 2, 56, 78, 6, 30, 27, 81, 7, 7, 84, 20]
# function call. Note the passed parameter (my_array)
print(bubble_sort(my_array))
print(my_array) # original array remained untouched
# Another example
my_array2 = [-2, -9, 5, 9, 5, 2, 4, -3, 8, -6, 4, 6]
print(bubble_sort(my_array2))
print(my_array2)
| true |
0c65b84132465c366b5eb84628cad04d5a80866f | StRobertCHSCS/fabroa-hugoli0903 | /Working/Practice Questions/2.livehack_practice_solution2.py | 896 | 4.46875 | 4 | '''
-------------------------------------------------------------------------------
Name: 2.livehack_practice_solution2.py
Purpose: Determining if the triangle is a right angled
Author: Li.H
Created: 14/11/2019
------------------------------------------------------------------------------
'''
# Receive the side lengths from the user
side_1 = (int(input("Enter the length of Side 1: ")))
side_2 = (int(input("Enter the length of Side 2: ")))
side_3 = (int(input("Enter the length of Side 3: ")))
# Calculate the formula
side_1 = side_1**2
side_2 = side_2**2
side_3 = side_3**2
# Calculate the possibilities
if side_1 + side_2 == side_3:
print("This is a right angled triangle")
elif side_1 + side_3 == side_2:
print("This is a right angled triangle")
elif side_2 + side_3 == side_1:
print("This is a right angled triangle")
else:
print("This is not a right angled triangle") | true |
f0a756e7cdc7e35be0efcc03def4afdd366376e7 | cloudacademy/pythonlp1-lab2-cli | /src/code/YoungestPresident/solution-code/youngest_pres.py | 1,449 | 4.15625 | 4 | #! /usr/bin/python3
import sys
sys.version_info[0]
lab_exercise = "YoungestPresident"
lab_type = "solution-code"
python_version = ("%s.%s.%s" % (sys.version_info[0], sys.version_info[1], sys.version_info[2]))
print("Exercise: %s" % (lab_exercise))
print("Type: %s" % (lab_type))
print("Python: %s\n" % (python_version))
print()
#====================================
#CODE1: Import datetime module
import datetime
#CODE2: Create a date creation helper function
def make_date(date_string):
raw_year, raw_month, raw_day = date_string.split('-')
year = int(raw_year)
month = int(raw_month)
day = int(raw_day)
return datetime.date(year, month, day)
#CODE3: Create empty list
all_presidents = []
#CODE4: Open data file and read each record
with open("./presidents.txt") as PRES:
for rec in PRES:
_, last_name, first_name, birthday, _, _, _, inauguration_day, *_ = rec.split(":")
birth_date = make_date(birthday)
took_office_date = make_date(inauguration_day)
raw_age_at_inauguration = took_office_date - birth_date
age_at_inauguration = round(raw_age_at_inauguration.days / 365.25, 1)
full_name = '{} {}'.format(first_name, last_name)
all_presidents.append((age_at_inauguration, full_name))
#CODE5: Loop through sorted list and print out to console
for age, name in sorted(all_presidents):
print(name, age)
| true |
bd3f71a840393b9e85508b627bc234bd20f670bc | CSPon/Workshop_Materials | /Python_Workshop_Files/Works_010.py | 2,236 | 4.34375 | 4 | # Python 2.X workshop
# File: Works_010.py
# Files I/O and Exceptions
# To simply print to the Python shell, use the print keyword
print "Hello, Python!"
print # Empty line
# To read keyboard input within the shell...
print "User input Demo"
string = raw_input("Enter your name: ")
print "Hello, " + string + "!"
print # Empty line
# You can also use 'input' keyword. Difference between raw_input
# is that input only takes valid Python expression
#string = input("Enter your valid Python command: ")
#print string
# To access to a file, you use open() function
filename = "foo.txt"
access_mode = "a+" # Opens file for read and writing
buffering = -1
fileToRead = open(filename, access_mode, buffering)
# file object has different attributes, such as...
print "File Name:", fileToRead.name # Shows name of the file
print "File Mode:", fileToRead.mode # Shows access mode
print "Is File Closed?:", fileToRead.closed # Shows if file is closed
print # Empty line
# To read a file...
aLine = fileToRead.read()
# To read up to specific byte size...
aLine = fileToRead.read(10) # Reads up to 10 bytes
# To write to a file...
print "Writting to foo.txt"
fileToRead.write("Hello World!")
# To check where the current position is...
position = fileToRead.tell()
print "Current Position:", position
# To move the current position within the file...
position = fileToRead.seek(0, 0)
print "Current Position:", position
# To close a file
fileToRead.close()
print # Empty line
# To rename a file
import os
os.rename("foo.txt", "bar.txt")
# To remove a file
os.remove("bar.txt")
# Note the access_mode flag
# r+ allows file to be read and write, with file starting at the beginning
# w is for writting only, and it overwrites from beginning of the file
# w also creates file if file does not exist
# w+ allows file for read and write, overwriting the entire file
# a allows file to be writting, appended from the end of the file
# Exception is used along with try-catch block
try:
aFile = open("Mmm.txt", "r")
except IOError:
print "No such file!"
# If you are not sure which exception is needed, omit the specific exception
try:
aFile = open("bar.txt", "r")
except:
print "No such file!"
# Go to Works_010_Exercise.py
| true |
070f868f26cdeaa2f44ccb0885a9dc5889b1070d | CSPon/Workshop_Materials | /Python_Workshop_Files/Try_Files_Completed/Works_Try_001.py | 644 | 4.125 | 4 | # Python 2.7.X
# Try_001.py
# Modifying the quadratic equation
# Continuing with quadratic equation, modify your code
# So it can check with imaginary numbers
# If 4 * a * c is negative, program must let user know
# quadratic equation is unsolvable
import math
a = 5.0
b = 2.0
c = 10.0
# Write your code here
if ((b**2) - 4 * a * c) < 0:
print "This quadratic function cannot be solved!"
else:
result = -b + math.sqrt((b**2) - 4 * a * c) / (2 * a)
print "-b + sqrt((b**2) - 4 * a * c) / (2 * a) is", result
result = -b - math.sqrt((b**2) - 4 * a * c) / (2 * a)
print "-b - sqrt((b**2) - 4 * a * c) / (2 * a) is", result
| true |
e8af090f30548f575478a7ef18ac554b77bf2dd4 | jonbleibdrey/python-playhouse | /lessons/space/planet.py | 971 | 4.25 | 4 | class Planet:
# class level attribute- has acesss to all instances
shape = "round"
#class methods
#this is allso a decorator and it extends the methods below here.
@classmethod
def commons(cls):
return f"All planets are {cls.shape} becuase of gravity"
#static methods
#this is allso a decorator and it extends the methods below here.
@staticmethod
def spin(speed = " 2000 miles per hour"):
return f"The planet spin and spins at {speed}"
#instint attribute- has acesss to the individual instants created
def __init__(self, name, radius, gravity, system):
self.name = name
self.radius = radius
self.gravity = gravity
self.system = system
def orbit(self):
return f"{self.name} is orbittin in the {self.system}"
# print(f"Name is : {PlanetX.name}")
# print(f"Radius is : {PlanetX.radius}")
# print(f"The gravity is : {PlanetX.gravity}")
# print(PlanetX.orbit())
| true |
009f0354abb393920fd0570f056dab386960f30f | nateychau/leetcode | /medium/430.py | 1,243 | 4.34375 | 4 | # 430. Flatten a Multilevel Doubly Linked List
# You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.
# Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
# Example 1:
# Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
# Output: [1,2,3,7,8,11,12,9,10,4,5,6]
class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head:
return head
dummy = prev = Node()
stack = [head]
while stack:
current = stack.pop()
current.prev = prev
prev.next = current
if current.next:
stack.append(current.next)
if current.child:
stack.append(current.child)
current.child = None
prev = current
dummy.next.prev = None
return dummy.next | true |
33457f0033848661c5312884471133f808943b54 | nateychau/leetcode | /medium/735.py | 2,073 | 4.15625 | 4 | # 735. Asteroid Collision
# We are given an array asteroids of integers representing asteroids in a row.
# For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
# Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
# Example 1:
# Input: asteroids = [5,10,-5]
# Output: [5,10]
# Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
# Example 2:
# Input: asteroids = [8,-8]
# Output: []
# Explanation: The 8 and -8 collide exploding each other.
# Example 3:
# Input: asteroids = [10,2,-5]
# Output: [10]
# Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
# Example 4:
# Input: asteroids = [-2,-1,1,2]
# Output: [-2,-1,1,2]
# Explanation: The -2 and -1 are moving left, while the 1 and 2 are moving right. Asteroids moving the same direction never meet, so no asteroids will meet each other.
# Constraints:
# 1 <= asteroids <= 104
# -1000 <= asteroids[i] <= 1000
# asteroids[i] != 0
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
output = [asteroids[0]]
for rock in asteroids[1:]:
if rock < 0:
destroyed = False
while output and output[-1] > 0:
if output[-1] == abs(rock):
output.pop()
destroyed = True
break
elif output[-1] > abs(rock):
destroyed = True
break
else:
output.pop()
if not destroyed:
output.append(rock)
else:
output.append(rock)
return output
| true |
35c0dd06be1544c645f19ff2b6ff101cc04e06c0 | macyryan/lists | /main.py | 1,855 | 4.53125 | 5 | # a list is a sequence of items
# 1D list like a single row or a single column in Excel
# Declare a list using [] and a coma seperated of values
list_ints = [0, 1, 10, 20]
#there are unique indexes for each element in the list
# 0-based, meaning the first element is at zero and the last element is n-1
# where n is the number of elements in this list
# 0 (0), 1 (1), 10 (2), 20(3)
print(list_ints[0])
print(list_ints[-4])
#types can be mixed in a list
list_numbers = [0, 0.0, 1, 1.0, -2]
print(list_numbers)
print(type(list_numbers))
#lists are mutable
list_numbers[0] = "hello"
print(list_numbers)
# ise len() to figure out how many elements are in a list
print(len(list_numbers))
list_numbers.append("another element")
# print out the last element in the list when you dont knoe the number of elements in the list
print(list_numbers[len(list_numbers)-1])
# we can have an empty list
empty_list = []
# we can have lists of lists
nested_list = [[0,1], [2], [3], [4, 5]]
print(len(nested_list))
print(len(nested_list[0]))
# looping through list items
candies = ["twix", "sneakers", "smarties"]
print(candies)
for candy in candies:
print(candy)
i = 0
while i < len(candies):
print(i, candies[i])
i += 1
i = 0
for i in range(len(candies)):
print(i, candies[i])
# common list operators
# list concatenation.. adding two lists together
print(candies)
candies += ["m&ms", "starburst"]
print(candies)
# list repitition... repeating elements in a list
bag_o_candies = 5 * ["twix", "snikers"]
print(bag_o_candies)
#list sclicing
print(candies[1:3]) # : is the slice operator. start index is inclusive
#end index is exclusive
# if you ever need a copy of a list you can simply use the : with no start or end
copy_of_candies = candies[:]
copy_of_candies[0] = "TWIX"
print(copy_of_candies)
print(candies)
#list methods candies.
| true |
08ee5d07cc4cd9fa9ac995979b3ae921875651e9 | eluttrell/string-exercises | /rev.py | 274 | 4.3125 | 4 | # This way works, but is too easy!
# string = raw_input("Give me a string to reverse please\n:")
# print string [::-1]
string = "Hello"
char_list = []
for i in range(len(string) - 1, - 1, - 1):
char list.append(string[i])
#
output = ' '.join(char_list)
print output
| true |
aae92769398e2798c61f59b17eb3e509c1437bfa | Techie-Tessie/Big_O | /linear.py | 766 | 4.28125 | 4 | #Run this code and you should see that as the number of elements
#in the array increases, the time taken to traverse it increases
import time
#measure time taken to traverse small array
start_time = time.time()
array1 = [3,1,4]
for num in array1:
print(num)
print("\n%s seconds" % (time.time() - start_time))
#measure time taken to traverse slightly larger array
start_time = time.time()
array2 = [3,1,4,1,5,9,2]
for num in array2:
print(num)
print("\n%s seconds" % (time.time() - start_time))
#measure time taken to traverse even larger array
start_time = time.time()
array3 = [3,1,4,1,5,9,2,6,5,3,5,8,9,7,9]
for num in array3:
print(num)
print("\n%s seconds" % (time.time() - start_time))
| true |
1bbdf14acb9ddbc2a8d4074b54330152dae6a582 | rajeshkr2016/training | /chapter2_list_map_lambda_list_comprehension/51_loopin1.py | 681 | 4.40625 | 4 | #When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
#To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
for i in reversed(range(1, 11, 1)):
print(i)
| true |
436590717e700ec74574b56332a1023362f73ee7 | rajeshkr2016/training | /chapter4_class_method_inheritance_override_polymorphism/3_method_1.py | 585 | 4.625 | 5 | '''
The Constructor Method
The constructor method is used to initialize data.
It is run as soon as an object of a class is instantiated.
Also known as the __init__ method, it will be the first definition of a class and looks like this:
'''
class Shark:
def __init__(self):
print("This is the constructor method.")
def swim(self, b):
print("The shark is swimming.", b)
def be_awesome(self):
print("The shark is being awesome.")
def main():
sammy = Shark()
sammy.swim("r")
sammy.be_awesome()
if __name__ == "__main__":
main()
| true |
22ea187f2fe994d8aca2eabeda4ea458af8162b9 | rajeshkr2016/training | /chapter10-Generator_Fibanocci/8-Nested_list_comp.py | 369 | 4.21875 | 4 | #'''
my_list = []
for x in [20, 40, 60]:
for y in [2, 4, 6]:
my_list.append(x * y)
#print(my_list)
my_list = [x * y for x in [20, 40, 60] for y in [2, 4, 6]]
print(my_list)
'''
List comprehensions allow us to transform one list or other sequence into a new list.
They provide a concise syntax for completing this task, limiting our lines of code.
''' | true |
798da748346e83c63566d0a2c24d36aa5467b49e | rajeshkr2016/training | /senthil/primeFactor.py | 768 | 4.1875 | 4 | '''
Given int x, determine the set of prime factors
f(5) = [1,5]
f(6) = [2,3]
f(8) = [2,2,2]
f(10) = [2,5]
1) While n is divisible by 2, print 2 and divide n by 2.
2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i, increment i by 2 and continue.
3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2.
'''
def primefactor(n):
print(n)
if n < 2:
print("The number cannot have prime factors")
while n % 2 == 0:
print("while loop")
print(2)
n = n/2
for i in range(3, n+1, 2):
while (n % i) == 0:
print(i)
n = n / i
n = 10
primefactor(n)
| true |
0a72c3b845963090b651d57389478370565788c8 | rajeshkr2016/training | /chapter2_list_map_lambda_list_comprehension/10_list_comp_if.py | 669 | 4.3125 | 4 | '''
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses.
The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
For example, this listcomp combines the elements of two lists if they are not equal:
'''
print("Generating List combo with regular method")
list1=[1,2,3]
list2=[3,1,4]
combs = []
for x in list1:
for y in list2:
if x !=y:
combs.append([x,y])
print(combs)
print("Generating List combo with list comprehension")
combs1=[[x, y] for x in list1 for y in list2 if x != y]
print(combs1) | true |
09300b989cf42a78381dfd25fa4011cb33f346a0 | sujitdhamale/Python | /0505_Aggregating_lists_and_tuples.py | 892 | 4.5 | 4 | #!/usr/bin/python
#0505_Aggregating_lists_and_tuples.py by SUjit Dhamale
def main():
print("Tuple ") #tuple is immutable object. we cannot insert, append, delete in tuple
x=(1,2,3,4)
print(type(x),x)
print("List") # list is mutable object
x=[1,2,3,4]
print(type(x),x)
#list is mutable object so we can insert, append, delete in list
x.append(5)
print(type(x),x)
x.insert(2,6)
print(type(x),x)
print("String ")
x='string'
print(type(x),x[2])
print(type(x),x[2:4]) # this is slices
#these sequence type can be used as iterators
print("these sequence type can be used as iterators")
x=(1,2,3,4)
for i in x:
print(i)
x=[1,2,3,4]
for i in x:
print(i)
x='string'
for i in x:
print(i)
if __name__ == "__main__": main()
| true |
e281a51a657d101f2127c4800eb8c2077f434822 | BogartZZZ/Python-Word-Reverse | /WordReverse.py | 330 | 4.15625 | 4 | #my_string = input("Input a word to reverse: ")
#for char in range(len(my_string) -1, -1, -1):
# print(my_string[char], end="")
def reverseWord(Word):
words = Word.split(" ")
newWords = [word[::-1] for word in words]
newWord = " ".join(newWords)
return newWord
Word = "Can't stop me"
print(reverseWord(Word)) | true |
b999f987b9b161c094cec43815873c38d18d9c66 | PeturOA/2021-3-T-111-PROG | /assignments/while_loops/every_other_int.py | 273 | 4.40625 | 4 | num_int = int(input("Enter a number greater than or equal to 2: ")) # Do not change this line
counter = 2
# Fill in the missing code below
if num_int < 2:
print("The number is too small.")
else:
while counter <= num_int:
print(counter)
counter += 2 | true |
0e5f551d767c513eeaa4c14a635b798555d5d45a | tiannaparmar/Python-Level-2 | /Functions.py | 1,885 | 4.34375 | 4 | #Create new file
#Save as Functions.py
#Save in Python-Level-2 folder ---- repo(repository)
#Add two numbers
def AddNumbers(x,y,z): #Definition of the function
return x + y + z
def GetSquares(x):
return x * x
#Call our Function
Total = AddNumbers(4,9,100)
#Output the results
print(f"The sum total is = {Total}")
#Ask the user for inputs from the keyboard
num1 = int(input("Enter any number \n"))
num2 = int(input("Enter another number \n"))
num3 = int(input("Enter another number again \n"))
#Call the function once again
sum = AddNumbers(num1,num2,num3)
#Print the sum
print("The sum now of {0} plus {1} plus {2} is equal to {3}".format(num1, num2, num3, sum))
#Call the squares function
print(GetSquares(4))
square = GetSquares(16)
print("The square is", square)
#A function that calculates the area of a Circle
def AreaofCircle(r):
PI = 3.142 #declared a constant --- whose values don't change --- static -- uppercase
return (PI * r * r)
#function call
area = AreaofCircle(14)
#display the results
print("The area is =",area)
#function definition
def AreaOfRectangle(): #No parameters
l = eval(input("Enter the value for the length of your rectangle \n")) #prompt user inputs for the length
w = eval(input("Enter the value for the width of your rectangle \n")) #prompt user for width
Area = l * w
print("Area of rectangle is", Area)
#function call
AreaOfRectangle()
#Exercise write a function to calculate the perimeter of rectangle
#Push your code online
def PerimeterOfRectangle():
Length = eval(input("Enter the value for the length of your rectangle \n"))
Width = eval(input("Enter the value for the width of your rectangle \n"))
PerimeterOfRectangle = (Length + Width) * 2
print("Perimeter of rectangle is", PerimeterOfRectangle)
#function call
PerimeterOfRectangle()
| true |
115c846183893a1b02c883fe8418cd0190958d1d | kumarUjjawal/python_problems | /leap_year.py | 349 | 4.28125 | 4 | # Return true if the given input is a leap year else return false.
def leap_year(year):
leap = False
if (year % 4 == 0):
if (year % 100 == 0 and year % 400 == 0):
leap = True
else:
leap = False
else:
leap = False
return leap
years = int(input())
print(leap_year(years))
| true |
b9cba0bc0de5e2ea45ab195ae4a756c419bfe1b4 | arbiben/cracking_the_coding_interview | /recursion_and_dynamic_programming/multiply_recursively.py | 1,445 | 4.46875 | 4 | # write a recursive function to multiply two positive integers without using
# the * operator. others are allowed, but you should minimize the number of operations
def recursive_multiply(a, b):
smaller = b if a > b else a
larger = a if a > b else b
print("recursing and decrementing: {}".format(multiply_decrement(larger, smaller)))
print("recursion with bit manipulation: {}".format(bit_manipulation(larger, smaller)))
print("better solution: {}".format(min_product(larger, smaller)))
def multiply_decrement(larger, smaller):
if smaller == 1:
return larger
return multiply_decrement(larger, smaller-1) + larger
def multiply_decrement(larger, smaller):
if smaller == 1:
return larger
return multiply_decrement(larger, smaller-1) + larger
def bit_manipulation(a, b):
if (a & a-1) == 0 or (b & b-1) == 0:
return multiply_with_bits(a, b)
return bit_manipulation(a, b - 1) + a
def multiply_with_bits(a, b):
perf_power = a if (a & a-1) == 0 else b
other_num = b if (a & a-1) ==0 else a
i = 0
while not perf_power & 1 << i:
i += 1
return other_num << i
def min_product(larger, smaller):
if smaller == 0:
return 0
if smaller == 1:
return larger
smaller = smaller >> 1
half = min_product(larger, smaller)
if half % 2 == 0:
return half + half
return half + half + larger
recursive_multiply(7, 33)
| true |
a3e35c2ef4501db0f733d10746df79993a226ffe | JeffreyYou55/cit | /TermProject/plotting.py | 960 | 4.15625 | 4 | from turtle import *
import coordinates
import square
import linear
import quadratic
border = {
"width" : 620,
"height" : 620
}
# draw square and coordinate
print("< Jeffrey's Plotting Software >")
print("drawing rectangular coordinates...")
square.draw_square(border["width"], border["height"], -310, -300)
penup()
setx(0)
sety(0)
pendown()
coordinates.draw_coordinate()
draw_finished = False
while not draw_finished :
function_type = int( input("linear : 1, quadratic : 2 ") )
if(function_type == 1) :
slope = int( input("type the slope : ") )
y_incpt = int( input("type the y intercept : ") )
linear.linear(slope, y_incpt)
if(function_type == 2) :
a = float( input("type a : ") )
b = int( input("type b : ") )
c = int( input("type c : ") )
quadratic.quadratic(a,b,c)
draw_ends = input("press N to finish drawing. ")
if (draw_ends == "N" ):
draw_finished = True
done()
| true |
c8257d92fba77a9b9c006c7b2277c393d546403f | cbain1/DataScience210 | /python/ListsQ2.py | 924 | 4.125 | 4 | import sys
import random
def beret(request):
total = 0
strings = 0
#Loops through all words in request
for elem in request:
count =0
#splits each word into its own string value
word = list(elem)
# this loops through each letter in each word to see the number of letters in each word
for elem in word:
count +=1
total += count
strings +=1
average = total/strings
return (average)
# Define main for loops, bro
def main():
request = ['lists', 'are', 'pretty', 'cool', 'well', 'as', 'cool', 'as', 'computer', 'science', 'gets', 'which', 'is', 'not', 'very', 'cool' ]
print("Your average number of letters is: ", beret(request))
if __name__ == '__main__':
main()
"""
catherinebain > python3 ListsQ2.py
Your average number of letters is: 4.1875
""" | true |
f23c5207a4cab807e897918fa84aea19db8023d9 | andrewnnov/100days | /guess_number/main.py | 1,530 | 4.15625 | 4 | import random
from art import logo
print(logo)
print("Welcome to the Number Guessing Game!")
def play_game():
guess_number = random.randint(1, 100)
print(guess_number)
result_of_guess = True
while result_of_guess:
attempts = 0
print("I'm thinking of number between 1 and 100")
level = input("Choose a difficulty. Type 'easy' or 'hard' : ")
if level == 'hard':
attempts = 5
print(f"You have {attempts} attempts to guess the number. ")
else:
attempts = 10
print(f"You have {attempts} attempts to guess the number. ")
# user_guess = int(input("Make a guess: "))
while attempts > 0:
user_guess = int(input("Make a guess: "))
if user_guess > guess_number:
attempts = attempts - 1
print("Less")
if attempts == 0:
print("You lose")
result_of_guess = False
elif user_guess < guess_number:
print("More")
attempts = attempts - 1
if attempts == 0:
print("You lose")
result_of_guess = False
else:
print("You guess")
result_of_guess = False
attempts = 0
play_again = input("Do you want to play again? y - yes, n - no: ")
if play_again == "y":
play_game()
else:
result_of_guess = False
play_game() | true |
16ec5926aa96c5a92794b797f3a597b3e60dbe39 | mirielesilverio/cursoPython3 | /logicOperators/using_logic_operators.py | 337 | 4.21875 | 4 | name = input('What is your name? ')
age = int(input('How old are you? ') or 0)
if not name:
print('The name cannot be empty')
elif ' ' in name:
print('Very good! You entered your full name')
elif ' ' not in name:
print('You must enter your full name.')
if not age or age < 0:
print('Oh no! You entered an invalid age')
| true |
8b84715a6d780d92c3bd97fd0c92496f1c1e8c09 | iam-amitkumar/BridgeLabz | /AlgorithmPrograms/Problem1_Anagram.py | 605 | 4.21875 | 4 | """Anagram program checks whether the given user-input
strings are anagram or not.
@author Amit Kumar
@version 1.0
@since 02/01/2019
"""
# importing important modules
import utility.Utility
import util.Util
global s1, s2
try:
s1 = utility.Utility.get_string()
s2 = utility.Utility.get_string()
except Exception as e:
print(e)
res = util.Util.is_anagram(s1, s2)
if res is True: # checking whether the function returns true or not, of true then both the strings are anagram
print("\n", s1, "and ", s2, " are anagram string")
else:
print("\n", s1, "and ", s2, " are not anagram string")
| true |
6416fd722282681c9da97207183871b94cf9e51f | iam-amitkumar/BridgeLabz | /ObjectOrientedPrograms/Problem1_Inventory.py | 1,976 | 4.28125 | 4 | """In this program a JSON file is created having Inventory Details for
Rice, Pulse and Wheat with properties name, weight, price per kg. With
the help of 'json' module reading the JSON file.
@author Amit Kumar
@version 1.0
@since 10/01/2019
"""
# Importing important modules
import json
# Inventory class
class Inventory:
# run_inventory method read the JSON file and convert it to the Dictionary object printing each type of grains
# with their every keys and values and printing them
@staticmethod
def run_inventory():
global dataStore, type # declaring variables as a global variable
f = open('Problem1.json', 'r') # opening the JSON file and reading it
dataStore = json.load(f) # after reading the whole JSON file converting it to the Dictionary object
for i in range(len(dataStore)): # this loop access all the keys and values present in the dictionary
if i == 0: # here we are assigning the variable 'type' as Rice if the index of the Dictionary is 0(zero)
type = "Rice"
if i == 1:
type = "Pulse"
if i == 2:
type = "Wheat"
# printing each properties of each grain after Dictionary which we get after converting the JSON file
print("\nGrain Type: ", type, "\n-------------------")
for j in range(len(dataStore[type])):
print("Name: ", dataStore[type][j]['name'])
print("Weight: ", dataStore[type][j]['weight'])
print("Price per kg: ", dataStore[type][j]['price'])
print("Total Price: ", (dataStore[type][j]['weight'])*(dataStore[type][0]['price']))
print()
# from this python file only program will compile not from the imported file
if __name__ == '__main__':
obj = Inventory() # creating object of Inventory class
obj.run_inventory() # accessing 'run_inventory' method through object reference variable
| true |
b0574f764eb2af8d4e06fddc1c9781c13b7f73a2 | iam-amitkumar/BridgeLabz | /DataStructureProgram/Problem4_BankingCashCounter.py | 2,955 | 4.375 | 4 | """this program creates Banking Cash Counter where people
come in to deposit Cash and withdraw Cash. It have an input panel to add people
to Queue to either deposit or withdraw money and de-queue the people maintaining
the Cash Balance.
@author Amit Kumar
@version 1.0
@since 08/01/2019
"""
# importing important modules
from DataStructureProgram.Queue import *
# creating the object of Queue class
q1 = Queue()
global opinion, amount, size_of_queue # globalizing the variables
amt_of_money = 1000 # initializing the bank balance
print("\nYour cleared balance: ", amt_of_money)
try: # handling the invalid user input for "size of the queue"
size_of_queue = int(input("\nEnter the size of the queue: "))
except Exception as e:
print(e)
# initialing the queue
try:
for i in range(size_of_queue):
q1.enqueue(i)
except Exception as e:
print(e)
# processing the steps until the queue even a single element
while q1.is_empty() is False:
print("\nEnter your opinion: \n"
"1. Press 1 to deposit\n"
"2. Press 2 to withdraw\n")
try: # handling the invalid user input for "opinion of user"
opinion = int(input("Enter your opinion: "))
except Exception as e:
print(e)
try:
if opinion == 1: # checking for the input of the user, whether to deposit or withdraw
try: # handling the invalid user input for "amount to deposit"
amount = int(input("Enter the amount you want to deposit in the account: "))
except Exception as e:
print(e)
if amount < 0:
print("Enter a valid amount")
else:
amt_of_money += amount # adding the money to the account
print("Remaining balance: ", amt_of_money)
q1.de_queue()
elif opinion == 2: # checking for the input of the user, whether to deposit or withdraw
try: # handling the invalid user input for "amount to withdraw"
amount = int(input("Enter the amount you want to withdraw from the account: "))
except Exception as e:
print(e)
if amount < 0:
print("!!! Enter a valid amount !!!")
print("Remaining balance: ", amt_of_money)
else:
if (amt_of_money - amount) < 0:
print("\n>>> Don't have sufficient balance, reenter withdraw amount or Deposit first. <<<")
print("Remaining balance: ", amt_of_money)
else:
amt_of_money -= amount # deducting the amount of money from the account
print("Remaining balance: ", amt_of_money)
q1.de_queue()
else:
print("Invalid Input !!!")
except Exception as e:
print(e)
# printing final available balance present in the account
print("\n>>> Available Balance :", amt_of_money, " <<<")
| true |
e1a0391349896b3ab22365f4c9f295240dae6a9a | iam-amitkumar/BridgeLabz | /AlgorithmPrograms/Problem7_InsertionSort.py | 963 | 4.21875 | 4 | """This program reads in strings from standard input
and prints them in sorted order using insertion sort
algorithm
@author Amit Kumar
@version 1.0
@since 04/01/2019
"""
# importing important modules
import utility.Utility
import string
global u_string
try:
u_string = input("Enter the number of string you want to enter: ")
except Exception as e:
print(e)
list1 = u_string.split() # converting user-input string into string list
input_list = [word.strip(string.punctuation) for word in list1] # trimming commas/punctuation present in the user list
user_string = ' '.join(input_list) # converting trimmed list into string separated by space to print as unsorted string
print("\nYour string: \n%s" % user_string)
utility.Utility.insertion_sort(input_list) # sorting the trimmed list using user-defined insertion_sort method
res = ' '.join(input_list) # converting sorted list into string separated by space
print("\nYour sorted string: \n%s" % res)
| true |
8e1f1ee70acfa12c836eb7bc7274e1b424e5e747 | iam-amitkumar/BridgeLabz | /DataStructureProgram/Problem3_BalancedParentheses.py | 1,862 | 4.1875 | 4 | """Take an Arithmetic Expression where parentheses are used to order the
performance of operations. Ensure parentheses must appear in a balanced
fashion.
@author Amit Kumar
@version 1.0
@since 08/01/2019
"""
# importing important modules
from DataStructureProgram.Stack import *
s1 = Stack() # creating object of Stack class
# this function checks whether the string given by the user has balanced parentheses or not, on that basis return
# boolean value
def check_bal(exp1):
for i in range(0, len(exp1)):
if exp1[i] == '(' or exp1[i] == '{' or exp1[i] == '[': # pushing in stack if string contain open parentheses
s1.push(exp1[i])
try:
if exp1[i] == ')':
x = s1.pop() # popping the stored open parentheses if any close parentheses found in the string
if x != '(':
return False
elif exp1[i] == '}':
x = s1.pop() # popping the stored curly braces if any close curly braces found in the string
if x != '{':
return False
elif exp1[i] == ']':
x = s1.pop() # popping the stored brackets if any close brackets found in the string
if x != '[':
return False
except Exception as e1: # handling the exception of "Stack Underflow"
print(e1)
global exp
try:
exp = input("Please enter your expression")
except Exception as e:
print(e)
check = check_bal(exp)
if s1.is_empty() and check: # printing the result if function return True otherwise False
print("\n>>> Your expression is balanced <<<")
# elif s1.is_empty(): # if the user-input string don't has any parentheses then print "Balanced"
# print("\n>>> Your expression is balanced <<<")
else:
print("\n>>> Your expression is not balanced <<<")
| true |
e993fb4db905e0d672d59137c376cbb9368d93a0 | PhilipCastiglione/learning-machines | /uninformed_search/problems/travel.py | 2,072 | 4.28125 | 4 | from problems.dat.cities import cities
"""Travel is a puzzle where a list of cities in North America must be navigated
in order to find a goal city. The navigation approach presents a problem to be
solved using search algorithms of various strategies.
The distance between cities is provided and a heuristic, straight line distance
is provided to the goal city.
refer: ./cities.py
"""
class Travel:
"""Travel defines the search space, contents and rules for the conceptual
travel board, and makes itself available through state manipulation for
search algorithms.
"""
"""Instantiate with an initial state and the board cities."""
def __init__(self, initial_state):
self.cities = cities
self.current_city = initial_state
# the goal city is fixed as straight line distance data is supplied
self.goal_city = 'sault ste marie'
"""For debugging."""
def print(self):
print("CITIES:")
print(self.cities)
print("CURRENTLY IN: {}".format(self.current_city))
print("GOAL: {}".format(self.goal_city))
"""Returns the current state."""
def current_state(self):
return self.current_city
"""Returns the cost of moving from one state to another state. The move
is assumed to be legal.
"""
def move_cost(self, state1, state2):
return self.cities[state1]["neighbours"][state2]
"""Returns the heuristic cost of the current or provided state, determined
using the straight line distance to the goal city.
"""
def heuristic_cost(self, state=None):
# sld => Straight Line Distance
city = state or self.current_city
return self.cities[city]["sld"]
"""Returns the legal states available from the current state."""
def next_states(self):
return list(self.cities[self.current_city]["neighbours"].keys())
"""Sets the current state."""
def set_state(self, state):
self.current_city = state
"""Returns the goal state."""
def goal_state(self):
return self.goal_city
| true |
c8f4625094cc322c498da1b751ad70e838c98775 | namelessnerd/flaming-octo-sansa | /graphs/breadth_first_search.py | 1,609 | 4.25 | 4 |
def breadth_first_search(graph, starting_vertex):
# store the number of steps in which we can reach a starting_vertex
num_level= {starting_vertex:0,}
#store the parent of each starting_vertex
parent={starting_vertex:None,}
#current level
level= 1
#store unexplored vertices
unexplored=[starting_vertex]
print type(graph)
#while we have unexplored vertices, explore them
while unexplored:
#explore each unexplored vertices. We will keep a list of the next vertices to explore. This will be a list of
#all unexplored vertices that are reachable from the current unexplored vertices
next_vertices_to_explore=[]
for unexplored_vertex in unexplored:
#get all the nodes we can reach from this starting_vertex
for reachable_node in graph[unexplored_vertex]:
#see if have visited this vertex. If we have, we will have a level value for initialization
if reachable_node not in num_level:
#we have reached a previously unreachable node in level steps
num_level[reachable_node]= level
# the parent of this node is the current unexplored vertex
parent[reachable_node]= unexplored_vertex
#add this to the next_vertices_to_explore
next_vertices_to_explore.append(reachable_node)
#now we have explored all unexplored vertices
unexplored= next_vertices_to_explore
print unexplored
level+=1
print parent
print num_level
def main():
graph={'a':['s','z',], 'z':['a',], 's':['a','x',], 'd':['x','c','f'], 'f':['d','c','v',], 'v':['f','c'], 'c':['d','f','x','v'], 'x':['s','d','c'],}
breadth_first_search(graph,'s')
if __name__ == '__main__':
main() | true |
8800b16c4518c85952934c96ba8ccf04cb2d3fe7 | vaddanak/challenges | /mycode/fibonacci/fibonacci.py | 2,392 | 4.15625 | 4 | #!/usr/bin/env python
'''
Author: Vaddanak Seng
File: fibonacci.py
Purpose: Print out the first N numbers in the Fibonacci sequence.
Date: 2015/07/25
'''
from __future__ import print_function;
import sys;
import re;
sequence = [0,1];
'''
Calculate and collect first N numbers in Fibonacci number sequence.
Store result in global variable "sequence".
'''
def fibonacci(N):
global sequence;
if N>2:
sequence.append(sequence[len(sequence)-1] + sequence[len(sequence)-2]);
fibonacci(N-1);
N = int(raw_input());
fibonacci(N);
listStr = [str(sequence[x]) for x in range(N)];
#for x in listStr:
# print(x, end=''); #0112358132134 when N = 10; WRONG !!! WHY???
# still won't space correctly eventhough sequence element is str type ???
#for x in range(N):
# won't space correctly when sequence element is int type ??? WHY???
#print('%d' % sequence[x], end=''); #0112358132134 when N = 10; WRONG !!!
###option 1 -- using string join() function
mstr = ' '.join(listStr);
#print(mstr, end=''); #0 1 1 2 3 5 8 13 21 34 when N = 10; CORRECT spacing !!!
###option 2 -- using sys.stdout.write
#for x in range(N):
# sys.stdout.write('%d' % sequence[x]);
# if x < N-1: # alternative to force correct spacing
# sys.stdout.write(' '); #0 1 1 2 3 5 8 13 21 34 when N = 10; CORRECT !!!
###option 3 -- using regular expression
sequence = [sequence[x] for x in range(N)]; #ensures number of elements == N
mstr2 = str(sequence);
#print(mstr2); # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#target string: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
reObject = re.compile(r'^(\[\s*){1}(\d+[, ]+)*\d+(\])$');#match whole string
reo1 = re.compile(r'^(\[ *){1}');#match left most [
reo2 = re.compile(r', +');#match each sequence of comma-followed-by-space
reo3 = re.compile(r'\]$');#match right most ]
matchObject = reObject.match(mstr2);
#if matchObject:
# print(matchObject.group(0));# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] when N=10
modifiedString = mstr2;
#print(modifiedString);# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] when N=10; original
modifiedString = reo1.sub('',modifiedString);
#print(modifiedString);# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
modifiedString = reo3.sub('',modifiedString);
#print(modifiedString);# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
modifiedString = reo2.sub(' ',modifiedString);
print(modifiedString, end='');# 0 1 1 2 3 5 8 13 21 34 ; CORRECT !!!
| true |
4296c919d465767998bee122b61e3cabc683d101 | officialtech/xPython | /static_variable | xpython.py | 2,954 | 4.125 | 4 | **********************************************# STATIC VARIABLES *****************************************
# The variables which are declared inside the class and outside the 'method' are called static variable.
# Static variables will holds common values for every object.
# Static variables will get memory for one time.
# To call static variables we use class name.
# Static variable will get memory at class loading time.
class Employee:
c_name = "official tech"
c_cno = 10010101000010
print(Employee.c_name)
print(Employee.c_cno)
*******************************************************************************************************************
# Using global and static variable in function
a = 1010
print(a)
class Employee():
c_name = "official tech"
c_cno = "10010101000010"
print(a)
print(Employee.c_name)
print(Employee.c_cno)
def function():
print(a)
print(Employee.c_name)
print(Employee.c_cno)
function()
**********************************************************************************************************************
# REMEMBER BELOW WE ARE CREATING TWO 'PYTHON FILES' OR MODULES
**********************************************************************************************************************
# Import a class to another class
--------------------# step 1: create a module, like
class Employee:
name = "official tech"
ctn = 1010
---------------------# step 2: save as whatever.py
---------------------# step 3: create annother module, like
from whatever import Employee
print(Employee.name)
print(Employee.ctn)
---------------------# step 4: save as what_so_ever.py and run
----------------------------------# Program on instance and static variable ----------------------------------------------
class Official_tech:
# static block start
comp_name = 'official tech Inc.'
comp_c_no = 10010101000010
# static block ends
def team_member(self, id, name, salary = 00.00): # Remember this is a method, not a function
# Instance block
self.i_d = id
self.n_m = name
self.sal = salary
def mess_disp(self):
print(Official_tech.comp_c_no) # printing Static variable using Class name
print(self.i_d) # printing instance variable
print(self.sal)
print(self.n_m)
print(Official_tech.comp_name)
obj_var = Official_tech() # 1.creating object and storing to variable
obj_var.team_member(808, 'tppa', 400000.00) # giving arg's to parameters
obj_var.mess_disp()
print("~ " * 10)
obj_var1 = Official_tech() # 2.creating another object and storing to variable
obj_var1.team_member(1010, 'sqst', 350000.00)
obj_var.mess_disp()
print("~ " * 10)
print(obj_var.comp_name) # calling static variable
print("~ " * 10)
print(obj_var1.i_d) # calling Instance variable
print(obj_var1.comp_c_no)
| true |
6da56124e837982d56bed013942e60fc9068692b | amersulieman/Simple-Encryption-Decryption | /Decryption.py | 1,552 | 4.15625 | 4 | '''@Author: Amer Sulieman
@Version: 10/07/2018
@Info: A decryption file'''
import sys
from pathlib import Path
#check arguments given for the script to work
if len(sys.argv)< 2:
sys.exit("Error!!!!\nProvide <fileName> to decrypt!!");
def decryption(file):
#File path to accomdate any running system
filePath = Path("./"+file);
#The file data will be copied to this variable encrypted
Decrypt1="";
Decrypt2="";
#Open the file
with open(filePath) as myFile:
#read the file data
readFile = myFile.read()
#every letter in the read data
for character in readFile:
#decrypt1 gets shifted back 2^2 places
Decrypt1+=chr(ord(character)>>2)
#Loop every letter in decrypt1
for letter in Decrypt1:
#If the letter is small 'a' to small 'z' shift it by 13 in alpha order
if ord(letter)>=97 and ord(letter)<=122:
#Replace the letter and concatnate to ENC variable
Decrypt2+=chr(((ord(letter)-97+13)%26)+97);
#If the letter is capital 'A' to capital 'Z' shoft it by 13 in alpha order
elif ord(letter)>=65 and ord(letter)<=90 :
#Replace the letter and concatnate to ENC variable
Decrypt2+=chr(((ord(letter)-65+13)%26)+65);
#If it is a line feed then add the line feed so i can keep the format
elif ord(letter)==10:
Decrypt2+="\n"
#Any other character shift its asic by 2 spots
else:
Decrypt2+=chr(ord(letter)>>2);
#Write the decrypted data back to the file
with open(filePath,"w") as myFile:
myFile.write(Decrypt2);
print(file +" Decrypted!!");
decryption(sys.argv[1]); | true |
323349df70f4586b2055c9ae5894a0195f1e79ba | vladn90/Algorithms | /Numbers/fibonacci.py | 1,940 | 4.125 | 4 | """ Comparison of different algorithms to calculate n-th Fibonacci number.
In this implemention Fibonacci sequence is gonna start with 0, i.e.
0, 1, 1, 2, 3, 5...
"""
from timeit import timeit
from functools import lru_cache
def fib_1(n):
""" Recursive algorithm. Very slow. Runs in exponential time.
"""
# base case 0th Fibonacci number = 0
if n == 0:
return 0
# base case 1st Fibonacci number = 1
elif n == 1:
return 1
return fib_1(n - 1) + fib_1(n - 2)
fib_cache = {0: 0, 1: 1} # Fib index: Fib number
def fib_2(n):
""" Improved algorithm using memoization, runs in linear time.
"""
if n in fib_cache:
return fib_cache[n]
fib_cache[n] = fib_2(n - 1) + fib_2(n - 2)
return fib_cache[n]
@lru_cache()
def fib_3(n):
""" Same logic as above but using cache function as a decorator.
"""
# base case 0th Fibonacci number = 0
if n == 0:
return 0
# base case 1st Fibonacci number = 1
elif n == 1:
return 1
return fib_3(n - 1) + fib_3(n - 2)
def fib_4(n):
""" Dynamic programming solution. Runs in O(n) time and uses O(1) space.
"""
if n < 2:
return n
prev, curr = 0, 1
for i in range(2, n + 1):
prev, curr = curr, prev + curr
return curr
if __name__ == "__main__":
# stress testing solutions against each other up to 20th Fibonacci number
for n in range(0, 21):
f1 = fib_1(n)
f2 = fib_2(n)
f3 = fib_3(n)
f4 = fib_4(n)
assert f1 == f2 == f3 == f4
# time comparison for n-th Fibonacci number
n = 30
t1 = timeit("fib_1(n)", number=1, globals=globals())
t3 = timeit("fib_2(n)", number=1, globals=globals())
t4 = timeit("fib_4(n)", number=1, globals=globals())
print(f"Recursive implemention: {t1}")
print(f"Recursive implemention with memoization: {t3}")
print(f"Dynamic programming solution: {t4}")
| true |
6b974c6dfc21b4d8aeea7cf2a9536b8a33b02929 | vladn90/Algorithms | /Sorting/insertion_sort.py | 1,207 | 4.4375 | 4 | """ Insertion sort algorithm description,
where n is a length of the input array:
1) Let array[0] be the sorted array.
2) Choose element i, where i from 1 to n.
3) Insert element i in the sorted array, which goes from i - 1 to 0.
Time complexity: O(n^2).
Space complexity: O(1).
"""
import random
def insertion_sort(array):
""" Sorts array in-place.
"""
for i in range(1, len(array)):
for j in range(i - 1, -1, -1):
if array[i] < array[j]:
array[i], array[j] = array[j], array[i]
i -= 1
else:
break
if __name__ == "__main__":
# stress testing insertion_sort by comparing with built-in sort()
while True:
nums = [random.randrange(10**3, 10**12)
for i in range(random.randrange(10**2, 10**3))]
nums_insert = nums[:]
nums.sort()
insertion_sort(nums_insert)
if nums == nums_insert:
print("OK")
print(f"size of the sorted array: {len(nums)}")
else:
print("Something went wrong.")
print(f"bult-in sort result: {nums}")
print(f"insertion sort result: {nums_insert}")
break
| true |
2f5ea417ad6f0ff70f0efcede02f9579c580533a | vladn90/Algorithms | /Sorting/bubble_sort.py | 1,196 | 4.375 | 4 | """ Bubble sort algorithm description,
where n is a length of the input array:
1) Compare consecutive elements in the list.
2) Swap elements if next element < current element.
4) Stop when no more swaps are needed.
Time complexity: O(n^2).
Space complexity: O(1).
"""
import random
def bubble_sort(array):
""" Sorts array in-place.
"""
need_swap = True
while need_swap:
need_swap = False
for i in range(len(array) - 1):
if array[i + 1] < array[i]:
array[i], array[i + 1] = array[i + 1], array[i]
need_swap = True
if __name__ == "__main__":
# stress testing bubble_sort by comparing with built-in sort()
while True:
nums = [random.randrange(10**3, 10**12)
for i in range(random.randrange(10**2, 10**3))]
nums_bubble = nums[:]
nums.sort()
bubble_sort(nums_bubble)
if nums == nums_bubble:
print("OK")
print(f"size of the sorted array: {len(nums)}")
else:
print("Something went wrong.")
print(f"bult-in sort result: {nums}")
print(f"bubble sort result: {nums_bubble}")
break
| true |
8c57f071fe179750c8be0d2b81ed023d94299ad7 | vladn90/Algorithms | /Matrix_problems/spiral_matrix.py | 2,011 | 4.25 | 4 | """ Problem description can be found here:
https://leetcode.com/problems/spiral-matrix/description/
Given a matrix of m x n elements,
return all elements of the matrix in spiral order.
For example, given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1, 2, 3, 6, 9, 8, 7, 4, 5].
"""
def spiral_order(matrix):
result = []
n = len(matrix) * len(matrix[0])
right = len(matrix[0])
left = -1
bottom = len(matrix)
top = 0
i, j = 0, -1
while len(result) < n:
j += 1
while j < right and len(result) < n:
result.append(matrix[i][j])
j += 1
j -= 1
right -= 1
i += 1
while i < bottom and len(result) < n:
result.append(matrix[i][j])
i += 1
i -= 1
bottom -= 1
j -= 1
while j > left and len(result) < n:
result.append(matrix[i][j])
j -= 1
j += 1
left += 1
i -= 1
while i > top and len(result) < n:
result.append(matrix[i][j])
i -= 1
i += 1
top += 1
return result
def display_matrix(matrix):
x = len(matrix) // 2
for i in matrix:
for j in i:
print(str(j).rjust(3), end=" ")
print()
if __name__ == "__main__":
# 3 x 3 matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
display_matrix(matrix)
result = spiral_order(matrix)
assert result == [1, 2, 3, 6, 9, 8, 7, 4, 5]
print(f"result: {result}")
print()
# 5 x 5 matrix
matrix = []
for i in range(1, 26, 5):
matrix.append(list(range(i, i + 5)))
display_matrix(matrix)
result = spiral_order(matrix)
print(f"result: {result}")
print()
# 10 x 10 matrix
matrix = []
for i in range(1, 101, 10):
matrix.append(list(range(i, i + 10)))
display_matrix(matrix)
result = spiral_order(matrix)
print(f"result: {result}")
| true |
cfadda58720b5b635c21235c4a73a91f6cffca40 | ayr0/numerical_computing | /Python/GettingStarted/solutions_GettingStarted.py | 2,065 | 4.375 | 4 | # Problem 1
'''
1. Integer Division returns the floor.
2. Imaginary numbers are written with a suffix of j or J.
Complex numbers can be created with the complex(real, imag) function.
To extract just the real part use .real
To extract just the imaginary part use .imag
3. float(x) where x is the integer.
4. //
'''
# problem 2
'''
1. A string is immutable because its content cannot be changed.
2. string[::2] returns every other letter of the string.
string[27:0:-1] returns the string in reverse - without the first character.
3. The entire string in reverse can be accessed by string[::-1]
'''
# problem 3
'''
1. Mutable objects can be changed in place after creation.
The value stored in memory is changed.
Immutable objects cannot be modified after creation.
2. a[4] = "yoga"
a[:] is a copy of the entire list
a[:] = [] clears the list (del a[:] is also an option)
len(a) returns the list size.
a[0], a[1] = "Peter Pan", "camelbak"
a.append("Jonathan, my pet fish")
3.
my_list = []
my_list = [i for i in xrange(5)]
my_list[3] = float(my_list[3])
del my_list[2]
my_list.sort(reverse=True)
'''
# Problem 4
'''
1.
set() (must be used to create an empty set) and {}
2.
union = set.union(setA, setB)
or union = setA | setB
3. trick questions! sets don't support indexing, slicing, or any other
sequence-like behavior. Works because sets are unordered and don't allow duplicates.
'''
# problem 5
'''
1. dict() and {} (must be used to create an empty dictionary)
2. sq = {x: x**2 for x in range(2,11,2)}
3. del(dict[key])
4. dict.values()
'''
#problem 6
'''
1. The print statement writes the value of the expression(s) it's given
to the standard output. The return statement allows a function to specify
a return value to be passed back to the calling function.
2. Grocery List cannot have a space. It is also important NOT to call your list "list".
Doing so shadows Python's built in list constructor.
for loop and if statement require a colon and nested indentation
i%2 == 0. Not an assignment.
Grocery List[i]. Needs brackets.
'''
| true |
7eb6f26a36fd55f437aef7510db2d9df1e055d2e | flyburi/python-study | /io_input.py | 223 | 4.375 | 4 | def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
sth = raw_input("Enter text:")
if is_palindrome(sth):
print "yes it is a palindrome"
else:
print "no it is not a palindrome"
| true |
89ebfba3b074ecdf011aff1e1f0a1013f980ab56 | rafa761/algorithms-example | /insertion_sort.py | 585 | 4.28125 | 4 | unsorted_list = [7, 3, 9, 2, 8, 4, 1, 5, 6]
def insertion_sort(num_list):
# We don't need to consider the index 0 because there isn't any number on the left
for i in range(1, len(num_list)):
# store the current value to sort
value_to_sort = num_list[i]
# While there are greater values on the left
while num_list[i - 1] > value_to_sort and i > 0:
# switch the values
num_list[i], num_list[i - 1] = num_list[i - 1], num_list[i]
i -= 1
return num_list
if __name__ == '__main__':
print('Before:', unsorted_list)
print('After: ', insertion_sort(unsorted_list))
| true |
7fac6b0e87c550f517d9bea7834585812ff6ddac | Raeebikash/python_class2 | /practice/exercise77.py | 538 | 4.25 | 4 | # define is_palindrome function that take one world in string as input
# and return True if it is palindrome else return false
# palindrome - word that reads same backwards as forwards
#example
# is_palindrome ("madam") ------> True
# is_palindrome ("naman")------> True
#is_palindrome ("horse")----->False
# logic (algorithm)
#step 1-> reverse the string
# step 2 - compare reversed string with original string
def is_palindrome(word):
return word == word[::-1]
print(is_palindrome("naman"))
print(is_palindrome("horse"))
| true |
8fa3d457aeb3c0162a2b0d677ce3b089dd8e1e25 | BalaKumaranKS/Python | /codes/assignment 01- 01.py | 209 | 4.4375 | 4 | #program for calculating area ofcircle
value01 = int (input('Enter radius of circle in mm '))
value02 = (value01 * value01)
value03 = (3.14 * value02)
print ('The area of circle is',str(value03),'mm^2' )
| true |
628bfaf8e262ab8186103f95e52f478ed7381082 | BalaKumaranKS/Python | /codes/assignment 02- 02.py | 235 | 4.3125 | 4 | # Program to check number is positive or negative
inp = int(input('Enter the Number: '))
if inp > 0:
print('The number is Positive')
elif inp== 0:
print ('The number is 0')
else:
print('The number is Negative')
| true |
0bd9287e31945c94caf4cb3ee7c41635435a7273 | heecho/Database | /webserver-3.py | 2,628 | 4.1875 | 4 | '''
Phase three: Templating
Templating allows a program to replace data dynamically in an html file.
Ex: A blog page, we wouldn't write a whole new html file for every blog page. We want to write
the html part, and styling just once, then just inject the different blog data into that page.
1) Add the following line to index.html in the body
<h2>###Title###</h2>
2) When a request come in for index (/)
- read the file data for index.html
- change the ###Title### string to the string "This is templating"
- return the changed html
3) Write a function render_template to take an html template, and a hash context
Ex: render_template("<html>...",{"Title":"This is templating"})
- Render will then try to replace all the fields in that hash
Ex: context = {"Title":"This is the title","BlogText":"this is blog data"}
In the html template replace ###Title### and ###BlogText### with corresponding key values.
- Test by using this context {"Title":"This is the title","BlogText":"this is blog data"}
4) Add render_template to index_page with the sample context above
'''
import socket
HOST, PORT = '', 8888
VIEWS_DIR = "./views"
def run_server():
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
urls = {'/': index_page(), '/about': about_page()}
print 'Serving HTTP on port %s ...' % PORT
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(4096)
request_line = request.split('\r\n')
request_first_part = request_line[0].split(' ')
request_verb = request_first_part[0]
request_page = request_first_part[1]
print request_verb, request_page
http_response = """HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"""
if request_page in urls.keys():
http_response += urls[request_page]
if not request:
continue
client_connection.sendall(http_response)
client_connection.close()
def read_file(page):
page_file = VIEWS_DIR + page
with open(page_file, 'r') as f:
return f.read()
def index_page():
filehash = {"Title":"This is a New Title"}
filedata = read_file('/index.html')
return render_template(filedata,filehash)
def about_page():
return read_file('/about.html')
def render_template(filedata, data_hash):
for k,v in data_hash.iteritems():
filedata = filedata.replace('###%s###' %k, v)
return filedata
run_server()
| true |
afc147e559f9589487ce969973e8342beae3a05b | Ulkuozturk/SQL_Python_Integration | /movie_Create_AddData.py | 648 | 4.4375 | 4 | import sqlite3
connection = sqlite3.connect("movie.db")
cursor= connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS Movies
(Title TEXT, Director TEXT, Yera INT)''' )
famousfilms=[("Pulp Fiction","Quantin Tarantino", 1994),("Back To The Future","Steven Spielberg", 1985),
("Moonrise Kingdom","Wes Anderson", 2012)]
cursor.executemany('INSERT INTO Movies VALUES (?,?,?)', famousfilms) # To insert multiple values.
records=cursor.execute("SELECT * FROM Movies ")
print(cursor.fetchall())
for record in records:
print(record)
connection.commit()
connection.close()
## Simply run the file to create db file we just create.
| true |
554f4435cd9ec0bdbdff8e5f6b61a50b3ae8f355 | taylortom/Experiments | /Python/MyFirstPython/Lists.py | 518 | 4.3125 | 4 | #
# Lists
#
list = [0,1,'two', 3, 'four', 5, 6, 'Bob']
# add to the list
list.append('kate')
print list
# remove an item
list.pop(3)
# can also use list.pop() to remove last item
print list
# sort a list
list.sort()
print list
# reverse a list
list.reverse()
print list
# list nesting
matrix = [[-1,0,0], [0,-1,0], [0,0,1]]
print matrix[2], matrix[2][2]
# access a 'column' in the matrix
print [row[0] for row in matrix]
# add 1 to each item in column 1
matrix2 = [row[0] + 1 for row in matrix]
print matrix2
| true |
fa5e9a2770fbc24836104db247d0d1e6866ee77b | sidmaskey13/python_assignments_2 | /P12.py | 599 | 4.375 | 4 | # Create a function, is_palindrome, to determine if a supplied word is
# the same if the letters are reversed.
givenString = input('Enter string: ')
def check_palindrome(given_string):
word_length = len(given_string)
half_word_length = int(word_length/2)
match = 0
for i in range(0, half_word_length):
if given_string[i] == given_string[-i-1]:
match += 1
if match == half_word_length:
return f"{given_string} is Palindrome"
else:
return f"{given_string} is not Palindrome"
print(check_palindrome(givenString))
| true |
61e354e9f4d5c5cabbd6a804150cf5e6c505285a | sidmaskey13/python_assignments_2 | /P3.py | 586 | 4.3125 | 4 | # Write code that will print out the anagrams (words that use the same
# letters) from a paragraph of text.
givenString = input('Enter string: ')
def check_anagrams(given_string):
word_length = len(given_string)
half_word_length = int(word_length/2)
match = 0
for i in range(0, half_word_length):
if given_string[i] == given_string[-i-1]:
match += 1
if match == half_word_length:
return f"{given_string} is Anagram"
else:
return f"{given_string} is not Anagram"
print(check_anagrams(givenString))
| true |
70a2412549fe5a7e8bf54f626457e529363f3a9b | mccricardo/project_euler | /problem_46/python/problem46.py | 627 | 4.3125 | 4 | # Start with prime 3.
#
# If none of the primes in prime_list divide n, then it's also prime and
# add it to the list.
#
# If not, let's put the problem formula with another aspect:
# prime = odd_number - 2 * pow(i, 2)
#
# This means that we can check if any of the primes can be constructed in terms
# of the odd number. If not, we found our number.
number = 3
primes_list = set()
while True :
if all(number % p for p in primes_list) :
primes_list.add(number)
else :
if not any((number-2*pow(i,2)) in primes_list for i in xrange(1, number)):
break
number += 2
print "The number is:", number
| true |
a3def7eec0586d8dfdbef1aa55c6feec20b5c854 | wreyesus/Learning-to-Code | /python/python_crash_course/chapter_4/4-1.pizzas.py | 273 | 4.6875 | 5 | """ Store three kinds of pizza in a list
1. print them in a for loop
2. write about why you love pizza """
pizzas = ['americana', 'hawaina', 'peperoni']
for pizza in pizzas: #1
print(f'I like {pizza}')
print('I REALLY LOVE PIZZA IS MY FAVORITE FOOD IN THE WORLD') #2 | true |
d1076809fe1826dad2117b9ced283dcb7173fcdb | wreyesus/Learning-to-Code | /python/python_crash_course/chapter_10/10-2.learning_c.py | 458 | 4.28125 | 4 | """ Read in each line from the file you just created, learning_python.txt,
and replace the word Python with the name of another language, such
as C. Print each modified line to the screen. """
filename = './learning_python.txt'
with open(filename) as f:
lines = f.readlines()
for line in lines:
if 'Python' in line:
c = line.replace('Python', 'C')
print(c.strip())
def if the name of iquales main is more than just | true |
8655935a7d3a32c2e1a89ef3091db2f3f3de256a | wreyesus/Learning-to-Code | /python/python_crash_course/chapter_9/9-2.three_restaurants.py | 838 | 4.4375 | 4 | """ Start with your class from Exercise 9-1. Create three
different instances from the class, and call
describe_restaurant() for each instance. """
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(f'Welcome to {self.restaurant_name.title()}')
print(f'Our cousine type is: {self.cuisine_type.title()}')
def open_restaurant(self):
print(f'The {self.restaurant_name.title()} is OPEN')
restaurant1 = Restaurant('Don Pancho', 'fried chicken')
restaurant2 = Restaurant('American Store', 'burguer')
restaurant3 = Restaurant('Healthy place', 'burguer')
restaurant1.describe_restaurant()
restaurant2.describe_restaurant()
restaurant3.describe_restaurant() | true |
085723b30c9de5a3dae534fa25a02f3deaafe065 | wreyesus/Learning-to-Code | /python/python_crash_course/chapter_8/8-12.sandwiches.py | 545 | 4.15625 | 4 | """ Write a function that accepts a list of items a person
wants on a sandwich. The function should have one parameter
that collects as many items as the function call provides,
and it should print a summary of the sandwich that is being ordered. """
def sandwiches_order(*sandwich):
print('ORDER:')
for order in sandwich:
print(f'- {order.title()}')
sandwiches_order('peruvian', 'mcburger', 'chicken junior')
sandwiches_order('american classic', 'fish burger', 'chicken')
sandwiches_order('onion', 'simple burger', 'turkey') | true |
2565e37340942909c482bb4501d45d057fb3960e | wreyesus/Learning-to-Code | /regExp/scripts/exercise_2.py | 323 | 4.25 | 4 | """Write a Python program that matches
a string that has an a followed by zero
or more b's."""
import re
def finder(string):
"""using 're.match'"""
regex = re.match('^a[\w]*', string)
if regex:
print('We have a MATCH')
else:
print('NO MATCH')
finder('abc')
finder('abbc')
finder('abbba')
| true |
2264c01614e3ba01e621b7cc9ae50920f2a54bc0 | wreyesus/Learning-to-Code | /python/python_crash_course/chapter_5/5-2.more_conditional_tests.py | 1,021 | 4.3125 | 4 | # 1. Tests for equality and inequality with strings
print('='*5)
car = 'Tesla'
print(car == 'tesla')
print(car == 'Tesla')
# 2. Tests using the lower() function
print('='*5)
name = 'James'
test = name.lower() == 'james'
print(test)
# 3. Numerical tests involving equality and inequality,
# greater than and less than, greater than or equal to,
# and less than or equal to
print('='*5)
age = 18
print(age != 19)
20 > 10
print(20 < 10)
10 >= 10
print(10<10)
print(10==10)
# 4. Tests using the and keyword and the or keyword
print('='*5)
tickets = 5
10 >= 10
test_2 = (tickets == 5) and (10 > 10)
test_3 = (tickets == 5) or (10 > 10)
print(test_2)
print(test_3)
# 5. Test whether an item is in a list
print('='*5)
pets = ['cat', 'dog', 'mouse']
print(pets)
if 'cat' in pets:
print(f'The {pets[0]} is a cute pet')
else:
print('I do not like that one')
# 6. Test whether an item is not in a list
print('='*5)
foods = ['ceviche', 'peruavian beans', 'pizza']
food = 'turkey'
if food not in foods:
print('OK') | true |
ab3e9f61cd9942019c125f1d940daff547c80888 | Abdulvaliy/Tip-calculator | /Tip calculator.py | 468 | 4.125 | 4 | #If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
print("Welcometo the tip calculator.")
bill = float(input("What was the total bill? $"))
percent = int(input("What percentage tip would you like to give? 10, 12 or 15? "))
people = int(input("How many people to split the bill? "))
cost = str(round((bill * (100 + percent)/100) / people , 2))
print(f"Each person should pay: ${cost}")
| true |
240cad4398853e25f993842413a88eef365af76b | brian-rieder/DailyProgrammer | /DP146E_PolygonPerimeter.py | 1,903 | 4.3125 | 4 | __author__ = 'Brian Rieder'
# Link to reddit: http://www.reddit.com/r/dailyprogrammer/comments/1tixzk/122313_challenge_146_easy_polygon_perimeter/
# Difficulty: Easy
# A Polygon is a geometric two-dimensional figure that has n-sides (line segments) that closes to form a loop.
# Polygons can be in many different shapes and have many different neat properties, though this challenge is about
# Regular Polygons . Our goal is to compute the permitter of an n-sided polygon that has equal-length sides
# given the circumradius . This is the distance between the center of the Polygon to any of its vertices;
# not to be confused with the apothem!
# Input Description
# Input will consist of one line on standard console input. This line will contain first an integer N, then
# a floating-point number R. They will be space-delimited. The integer N is for the number of sides of the Polygon,
# which is between 3 to 100, inclusive. R will be the circumradius, which ranges from 0.01 to 100.0, inclusive.
# Output Description
# Print the permitter of the given N-sided polygon that has a circumradius of R. Print up to three digits precision.
# Sample Inputs & Outputs
# Sample Input 1
# 5 3.7
# Sample Output 1
# 21.748
# Sample Input 2
# 100 1.0
# Sample Output 2
# 6.282
from math import sin
from math import pi
class Polygon:
def __init__(self, num_sides, circumradius):
self.num_sides = float(num_sides)
self.circumradius = float(circumradius)
def find_side_length(self):
return 2 * self.circumradius * sin(pi / self.num_sides)
def find_perimeter(self, side_length):
return side_length * self.num_sides
if __name__ == "__main__":
user_input = input("Enter arguments as <number of sides> <circumradius>: ").split()
polygon = Polygon(user_input[0], user_input[1])
print("Perimeter: %.3f" % polygon.find_perimeter(polygon.find_side_length()))
| true |
7bbd62ff212c1a9a6b33b8bab369ba3b9c025488 | amandazhuyilan/Breakfast-Burrito | /Data-Structures/BinarySearchTree.py | 2,911 | 4.1875 | 4 | # Binary Search tree with following operations:
# Insert, Lookup, Delete, Print, Comparing two trees, returning tree
# elements
# example testing tree:
# 8
# / \
# 3 10
# / \ \
# 1 6 14
# / \ /
# 4 7 13
class node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert node with value data. Look for right location recursively.
# ex. root.insert(3)
def insert(self,data):
if self.data:
if data > self.data:
if self.right is None:
self.right = node(data)
else:
self.right.insert(data)
elif data < self.data:
if self.left is None:
self.left = node(data)
else:
self.left.insert(data)
elif data == self.data:
print("Node already exists!")
else:
self.data = data
# Lookup node with given data, do it recursively until find it. Returns
# node and its parent
# ex: root.lookup
def lookup(self, data, parent=None):
if data < self.data:
if self.left is None:
return None, None
return self.left.lookup(data, self)
elif data > self.data:
if self.right is None:
return None, None
else:
return self.right.lookup(data,self)
else:
return self, parent
# Removes the node in the tree. Need to consider if the removed node has
# 0, 1 or 2 children (added in count_children function)
# Always need to consider different scenrios when node is root
def delete(self, data):
def count_children(self):
count = 0
if self.left:
count += 1
if self.right:
count += 1
return count
node, parent = self.lookup(data)
if node:
if count_children == 0:
if parent:
if parent.left is node:
parent.left = None
else:
parent.right = None
del node
# If the node to be removed is a root:
else:
self.data = None
if count_children == 1:
if node.left:
n = node.left
if node.right:
n = node.right
if parent:
if parent.left is node:
parent.left = n
else:
parent.right = n
else:
self.left = n.left
self.right = n.right
self.data = n.data
if count_children == 2:
parent = node
successor = node.right
while successor.left:
parent = successor
successor = successor.left
node.data = successor.data
if parent.left == successor:
parent.left = successor.right
else:
parent.right = successor.right
# Use recursive to walk tree depth-first. Left subtree->Root->Right
# subtree
def print_tree(self):
if self.left:
self.left.print_tree()
print self.data
if self.right:
self.right.print_tree()
#Tests
root = node(8)
root.insert(3)
root.insert(1)
root.insert(6)
root.insert(4)
root.insert(7)
root.insert(2)
root.insert(5)
root.insert(10)
root.insert(14)
root.insert(13)
print(root.lookup(6))
| true |
7c9c7bfbaac7077ec4beaa4dac1405d726799eb7 | hayleymathews/data_structures_and_algorithms | /Lists/examples/insertion_sort.py | 819 | 4.34375 | 4 | """python implementation of Insertion Sort with Positional List
>>> p = PositionalList()
>>> p.add_first(1)
Position: 1
>>> p.add_first(3)
Position: 3
>>> p.add_first(2)
Position: 2
>>> insertion_sort(p)
PositionalList: [1, 2, 3]
"""
from Lists.positional_list import PositionalList
def insertion_sort(List):
if len(List) > 1:
marker = List.first()
while marker != List.last():
pivot = List.after(marker)
value = pivot.element()
if value > marker.element():
marker = pivot
else:
walk = marker
while walk != List.first() and List.before(walk).element() > value:
walk = List.before(walk)
List.delete(pivot)
List.add_before(walk, value)
return List
| true |
cbe8c75f0538700abf4c7e528176c83944be8080 | hayleymathews/data_structures_and_algorithms | /Arrays/examples/insertion_sort.py | 439 | 4.28125 | 4 | """ python implementation of Insertion Sort
>>> insertion_sort([3, 2, 1])
[1, 2, 3]
"""
def insertion_sort(array):
"""
sort an array of comparable elements in ascending order O(n^2)
"""
for index in range(1, len(array)):
current = array[index]
while index > 0 and array[index - 1]> current:
array[index] = array[index - 1]
index -= 1
array[index] = current
return array
| true |
97e9c3f73ab4dfa755eb467fa8bba65f2d4c71f5 | epicmonky/Project-Euler-Solutions | /problem020.py | 430 | 4.125 | 4 | # n! means n x (n - 1) x ... x 3 x 2 x 1
# For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
# Find the sum of the digits in the number 100!
import math
def sum_of_digits(n):
s = 0
while n > 0:
s += n % 10
n = n // 10
return s
if __name__ == '__main__':
n = math.factorial(100)
print(sum_of_digits(n))
| true |
440f7e019f7621b8f497beb4dd3d6156870bfb3c | colehoener/DataStructuresAndAlgorithms | /Hash/open_hash.py | 1,809 | 4.15625 | 4 | #Mark Boady - Drexel University CS260 2020
#Implement an OPEN hash table
import random
#Hash Functions to test with
def hash1(num,size):
return num % size
def hash2(num,size):
x=2*(num**2)+5*num+num
return x % size
def hash3(num,size):
word=str(num)
total=0
for x in range(0,len(word)):
c=word[x]
total=total+ord(c)
total=total*1010
return total % size
#Here is a helper function for testing
#It gives you a random sequence
#with no duplicates
def random_sequence(size):
X=[x for x in range(0,5*size+1)]
random.shuffle(X)
return X[0:size]
#The class for the open hash table
class OpenHash:
#n is the size of the table
#h_fun is the hash function to use
#h_fun must be a function that takes two inputs
#the number to hash and size of the table.
#It returns an integer between 0 and n-1
#The index to put the element.
def __init__(self,n,h_fun):
self.size = n
self.data = [ [] for x in range(0,n)]
self.hash_func = h_fun
#You can use this str method to help debug
def __str__(self):
res=""
for x in range(0,self.size):
res+="Row "+str(x)+" "+str(self.data[x])+"\n"
return res
#Insert num into the hashtable
#Do not keep duplicates in the table.
#If the number is already in the table, do not
#Insert it again
def insert(self,num):
pos = self.hash_func(num, self.size)
if not(num in self.data[pos]):
self.data[pos].append(num)
return
#Member returns True is num is in the table
#It returns False otherwise
def member(self,num):
pos = self.hash_func(num, self.size)
if (num in self.data[pos]):
return True
return False
#Delete removes num from the table
def delete(self,num):
pos = self.hash_func(num, self.size)
if (num in self.data[pos]):
self.data[pos].remove(num)
return
#You may create any additional
#Helper methods you wish
| true |
abf112da79470c8d9b14e7d17747ad699858718b | arcPenguinj/CS5001-Intensive-Foundations-of-CS | /homework/HW1/tables.py | 1,226 | 4.25 | 4 | '''
Yici Zhu
CS 5001, Fall 2020
it's a program calculating how many table can be assembled
test cases :
4 tops, 20 legs, 32 screws => 4 tables assembled. Leftover parts: 0 table tops, 4 legs, 0 screws.
20 tops, 88 legs, 166 screws => 20 tables assembled. Leftover parts: 0 table tops, 8 legs, 6 screws.
100 tops, 88 legs, 200 scews => 22 tables assembled. Leftover parts: 78 table tops, 0 legs, 24 screws.
'''
def main ():
tabletop_number = int(input("Number of tops: "))
leg_number = int(input("Number of legs: "))
screw_number = int(input("Number of screws: "))
top_per_table = tabletop_number / 1
legs_per_table = leg_number / 4
screw_per_table = screw_number / 8
table_can_be_assembled = int(min(top_per_table, legs_per_table, screw_per_table))
top_leftover = int(tabletop_number - table_can_be_assembled)
leg_leftover = int(leg_number - table_can_be_assembled * 4)
screw_leftover = int(screw_number - table_can_be_assembled * 8)
print (str(table_can_be_assembled) + " tables assembled. Leftover parts: " + str(top_leftover) + " tops, " + str(leg_leftover) + " legs, " + str(screw_leftover) + " screws.")
if __name__ == "__main__":
main() | true |
cc47e4a1c80f09bbeb121b624dc1f5d2fca087f8 | arcPenguinj/CS5001-Intensive-Foundations-of-CS | /homework/HW2/exercise.py | 1,669 | 4.21875 | 4 | '''
Fall2020
CS 5001 HW2
Yici Zhu
it's a program for planning exercise based on different conditions
'''
def main():
days = input("What day is it? ").title()
holidays = input("Is it a holiday? ").title()
rains = input("Is it raining? ").title()
temps = float(input("What is the temperature? "))
# print(days, holidays, rains, temps)
holidaybool = True
workoutdays_bool = True
rainsbool = True
if days != "M" and days != "Tu" and days != "W" and days != "Th" and \
days != "F" and days != "Sa" and days != "Su":
print("Swim for 35 minutes")
return
if holidays == "Y":
holidaybool = True
elif holidays == "N":
holidaybool = False
else:
print("Swim for 35 minutes")
return
if rains == "Y":
rainsbool = True
elif rains == "N":
rainsbool = False
else:
print("Swim for 35 minutes")
return
if days == "M" or days == "W" or days == "F" or \
days == "Sa" or holidaybool:
workoutdays_bool = True
else:
print("Take a rest day")
return
excersice = ""
if days == "M" or days == "W" or days == "F":
excersice = "Run"
if days == "Sa" or holidaybool:
excersice = "Hike"
if rainsbool and workoutdays_bool:
excersice = "Swim"
excersice_time = ""
if excersice == "Run" and (temps > 75 or temps < 35):
excersice_time = "30"
else:
excersice_time = "45"
print(excersice + " for " + excersice_time + " minutes")
if __name__ == "__main__":
main()
| true |
a77c1e503d0e39d55e2915962131bad2f0970126 | algorithmsmachine/PythonAlgorithms | /misc/factorial.py | 256 | 4.1875 | 4 | num = 90
factorial=1
if num <0:
print("cannot print factorial of negative num ")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num," is ",factorial)
| true |
84a41b50164514518b02a83722820605d0468e0e | prabhakarzha/pythonimportantcode | /main.py | 2,146 | 4.125 | 4 |
# reduce() function is not a built-in function anymore ,and it can be found in the functools module
from functools import reduce
def add(x,y):
return x+y
list =[2,3,4,5,6]
print(reduce(add,list))
# map() function -The map() function iterates through all items in the given iterable
# and execute the function we passes as an argument on each of them
def starts_with_A(s):
return s[0]=="A"
fruit =["Apple","Banana","pear","mango","Apricot"]
map_object =map(starts_with_A,fruit)
print(list(map_object))
#another example
def sq(a):
return a*a
num =[2,3,4,5,6,7,8,9,]
square = list(map(sq,num))
print(square)
#filter() function forms a new list that contains only elements that satisfy a certain condition
def starts_with_A(s):
return s[0]=="A"
fruit =["Apple","Banana","pear","mango","Apricot"]
filter_object =filter(starts_with_A,fruit)
print(list(filter_object))
#--------------------------MAP------------------------------
numbers = ["3", "34", "64"]
numbers = list(map(int, numbers))
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
numbers[2] = numbers[2] + 1
print(numbers[2])
def sq(a):
return a*a
num = [2,3,5,6,76,3,3,2]
square = list(map(sq, num))
print(square)
num = [2,3,5,6,76,3,3,2]
square = list(map(lambda x: x*x, num))
print(square)
def square(a):
return a*a
def cube(a):
return a*a*a
func = [square, cube]
num = [2,3,5,6,76,3,3,2]
for i in range(5):
val = list(map(lambda x:x(i), func))
print(val)
#--------------------------FILTER------------------------------
list_1 = [1,2,3,4,5,6,7,8,9]
def is_greater_5(num):
return num>5
gr_than_5 = list(filter(is_greater_5, list_1))
print(gr_than_5)
#--------------------------REDUCE------------------------------
from functools import reduce
list1 = [1,2,3,4,2]
num = reduce(lambda x,y:x*y, list1)
# num = 0
# for i in list1:
# num = num + i
print(num)
from array import*
# vals = array('i',[1,2,3,4,5,])
#
# for i in range(5):
# print(vals[i])
# val =array('i',[2,3,4,5,])
# for i in range(4):
# print(val[i])
val=array('i',[2,3,4,5,6,7])
val.reverse()
print(val)
| true |
ca3819dc5cd360988f9eb8c2f6f3ae7942ac1446 | Gowthini/gowthini | /factorial.py | 261 | 4.28125 | 4 | num=int(input("enter the number"))
factorial=1
if num<0:
print("factorial does not exist for negative numbers")
elif num==0:
print("The factorial is")
else:
for i in range(1,num+1):
factorial=factorial*i
print("The factorial of"num,"is",factorial)
| true |
d33fb48a41a852ab3d3bfcb4624e7693dad18f9c | jwmarion/daily | /euler/35multiple.py | 427 | 4.21875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
multiples = []
result = 0
for x in range(0,1000):
if x % 3 == 0:
multiples.append(x)
if x % 5 == 0 and x % 3 != 0:
multiples.append(x)
for x in range(len(multiples)):
result += multiples[x]
print result
| true |
d19cef12494dc50a7beb21a625a23823ce93d98c | eghadirian/Python | /P10-FindTwoElements.py | 377 | 4.15625 | 4 | # find the if sum of two elements is a value
# find pythagoream triplets
def sum_of_two(arr, val):
found = set()
for el in arr:
if val - el in found:
return True
found.add(el)
return False
def func(arr):
n = len(arr)
for i in range(n):
if sum_of_two(arr[:i]+arr[i+1:], arr[i]):
return True
return False
| true |
e358e998f4b59281e990ffd5b41dc2ecc81db548 | devpatel18/PY4E | /ex_05_02.py | 484 | 4.21875 | 4 | largest=None
smallest=None
while True:
num1=input("Enter a number:")
if num1=="done":
break
try:
num=int(num1)
except:
print("Please enter numeric value")
continue
if largest is None:
largest=num
elif num>largest:
largest=num
if smallest is None:
smallest=num
elif num<smallest:
smallest=num
print("ALL DONE")
print("largest is :",largest,"\n smallest is:",smallest)
| true |
a6d8a0779cfc7092ef6f8651f0b8bc9ab9da774c | joelmedeiros/studies.py | /Fase7/Challange6.py | 265 | 4.28125 | 4 | number = int(input("Tell me the number you want to know the double, triple and square root: "))
double = number*2
triple = number*3
sqrt = number**(0.5)
print("The double of {} is {} and the triple is {} and the sqrt is {:.2f}".format(number, double, triple, sqrt)) | true |
8907a33161a9922cca2925059520c857ee7c4451 | Jay-mo/Hackerrank | /company_logo.py | 1,604 | 4.53125 | 5 | """
A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name.
They are now trying out various combinations of company names and logos based on this condition. Given a string S, which is the company name in lowercase letters,
your task is to find the top three most common characters in the string.
Print the three most common characters along with their occurrence count.
Sort in descending order of occurrence count.
If the occurrence count is the same, sort the characters in alphabetical order.
For example, according to the conditions described above,
Sample Input
aabbbccde
b 3
a 2
c 2
"""
from operator import itemgetter
from collections import Counter, OrderedDict
if __name__ == "__main__":
company_name = input()
#use counter to get dictionary of the all the elements in the strings and their count as values
name_dict = Counter(list(company_name))
#because sorted keeps the original order of sorted items when the sorted keys are the same, I have to sort the keys firsts in ascending order.
s = sorted(name_dict.items(), key=itemgetter(0))
#using sorted and passing itemgetter to get sort based on the values. Reverse flag set to sort in descending order
sorted_name_tuple = sorted(s, key=itemgetter(1), reverse=True)
#use ordered dict so that the order is maintained.
sorted_name_dict = OrderedDict({ k:v for k, v in sorted_name_tuple})
#print only the first 3 items
for i in list(sorted_name_dict.keys())[:3]:
print( i , sorted_name_dict[i])
| true |
a163cf56718a5fe33b00f120073ba193292a5933 | VickeeX/LeetCodePy | /desighClass/ShuffleArray.py | 1,198 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
File name : ShuffleArray
Date : 18/05/2019
Description : 384. Shuffle an Array
Author : VickeeX
"""
import random
class Solution:
def __init__(self, nums: list):
# # trick
# self.reset = lambda: nums
# self.shuffle = lambda: random.sample(nums, len(nums))
self.nums = nums
def reset(self) -> list:
"""
Resets the array to its original configuration and return it.
"""
return self.nums
def shuffle(self) -> list:
"""
Returns a random shuffling of the array.
"""
# # random comparision: reduce the swap times for element
# return sorted(self.nums, key=(lambda x: random.random()))
count, l = 0, len(self.nums) - 1
tmp = [i for i in self.nums]
while count < l:
choice = random.randint(count, l)
tmp[count], tmp[choice] = tmp[choice], tmp[count]
count += 1
return tmp
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
| true |
cea604980474aeb6996ab3b925b4c1fe8dc17cd2 | Qurbanova/PragmatechFoundationProjects | /Algorithms/week09_day04.py | 2,679 | 4.5625 | 5 | # 1)Write a Python function to sum all the numbers in a list. Sample List : (8, 2, 3, 0, 7) Expected Output : 20
# 2)Write a Python function to multiply all the numbers in a list. Sample List : (8, 2, 3, -1, 7) Expected Output : -336
# 3)Write a function called returnDay. This function takes in one parameter ( a number from 1-7) and returns the day of the week ( 1 is Sunday, 2 is Monday etc.). If the number is less than 1 or greater than 7, the function should return None. Expected Output: returnDay(1) --> Sunday
# 4)-Write a function called lastElement. This function takes one parameter (a list) and returns the last value in the list. It should return None if the list is empty. Example Output lastElement([1,2,3]) # 3 lastElement([]) # None
# 5)Write a Python program to print the even numbers from a given list. Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9] Expected Result : [2, 4, 6, 8]
#GOOD LUCK FOR ME !
#FUNCTIONS
# def my_function():
# print('hello from a function!')
# my_function()
''' def lst():
lst=[]
mylist=[8, 2, 3, 0, 7]
num=0
num+=1
if num in mylist:
lst.append(mylist)
print("Sum of elements in given list is :", sum(lst)) '''
''' mylist=[8, 2, 3, 0, 7]
Sum=sum(mylist)
print(Sum) '''
''' def hasil(my_list):
netice=1
for i in my_list:
netice=netice*i
return(netice)
hasil([8, 2, 3, -1, 7]) '''
''' def hefteninGunleri(eded):
hefteninGunleri={
1:'Sunday',
2:'Monday',
3:'Tuesday',
4:'Wensday',
5:'Thursday',
6:'Friday',
7:'Saturday'
}
if 1<=eded<=7:
return(hefteninGunleri[eded])
else:
return None
eded=int(input("Bir gun qeyd edin 1-7 arasi: "))
x=hefteninGunleri(eded)
if x[0]=='F':
print('cume gunu') '''
# def last_element(my_list):
# if my_list:
# return my_list[-1]
# return None
# print(last_element([1,2]))
even_list=[]
def even_element(my_list):
for i in my_list:
if i%2==0:
even_list.append(i)
even_element([1,2,3,4,5,6,7,8])
even_element([10,5,6,367,6])
print(even_list)
''' def topla(my_list):
cem=0
for i in my_list:
cem+=i
return cem
print(topla([8,2,3,0,7]))
'''
#lst = []
#num = int(input('How many numbers: '))
#for n in range(num):
# numbers = int(input('Enter number '))
# lst.append(numbers)
#print("Sum of elements in given list is :", sum(lst))
''' def my_function(fname, fsurname):
print(fname + " " +fsurname +" Refsnes")
my_function("Emil","Quliyev")
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus") ''' | true |
7dc89b6e60710ae6437519899cb6e3520e6cf53f | nandhinipandurangan11/CIS40_Chapter4_Assignment | /CIS40_Nandhini_Pandurangan_P4_9.py | 664 | 4.15625 | 4 | # CIS40: Summer 2020: Chapter 4 Assignment: Problem 9 : Nandhini Pandurangan
# This program reads a string and prints the string in reverse.
# print_reverse() reads user input and prints it in reverse
def print_reverse():
string = input("Please enter a word: ").strip()
for i in range(len(string) - 1, -1, -1): # iterate in reverse
print(string[i], end="") # print string in reverse
print_reverse()
'''
Output:
Please enter a word: harry
yrrah
----------------------------
Please enter a word: She sells seashells by the seashore
erohsaes eht yb sllehsaes slles ehS
-----------------------------
Please enter a word: 123456789
987654321
''' | true |
a9be48c1b64fc1dfdf33f58b9d6c35f8b9caae1a | sich97/WakeyWakey | /server/server_setup.py | 2,149 | 4.375 | 4 | """
File: server_setup.py
This file creates / or resets the server database.
"""
import sqlite3
import os
DATABASE_PATH = "server/db"
def main():
"""
In the case that a database already exists, ask the user if it's really okay to reset it. If no, then do nothing
and exit. If yes, delete the existing database and create a new one.
:return: None
"""
reset = False
# A database already exists
if os.path.isfile(DATABASE_PATH):
# Ask the user what to do
print("Database already exists. Do you want it reset? [NO]: ", end="")
reset = input()
# User answered yes
if reset == "YES" or reset == "Yes" or reset == "yes":
# Delete the database
os.remove(DATABASE_PATH)
# Create a new one
create_database()
# A database does not exist
else:
create_database()
def create_database():
"""
Creates a database and fills it with initial information.
:return: None
"""
# Establish database connection
db = sqlite3.connect(DATABASE_PATH)
cursor = db.cursor()
# Create the server settings table
sql_query = """CREATE TABLE server_settings(id INTEGER PRIMARY KEY, address TEXT, port INTEGER,
alarm_state INTEGER)"""
cursor.execute(sql_query)
# Fill the table with data
sql_query = """INSERT INTO server_settings(address, port, alarm_state) VALUES(?, ?, ?)"""
data = "", 49500, 0
cursor.execute(sql_query, data)
# Create the user preferences table
sql_query = """CREATE TABLE user_preferences(id INTEGER PRIMARY KEY, wakeup_time_hour INTEGER,
wakeup_time_minute INTEGER, utc_offset INTEGER, wakeup_window INTEGER, active_state INTEGER)"""
cursor.execute(sql_query)
# Fill the table with data
sql_query = """INSERT INTO user_preferences(wakeup_time_hour, wakeup_time_minute, utc_offset, wakeup_window,
active_state)
VALUES(?, ?, ?, ?, ?)"""
data = 16, 00, 2, 2, 0
cursor.execute(sql_query, data)
# Save changes to database
db.commit()
# Close database
db.close()
if __name__ == '__main__':
main()
| true |
8a2e5a2ed33489e1db0dc410db6cc3aa8e083f44 | sweekar52/APS-2020 | /Daily-Codes/Median of an unsorted array using Quick Select Algorithm.py | 2,067 | 4.15625 | 4 | # Python3 program to find median of
# an array
import random
a, b = None, None;
# Returns the correct position of
# pivot element
def Partition(arr, l, r) :
lst = arr[r]; i = l; j = l;
while (j < r) :
if (arr[j] < lst) :
arr[i], arr[j] = arr[j],arr[i];
i += 1;
j += 1;
arr[i], arr[r] = arr[r],arr[i];
return i;
# Picks a random pivot element between
# l and r and partitions arr[l..r]
# around the randomly picked element
# using partition()
def randomPartition(arr, l, r) :
n = r - l + 1;
pivot = random.randrange(1, 100) % n;
arr[l + pivot], arr[r] = arr[r], arr[l + pivot];
return Partition(arr, l, r);
# Utility function to find median
def MedianUtil(arr, l, r,
k, a1, b1) :
global a, b;
# if l < r
if (l <= r) :
# Find the partition index
partitionIndex = randomPartition(arr, l, r);
# If partion index = k, then
# we found the median of odd
# number element in arr[]
if (partitionIndex == k) :
b = arr[partitionIndex];
if (a1 != -1) :
return;
# If index = k - 1, then we get
# a & b as middle element of
# arr[]
elif (partitionIndex == k - 1) :
a = arr[partitionIndex];
if (b1 != -1) :
return;
# If partitionIndex >= k then
# find the index in first half
# of the arr[]
if (partitionIndex >= k) :
return MedianUtil(arr, l, partitionIndex - 1, k, a, b);
# If partitionIndex <= k then
# find the index in second half
# of the arr[]
else :
return MedianUtil(arr, partitionIndex + 1, r, k, a, b);
return;
# Function to find Median
def findMedian(arr, n) :
global a;
global b;
a = -1;
b = -1;
# If n is odd
if (n % 2 == 1) :
MedianUtil(arr, 0, n - 1, n // 2, a, b);
ans = b;
# If n is even
else :
MedianUtil(arr, 0, n - 1, n // 2, a, b);
ans = (a + b) // 2;
# Print the Median of arr[]
print("Median = " ,ans);
# Driver code
arr = [ 12, 3, 5, 7, 4, 19, 26 ];
n = len(arr);
findMedian(arr, n);
# This code is contributed by AnkitRai01
| true |
fa9b017ec497e894b7222af17575ad0abe015f52 | sajaram/Projects | /text_adventure_starter.py | 1,609 | 4.375 | 4 | start = '''
You wake up one morning and find that you aren’t in your bed; you aren’t even in your room.
You’re in the middle of a giant maze.
A sign is hanging from the ivy: “You have one hour. Don’t touch the walls.”
There is a hallway to your right and to your left.
'''
print(start)
print("Type 'left' to go left or 'right' to go right.")
user_input = input()
if user_input == "left":
print("You decide to go left and you see that there are two doors: one door is red and one door is green. What door do you choose?")
print("Type 'green' to go through the green door or 'red' to go through the red door")
user_input = input()
if user_input == "green":
print ("Congrats, you are safe!")
elif user_input == "red":
print("Sorry, you fell through the Earth and died!")
#while user_input != "red" or "green":
#user_input == input("Enter red or green ")
elif user_input == "right":
print("You choose to go right and you come across a shoreline. You can decide whether you want to swim or take the boat that is next to the shoreline. What do you choose?") # finished the story writing what happens
print ("Type 'swim' to swim across or type 'boat' to take the boat across.")
user_input = input()
if user_input == "swim":
print("Wow, you are an amazing swimmer, and you survived!")
elif user_input == "boat":
print("I'm sorry, the boat had a hole and you drowned!")
#while user_input != "swim" or "boat":
#user_input == input("Enter swim or boat ")
#while user_input != "right" or "left":
#user_input == input("Enter right or left ") #these aren't supposed to work
| true |
bb7219177527b96c77d15869c247ad16615a0693 | sagdog98/PythonMiniProjects | /Lab_1.py | 2,248 | 4.34375 | 4 | # A list of numbers that will be used for testing our programs
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# Question 1: Create a function called even, which takes in an integer as input and returns true if the input is even, and false otherwise
def even(num):
# Provide your code here
return True if num % 2 == 0 else False
print("even(1):\t\t\t\t", even(1)) # should return False
print( "even(2):\t\t\t\t", even(2)) # shourd return True
print()
# Question 2: Create a function called odd, which takes in an integer as input and returns true if the input is odd, and false otherwise
def odd(num):
# Provide your code here
return False if num % 2 == 0 else True
print("odd(1):\t\t\t\t\t", odd(1)) # should return True
print("odd(2):\t\t\t\t\t", odd(2)) # shourd return False
print()
# Question 3: Given a list of integers, create a function called count_odd, which takes in a list and counts the number of odd. Your function should employ a divide and conquer approach. Select an appropriate base case and implement a recursive step.
def count_odd(list):
# Provide your code here
return 0 if len(list) == 0 else (list[0] % 2 + count_odd(list[1:]))
print("count_odd([1, 2, 3, 4, 5, 6, 7, 8]):\t", count_odd(numbers)) # should return 4
print()
# Question 4: Given a list of integers, use a divide and conquer approach to create a function named reverse, which takes in a list and returns the list in reverse order.
def reverse(list):
# Provide your code here
if len(list) == 0:
return []
else:
return reverse(list[1:]) + list[:1] if list else []
print("reverse([1, 2, 3, 4, 5, 6, 7, 8]):\t", reverse(numbers)) # should return [8, 7, 6, 5, 4, 3, 2, 1]
print()
# Question 5: Given two sorted lists, it is possible to merge them into one sorted lists in an efficient way. Design and implement a divide and conquer algorithm to merge two sorted lists.
def merge(list1, list2):
# Provide your code here
if list1 and list2:
if list1[0] > list2[0]:
list1, list2 = list2, list1
return [list1[0]] + merge(list1[1:], list2)
return list1 + list2
print("merge([1, 3, 5, 7], [2, 4, 6, 8]):\t", merge([1, 3, 5, 7], [2, 4, 6, 8])) # should return [1, 2, 3, 4, 5, 6, 7, 8]
| true |
61fe504a5f0ef1f70db4799e6901f84b8e9f3333 | roince/Python_Crash_Course | /Mosh_Python/guessing_game.py | 1,073 | 4.125 | 4 | chance = 3
# get a myth number, and check : whether it is a number and whether it is in
# range (0-9)
myth = input("your myth number: ")
if myth.isdigit():
myth = int(myth)
if myth > 9 or myth < 0:
print("please enter a number in range (0-9)")
quit()
else:
print("only numbers are allowed!")
quit()
# guess game implemented below
print(f'This is a guessing game, and you have {chance} chances to guess the '
f'mythical number (0-9)')
guess = 11
while chance > 0:
guess = input("Guess: ")
# checking the input whether is a number and whether in range
if guess.isdigit():
guess = int(guess)
if guess > 9 or guess < 0:
print("please enter a number in range (0-9)")
elif int(guess) == int(myth):
print(f"You guess right! Good one! Only takes you {4-chance} "
f"times to guess")
break
else:
print("Wrong guess! Try again!")
else:
print("only numbers are allowed!")
chance -= 1
else:
print("Sorry, you loose :(")
| true |
434e727b3400f54428c65c146ec4e44eab74bc6c | Lewis-blip/python | /volume.py | 233 | 4.125 | 4 | pie = 3.14
radius = int(input("input radius: "))
height = float(input("input height: "))
rradius = radius**2
volume = pie * rradius * height
final_volume = volume//1
print("the volume of the cyclinder is ", final_volume, "m^3") | true |
2e3a8be86da4c724d636afc20f3dbf784c23b6c5 | Snafflebix/learning_python | /ex9.py | 507 | 4.125 | 4 | # Here's some new strange stuff, remember type it exactly
days = "Mon Tue Wed Thu Fri Sat Sun"
#this makes each thing after \n on a new line
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
#this puts days after the string with a space
print "Here are the days: ", days
print "Here are the months: ", months
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
#but you can't do that with comments!
| true |
f023205fbfb15d2d12ee1460cb13ab31a27e504b | shalemppl/PythunTuts | /Tuples.py | 2,143 | 4.59375 | 5 | # Tuples are similar to lists, but once a tuple is created it cannot be changed
#List (created with [])
mylist = [1, 2, 3]
print(mylist)
mylist[2] = 4
print(mylist)
#Tuple (created with ())
mytuple = (1, 2, 3)
print(mytuple)
#mytuple[2]=4 would result in a traceback, as an item within a tuple cannot be changed
#So why use a tuple instead of a list?
# 1. Tuples are more memory efficient and are faster to access
# 2. CANNOT sort, append or reverse a tuple (as you can with a list)
# 3. CAN count and index a tuple
# 4. Tuples are normally used as temporary variables in limited scopes
#Comparing and Sorting tuples
d = {'a':10, 'b':1, 'c':22} #create a dictionary
d.items()
print(sorted(d.items())) #sort the disctionary (will sort by the first item in the dict first, so a,b,c)
for (k, v) in sorted(d.items()): print(k,v) #create and print a sorted tuple based on the dict
#Sort by the values instead:
tmp = list()
for k,v in d.items(): tmp.append((v,k)) #flip the values, put v first -- notice the double ()
print(tmp)
tmp = sorted(tmp)
print(tmp)
tmp = sorted(tmp,reverse=True) #reverse the order of the items
print(tmp)
#Print the 10 most common words in a file:
fhand = open('intro.txt')
counts = {} #create a dictionary
for line in fhand:
words = line.split() #split each line in the file into a dictionary of words
for word in words:
counts[word] = counts.get(word,0)+1 #for each word, add it to the dict and count it
lst=[] #create a new list
for key,val in counts.items(): #create a tuple containing each pair in the dict we created
newtup=(val,key) #when creating the tuple, reverse the key/val into val/key so that we can sort by val
lst.append(newtup) #place the tuple pairs into the list, so we can sort them
lst=sorted(lst,reverse=True) #sort the list, based on val, in reverse (descending) order
for val,key in lst[:10]: #print just the first 10 (most commont) words
print(key,val)
print('\n')
#A shorter version of the above:
print(sorted([(val,key) for key,val in counts.items()],reverse=True)) #but prints the entire item list, not just the top 10
#the [] creates a "list comprehension"
| true |
4a3c26ab8368289cdb8e20912c26def8660bdd52 | AFishyOcean/py_unit_five | /fibonacci.py | 482 | 4.34375 | 4 | def fibonacci(x):
"""
Ex. fibonacci(5) returns "1 1 2 3 5 "
:param number: The number of Fibonacci terms to return
:return: A string consisting of a number of terms of the Fibonacci sequence.
"""
fib = ""
c = 0
a = 0
b = 1
for x in range(x):
c = a + b
a = b
b = c
fib +=str(c)+ " "
return fib
def main():
x = int(input("How many terms would you like?"))
fibonacci(x)
print(fibonacci(x))
main() | true |
31bb7ccdea6104bfacbd18e099f0935b3bc2d0e7 | eecs110/spring2020 | /course-files/lectures/lecture_04/in_class_exercises/08_activity.py | 869 | 4.15625 | 4 | # Write a function that prints a message for any name
# with enough stars to exactly match the length of the message.
# Hint: Use the len() function.
def print_message(first_name:str, symbol:str='*'):
message = 'Hello ' + first_name + '!'
print(symbol * len(message))
print(message)
print(symbol * len(message))
print()
def print_message_alt(first_name:str):
symbol = input('Enter your favorite symbol (one character only please): ')
if symbol == '':
symbol = '*'
message = 'Hello ' + first_name + '!'
print(symbol * len(message))
print(message)
print(symbol * len(message))
print()
# invoking it...
# my_symbol = input('Enter your favorite symbol (one character only please): ')
print_message('Sarah', symbol='%')
print_message('Caroline', symbol='$')
print_message('Peter', '^')
print_message('Matthew')
| true |
d740731f12f6aff6f7175086263f0c9308b43b4a | eecs110/spring2020 | /course-files/lectures/lecture_03/challenge_problem_2.py | 1,900 | 4.34375 | 4 | from tkinter import Canvas, Tk
#####################################
# begin make_grid function definition
#####################################
def make_grid(canvas, w, h):
interval = 100
# Delete old grid if it exists:
canvas.delete('grid_line')
# Creates all vertical lines at intevals of 100
for i in range(0, w, interval):
canvas.create_line(i, 0, i, h, tag='grid_line')
# Creates all horizontal lines at intevals of 100
for i in range(0, h, interval):
canvas.create_line(0, i, w, i, tag='grid_line')
# Creates axis labels
offset = 2
for y in range(0, h, interval):
for x in range(0, w, interval):
canvas.create_oval(
x - offset,
y - offset,
x + offset,
y + offset,
fill='black'
)
canvas.create_text(
x + offset,
y + offset,
text="({0}, {1})".format(x, y),
anchor="nw",
font=("Purisa", 8)
)
###################################
# end make_grid function definition
###################################
'''
1. Write a program that prompts the user for a color, which can be any string representation of a color
2. Then, draw a rectangle (of any dimensions) with that color
'''
user_color = input('Hey, what color do you want this circle to be? ')
center_x = int(input('Hey, what\'s the center x coord? '))
center_y = int(input('Hey, what\'s the center y coord? '))
radius = 100
# initialize window
window = Tk()
canvas = Canvas(window, width=700, height=550, background='white')
canvas.pack()
canvas.create_oval(
[(center_x - radius, center_y - radius), (center_x + radius, center_y + radius)], # coords: top-left, bottom-right
fill=user_color)
make_grid(canvas, 700, 550)
canvas.mainloop()
| true |
3d2de0860b3c106661671232cffcef522c187993 | liturreg/blackjack_pythonProject | /deck.py | 2,389 | 4.125 | 4 | import random
card_names = {
1: "Ace",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine",
10: "Ten",
11: "Jack",
12: "Queen",
13: "King"
}
card_suits = {
0: "Hearts",
1: "Diamonds",
2: "Clubs",
3: "Spades"
}
def generate_deck_dict():
"""Function to generate a full deck of cards in form of a dictionary. Currently not used"""
list = []
# This list first to create the dictionary
for num in range(0,4):
for i in range(1, 14):
suit = num
number = i
value = 0
if i == 1:
# This used to be a tuple before
value = (1)
elif i > 10:
value = 10
else:
value = i
list.append((suit, number, value))
dict = {}
for card in list:
# Use another function to generate all the keys
# dict[cardname_from_tuple(list, card)] = card
suit = card_suits.get(card[0])
number = card_names.get(card[1])
dict[f"{number} of {suit}"] = card
return dict
def generate_deck_list():
"""Function to generate a whole deck of cards as list"""
list = []
for num in range(0,4):
for i in range(1, 14):
suit = num
number = i
value = 0
if i == 1:
# I'm assigning only 1 for now, it will become 11 later
value = (1)
elif i > 10:
value = 10
else:
value = i
list.append((suit, number, value))
return list
def cardname_from_index(list, index):
"""Funcion to print a card name when list name and index are known.
Asks for list name and list index."""
suit = card_suits.get((list[index])[0])
number = card_names.get((list[index])[1])
return f"{number} of {suit}"
def cardname_from_tuple(list, name):
"""Function to print a card name when only the values are known.
Asks for list name and card object name."""
result = cardname_from_index(list, list.index(name))
return result
def print_deck(deck_name):
"""Function to print a whole deck card by card. Mostly used during development."""
for i in range(len(deck_name)):
print(cardname_from_index(deck_name, i)) | true |
eee192feba564a8682d06b98c26abc33c0c31a38 | alisiddiqui1912/rockPaperScissors | /Rock Pap S/finalVersion.py | 1,229 | 4.34375 | 4 | import random
player_win = 0
computer_win = 0
win_score = input("Enter the Winning Score: ")
win_score = int(win_score)
while win_score > player_win and win_score > computer_win:
print(f"Your Score:{player_win},Computer Score:{computer_win}")
player = input("Make your move: ").lower()
rand_num = random.randint(0,2)
if rand_num == 0:
computer = "rock"
elif rand_num == 1:
computer = "paper"
else:
computer = "scissors"
print("Computer move is: " + computer)
if player == computer:
print("It's a tie.")
elif player == "rock":
if computer == "scissors":
print("You win!!")
player_win += 1
else:
print("computer wins!!")
computer_win += 1
elif player == "paper":
if computer == "rock":
print("You win!!")
player_win += 1
else:
print("computer wins!!")
computer_win += 1
elif player == "scissors":
if computer == "rock":
print("computer wins!!")
computer_win += 1
else:
print("You win!!")
player_win += 1
else:
print("Plese enter valid move.")
print(f"Final Score:-Your Score:{player_win},Computer Score:{computer_win}")
if player_win > computer_win:
print("You Win!!")
else:
print("Computer Wins") | true |
a3f70a3c9d8b47aa53eaa3ca9c4337b9b7bb4d2e | vukasm/Problem-set-2019-Programming-and-Scripting- | /question-vii.py | 619 | 4.46875 | 4 | #Margarita Vukas, 2019-03-09
#Program that takes a positive floating number as input and outputs an approximation of its square root.
#This will import math module.
import math
#Asking user to enter a positive floating number which will be tha value of f.
f=float(input("Please enter a positive number:"))
#Using math.sqrt module to calculate the square root of the number.
sqrtf=math.sqrt(f)
#Using round() method rounding the square root to only two decimals which is approximation of the full number.
sqrtf=round(sqrtf,2)
#Printing the result on the screen.
print ("The square root of", f, "is approx.", sqrtf) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.