blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ed5388f3c390d596cd6a2927960cf28e0065d8d2 | ceeblet/OST_PythonCertificationTrack | /Python1/python1Homework/caserFirst.py | 1,284 | 4.34375 | 4 | #!/usr/local/bin/python3
""" caser.py """
import sys
def capitalize(mystr):
""" capitalize(str) - takes a string
and returns the string with first letters
capitalized.
"""
print(mystr.capitalize())
def title(mystr):
""" title(str) - takes a string and
returns the string in title form.
"""
print(mystr.title())
def upper(mystr):
""" upper(str) - takes a string and
makes it all caps.
"""
print(mystr.upper())
def lower(mystr):
""" lower(str) - takes a string and
makes it all lowercase.
"""
print(mystr.lower())
def exit(mystr):
""" exit() - ends the program."""
sys.exit()
if __name__ == "__main__":
switch = {
'capitalize': capitalize,
'title': title,
'upper': upper,
'lower': lower,
'exit': exit
}
options = switch.keys()
while True:
prompt1 = 'Enter a function name ({0}) '.format(', '.join(options))
prompt2 = 'Enter a string: '
inp1 = input(prompt1)
inp2 = input(prompt2)
option = switch.get(inp1, None)
inpstr = inp2
if option:
option(inpstr)
print("-" * 30)
else:
print("Please enter a valid option!")
| true |
4c490de53e3bed60e94a60e4229cffb4181d7ed8 | dotnest/pynotes | /Exercises/swapping_elements.py | 284 | 4.21875 | 4 | # Swapping list elements
def swap_elements(in_list):
""" Return the list after swapping the biggest integer in the list
with the one at the last position.
>>> swap_elements([3, 4, 2, 2, 43, 7])
>>> [3, 4, 2, 2, 7, 43]
"""
# your code here
| true |
d859287b31a1883963543dea6c9f335ade0c0755 | Jokekiller/Theory-Programmes | /Program converting ASCII to text and other way.py | 956 | 4.125 | 4 | #Harry Robinson
#30-09-2014
#Program converting ASCII to text and other way
print("Do you want to convert an ASCII code ? (y/n)")
response = input()
if response == "y":
ASCIINumber = int(input("Give an ASCII number"))
ASCIINumberConverted = chr(ASCIINumber)
print("The ASCII number is {0} in text characters.".format(ASCIINumberConverted))
if response == "n":
print("Do you want to convert a text character? (y/n)")
response2 = input()
if response2 == "y":
<<<<<<< HEAD
textNumber = input("Give text character: ")
textNumberConverted = ord(textNumber)
print("The ASCII code is {0}".format(textNumberConverted))
=======
textNumber = int(input("Give text character"))
textNumberConverted = ord(textNumber)
print("Text character is {1}".format(textNumberConverted))
>>>>>>> branch 'master' of https://github.com/Jokekiller/Theory-Programmes.git
| true |
0f4085b0b240aab78424953c0a66eeb09e6b019e | krouvy/Useless-Python-Programms.- | /18 - Checking the list for parity/pop_break.py | 707 | 4.21875 | 4 | """
This program checks the list
items for odd parity. If all
elements are even, then the list
will be empty. Because the "pop ()"
method cuts out the last item from the list.
"""
List = list(map(int, input("Enter your digit values ").split())) # Entering list items separated by a space
while len(List) > 0: # Execute as long as the length of the list is greater than zero
last = List.pop() # Cuts last element of List, and record in variable "last"
if last % 2 != 0: # if variable "last" is not even
print("Number", last, "is not even") # print this value
break # Exit the loop
else:
print("All numbers are even") # else print message
print(List) # and empty list
| true |
4e93aec8e1cf56a3fc4610ac438fb50d77a856b8 | yding57/CSCI-UA-002 | /Lecture 3.py | 2,238 | 4.15625 | 4 | #Data types
# "=" is an assignment operator
# x=7+"1.0" this is ERROR
answer = input("Enter a value: ")
print(answer,type(answer))
n1 = input("Number 1: ")
n2 = input('Number 2: ')
#convert this into an integer
n1_int = int(n1)
n2_int = int(n2)
print(n1_int + n2_int)
#different from:
print(n1 + n2)
#简便convert的方法:nesting
x = int(input('Enter a number: ')) #注:there are two parentheses
#Programming Challenge
#ask the user for their name
name = input("Name: ")
#ask the user for 3 test scores
score1 = float(input ("Enter score 1: "))
#the user input mismatch the converting data type can crash the program
score2 = float(input ("Enter score 2: "))
score3 = float(input ("Enter score 3: "))
#compute sum of scores
total = score1 + score2 + score3
#compute average
average = total/3
#generate output
print("Your score in class is",average)
#Programming challenge -coin
#ask the user for the number of coins they have
#pennies
#nickels
#dimes
#quarters
pennies = int(input("Pennies: "))
nickels = int(input("Nickels: "))
dimes = int(input("Dimes: "))
quarters = int(input("Quarters: "))
#somehow convert these coins into currency
money = pennies*0.01 + nickels *0.05 + dimes*0.1 + quarters *0.25
#generate output
print('You have',money,'in your pocket!')
Weired Issue:
Pennies: 3
Nickels: 2
Dimes: 2
Quarters: 1
You have 0.5800000000000001 in your pocket
This is due to the "floating point inaccuracy"
#Errors:
#Syntax errors: didn't use your laguage right
#Runtime errors: laguage is fine, but the program crashed (usually, problem with user input)
#Logic errors: sytax-correct, runs perfectly but the result is not expected
#Metro Card program
card = float(input("How much is left on your card: "))
#compute the left rides
rides_left =int(card//2.75) # // or int()
print(rides_left)
#Time Calculations
seconds = int(input('Enter second: '))
#compute minutes
minutes = seconds // 60
reminder_seconds = seconds % 60
hours = minutes//60
reminder_minutes = minutes % 60
print("That is",hours,"hours",reminder_minutes,"minutes",reminder_seconds,"seconds")
#Format functions
format(52752.3242,".2f")#generates string
money = 100.70
money_format= format(100.70,".2f") #perserve your insignificant 0s
| true |
607b6d533f1ac9a6ca74f04edcb43f50ad164b4d | AMRobert/Word_Counter | /WordCounter_2ndMethod.py | 268 | 4.1875 | 4 | #WORD COUNTER USING PYTHON
#Read the text file
file = open(r"file path")
Words = []
for i in file:
Words.extend(i.split(" "))
print(Words)
#Count the Number of Words
Word_Count=0
for x in range(len(Words)):
Word_Count = Word_Count + 1
print(Word_Count)
| true |
b4ad1c25c8d0ecee08a1a48787fb7c116bcba965 | igotboredand/python-examples | /loops/basic_for_loop.py | 514 | 4.59375 | 5 | #!/usr/bin/python3
#
# Python program to demonstrate for loops.
#
# The for loop goes through a list, like foreach in
# some other languages. A useful construct.
for x in ['Steve', 'Alice', 'Joe', 'Sue' ]:
print(x, 'is awesome.')
# Powers of 2 (for no obvious reason)
power = 1
for y in range(0,25):
print("2 to the", y, "is", power)
power = 2 * power
# Scanning a list.
fred = ['And', 'now', 'for', 'something', 'completely', 'different.'];
for i in range(0,len(fred)):
print(i, fred[i]) | true |
00587653e7706bed6683f00538a9e22f00590cdc | FengdiLi/ComputationalLinguistic | /update automation/menu_update.py | 2,857 | 4.15625 | 4 | #!/usr/bin/env python
import argparse
import re
def main(old_menu, new_menu, category_key, update_key):
"""This main function will read and create two dictionaries
representing the category keys and update keys, then check and
update the price according to its multiplier if the item is
associated with a category stated in category keys"""
new_menu_lines = []
# add code to read the old menu and look for items with price updates
#########################################################################
# define a function to check and update the price in a line
def update(line, keys, cats):
for key in keys:
# search item
if re.search(f'(^|\W){key}($|\W)', line):
# retrieve price
m = re.match('.*\$(\d+(?:\.\d+)?).*', line)
if m:
# update and format price
price = f'{float(m.group(1))*cats[keys[key]]:.2f}'
result = re.sub('\$\d+(\.\d+)?', f'${price}', line)
return result
return line
# initiate category keys
d = {}
with open(category_key, 'r') as cat:
for line in cat:
line = line.strip().split('\t')
d[line[0]] = line[1]
# initiate category updates
d2 = {}
with open(update_key, 'r') as cat:
for line in cat:
line = line.strip().split('\t')
d2[line[0]] = float(line[1])
# update menu line by line
with open(old_menu, 'r') as orig_menu:
for line in orig_menu:
new_line = update(line, d, d2)
new_menu_lines.append(new_line)
# write a new file with your updates
# 'newline' set each ending as LF match the format of example
with open(new_menu, 'w', newline = '\n') as new_menu_out:
for line in new_menu_lines:
new_menu_out.write(line)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Update a menu')
parser.add_argument('--path', type=str, default="practice_menu.txt",
help='path to the menu to update')
parser.add_argument('--output_path', type=str, default="practice_menu_new.txt",
help='path to write the updated menu')
parser.add_argument('--category_key', type=str, default="item_categories.txt",
help='path to the key to item categories')
parser.add_argument('--update_key', type=str, default="category_update.txt",
help='path to the key to item categories')
args = parser.parse_args()
old_menu = args.path
new_menu = args.output_path
category_key = args.category_key
update_key = args.update_key
main(old_menu, new_menu, category_key, update_key)
| true |
6172e61f25108eec6aee06c155264e74441ee10c | bacizone/python | /ch5-bubble-report.py | 2,046 | 4.3125 | 4 | #Pseudocode for Ch5 2040 excercise
#First we have a list with solutions and their scores. We are writing a loop where it iterates until all solution -score pair are output to the screen.
#Second: using the len function we display the total number of bubble tests, that is the number of elements in the list.
#Then we need a kind of ordering algorithm, that compares the score values and select the highest. Possible solution: 1. sort the list by increasing values and select its last item (the highest) 2. always compare two values, select the highest and compare it to the next value, until there is no higher value left.
# Display the list indices assigned to the highest values - how?
scores = [60, 50, 60, 58, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18, 41, 53, 55, 61, 51, 44]
costs = [.25, .27, .25, .25, .25, .33, .31, .25, .29, .27, .22, .31, .25, .25, .33, .21, .25, .25, .25, .28, .25, .24, .22, .20, .25, .30, .25, .24, .25, .25, .25, .27, .25, .26, .29]
# i = 0
length = len(scores)
high_score = 0
# this was a less efficient method
# while i < length:
# bubble_string = 'Bubble solution #'+ str(i)
# print(bubble_string, 'score:', scores[i])
# i = i + 1
for i in range(length):
bubble_string = 'Bubble solution #'+ str(i)
print(bubble_string, 'score:', scores[i])
if scores[i] > high_score:
high_score = scores[i]
print('Bubble test:', length)
print('Highest bubble score:', high_score)
# best_solutions = []
# if scores[i] == high_score:
# for j in range(high_score):
# best_solutions.append(high_score)
best_solutions = []
for i in range(length):
if high_score == scores[i]:
best_solutions.append(i)
print('Solutions with highest score:', best_solutions)
cost = 100.0
most_effective = 0
for i in range(length):
if scores[i] == high_score and costs[i] < cost:
most_effective = i
cost = costs[i]
print('Solution', most_effective, 'is the most effective with a cost of', costs[most_effective])
| true |
b3f3acc08c5777696db004a6ccabcb09c1dd3c36 | kirankumarcs02/daily-coding | /problems/exe_1.py | 581 | 4.125 | 4 | '''
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
'''
def checkSumPair(input, k):
givenNumbers = set()
for number in input:
if (k - number) in givenNumbers:
return True
else:
givenNumbers.add(number)
return False
if __name__ == "__main__":
input = [10, 15, 3, 7]
k = 17
print(checkSumPair(input, k))
| true |
bc4126d785715c1aebf52f99fbafea90fc21f6fe | kirankumarcs02/daily-coding | /problems/exe_40.py | 704 | 4.1875 | 4 | # This problem was asked by Google.
#
# Given an array of integers where every integer occurs three
# times except for one integer, which only occurs once,
# find and return the non-duplicated integer.
#
# For example, given [6, 1, 3, 3, 3, 6, 6],
# return 1. Given [13, 19, 13, 13], return 19.
def get_non_duplicate(arr):
non_duplicate = 0
number_count = dict()
for i in arr:
if i in number_count:
number_count[i] +=1
else:
number_count[i] = 1
for key in number_count.keys():
if number_count[key] == 1:
non_duplicate = key
return non_duplicate
if __name__ == "__main__":
print(get_non_duplicate([13, 19, 13, 13])) | true |
63c881db45cfac236675707f637c29c74f86d257 | bhanuxhrma/learn-python-the-hard-way | /ex16.py | 882 | 4.1875 | 4 | from sys import argv
script, filename = argv
#some important file operations
#open - open the file
#close - close the file like file -> save ...
#readline - read just one line of the text
#truncate - Empties the file watch out if you care about file
#write('stuff') - write "stuff" to the file
print("we are going to erase %r"%filename)
print("If you do not want that hit ctrl-C(^C)")
print("If you want to continue hit return")
input("?")
print("opening the file.....")
target = open(filename, 'w')
print("truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines")
line1 = input('line1: ')
line2 = input('linw2: ')
line3 = input('line3: ')
print("now I'm going to write these to file")
target.write(line1)
target.write('\n')
target.write(line2)
target.write('\n')
target.write(line3)
print("And finally we close it.")
target.close()
| true |
fd25c5909d3329a11e7eed49c14d08dfbf81ec95 | deepakmarathe/whirlwindtourofpython | /string_regex/regex_syntax.py | 1,772 | 4.21875 | 4 | # Basics of regular expression syntax
import re
# Simple strings are matched directly
regex = re.compile('ion')
print regex.findall('great expectations')
# characters with special meanings
# . ^ $ * + ? { } [ ] \ | ( )
# Escaping special characters
regex = re.compile('\$')
print regex.findall(r"the cost is $100")
print "standard python strings : ", "a\tb\tc"
print "raw python strings : ", r"a\tb\tc"
# Special characters can match character groups
regex = re.compile('\w\s\w')
print regex.findall('the fox is 9 years old')
# \d match any digit
# \D match any non-digit
# \s match any whitespace
# \S match any non-whitespace
# \w match any alphanumeric character
# \W match any non-alphanumeric character
# Square brackets match custom character groups
regex = re.compile('[aeiou]')
print regex.split('consequential')
regex = re.compile('[A-Z][0-9]')
print regex.findall('1043, G2, H6')
# Wildcard match repeated characters
regex = re.compile(r"\w{3}")
print regex.findall('The quick brown fox')
regex = re.compile('\w+')
print regex.findall("The quick brown fox")
# Table of repitition markers
# ? Match 0 or 1 repetitions of proceeding
# * Match 0 or more repetitions of preceeding
# + match 1 or more repetitions of the preceeding
# {n} Match n repetitions of the preceeding
# {m, n} Match between m and n repetitions of proceeding
email2 = re.compile(r'[\w+.]+@\w+\.[a-z]{3}')
print email2.findall('barack.obama@whitehouse.gov')
# Paranthesis indicate groups to extract
email3 = re.compile('([\w+.]+)@(\w+)\.([a-z]{3})')
text ="To email Guido, try guido@python.org or the older address guido@google.com"
print email3.findall(text)
# We can even name the groups
email4 = re.compile('(?P<name>[\w+.]+)@(?P<domain>\w+)\.(?P<suffix>[a-z]{3})')
print email4.findall('guido@python.org')
| true |
380cccfd40ee68bf5ffa1a99d145cffcd1fa6d4b | TETSUOOOO/usercheck | /passwordDetect.py | 1,058 | 4.4375 | 4 | #! python3
# passwordDetect.py - Ensures that password is 8 characters in length, at least one lowercase and one uppercase letter,
# and at least one digit
# saves accepted passwords into a json file
import json, re
filename = 'passwords.json'
def passwordDetector(text):
"""Uses a regex to parse the user input containing the password"""
passRegEx = re.compile(r'[a-z{1,6}A-Z{1,6}0-9+]{8}')
passObject = passRegEx.search(text)
try:
passObject.group()
except AttributeError:
print('Your password is not secure!')
text = input('Please re-enter password>')
passwordDetector(text)
else:
print('Your password is secure! Please confirm password>')
confirmed = input()
if confirmed == text:
with open(filename, 'a') as pass_obj:
json.dump(text, pass_obj)
print('Password is saved!')
else:
print('Does not match! Please try again.')
text = input('Please re-enter password>')
passwordDetector(text)
| true |
c23b9c26d90994d5aac03bdeb8cf2c038762336c | davekunjan99/PyPractice | /Py6.py | 218 | 4.28125 | 4 | string = str(input("Enter a string: "))
revString = string[::-1]
if(string == revString):
print("Your string " + string + " is palindrome.")
else:
print("Your string " + string + " is not palindrome.")
| true |
659de313db36bb521842ba837228b6fd87d66b52 | davekunjan99/PyPractice | /Py11.py | 455 | 4.375 | 4 | num = int(input("Please enter a number: "))
def checkPrime(num):
isPrime = ""
if num == 1 or num == 2:
isPrime = "This number is prime."
else:
for i in range(2, num):
if num % i == 0:
isPrime = "This number is not prime."
break
else:
isPrime = "This number is prime."
return isPrime
##while(num != 0):
checkPrime = checkPrime(num)
print(checkPrime)
| true |
f5686d3db18f0f77a679085954f752e648f8e5f4 | mjixd/helloworld-sva-2018 | /week2/mjstory.py | 1,551 | 4.5 | 4 | # let the user know what's going on
print ("Welcome to MJ World!")
print ("Answer the questions below to play.")
print ("-----------------------------------")
# variables containing all of your story info
adjective1 = raw_input("Enter an adjective: ")
food1 = raw_input("What is your favorite food?: ")
location1 = raw_input("Name a place: ")
object1 = raw_input("An object from New Yok City: ")
famousPerson1 = raw_input("A famous person you don't really like: ")
famousPerson2 = raw_input("A famous person you sort of like, but not you're favorite: ")
yourName = raw_input("What's your name?: ")
adjective2 = raw_input("Enter favorite adjective: ")
# this is the story. it is made up of strings and variables.
# the \ at the end of each line let's the computer know our string is a long one
# (a whole paragraph!) and we want to continue more code on the next line.
# play close attention to the syntax!
story = "A traveler" + adjective1 + " good " + food1 + " sushi " + location1 + ", japanese sushi restaurant " \
"providing a " + object1 + " for meals which she has made by " + famousPerson1 + ". " \
"This is an " + adjective2 + " sushi with sushi with fish egges in it made in "
+ yourName + " incredibly the most delicious recipe. " \
"" + yourName + " then have a sweet potato ice cream with roasted rice tea. " \
"the food is beautifully arranged as much as they are delicious " + food1 + " too sweet things are sent by " + famousPerson2 + " " \
"to eat some food back to " + yourName + "."
# finally we print the story
print (story) | true |
e90ff02843379fd3ff97a9ff61ab7fc351039e03 | binthafra/Python | /2-Python Basics 2/6-iterable.py | 422 | 4.1875 | 4 | #iterable -list ,dict,tuple,set,string
# iterable ->ono by one check each item in the collection
user = {
'name': "afra",
'age': 20,
'can_swim': False
}
# print only keys
for item in user:
print(item)
for item in user.keys():
print(item)
# print key and value
for item in user.items():
print(item)
for item in user.values():
print(item)
for key, value in user.items():
print(key, value)
| true |
6cc518e1a3e69721374315bcced5aed005cb4d75 | jwodder/euler | /digits/euler0055.py | 1,808 | 4.125 | 4 | #!/usr/bin/python
"""Lychrel numbers
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like
196, never produce a palindrome. A number that never forms a palindrome
through the reverse and add process is called a Lychrel number. Due to the
theoretical nature of these numbers, and for the purpose of this problem, we
shall assume that a number is Lychrel until proven otherwise. In addition
you are given that for every number below ten-thousand, it will either (i)
become a palindrome in less than fifty iterations, or, (ii) no one, with all
the computing power that exists, has managed so far to map it to a
palindrome. In fact, 10677 is the first number to be shown to require over
fifty iterations before producing a palindrome: 4668731596684224866951378664
(53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel
numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
NOTE: Wording was modified slightly on 24 April 2007 to emphasise the
theoretical nature of Lychrel numbers."""
__tags__ = ['digits', 'palindromic number', 'iterated functions']
def solve():
qty = 0
for i in xrange(1, 10000):
istr = str(i)
for _ in xrange(49):
i += int(istr[::-1])
istr = str(i)
if istr == istr[::-1]:
break
else:
qty += 1
return qty
if __name__ == '__main__':
print solve()
| true |
3ade90c1e0cac84869460cd0aa453552002528d5 | jwodder/euler | /euler0173.py | 1,745 | 4.15625 | 4 | #!/usr/bin/python
"""Using up to one million tiles how many different "hollow" square laminae can
be formed?
We shall define a square lamina to be a square outline with a square "hole"
so that the shape possesses vertical and horizontal symmetry. For example,
using exactly thirty-two square tiles we can form two different square
laminae:
###### #########
###### # #
## ## # #
## ## # #
###### # #
###### # #
# #
# #
#########
With one-hundred tiles, and not necessarily using all of the tiles at one
time, it is possible to form forty-one different square laminae.
Using up to one million tiles how many different square laminae can be
formed?"""
# The number of laminae with an inner hole of side length $s$ that can be
# formed from at most 1e6 tiles is $(S-s)/2$ where $S$ is the largest integer
# of the same parity as $s$ such that $S^2 - s^2 \leq 1e6$, i.e., `S =
# floor(sqrt(1e6 + s*s))`, possibly minus 1 (difference eliminated by rounding
# down when dividing by 2).
import math
__tags__ = ['integer sequences', 'arithmetic sequence', 'partial sums',
'integer partition']
maxTiles = 1000000
def intSqrt(x):
# faster than the one in eulerlib, and just as accurate
return int(math.floor(math.sqrt(x)))
def solve():
return sum((intSqrt(maxTiles + s*s) - s)//2 for s in xrange(1, maxTiles//4))
if __name__ == '__main__':
print solve()
| true |
d81f15a0dd213f3f16396fbe09213fa0b90a3273 | paulknepper/john | /guess_your_number.py | 2,836 | 4.4375 | 4 | #!/usr/local/bin/python3
# guess_your_number.py
"""
Guess Your Number rules:
I, the computer, will attempt to guess your number. This is the exact
opposite of the proposition made in guess_my_number.py. You must pick
a number between one and ten. I will make a guess. If I am incorrect,
tell me if I am too high or too low. If I guess, I win.
Note that you need to run this with python 3.x for it to work.
"""
from random import randint, choice
def main():
print("""Think of a number between 1 and some arbitrary upper bound and I
will guess it. For example, if you are thinking of a number between 1 and
1000, 1000 is your upper bound.
Don't let my artificial intelligence intimidate you.\n""")
lBound = 1
uBound = get_upper_bound()
play = input("Alright. I'm ready. Are you ready to play? (y/n): ")
while play.lower()[0] != 'n':
if lBound == uBound:
print("Ah, this must be your number: {num}".format(num=uBound))
guess = get_guess(lBound, uBound)
print("Is this your number?: {num}".format(num=guess))
answer = input("Enter 'y' for yes or 'n' for no: ")
if answer.lower()[0] == 'y':
print(choice(WIN_MESSAGE))
play = play_again(action='play')
if play.lower()[0] == 'y':
input("Think of another number, then press <enter>.")
lBound, uBound = 1, get_upper_bound()
else:
print(choice(LOSE_MESSAGE))
play = play_again()
if play.lower()[0] == 'n': break
direction = input("Was I too high (enter 'h') or too low (enter 'l')?: ")
if direction.lower()[0] == 'h':
uBound = guess - 1
else: # guess was too low
lBound = guess + 1
print(choice(ENDING_MESSAGE))
def get_upper_bound():
return int(input("So tell me--you're thinking of a number between 1 and...what?: "))
def play_again(action='guess'):
questions = ["I'm feelin' good! I think I've got your number. Give it another shot? (y/n) ",
"Shall I guess again? (y/n) "]
return input(questions[0] if action == 'play' else questions[1])
def get_guess(lower, upper):
return (upper + lower) // 2
WIN_MESSAGE = ["BAM!!! I win!", "Simple minds are easy to read.",
"Looks like I've got you figured out."]
LOSE_MESSAGE = ["You must be wearing a tinfoil hat...",
"I think you cheated.",
"Darn it. Are you sure you weren't thinking of a letter?"]
ENDING_MESSAGE = ["Aww, c'mon!!! I was just getting warmed up! Fine, then, get lost.",
"I'd be scared, too, if I were you. Goodbye.",
"Don't like being that easy to read, huh? Goodbye."]
if __name__ == '__main__': main()
| true |
4258ab9b79c0d20997c84a2d6d4414bc29d953e1 | Nathan-Zenga/210CT-Coursework-tasks | /cw q9 - binary search 2 - adapted.py | 1,448 | 4.15625 | 4 | number1 = int(input("1st number: "))
number2 = int(input("2nd number: "))
List = [4, 19, 23, 36, 40, 43, 61, 64, 78, 95]
def binarySearch(num1, num2, array):
'''performs binary search to identify if there is
a number in the List within a given interval'''
mid = len(array)//2
try:
if num1 <= num2: ##calls itself with the array halved to the right side of the pivot
if array[mid-1] >= num1 and array[mid-1] <= num2:
return True
elif array[mid-1] > num2: ##if the value is larger than pivot (to the right of the array)
return binarySearch(num1, num2, array[:mid-1]) ##calls itself with the array halved to the right side of the pivot
elif array[mid-1] < num1: ##if the value is smaller than pivot (to the left of the array)
return binarySearch(num1, num2, array[mid:]) ##calls itself with the array halved to the left side of the pivot
return False
else:
return "ERROR! Lower value > upper value"
except IndexError or RecursionError: ##signifying the two common errors during runtime
return False
print("Is there an integer between %d and %d in the list? Answer: %s" % (number1, number2, binarySearch(number1, number2, List)))
| true |
06e6078bb3b5585e95aa3f0f11bb011e6f2723c8 | shalu169/lets-be-smart-with-python | /Flatten_Dictionary.py | 540 | 4.15625 | 4 | """
This problem was asked by Stripe.
Write a function to flatten a nested dictionary. Namespace the keys with a period.
For example, given the following dictionary:
{ "key": 3, "foo": { "a": 5, "bar": { "baz": 8 }}}
it should become:
{ "key": 3, "foo.a": 5, "foo.bar.baz": 8 }
You can assume keys do not contain dots in them, i.e. no clobbering will occur. """
a = eval(input())
d = {}
'''for i,j in a:
if type(j)!=dict:
d[i] = j
a.pop(i)
else:
'''
b = list(a.keys())
c = list(a.values())
d =[]
for i in c:
| true |
f8e2832fa04459261dd5d89ec41dbc329f41cee9 | shalu169/lets-be-smart-with-python | /object_to_iter.py | 2,675 | 4.40625 | 4 | #The __iter__() function returns an iterator for the given object (array, set, tuple etc. or custom objects).
#It creates an object that can be accessed one element at a time using __next__() function,
#which generally comes in handy when dealing with loops.
#iter(object)
#iter(callable, sentinel)
# Python code demonstrating
# basic use of iter()
#way 1:
listA = ['a', 'e', 'i', 'o', 'u']
iter_listA = iter(listA)
print(type(iter_listA)) #<class 'list_iterator'>
try:
print(next(iter_listA))
print(next(iter_listA))
print(next(iter_listA))
print(next(iter_listA))
print(next(iter_listA))
print(next(iter_listA)) # StopIteration error
except:
pass
# way 2:
# Python code demonstrating
# basic use of iter()
lst = [11, 22, 33, 44, 55]
iter_lst = iter(lst)
while True:
try:
print(iter_lst.__next__())
except:
break
# Way 3
# Python code demonstrating
# basic use of iter()
listB = ['Cat', 'Bat', 'Sat', 'Mat']
iter_listB = listB.__iter__()
print(type(iter_listB))
try:
print(iter_listB.__next__())
print(iter_listB.__next__())
print(iter_listB.__next__())
print(iter_listB.__next__())
print(iter_listB.__next__()) # StopIteration error
except:
print(" \nThrowing 'StopIterationError'",
"I cannot count more.")
# Way 4
# Python code showing use of iter() using OOPs
class Counter:
def __init__(self, start, end):
self.num = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.num > self.end:
raise StopIteration
else:
self.num += 1
return self.num - 1
# Driver code
if __name__ == '__main__':
a, b = 2, 5
c1 = Counter(a, b)
c2 = Counter(a, b)
# Way 1-to print the range without iter()
print("Print the range without iter()")
for i in c1:
print("Eating more Pizzas, couting ", i, end="\n")
print("\nPrint the range using iter()\n")
# Way 2- using iter()
obj = iter(c2)
try:
while True: # Print till error raised
print("Eating more Pizzas, couting ", next(obj))
except:
# when StopIteration raised, Print custom message
print("\nDead on overfood, GAME OVER")
# Python 3 code to demonstrate
# property of iter()
# way how iteration can not reassign back to
# initializing list
lis1 = [1, 2, 3, 4, 5]
# converting list using iter()
lis1 = iter(lis1)
# prints this
print("Values at 1st iteration : ")
for i in range(0, 5):
print(next(lis1))
# doesn't print this
print("Values at 2nd iteration : ")
for i in range(0, 5):
print(next(lis1)) | true |
01240ebbeac9cd0dd912097c8249ca7c6654b73f | janedallaway/ThinkStats | /Chapter2/pumpkin.py | 1,975 | 4.25 | 4 | import thinkstats
import math
'''ThinkStats chapter 2 exercise 1
http://greenteapress.com/thinkstats/html/thinkstats003.html
This is a bit of an overkill solution for the exercise, but as I'm using it as an opportunity to learn python it seemed to make sense'''
class Pumpkin():
def __init__ (self, type, size, number):
self.type = type
self.size = size
self.number = number
def getType(self):
return self.type
def getSize(self):
return self.size
def getNumber(self):
return self.number
class Pumpkins():
def __init__ (self):
self.pumpkins = [] # store complete pumpkin objects
self.weightsOnly = [] # store the weights only, one entry per pumpkin
pass
def addPumpkin (self, myPumpkin):
self.pumpkins.append (myPumpkin)
for i in range (myPumpkin.getNumber()):
self.weightsOnly.append (myPumpkin.getSize())
def writePumpkins(self):
for pumpkin in self.pumpkins:
print "There are",pumpkin.getNumber()," ",pumpkin.getType()," pumpkins which weigh",pumpkin.getSize(),"pound each"
def writeWeights(self):
for weight in self.weightsOnly:
print weight
def meanPumpkin(self):
return thinkstats.Mean(self.weightsOnly)
def variancePumpkin(self):
return thinkstats.Var(self.weightsOnly)
def stdDeviationPumpkin(self):
return math.sqrt(self.variancePumpkin())
myPumpkins = Pumpkins()
myPumpkins.addPumpkin(Pumpkin("Decorative",1,3))
myPumpkins.addPumpkin(Pumpkin("Pie",3,2))
myPumpkins.addPumpkin(Pumpkin("Atlantic Giant",591,1))
print "The mean weight is", myPumpkins.meanPumpkin() # should be 100
print "The variance weight is", myPumpkins.variancePumpkin()
print "The standard deviation is", myPumpkins.stdDeviationPumpkin()
| true |
254057aa4f45292225fea68a65458c4fb8098bba | gusmendez99/ai-hoppers | /game/state.py | 700 | 4.15625 | 4 | from copy import deepcopy
class GameState:
"""
Class to represent the state of the game.
- board = stores board information in a certain state
- current_player = stores current_player information in a specified state
- opponent = stores opponent information in specified state
"""
def __init__(self, board, player_1, player_2):
""" Constructor """
self.board = deepcopy(board)
self.current_player = deepcopy(player_1)
self.opponent = deepcopy(player_2)
def next_turn(self):
""" Switches player simulating a turn """
temp = self.current_player
self.current_player = self.opponent
self.opponent = temp
| true |
1dfda62b11b9721499dff52d38617d547647198a | DinakarBijili/Python-Preparation | /Data Structures and Algorithms/Algorithms/Sorting_Algorithms/2.Bubble.sort.py | 1,042 | 4.375 | 4 | # Bubble sort is a Simple Sorting algorithm that repeatedly steps through the array, compare adjecent and swaps them if they are in the wrong order.
# pass through the array is repeated until the array is sorted
#Best O(n^2); Average O(n^2); Worst O(n^2)
"""
Approach
Starting with the first element(index = 0), compare the current element with the next element of the array.
If the current element is greater than the next element of the array, swap them.
If the current element is less than the next element, move to the next element.
"""
def bubble_sort(List):
for i in range(len(List)): # Traverse through all array elements
for j in range(len(List)-1, i, - 1): # Last i elements are already in correct position(reverse order)
if List[j] < List[j - 1]:
List[j],List[j - 1] = List[j - 1], List[j] #swap
return List
if __name__ == "__main__":
# List = list(map(int,input().split())) <-- for user input
List = [3, 4, 2, 6, 5, 7, 1, 9]
print("Sorting List", bubble_sort(List))
| true |
e88b39744da6626bb46d84c211c9475a0c45ec93 | DinakarBijili/Python-Preparation | /Problem Solving/Loops/Remove_Duplication_from_string.py | 330 | 4.125 | 4 | """Remove Duplication from a String """
def remove_duplication(your_str):
result = ""
for char in your_str:
if char not in result:
result += char
return result
user_input = input("Enter Characters : ")
no_duplication = remove_duplication(user_input)
print("With out Duplication = ",no_duplication)
| true |
224fc51576ce0320b8b78210fde376cf4aba4b37 | S411m4/very_simple_python_database | /very_simple_python_database.py | 1,386 | 4.21875 | 4 | class School:
def __init__(self, firstName, lastName, email, money, job):
self.firstName = firstName
self.lastName = lastName
self.email = email
self.money = money
self.job = job
def __str__(self):
data = [self.firstName, self.lastName, self.email, self.money, self.job]
return str(data)
def enter_data():
global firstName, lastName, money, job, email
firstName = input("first name: ")
lastName = input("last name: ")
money = input("student's fees or worker's salary: ")
email = input("email: ")
job = input("job: ")
print("\n")
def enter_data_answer():
answer = input("do you want to enter data of another person (yes / no): ")
if answer not in ["yes", "y", "no", "n"]:
print("\n")
print("enter a valide option (yes / no)")
print("\n")
enter_data_answer()
return answer
data_base = []
def make_object():
school_object = School(firstName, lastName, money, email, job)
data_base.append(school_object.__str__())
if __name__ == '__main__':
enter_data()
make_object()
while enter_data_answer() in ["yes", "y"]:
enter_data()
make_object()
print("\n")
for data in data_base:
print(data)
| true |
9492b53ff84e6463ca659d5ade4c4b6be287501a | michalmaj90/basic_python_exercises | /ex1.py | 346 | 4.21875 | 4 | '''Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.'''
name = input("What's your name?? ")
age = input("What's your age?? ")
year = str((100 - int(age)) + 2018)
print("Hello " + name + "! You'll be 100 years old in " + year)
| true |
dc7a57d761082468346561bfa10083e4e5b80e56 | mohammedjasam/Coding-Interview-Practice | /LeetCode/LongestSubstring.py | 850 | 4.125 | 4 | """Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring."""
#
class LongestSubstring:
maxi = ""
def find(self, s):
sub = ""
lsub = []
for i in s:
if not(i in sub):
# print(i)
sub += i
else:
# print(i)
lsub.append((len(sub),sub))
sub = ""
sub += i
# sorted(lsub,reverse = True)
return max(lsub)[1]
s = 'pojasam'
# if 'a' in s:
a = LongestSubstring();
print(a.find(s))
| true |
0e8f5383d8e33592ec5f1b0ebb18c7f9bfe9f7dc | Shashankhs17/Hackereath-problems_python | /Basic/palindrome_string.py | 461 | 4.15625 | 4 | '''
You have been given a String S.
You need to find and print whether this string is a palindrome or not.
If yes, print "YES" (without quotes), else print "NO" (without quotes).
'''
string = input("Enter the string:")
lenght = len(string)
flag = 0
i = 0
while i<lenght/2:
if string[i] == string[lenght - 1]:
flag = 1
else:
flag = 0
break
i += 1
lenght -= 1
if flag == 1:
print("YES")
else:
print("NO") | true |
247bf8d334045c2af71b90ee7dd9be4a67dc1941 | mmore500/hstrat | /hstrat/_auxiliary_lib/_capitalize_n.py | 454 | 4.1875 | 4 | def capitalize_n(string: str, n: int) -> str:
"""Create a copy of `string` with the first `n` characers capitalized.
If `n` is negative, the last `n` characters will be capitalized.
Examples
--------
>>> capitalize_n('hello world', 2)
'HEllo world'
>>> capitalize_n('goodbye', 4)
'GOODbye'
"""
return (
string[:n].upper() + string[n:]
if n >= 0
else string[:n] + string[n:].upper()
)
| true |
4adec0efa3c15a3ab80eb6ec7706f4dfc51cb015 | mmore500/hstrat | /hstrat/_auxiliary_lib/_render_to_numeral_system.py | 1,278 | 4.21875 | 4 | # adapted from https://cs.stackexchange.com/a/65744
def render_to_numeral_system(n: int, alphabet: str) -> str:
"""Convert an integer to its digit representation in a custom base.
Parameters
----------
n : int
The non-negative integer to be converted to a custom base
representation.
alphabet : str
A string of unique characters representing the digits in the custom
base.
The i-th character in the alphabet corresponds to the i-th digit in the
base.
Returns
-------
str
A string of characters representing the custom base representation of the given integer.
Raises
------
AssertionError
If the integer is negative or if the alphabet contains repeated
characters.
Examples
--------
>>> render_to_numeral_system(163, '0123456789abcdef')
'a3'
>>> render_to_numeral_system(42, '01234567')
'52'
>>> render_to_numeral_system(7, '01')
'111'
"""
assert n >= 0
assert len(alphabet) == len(set(alphabet))
if n == 0:
return alphabet[0]
b = len(alphabet)
reverse_digits = []
while n > 0:
reverse_digits.append(alphabet[n % b])
n = n // b
return "".join(reversed(reverse_digits))
| true |
02901ed5551932dcd71f9c33e75361f815bc963c | Isaac12x/codeexamples | /split_list.py | 1,858 | 4.40625 | 4 | def sub_split_list_by_reminder(list, splitter):
"""
Function to create a nested list with length equal
to the reminder of division
This function splites the list into an amount of nested lists equally sized
to the second parameter.
It also spreads the contents of the first list in nested lists equals to
that reminder.
Parameters
----------
list : list of ints
splitter : int
Returns
-------
nested list of ints
>>> sub_split_list_by_reminder([1,2,3,4,5], 3)
[[1,2], [3,4], [5]]
>>> sub_split_list_by_reminder([21, 3123, 34], 2)
[[21, 3123], [34]]
"""
# Required variables
list_length = len(list)
new_list = []
lower_end_slice = 0
next_slice = 0
# Calculate the length of each new nested list
nested_list_length = list_length % splitter
next_slice = nested_list_length
# Use the splitter as the iterator - can also be accomplished with
# list comprehension, but it seems clearer in this more verbose way
while splitter >= 1:
# Construct a new list by slicing the first one where required
new_list.append(list[lower_end_slice:next_slice])
# Update the slicers
lower_end_slice += nested_list_length
next_slice += nested_list_length
# Once a list is created, substract that from the remaining to create
splitter -= 1
# Uncoment the following line if you want to see the results
print new_list
# Return the updated list
return new_list
# You can check the otutputs by going to terminal and write in the directory
# python test.py and you'll see the results || alternatively you can use
# Doctest to test the input in the docstring.
sub_split_list_by_reminder([1, 2, 3, 4, 5], 3)
sub_split_list_by_reminder([21, 3123, 34], 2)
sub_split_list_by_reminder([21, 3123, 34], 30)
| true |
787d8c98b29972ac759a8e13175dccb84f1dd69a | paulopimenta6/ph_codes | /python/edx_loop_for_3.py | 263 | 4.34375 | 4 | #Using a for loop, write a program which asks the user to type an integer, n, and then prints the sum of all numbers from 1 to n (including both 1 and n).
number = int(input("write a number: "))
sum=0
for i in range(1,number+1):
sum = sum + (i**2)
print(sum)
| true |
90b9a6ed8f46b120764be142824d76cac1f88a2f | sssandesh9918/Python-Basics | /Functions/11.py | 291 | 4.28125 | 4 | '''Write a Python program to create a lambda function that adds 15 to a given
number passed in as an argument, also create a lambda function that multiplies
argument x with argument y and print the result.'''
add= lambda a: a+15
mul =lambda x,y: x*y
r=add(10)
s=mul(15,10)
print(r)
print(s)
| true |
ff1908e083e96ca7f60b802cf1ff4549a789fde2 | sssandesh9918/Python-Basics | /Data Types/7.py | 373 | 4.21875 | 4 | '''Write a Python function that takes a list of words and returns the length of the
longest one.'''
def func(a):
b=[]
for i in range(a):
words=list(input("Enter words"))
b.append(words)
print(b)
c=[]
for j in range(len(b)):
c.append(len(b[j]))
print(max(c))
a=int(input("Enter the number of words you want to enter"))
func(a) | true |
a8434f61ab39cdab8ba3622b7b0f0456bcd424de | sssandesh9918/Python-Basics | /Functions/1.py | 254 | 4.28125 | 4 | '''Write a Python function to find the Max of three numbers.'''
def highest(x,y,z):
return(max(x,y,z))
a=input("Enter first number")
b=input("Enter second number")
c=input("Enter third number")
m=highest(a,b,c)
print("The max of three numbers is ",m) | true |
9d3fdd56d2421bbaf118afaa03bbba63f2c39382 | ArthurMelo9/100daysofCode | /examples.py | 955 | 4.15625 | 4 | #A rollercoaster ride
#print("Welcome to Rollercoaster!")
#height= int(input("Enter your height in cm: "))
#if height > 120:
# print("You can ride the rollercoaster!")
#else:
# print("Sorry, you have to grow taller before you can ride.")
print("Welcome to rollercoaster!")
height=int(input("What is your height in cm? "))
if height>=120:
print("You're eligible to ride")
age= int(input("What is your age? "))
bill = 0
#if age < 18:
#print("Ticket costs $5")
#else:
#print ("Ticket costs $12")
if age < 12:
bill = 5
print ("Ticket costs $5")
elif age <=18:
bill = 18
print ("Ticket costs $7")
elif age>=45 and age<=55:
bill = 0
print ("You have a free ride!")
else:
bill = 12
print("Ticket costs $12")
want_photo = input ("Do you want a picture? Y or N ")
if want_photo == "Y":
bill +=3
print(f"Your total bill is ${bill}")
else:
print("You're not eligible to ride") | true |
0c7efc52a64526e2c9fb5c3dbc7495bb479908b7 | omvikram/python-advance | /decorators.py | 661 | 4.125 | 4 | #Return a function
def myfunc1(name=""):
print("This is myfunc1()")
def welcome():
print("\t This is welcome()")
def greet():
print("\t This is greet()")
if(name == "Om"):
return welcome
else:
return greet
f = myfunc1()
f()
f= myfunc1("Om")
f()
#Pass a function as param
def myfunc2(param_func):
print("This is myfunc2() start")
param_func()
print("This is myfunc2() end")
myfunc2(myfunc1("Om"))
#Check the decorator now
# add @myfunc2 on top of myfunc1 so that myfunc1() can be wrapped under the myfunc2()
@myfunc2
def myfunc3():
print("This is myfunc3() which will use the decorator") | true |
8436a1dc91a3328e45aba2a4b8e9c8192561aef8 | mingyuea/pythonScriptingProblems | /routeCircle.py | 821 | 4.125 | 4 | class Solution:
def judgeCircle(self, moves):
"""
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle
Example 1:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false
"""
moveDict = {'U': (1,1), 'D':(1, -1), 'L':(0, -1), 'R':(0, 1)}
pos = [0, 0]
for move in moves:
pos[moveDict[move][0]] += moveDict[move][1]
if pos[0] == 0 and pos[1] == 0:
return True
else:
return False | true |
1234197b9ea59d5b5004b2cd424e6e9b38417df0 | cskamil/PcExParser | /python/py_trees_insert_binarytree/insert_binarytree.py | 2,602 | 4.3125 | 4 | '''
@goalDescription(In a BinaryTree, adding new nodes to the tree is an important capability to have.\nConstruct a simple implementation of a BinaryTree consisting of an __init__ method and an insertLeft method, which adds new nodes to the tree to the left of the root. )
@name(Inserting binary tree)
'''
# Define a binary tree class
class BinaryTree:
'''@helpDescription( We want to define the __init__ method for the BinaryTree class to take in a root node, so we specify the two parameters to be self and root. Recall that self is a required parameter.)'''
def __init__(self, root):
'''@helpDescription(We set the key value of the BinaryTree equal to root)'''
self.key = root
'''@helpDescription(We set the node to the left of root equal to None (since it doesn’t exist yet))'''
self.left = None
'''@helpDescription(We set the node to the right of root equal to None (since it doesn’t exist yet))'''
self.right = None
# Define a function to insert node from the left
'''@helpDescription( We want to define a function that inserts a new node to the left of an existing node, so we specify the two parameters self and new_node)'''
def insert_left(self, new_node):
'''@helpDescription(We need to check if there are any existing node to the left of the root.)'''
if self.left is None:
'''@helpDescription( If the node to the left of the root doesn’t exist,then we set it equal to a new instance of BinaryTree with the new node as its root)'''
self.left = BinaryTree(new_node)
'''@helpDescription(If the node to the left of the root already exists, then we replace the already existing left node with the new node.)'''
else:
node_tree = BinaryTree(new_node)
'''@helpDescription(Here, we update the references to make sure the nodes reference each other correctly. Here we insert each left node right next to the root node.)'''
node_tree.left = self.left
self.left = node_tree
# Define a function to print the tree
'''@helpDescription(We need to define a function to print our tree structure.)'''
def print_tree(self):
'''@helpDescription(We want to print each node from left to right.)'''
if self.left:
self.left.print_tree()
print(self.key, " ", end="")
if self.right:
self.right.print_tree()
# Initializing a tree
root = BinaryTree(10)
root.insert_left(5)
root.insert_left(6)
root.insert_left(14)
root.print_tree() | true |
502ce16f0984b5d247561afe4fe2ef29f9a4bd72 | paulatumwine/andelabs | /Day 2/OOP/oop_concepts.py | 1,944 | 4.625 | 5 | from abc import ABCMeta
class Product(object):
"""
An abstract class
"""
__metaclass__ = ABCMeta
unit_price = 0
def __init__(self, name, maker):
self.__name = name
self.__maker = maker
self._quantity = 0
self._total_stock_price = 0
def add_stock(self, quantity):
self._quantity += quantity
self._total_stock_price += self.unit_price * quantity
def sell(self, quantity):
self._quantity -= quantity
self._total_stock_price -= self.unit_price * quantity
def get_name(self):
"""Demonstration of encapsulation; this is a wrapper to allow access to the value in __name"""
return self.__name
def check_product_catalogue(self):
"""A method to demonstrate polymorphism"""
pass
class Phone(Product):
"""
Implementing a phone class, which is a subclass
of the product class, to demonstrate inheritance
"""
unit_price = 400
def check_product_catalogue(self):
return str(self._quantity) + " " + self.get_name() + " phones at " + str(Phone.unit_price) + "@, total: " + str(self._total_stock_price)
class China(Phone):
"""
Similar to the Phone class
"""
unit_price = 100
def check_product_catalogue(self):
"""A demonstration of polymorphism"""
return str(self._quantity) + " " + self.get_name() + " at " + str(China.unit_price) + "@, total: " + str(self._total_stock_price)
def main():
product = Product("Corolla", "Toyota")
phone = Phone("Samsung Galaxy S6 Edge", "Samsung")
phone.add_stock(10)
print(phone.check_product_catalogue())
phone.sell(5)
print(phone.check_product_catalogue())
phone = China("Plates", "Nice house of plastics")
phone.add_stock(12)
print(phone.check_product_catalogue())
phone.sell(6)
print(phone.check_product_catalogue())
if __name__ == '__main__':
main() | true |
39c5f391e9016907762f2465f47b5251316bfd8c | Emile-Dadou-EPSI/EulerProject | /problem1.py | 501 | 4.15625 | 4 | ## Euler Project problem 1 :
## If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
## The sum of these multiples is 23.
## Find the sum of all the multiples of 3 and 5 below 1000.
def findMultiples(nbMax):
res = 0
for x in range(nbMax):
if x % 3 == 0 or x % 5 == 0:
res = res + x
return res
def main():
print("Start problem 1 : \n")
res = findMultiples(1000)
print(res)
if __name__ == "__main__":
main()
| true |
7d3a72a7c767addcf1320b785bedd3b5e61f95ea | padmini06/pythonExamples | /example.py | 486 | 4.1875 | 4 | #!/usr/bin/python3
print("hello")
x=""
x=input("enter your name \n")
print("Hello",x)
x=input("enter number 1 \n")
y=input("enter number 2 \n ")
if x>y:
print("x is greater than y");
print("anscscdsafasf")
else:
print("y is greater than x");
def MaxNumber(a,b,c):
"This function will return the max of the three value passed"
if a>b and a>c : return a
elif b>c and b>a : return b
else:return c
max= MaxNumber(5,12,10)
print("Max number is :",max)
| true |
deb17862f7715aca87c07a2b0a74571da13bbfc7 | padmini06/pythonExamples | /Example5.py | 970 | 4.21875 | 4 | #!/usr/bin/python3
"""
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. """
# Python code to generate random numbers and append them to a list
import random
def Rand(start, end, num):
res = []
for j in range(num):
res.append(random.randint(start, end))
return res
#num = 10
#start = 20
#end = 40
#print(Rand(start, end, num))
list_1 = Rand(10,100,8)
list_2 = Rand(10,100,6)
#a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(list_1)
print(list_2)
output = []
for i in list_1 :
if i in list_2 :
if i not in output :
output.append(i)
print(output)
| true |
a8170f6055aac917f096ce057feba9015c713bed | padmini06/pythonExamples | /example1.py | 396 | 4.375 | 4 | """
Create a program that asks the user to enter their name and their age.
Print out a message addressed to them that tells them the year that they will turn 100 years old."""
_name= input("Enter your name\n")
_age = int(input("Enter you age \n"))
if _age > 100 :
print("your age is greater than 100")
else:
diff = 100-_age;
print(_name + " will reach 100 after",diff,"years") | true |
0e12c929ff4cbb6a9b263a4bbe074edeea8546f1 | rogerwoods99/UCDLessons | /UCDLessons/DataCampDictionary.py | 2,374 | 4.4375 | 4 | # find the capital based on index of the country, a slow method
# Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']
# Get index of 'germany': ind_ger
ind_ger=countries.index("germany")
# Use ind_ger to print out capital of Germany
print(capitals[ind_ger])
#===========================================================
#===========================================================
# A dictionary has been defined. Find values within it
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }
# Print out the keys in europe
print(europe.keys())
# Print out value that belongs to key 'norway'
print(europe['norway'])
#===========================================================
#===========================================================
# add 2 new countries to the capitals list for Europe
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }
# Add italy to europe
europe['italy']='rome'
# Print out italy in europe. This verifies that Italy is in the list
print('italy' in europe)
# Add poland to europe
europe["poland"]='warsaw'
# Print europe
print(europe)
#===========================================================
#===========================================================
# add and edit items in a dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'bonn',
'norway':'oslo', 'italy':'rome', 'poland':'warsaw',
'australia':'vienna' }
# Update capital of germany
europe.update({'germany':'berlin'})
# Remove australia
del(europe["australia"])
# Print europe
print(europe)
#===========================================================
#===========================================================
# this is about dictionaries within dictionaries
europe = { 'spain': { 'capital':'madrid', 'population':46.77 },
'france': { 'capital':'paris', 'population':66.03 },
'germany': { 'capital':'berlin', 'population':80.62 },
'norway': { 'capital':'oslo', 'population':5.084 } }
# Print out the capital of France
print(europe['france']['capital'])
# Create sub-dictionary data
data={'capital':'rome','population':59.83}
# Add data to europe under key 'italy'
europe['italy']=data
# Print europe
print(europe)
| true |
444283f159d5fc198a4bb0a990968fd321c18e87 | planktonlex55/ajs | /basics/rough_works/2_iterators.py | 841 | 4.8125 | 5 | #for can be used to iterate over many data structures in python.
#ex. 1
list1 = [10, 20, 30]
for x in list1:
print x
string1 = "python"
for x in string1:
print x
dict1 = {"key1": "value1", "key2": "value2", "key3": 10}
print dict1 #order of printing seems to be from last to first
for x in dict1:
print x #o/p is: key3 key2 and key1
print dict1[x] #o/p are the values
#one more way to use for
#>>> for line in open("a.txt"):
#... print line,
#...
#first line
#second line
print "this way we can use for"
print "Note: The built-in function iter takes an iterable object and returns an iterator."
y = iter (list1)
print y #<listiterator object at 0x021375D0>
print y.next()
print y.next()
print y.next()
#parantheses is a must.
print y.next() #Expected StopIteration error
| true |
c9a7d17b5534f997709ab430eb851262b4e06a5d | Shivani-Y/assignment-3-prime-factors-Shivani-Y | /prime.py | 785 | 4.28125 | 4 | """
prime.py -- Write the application code here
"""
def generate_prime_factors(number):
""" Code to generate prime factors """
prime_list = []
i = 2
if not isinstance(number, int): #raises an error of function called for any type but integer
raise ValueError("Only integers can be used in the function")
if number == 1: #if number 1 then prints a blank list
print(prime_list)
elif number == 2 and number%i == 0: #if number is 2 then prime factor is 2
prime_list.append(number)
print(prime_list)
else:
while i <= number:
if (number%i) == 0:
prime_list.append(i)
number = number / i
else:
i = i+1
print(prime_list)
return prime_list
| true |
9511d38e439478be9b7166629091ba87f9652836 | YoungWenMing/gifmaze | /examples/example4.py | 1,793 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
This script shows how to run an animation on a maze.
"""
import gifmaze as gm
from gifmaze.algorithms import prim
# size of the image.
width, height = 605, 405
# 1. define a surface to draw on.
surface = gm.GIFSurface(width, height, bg_color=0)
# define the colors of the walls and tree.
# we use black for walls and white for the tree.
surface.set_palette('kw')
# 2. define an animation environment to run the algorithm.
anim = gm.Animation(surface)
# 3. add a maze into the scene.
# the size of the maze is 119x79 but it's scaled by 5
# (so it occupies 595x395 pixels) and is translated 5 pixels
# to the right and 5 pixels to the bottom to make it located
# at the center of the image.
maze = gm.Maze(119, 79, mask=None).scale(5).translate((5, 5))
# pause two seconds, get ready!
anim.pause(200)
# 4. the animation runs here.
# `speed` controls the speed of the animation,
# `delay` controls the delay between successive frames,
# `trans_index` is the transparent color index,
# `mcl` is the minimum code length for encoding the animation
# into frames, it's at least 2 and must satisfy
# 2**mcl >= number of colors in the global color table.
# `start` is the starting cell for running Prim's algorithm. (it's a cell,
# not a pixel).
# `cmap` controls how the cells are mapped to colors, i.e. {cell: color}.
# here `cmap={0: 0, 1: 1}` means the cells have value 0 (the walls) are colored
# with the 0-indexed color (black), cells have value 1 (the tree) are colored
# with the 1-indexed color (white).
anim.run(prim, maze, speed=30, delay=5, trans_index=None,
cmap={0: 0, 1: 1}, mcl=2, start=(0, 0))
# pause five seconds to see the result clearly.
anim.pause(500)
# 5. save the result.
surface.save('example4_simple_anim.gif')
surface.close()
| true |
5f4c8a6d164228395c8aaecd4893ee887de0034b | Lingrui/Learn-Python | /Beginner/tuple.py | 390 | 4.21875 | 4 | #!/usr/bin/python
#define an empty tuple
tuple = ()
#a comma is required for a tuple with one item
tuple = (3,)
personInfo = ("Diana",32,"New York")
#data access
print(personInfo[0])
print(personInfo[1])
#assign multiple variables at once
name,age,country,career = ('Diana',32,'Canada','CompSci')
print(country)
#append to an existing tuple
x = (3,4,5,6)
x = x + (1,2,3)
print(x)
| true |
b9a63cdacea35210a3952f4ca597399e1fc2cb87 | Lingrui/Learn-Python | /Beginner/objects_classes.py | 1,078 | 4.5 | 4 | #!/usr/bin/python
###class######
## The __init__() method is called the constructor and is always called when creating an object.
class User:
name = ""
def __init__(self,name):
self.name = name
def sayHello(self):
print "Hello, my name is " + self.name
#creat virtual objects
james = User("James")
david = User("David")
eric = User("Eric")
#call methods owned by virtual objects
james.sayHello()
david.sayHello()
###class variables
class CoffeeMachine:
name = ""
beans = 0
water = 0
def __init__(self,name,beans,water):
self.name = name
self.beans = beans
self.water = water
def addBean(self):
self.beans = self.beans + 1
def removeBean(self):
self.beans = self.beans - 1
def addWater(self):
self.water = self.water + 1
def removeWater(self):
self.water = self.water - 1
def printState(self):
print "Name = " + self.name
print "Beans = " + str(self.beans)
print "Water = " + str(self.water)
pythonBean = CoffeeMachine("Python Bean", 83,20)
pythonBean.printState()
print ""
pythonBean.addBean()
pythonBean.printState()
| true |
88073a7b852e94d8fcbf21de3b0c9b1ac0447563 | ChiDrummer/CodingDojoPythonStack | /PythonFundamentals/math.py | 504 | 4.53125 | 5 | """Multiples
Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise.
Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000."""
for number in range(1,101,2):
print number
for number in range(5,100):
if number % 5 == 0:
print number
#sum the list
"""a = [1, 2, 5, 10, 255, 3]
print sum(a)"""
#average of list
"""a = [1, 2, 5, 10, 255, 3]
average = sum(a)/len(a)
print average"""
| true |
54afcc3930bfaf9e2c5afa953cbcdd0438dd1e35 | smahs/euler-py | /20.py | 767 | 4.15625 | 4 | #!/usr/bin/python2
"""
Statement:
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!
"""
from unittest import TestCase, main
class Problem20(object):
def __init__(self, bound):
self.bound = bound
def fn(self):
return sum(map(int, str(reduce(lambda i, j: i*j,
xrange(*self.bound)))))
class TestProblem20(TestCase):
def setUp(self):
self.bound = (1, 100)
self.answer = 648
def test_main(self):
self.assertEqual(Problem20(self.bound).fn(), self.answer)
if __name__ == '__main__':
main()
| true |
a7b980f2e78b2720dbb60ca9ba2ef8c242a8e38b | jakubowskaD/Rock_Papper_Scissors-TEAM_ONE | /Rock_paper_scissors_game.py | 1,947 | 4.15625 | 4 | import random
scoretable = [0,0]
def computer_choice():
choices = ['rock', 'paper', 'scissors']
return random.choice(choices)
def player_choice(player):
if player == "1":
player_choice = "rock"
elif player == "2":
player_choice = "paper"
else:
player_choice = "scissors"
return player_choice
def add_point_computer():
scoretable[0] = scoretable[0] + 1
def add_point_player():
scoretable[1] = scoretable[1] + 1
def run_game():
print("\nGame begins")
computer = computer_choice()
player = input("Choose 1 = rock, 2 = paper, 3 = scissors: ")
if (player != "1" and player != "2" and player!="3"):
print("Invalid choice")
return
test = player + computer[0]
player_winning_condition = ['1s', '2r', '3p']
player_draw_condition = ['1r', '2p', '3s']
print("You picked: ", player_choice(player))
print("Computer picked:", computer)
if (test in player_winning_condition):
print("You won!")
add_point_player()
elif (test in player_draw_condition):
print("It's a draw!")
else:
print("You lost!")
add_point_computer()
print("")
score_display()
def score_display():
print("")
print("--------------------------------")
print("Score table")
print("Computer:", scoretable[0])
print("Player:", scoretable[1])
def game_finish():
score_display()
input("Press enter to exit")
quit()
if __name__ == "__main__":
while (True):
run_game()
while (True):
play_again = input("Play Again? [Y/n]: ").lower()
if play_again == "" or play_again == "y":
break
elif play_again == "n":
game_finish()
else:
print("Wrong choice, try again")
| true |
df08c1c86d29e0187566b66bd0e0cb8a8d7813a5 | RakhshandaMujib/The-test-game | /Test_game.py | 1,992 | 4.1875 | 4 | import math
def single_digits_only (list_is):
'''
This method checks a list of number for any number that has more than
2 digits. If there is any, it splits the digits of the same.
Argument:
list_is - List. The list of numbers to check.
Returns:
list_is - Revised list.
'''
index = 0
while True:
if list_is[index] >= 10:
insert = [int(digit) for digit in str(list_is[index])]
list_is = list_is[:index] + insert + list_is[index+1:]
index += 1
if index >= len(list_is):
break
return list_is
def del_spcl_char(list_is):
'''
This method removes specifiec the special characters & spaces from a list.
Argument:
list_is - List. The list of charcters we want to work with.
Returns:
list_is - Revised list.
'''
illegal_char = {' ', '.', ',', '?', "'", '!'}
list_is = [char for char in list_is if char not in illegal_char]
return list_is
def main():
event = input("What do you want to test?\n")
lower = event.lower()
unique_letters = set(lower)
in_order = sorted(unique_letters, key = lower.find)
filtered = del_spcl_char(in_order)
letter_count = {letter : lower.count(letter) for letter in filtered}
counts_list = [count for count in letter_count.values()]
counts_list = single_digits_only(counts_list)
is_100 = False
print(f"\nHere is your result:")
while len(counts_list) != 2:
back = len(counts_list) - 1
temp = []
for front in range(math.ceil(len(counts_list)/2)):
if back == front:
temp.append(counts_list[front])
break
temp.append(counts_list[front] + counts_list[back])
back -= 1
counts_list = single_digits_only(temp)[:]
if len(counts_list) == 3 and (counts_list[0]*100) + (counts_list[1]*10) + counts_list[2] == 100:
is_100 = True
break
if is_100:
result = 100
else:
result = (counts_list[0]*10)+counts_list[1]
print(f"\n\tWe are {result}% positive about the above!")
if __name__ == '__main__':
main() | true |
2b2989045ce3fbf972faf3653e8ea9f65ac45e71 | CadetPD/Kodilla_4_2 | /zad_4-2_palindrom_.py | 391 | 4.1875 | 4 | def palindrome(word):
"""
Palindrome(word) checks if a word is palindrome or not
Parameter: word
Argument: 'word'
Sollution: compare lists for argument ([normal] vs [reversed])
Func result: returns after func execution
"""
if list(word.lower()) == list(reversed(word.lower())):
return True
else:
return False
print(palindrome("Kajak")) | true |
2b7329ca49a053e7bb0392d43233c360a8344de3 | caitinggui/leetcode | /zigzag_conversion.py | 2,099 | 4.28125 | 4 | #!usr/bin/python
# coding:utf-8
''' The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
("PAYPALISHIRING", 3) ('ab', 2), ('abc', 2), ('abcd', 2)
'''
from collections import defaultdict
class Solution(object):
# @param {string} s
# @param {integer} numrows
# @return {string}
def convert(self, s, numrows):
if numrows == 1:
return s
lines = defaultdict(str)
for i, c in enumerate(s):
rem = i % (numrows + numrows - 2)
if rem < numrows:
lines[rem] += c
else:
lineno = numrows * 2 - 2 - rem
lines[lineno] += c
print str(lines)
ss = "".join([lines[i] for i in range(numrows)])
return ss
class Solution_ok(object):
def convert(self, s, numrows):
"""
:type s: str
:type numrows: int
:rtype: str
"""
# The key is started with zero line
if numrows <= 1:
return s
linelength = 2 * numrows - 2
ss = [[] for i in range(numrows)]
sm = []
for i, x in enumerate(s):
numlocation = i % linelength
if numlocation >= numrows:
numlocation = numrows - 1 - (numlocation - numrows + 1)
ss[numlocation].append(x)
for i in range(numrows):
sm += (ss[i])
return ''.join(sm)
solution = Solution()
assert 'PAHNAPLSIIGYIR' == solution.convert("PAYPALISHIRING", 3)
assert 'ab' == solution.convert("ab", 2)
assert 'acb' == solution.convert("abc", 2)
assert 'acbd' == solution.convert("abcd", 2)
| true |
566fa1ae85da1c75006ff57a27e582a1290b1047 | caitinggui/leetcode | /189_rotate_array.py | 1,410 | 4.34375 | 4 | # coding: utf-8
'''
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
'''
class Solution(object):
def rotate1(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
if not nums:
return
for _ in range(k):
nums.insert(0, nums.pop())
def rotate2(self, nums, k):
if not nums:
return
k = k % len(nums)
if k == 0:
return
nums[:k], nums[k:] = nums[-k:], nums[:-k]
# nums[-k:], nums[k:] = nums[:k], nums[-k:]
def rotate(self, nums, k):
if not nums:
return
k = k % len(nums)
nums[:] = nums[-k:] + nums[:-k]
s = Solution()
nums = [1, 2, 3, 4, 5, 6, 7]
s.rotate(nums, 3)
print(nums, [5,6,7,1,2,3,4])
print
nums = []
s.rotate(nums, 0)
print(nums, [])
print
nums = [1]
s.rotate(nums, 0)
print(nums, [1])
print
nums = [1, 2]
s.rotate(nums, 5)
print(nums, [2, 1])
print
nums = [1, 2]
s.rotate(nums, 0)
print(nums, [1, 2])
print
| true |
d8c7134b884879119809e2d4d9073df88fd472fe | romperstomper/petshop | /arrayflatten.py | 705 | 4.25 | 4 | """Flatten an array of arbitrarily nested arrays.
Array elements will be integers and nested arrays. Result in a flat array.
E.g. [[1,2,[3]],4] -> [1,2,3,4]."""
def flatten(target_list):
"""Flattens a nested list.
Args:
target_list: (int|list|tuple)
Yields:
(int)
Raises:
TypeError: Error if target array contains a type that is not an int or a
nested array.
"""
for elem in target_list:
if isinstance(elem, (list, tuple)):
for nested in flatten(elem):
yield nested
elif isinstance(elem, int):
yield elem
else:
raise TypeError
def nested(mylist):
"""Thin wrapper around flatten."""
return [x for x in flatten(mylist)]
| true |
f435655c8e051070c5672f122d0d6af36d29f28e | Anoopsmohan/Project-Euler-solutions-in-Python | /project_euler/pjt_euler_pbm_9.py | 406 | 4.1875 | 4 | '''A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc. '''
def pythagorean():
for a in xrange(1, 501):
for b in xrange(a+1, 501):
c = 1000 - a -b
if (a*a + b*b == c*c):
return a*b*c
print pythagorean()
| true |
acb00c5ece15950069d9a074de30b7b5e8e634d9 | onyinyealadiume/Count-Primes | /main.py | 523 | 4.15625 | 4 |
# Determine if the input number is prime
def isPrime(n):
for current_number in range(2,n):
# if the input number is evenly divisible by the current number?
if n % current_number == 0:
return False
return True
# Determine how many prime numbers are UNDER the input number
def countPrimes(n):
count_of_primes = 0
for(current_number) in range(2,n):
# check if prime number or not
if isPrime(current_number):
count_of_primes +=1
return count_of_primes
countPrimes(10) | true |
fe2db7b0d45f4bb358389c68557d21680f618b31 | sxdegithub/myPythonStudy | /Study/ds_str_methods.py | 497 | 4.375 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: sx
# 这是一个字符串对象
name = 'Swaroop'
if name.startswith('Swar'):
print('Yes,the string starts with Swar')
if name.startswith(('a', 's')):
print("yes there is a 'S'")
if 'a' in name:
print("Yes ,the string contains character 'a'")
if name.find('war') != -1:
print("Yes,it contains the string 'war'")
delimiter = '_*_'
mylist = ['brazil', 'Russia', 'India', 'China']
print(mylist)
print(delimiter.join(mylist))
| true |
f1e8831044ec44f2cae9076789715eb5682934f5 | prossellob/CodeWars | /duplicate_encoder.py | 721 | 4.15625 | 4 | '''
The goal of this exercise is to convert a string to a new string where each character in the new string is '(' if that character appears only once in the original string, or ')' if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
Examples:
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
'''
def duplicate_encode(word):
a,b,word = [],{},word.lower()
for letter in word:
b[letter] = 0
for letter in word:
b[letter] += 1
for letter in word:
if b[letter] >= 2:
a.append(')')
elif b[letter] < 2:
a.append('(')
return ''.join(a)
| true |
b36649f74f78e09023d0a9db48c12cbd2a4f769a | anoopch/PythonExperiments | /print_test.py | 832 | 4.28125 | 4 | # Pass it as a tuple:
name = "Anoop CH"
score = 9.0
print("Total score for %s is %s" % (name, score))
# Pass it as a dictionary:
print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
# There's also new-style string formatting, which might be a little easier to read:
# Use new-style string formatting:
print("Total score for {} is {}".format(name, score))
# Use new-style string formatting with numbers (useful for reordering or printing the same one multiple times):
print("Total score for {0} is {1}".format(name, score))
# Concatenate strings:
print("Total score for " + str(name) + " is " + str(score))
# The clearest two, in my opinion: Just pass the values as parameters:
print("Total score for", name, "is", score)
# Use the new f-string formatting in Python 3.6:
print(f'Total score for {name} is {score}')
| true |
b74d7bd074117eac432209dd90ec6117e890b53d | anoopch/PythonExperiments | /Lab_Ex_23_Factorial_Of_Number_while.py | 509 | 4.4375 | 4 | # Program to Factorial of a number
number = int(input('Enter an Integer number : '))
if number < 0:
print("Sorry, factorial does not exist for negative numbers")
elif number == 0 or number == 1:
print("The factorial of {0} is {1}".format(number, number))
else:
i = 1
factorial = 1
while i < number + 1:
factorial = factorial * i
i += 1
# for i in range(1, number + 1):
# factorial = factorial * i
print("The factorial of {0}, is {1}".format(number, factorial))
| true |
5ca09128a7e6200bc5df8a766fa1f86f739c8db4 | anoopch/PythonExperiments | /Lab_Ex_16_celcius_to_farenheit.py | 223 | 4.40625 | 4 | # Convert celcius to farenheit
celcius=float(input('Enter the temperature in Celcius : '))
farenheit=(celcius*(9/5)) + 32
print('The temperature equivalent of {} Celcius is {} Farenheit'.format(celcius, farenheit))
| true |
d1f09f88680f085e6666fefee0f6304430579d42 | MeghaGajare/Algorithms | /String/reverse a string.py | 247 | 4.3125 | 4 | #reverse a string
string = input()
a = string[::-1]
print('reverse string: ',a)
# or
b = ''
for i in string:
b=i+b
print(b)
#check palindrome string
if(a == string):
print("It is a palindrome.")
else:
print("It is not palindrome.")
| true |
ac34b15de951625480c670d0ce60bd3586b77931 | ddh/leetcode | /python/perform_string_shifts.py | 1,958 | 4.1875 | 4 | """
You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]:
direction can be 0 (for left shift) or 1 (for right shift).
amount is the amount by which string s is to be shifted.
A left shift by 1 means remove the first character of s and append it to the end.
Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.
Return the final string after all operations.
Example 1:
Input: s = "abc", shift = [[0,1],[1,2]]
Output: "cab"
Explanation:
[0,1] means shift to left by 1. "abc" -> "bca"
[1,2] means shift to right by 2. "bca" -> "cab"
Example 2:
Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]
Output: "efgabcd"
Explanation:
[1,1] means shift to right by 1. "abcdefg" -> "gabcdef"
[1,1] means shift to right by 1. "gabcdef" -> "fgabcde"
[0,2] means shift to left by 2. "fgabcde" -> "abcdefg"
[1,3] means shift to right by 3. "abcdefg" -> "efgabcd"
Constraints:
1 <= s.length <= 100
s only contains lower case English letters.
1 <= shift.length <= 100
shift[i].length == 2
0 <= shift[i][0] <= 1
0 <= shift[i][1] <= 100
"""
from typing import List
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
right_shifts_count = 0
left_shifts_count = 0
for step in shift:
if step[0] == 0:
left_shifts_count += step[1]
else:
right_shifts_count += step[1]
shift_count = (right_shifts_count - left_shifts_count)
if shift_count == 0:
return s
elif shift_count > 0:
return ''.join([s[i - (shift_count % len(s))] for i, letter in enumerate(s)])
else:
return ''.join([s[(i - shift_count) % len(s)] for i, letter in enumerate(s)])
# Driver
# print(Solution().stringShift("abcdefg", [[1,1],[1,1],[0,2],[1,3]])) # "efgabcd"
print(Solution().stringShift("wpdhhcj", [[0,7],[1,7],[1,0],[1,3],[0,3],[0,6],[1,2]])) # "hcjwpdh" | true |
d72c8326f3567ad955f46f848e232247bf1b573a | ddh/leetcode | /python/shortest_word_distance.py | 1,834 | 4.125 | 4 | """
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
"""
# Idea: Keep track of two indexes, one for encountering the first word, the other for the second word.
# We then iterate through the array just once, updating the index of each word we encounter.
# Whenever we encounter the word, we see if the currently held shortest_distance is better, then store it.
# Time complexity should be O(n) as we iterate through the list of words just the one time. O(1) space, no additional space created.
from typing import List
class Solution:
def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:
# Keep track of the indexes where we find word1, word2
word1_index = -1
word2_index = -1
shortest_distance = len(words) - 1 # The max distance if words were at both ends of the list
for i, word in enumerate(words):
if word == word1:
word1_index = i
if word2_index >= 0:
shortest_distance = min(abs(word1_index - word2_index), shortest_distance)
if word == word2:
word2_index = i
if word1_index >= 0:
shortest_distance = min(abs(word1_index - word2_index), shortest_distance)
return shortest_distance
# Driver:
print(Solution().shortestDistance(["practice", "makes", "perfect", "coding", "makes"], "coding", "practice")) # 3
print(Solution().shortestDistance(["practice", "makes", "perfect", "coding", "makes"], "makes", "coding")) # 1 | true |
a0157e9d059f448f30af6ddb873b9eef438ec171 | CalebKnight10/CS_260_4 | /factorial_recursive.py | 276 | 4.34375 | 4 | # A factorial is multiplying our num by the numbers before it
# Ex, 5 would be 5x4x3x2x1
def factorial(num):
if num <= 1:
return num
else:
return factorial(num - 1) * num
def main():
print(factorial(9))
if __name__ == '__main__':
main()
| true |
010fb27996b2a30bffb70755ba9c86266215f4b2 | Tradd-Schmidt/CSC236-Data-Structures | /T/T12/count_evens.py | 2,009 | 4.34375 | 4 | # -------------------------------------------------------------------------------
# Name: count_evens.py
# Purpose: This program is designed to use recursion to count the number of
# even numbers are read from a file. This sequence is stored in a
# linked list.
#
# Created: 08/10/2014
# -------------------------------------------------------------------------------
from ListNode import ListNode
from LList import LList
# recursive function to count the number of even numbers in this linked list.
def count_evens(currentNode, maximum):
"""
Keeps track of the largest item of the linked list and returns it
:param currentNode: Current node being checked
:param maximum: The maximum value so far
:return: the maximum value
"""
if currentNode == None:
return maximum
else:
if currentNode.item > maximum:
maximum = currentNode.item
return count_evens( currentNode.link, maximum)
else:
return count_evens(currentNode.link, maximum)
def read_numbers_return_list( ):
'''preconditions: none
postconditions: the numbers in the file with the name asked by the user will
be placed into a linked list and returned.'''
filename = input("What is the name of the file?")
file = open(filename, "r")
# get the list of strings from the file. This list will need to be converted to
# a list of numbers in a
stringList = file.read().split()
file.close()
# time to create an integer version of the numbers list
numberList = []
for item in stringList :
numberList.append(int(item))
# Now create a linked list version of this number sequence
created_list = LList(numberList)
return created_list
def main():
numbersList = read_numbers_return_list()
print( count_evens( numbersList.head, numbersList.head.item) )
if __name__ == '__main__':
main()
| true |
e8e7d5b2eac6d3937b518a55d0219d2951b2a784 | Tradd-Schmidt/CSC236-Data-Structures | /A/A08/LinkedLIst_smdriver.py | 2,037 | 4.125 | 4 | # -------------------------------------------------------------------------------
# Name: LinkedList_smdriver.py
# Purpose: Rudimentary driver for the LinkedList class.
#
# Edited by: Tradd Schmidt on 9/21/17
# -------------------------------------------------------------------------------
from LList import LList
def main():
print("Make a linked list in honor of Donna Schmidt")
mom = LList((8, 21, 1962)) # Named after Donna Schmidt, my mom because she is the strongest willed person I know
print("Make a linked list in honor of Jim Carrey")
truman = LList((6, 17, 1962)) # Named after Jim Carrey because he is always his true with himself and others about who he is
print("Make a linked list for a fictional character")
fictional = LList(((8 + 6) // 2, (21 + 17) // 2, 1962)) # Fictional persons birthday
# Printing the Birthdays
# ---------------------------------------------------------------------------------------
print("\n")
print("Printing Donna's birthday")
for item in mom:
print(str(item) + " ",)
print("\n")
print("Printing Jim Carrey's birthday")
for item in truman:
print(str(item) + " ",)
print("\n")
print("Printing the fictional character's birthday")
for item in fictional:
print(str(item) + " ",)
# Changing the year of the fictional character
# ---------------------------------------------------------------------------------------
year = fictional._find(len(fictional) - 1)
year.item += 100
print("\n")
print("Printing the fictional character's revised birthday")
for item in fictional:
print(str(item) + " ", )
# Deleting the date of the fictional character's birthday
# ----------------------------------------------------------------------------------------
fictional.__delitem__(1)
print("\n")
print("Printing the fictional character's revised birthday")
for item in fictional:
print(str(item) + " ", )
main()
| true |
92fb30404522bc211979ebf91b8c33d55c91be96 | gayatri-p/python-stuff | /challenge/games/guess.py | 541 | 4.21875 | 4 | import random
start = 0
end = 100
n = random.randint(start, end)
tries = 1
print('-----Guessing Game-----')
print(f'The computer has guessed an integer between {start} and {end}.')
guess = int(input('Guess the number: '))
while guess != n:
tries += 1
if n > guess:
print('The number is larger than you think.')
elif n < guess:
print('The number is smaller than you think.')
guess = int(input('Guess again: '))
print(f'Yes the number is {n}.')
print(f'You have guessed it correctly in {tries} tries.') | true |
8fcc321aa45145737d6343a0387637a586a20d01 | ramiro-arias/HeadPython | /HeadPython/Chapter02/p56.py | 732 | 4.15625 | 4 | # Source: Chapter01/The Basics/p56.py
# Book: Head First Python (2nd Edition) - Paul Barry
# Name in the book: Working with lists
# Eclipse project: HeadFirstPython
'''
Created on May 2, 2019
@author: ramiro
'''
# We will use the shell to first define a list called vowels, then check to see if
# each letter in a word is in the vowels list. Let us define a list of vowels:
vowels = ['a', 'e', 'i', 'o', 'u']
# With vowels defined, we now need a word to check, so let’s create a
# variable called word and set it to "Milliways":
word = 'Milliways'
print ('Vowels contained in', word)
# We can check if one object is contained within a collection with operator 'in'
for letter in word:
if letter in vowels:
print (letter) | true |
6e3542bf51343ab56329a32dfc76cbe504f55bf0 | dhking1/PHY494 | /03_python/heavisidefunc.py | 414 | 4.1875 | 4 | # Heaviside step function
def heaviside(x):
"""Heaviside step function
Arguments
---------
x = float
input value
Returns
---------
Theta : float
value of heaviside
"""
theta = None
if x < 0:
theta = 0.
elif x == 0:
theta = 0.5
else:
theta = 1.
return theta
x = 3
theta = heaviside(x)
print("heaviside", str(x), "|:", str(theta))
| true |
e1a778777bd164df6a46519e74ee6f35d84fc22b | missingcharacter/janky-stuff | /python/rename_trim_multiple_spaces.py | 515 | 4.21875 | 4 | #!/usr/bin/env python3
# Python3 code to rename multiple
# files in a directory or folder
# importing os module
import os
import re
# Function to rename multiple files
def main():
for filename in os.listdir("./"):
src = filename
dst = re.sub(' +', ' ', filename)
# rename() function will
# rename all the files
print(f"filename before {src} after {dst}")
os.rename(src, dst)
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
| true |
1fc26b0beb9013585a58985916541dcc1b95f3e1 | Tanges/assignment5_1-python | /sequence.py | 746 | 4.25 | 4 | n = int(input("Enter the length of the sequence: ")) # Do not change this line
#The sequence for the algorythm is 1, 2, 3, 6, 11, 20, 37, ___, ___, ___, …
#Idea: i + 2 power of i
#Algorithm adds up last 3 inputs and returns the sum of it
#Make a list with first 3 inputs which are already determined
#Print out the first 3 on the screen and then use a storage variable to keep the first 3 inputs
listi = [1,2,3]
for i in range(0, n):
if i < 3: #Check through the list and print out first 3 numbers
print(listi[i])
else: #Print out the rest until lenght of the sequence is finished
storage = sum(listi)
listi = listi[1:] + [storage] #Adds last number in list and adds it to storage variable
print(storage) | true |
a37ffbff5331c3c7e1741073bec9c177ec4ac244 | Sean-Stretch/CP1404_Pracs | /Prac_01/shop_calculator.py | 876 | 4.34375 | 4 | """
The program allows the user to enter the number of items and the price of each different item.
Then the program computes and displays the total price of those items.
If the total price is over $100, then a 10% discount is applied to that total before the amount is displayed on the screen.
"""
total_cost = 0
valid_input = False
while valid_input is False:
number_of_items = int(input("Enter number of items: "))
if number_of_items > 0:
valid_input = True
else:
print("Please enter a valid number")
for i in range(1, number_of_items + 1):
cost = float(input("Please enter price of item: $"))
total_cost += cost
if total_cost > 100:
print("Total Price for {0:} items is ${1:.2f}".format(number_of_items, total_cost - (total_cost * 0.1)))
else:
print("Total Price for {0:} items is {1:.2f}".format(number_of_items, total_cost))
| true |
327197a5ee25edcae773ad77af22eca04e35495b | nikhilbagde/Grokking-The-Coding-Interview | /topological-sort/examples/tasks-scheduling/python/MainApp/app/mainApp.py | 2,454 | 4.125 | 4 | from collections import defaultdict
class MainApp:
def __init__(self):
pass
'''
There are ‘N’ tasks, labeled from ‘0’ to ‘N-1’.
Each task can have some prerequisite tasks which need to be completed before it can be scheduled.
Given the number of tasks and a list of prerequisite pairs, find out if it is possible to schedule all the tasks.
Example 1:
Input: Tasks=3, Prerequisites=[0, 1], [1, 2]
Output: true
Explanation: To execute task '1', task '0' needs to finish first. Similarly, task '1' needs to finish
before '2' can be scheduled. A possible scheduling of tasks is: [0, 1, 2]
Example 2:
Input: Tasks=3, Prerequisites=[0, 1], [1, 2], [2, 0]
Output: false
Explanation: The tasks have cyclic dependency, therefore they cannot be scheduled.
Example 3:
Input: Tasks=6, Prerequisites=[2, 5], [0, 5], [0, 4], [1, 4], [3, 2], [1, 3]
Output: true
Explanation: A possible scheduling of tasks is: [0 1 4 3 2 5]
'''
@staticmethod
def run(req, tasks):
# turn req into req_graph
req_graph = defaultdict(list)
for (target, dependency) in req:
req_graph[target].append(dependency)
if dependency not in req_graph:
req_graph[dependency] = []
print(MainApp().run(req=[
(0, 1),
(1, 2),
(2, 0)
], tasks=3))
print("\n====================")
print(MainApp().run(req=[
(0, 1),
(1, 2)
], tasks=3))
print("\n====================")
print(MainApp().run(req=[
(2, 5),
(0, 5),
(0, 4),
(1, 4),
(3, 2),
(1, 3)
], tasks=3))
# def detect_cycle(req):
# # turn req into req_graph
# req_graph = defaultdict(list)
# for (target, dependency) in req:
# req_graph[target].append(dependency)
# if dependency not in req_graph:
# req_graph[dependency] = []
#
# def dfs(graph, start, visited=set()):
# if start not in visited:
# visited.add(start)
# for neighbour in graph[start]:
# if neighbour in visited:
# return False
# return dfs(graph, neighbour, visited)
# return True
#
# for node in req_graph:
# print(dfs(req_graph, node, set()))
# break
#
#
# req = [
# (0, 1),
# (1, 2)
# ]
# detect_cycle(req)
#
#
# req = [
# (0, 1),
# (1, 2),
# (2, 0)
# ]
# detect_cycle(req)
| true |
ca140ef57f7b1a6616faf90660071bf1e276fa9a | nikhilbagde/Grokking-The-Coding-Interview | /sliding-window/examples/no_repeat_substring/python/MainApp/app/mainApp.py | 1,272 | 4.15625 | 4 | import sys
class MainApp:
def __init__(self):
pass
'''
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""
Output: 0
'''
def run(self, s: str) -> int:
window_start = 0
longest_substring_length = float('-inf')
unique_character_set = set()
for window_end in range(len(s)):
if s[window_end] in unique_character_set:
unique_character_set.discard(s[window_start])
window_start += 1
else:
unique_character_set.add(s[window_end])
window_end += 1
longest_substring_length = max(
longest_substring_length, len(unique_character_set))
return (longest_substring_length, 0)[len(s) == 0]
| true |
aac73ba75af9ca633c06abf6d78725b838e55bfc | nikhilbagde/Grokking-The-Coding-Interview | /two-pointers/examples/subarrays-with-products-less-than-k/python/MainApp/app/mainApp.py | 1,235 | 4.125 | 4 | class MainApp:
def __init__(self):
pass
'''
Your are given an array of positive integers nums.
Count and print the number of (contiguous) subarrays
where the product of all the elements in the subarray is less than k.
Example 1:
Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
```
TPFA
10 5 2 6
^ ^
product = 60 == 100
subarray_count = [10] [5] [10 5] [2] [5 2] [6] [5 2 6] [2 6]
window_start = 0
window_end = 3
```
'''
def run(self, nums, target) -> int:
window_start = 0
if target <= 1:
return 0
subarray_count = 0
product = 1
for window_end in range(len(nums)):
product *= nums[window_end]
while product >= target:
product /= nums[window_start]
window_start += 1
subarray_count += window_end - window_start + 1
return subarray_count
print(MainApp().run([10, 5, 2, 6], 100))
| true |
c957a225ec65cf3aad4a51a334f7d241f51c866d | nikhilbagde/Grokking-The-Coding-Interview | /tree-bfs/examples/reverse-level-order-traversal/python/MainApp/app/mainApp.py | 1,853 | 4.1875 | 4 | from queue import Queue
class FifoDataStructure:
def __init__(self):
self.stack = list()
def push(self, e):
self.stack.insert(0, e)
def get(self):
if len(self.stack) == 0:
return None
self.stack.pop(0)
def get_stack(self):
return self.stack
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class MainApp:
def __init__(self):
pass
'''
Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values.
(i.e., from left to right, level by level from leaf to root).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
'''
@staticmethod
def run(root):
if not root:
return []
else:
q = Queue()
q.put((root, 0))
current_level = 0
nodes_in_corresponding_levels = FifoDataStructure()
nodes_in_current_level = list()
while not q.empty():
(node, level) = q.get()
if current_level == level:
nodes_in_current_level.append(node.val)
else:
nodes_in_corresponding_levels.push(nodes_in_current_level)
nodes_in_current_level = [node.val]
current_level += 1
if node.left:
q.put((node.left, level + 1))
if node.right:
q.put((node.right, level + 1))
nodes_in_corresponding_levels.push(nodes_in_current_level)
return nodes_in_corresponding_levels.get_stack()
| true |
957472acc148e3088ae2dc0a453c783065ff0dd4 | nikhilbagde/Grokking-The-Coding-Interview | /fast-and-slow-pointers/examples/middle-of-linked-list/python/MainApp/app/mainApp.py | 1,085 | 4.125 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MainApp:
def __init__(self):
pass
'''
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.nxt.val = 4, ans.nxt.nxt.val = 5, and ans.nxt.nxt.nxt = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
'''
@staticmethod
def run(head):
slow = fast = head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
return slow.val
| true |
82e2a58a20f4e9896cc97e34af2074e55baf6ccb | imtiazraqib/Tutor-CompSci-UAlberta | /CMPUT-174-Fa19/guess-the-word/Guess_The_Word_V1.py | 1,410 | 4.28125 | 4 | #WordPuzzle V1
#This version plans to implement the ability for the program to select a word from a limited word list
#The program will then remove the first letter and replace it with an _ and the player can make a guess
#if correct, the program congratulates. if not then condolensces are sent
#Functions such as multiple guesses and multiple _ in place of letters will be absent
import random
def main():
#This prints the instructions to the game
instructions_file = open("instructions Wordpuzzle.txt", "r")
file_contents = instructions_file.read()
instructions_file.close()
print(file_contents)
#the word list and the method used to delete the first letter
wordbank = ['Mango', 'Banana', 'Watermelon', 'Kiwi']
random_word = random.choice(wordbank)
rest_of_random = random_word[1:]
guess = '_' + rest_of_random
#prompts user for a guess
print("The answer so far is " )
print(guess)
player_input = input("Guess the letter: ")
#method used to remove all but the first letter in order to match player input
first_of_random = random_word[:1]
if player_input.lower() == first_of_random.lower():
print('Good job! You found the word ' + random_word + '!')
else:
print('Not quite, the correct word was ' + random_word + '. Better luck next time')
input('Press enter to end the game.')
main() | true |
15a6ed0d48f867c9163defbe6f25428091c0e2cd | Nandi22/hardway3 | /ex18.py | 697 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 18:45:33 2019
@author: ferna
"""
# this one is like your scripts with argv
def print_two(*args):# defines what function does
arg1, arg2 = args # asks for arguments
print (f"arg1: {arg1}, arg2: {arg2}")
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):# args inside ()
print(f"arg1: {arg1}, arg2: {arg2}")
# this just takes one argument
def print_one(arg1):
print(f"arg1: {arg1}")
# this one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none() | true |
dac7d2d70f4736f453f5b446453120568896df33 | jitendrabhamare/Problems-vs-Algorithms | /Sort_012.py | 1,364 | 4.25 | 4 | # Dutch National Flag Problem
# Author: Jitendra Bhamare
def sort_012(list_012):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args: list_012(list): List to be sorted
"""
next_pos_0 = 0
next_pos_2 = len(list_012) - 1
front_index = 0
while front_index <= next_pos_2:
if list_012[front_index] == 0:
list_012[front_index] = list_012[next_pos_0]
list_012[next_pos_0] = 0
next_pos_0 += 1
front_index += 1
elif list_012[front_index] == 2:
list_012[front_index] = list_012[next_pos_2]
list_012[next_pos_2] = 2
next_pos_2 -= 1
else:
front_index += 1
return list_012
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
## Edge cases
test_function([]) # Empty Array
test_function([0]) # Array with one element
test_function([2, 0]) # Array with 2 elements
test_function([2, 1, 0]) # Array with 3 elements
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
| true |
10e5e22683d76cd7f02845a05047643950bfa2d2 | Vivekagent47/data_structure | /Python/doubly_linked_list.py | 2,923 | 4.3125 | 4 | '''
In this program wi impliment the Doubly LinkedList
here we can do 4 differnt operations:
1- Insert Node at Beginning
2- Insert Node at End
3- Delete the node you want
4- Print List
'''
class Node:
def __init__(self, data, next = None, previous = None):
self.data = data
self.next = next
self.previous = previous
class LinkedList:
def __init__(self):
self.head = None
def insertNodeBeg(self, data):
if self.head == None:
newNode = Node(data)
self.head = newNode
else:
newNode = Node(data)
self.head.previous = newNode
newNode.next = self.head
self.head = newNode
def insertNodeEnd(self, data):
newNode = Node(data)
temp = self.head
while(temp.next != None):
temp = temp.next
temp.next = newNode
newNode.previous = temp
def deleteNode(self, data):
temp = self.head
if(temp.next != None):
if(temp.data == data):
temp.next.previous = None
self.head = temp.next
temp.next = None
return
else:
while(temp.next != None):
if(temp.data == data):
break
temp = temp.next
if(temp.next):
temp.previous.next = temp.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
else:
temp.previous.next = None
temp.previous = None
return
if (temp == None):
return
def printList(self):
temp = self.head
if self.head == None:
print("Empty List")
else:
print("List : ", end=" ")
while temp is not None:
print(temp.data, end=" ")
if temp.next:
print("-> ", end="")
temp = temp.next
print()
if __name__ == "__main__":
lst = LinkedList()
while True:
print("Select the any option")
print("[1] Insert Node at Beginning of List")
print("[2] Insert Node at End of List")
print("[3] Delete Node")
print("[4] Print List")
print("[5] Exit")
print("\n")
i = int(input())
print("\n")
if i == 1:
lst.insertNodeBeg(input("Enter data you want to insert: "))
elif i == 2:
lst.insertNodeEnd(input("Enter data you want to insert: "))
elif i ==3:
lst.deleteNode(input("Enter data you want to delete: "))
elif i == 4:
lst.printList()
elif i == 5:
break
print("\n") | true |
6da9eac046121212d554fa6500eb2da6cd2be4b0 | Rhornberger/Python | /python_folder/roll_dice.py | 1,235 | 4.125 | 4 | '''
Rolling dice with gui interface using tkinter
written by Rhornberger
last updated nov 12 2019
'''
# import library
from tkinter import *
# create the window size and welcome text
window = Tk()
window.title('Welcome to the D20 roller!')
lbl = Label(window, text = 'Welcome!', font =('arial', 20))
lbl.grid(column = 0, row = 0)
window.geometry('300x200')
# creat a function for the button to do something
def clicked():
lbl.configure(text = 'Button was clicked!!')
btn = Button(window, text = 'Click to Roll', command = clicked, bg = 'black', fg = 'red')
btn.grid(column = 1, row = 0)
# create check buttons for type of die to use
rad1 = Radiobutton(window, text = 'D20', value = 1)
rad2 = Radiobutton(window, text = 'D12', value = 2)
rad3 = Radiobutton(window, text = 'D10', value = 3)
rad4 = Radiobutton(window, text = 'D8', value = 4)
rad5 = Radiobutton(window, text = 'D6', value = 5)
rad6 = Radiobutton(window, text = 'D4', value = 6)
rad7 = Radiobutton(window, text = 'D%', value = 7)
rad1.grid(column = 0, row = 1)
rad2.grid(column = 1, row = 1)
rad3.grid(column = 2, row = 1)
rad4.grid(column = 3, row = 1)
rad5.grid(column = 4, row = 1)
rad6.grid(column = 5, row = 1)
rad7.grid(column = 6, row = 1)
window.mainloop() | true |
02e0f413935a045783423ee27aa57c71acb3551c | JaredBigelow/Python-Projects | /Nesting, Div, and Mod/Star.py | 2,516 | 4.1875 | 4 | #Author: Jared Bigelow
#Date: February 27 2015
#Purpose: To create star patterns based on inputted type and size
#Input: Type, size
#Output: Star Pattern
#Star Patterns
################################################################################
import math
repeat = "Y"
while repeat == "Y" or repeat == "y":
print("Choose your type:(1:Square 2:Triangle 3:Hollow Square 4:Hollow Triangle)")
patternType = int (input ("Type:"))
while patternType < 1 or patternType > 4:
patternType = int (input ("Error, enter a number between 1 and 4:"))
print("Choose your size. (1-30)")
patternSize = int (input ("Size:"))
while patternSize < 1 or patternSize > 30:
patternSize = int (input ("Error, enter a size between 1 and 30:"))
if patternType == 1:
print ()
for star in range (1, patternSize + 1):
print ("*","", end="")
for star in range (1, patternSize):
print ("*","", end="")
print ()
elif patternType == 2:
number = 0
print ()
for star in range (1, patternSize + 1):
number = number + 1
for star in range (1, number + 1):
print ("*","", end="")
print ()
elif patternType == 3:
print ()
for star in range (1, patternSize + 1):
print ("*","", end="")
print ()
for star in range (1, patternSize - 1):
print ("*","", end="")
for star in range (2, patternSize):
print (" ", end="")
print ("*","", end="")
print ()
for star in range (1, patternSize + 1):
print ("*","", end="")
print ()
elif patternType ==4:
numberOne = 0
numberTwo = 0
print ()
for star in range (1, 3):
numberOne = numberOne + 1
for star in range (1, numberOne + 1):
print ("*","", end="")
print ()
for star in range (1, patternSize - 2):
print ("*","", end="")
for star in range (2, patternSize - (patternSize - 3)):
numberTwo = numberTwo + 1
for star in range (1, numberTwo + 1):
print (" ", end="")
print ("*","", end="")
print ()
for star in range (1, patternSize + 1):
print ("*","", end="")
print ()
print ()
repeat = input ("Do another? (Y/N):")
| true |
ff9baf913c50c07d3b7805702505cbf78d01bde7 | chelseavalentine/Courses | /Intro-Programming/[10]AnotherSortOfSort.py | 647 | 4.1875 | 4 | """
Assignment Name: Another Sort of Sort
Student Name: Chelsea Valentine (cv851)
"""
import random
#ask for input & keep the user in a loop until they type 'done'
while True:
n = int(input("Enter an integer to create a random list, or type 'done' to finish: "))
#check whether user entered 'done' & define the random list
if n == 'done':
break
randomlist=[]
#show create a list of random values
for i in range(0,n):
randomlist.append(random.randint(1,3*n))
i += 1
print("The list with", n, "random values is:", randomlist)
print("When we sort that list, we get:", sorted(randomlist))
print()
| true |
4602412de2c9a2a876149e9ed2fb249a789b3413 | ShazamZX/Data-Structure-and-Algorithm | /Array Questions/PalinMerge.py | 1,084 | 4.3125 | 4 | """
Given an array of positive integers. We need to make the given array a ‘Palindrome’. The only allowed operation is”merging” (of two adjacent elements). Merging two adjacent elements means replacing them with their sum. The task is to find the minimum number of merge operations required to make the given array a ‘Palindrome’.
To make any array a palindrome, we can simply apply merge operation n-1 times where n is the size of the array (because a single-element array is always palindromic, similar to single-character string). In that case, the size of array will be reduced to 1. But in this problem, we are asked to do it in the minimum number of operations.
"""
def minMerge(arr):
ans = 0
n = len(arr)
l = 0
r = n-1
while(l<=r):
if arr[l] == arr[r]:
l+=1
r-=1
elif arr[l]<arr[r]:
l+=1
arr[l]+=arr[l-1]
ans+=1
else:
r-=1
arr[r]+=arr[r+1]
ans+=1
return ans
#driver code
arr = [1, 4, 5, 9, 1]
print(minMerge(arr)) | true |
8cc89bb11638aa49abdcfd1c52b5e8b983bd0131 | ShazamZX/Data-Structure-and-Algorithm | /Array Questions/ZeroSumSubA.py | 609 | 4.125 | 4 | #check if an array has a any subarray whose sum is zero (Prefix sum method)
#the idea is that we calculate prefix sum at every index, if two prefix sum are same then the subarray between those two index have sum as zero
def subSum(arr):
prefix_sum = set()
prefix_sum_till_i = 0
for i in range(len(arr)):
prefix_sum_till_i+=arr[i]
if prefix_sum_till_i == 0 or prefix_sum_till_i in prefix_sum:
return True
prefix_sum.add(prefix_sum_till_i)
return False
#driver code
arr = [-3, 2, 3, 1, 6]
print(subSum(arr))
arr1 = [4, 2, -3, 1, 6]
print(subSum(arr1))
| true |
9cfd7b4f89b93e5af2765e5c60e3eb0fb58db748 | Mehedi-Bin-Hafiz/Python-OOP | /classes/creating_a_class.py | 2,156 | 4.8125 | 5 | # Making an object from a class is called instantiation, and you work with
# instances of a class.
#### when we write function in a class then it called method
# ((Methods are associated with the objects of the class they belong to.
# Functions are not associated with any object. We can invoke a function just by its name.
# Functions operate on the data you pass to them as arguments.))
#### Variables that are accessible through instances like this are called attributes.
###The __init__() method at is a special method
#Python runs automatically whenever we create a new instance of a class
def call_able():
pass
class Dog():
"""A simple attempt to model a dog."""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name #Variables that are accessible through instances like this are called attributes.
self.age = age
##Any variable prefixed with self is available to every method in the class, and we’ll also be
##able to access these variables through any instance created from the class.
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command."""
print(self.name.title() + " rolled over!")
### __init___###
#it must be included in the definition because when Python calls this __init__() method later (to create an
#instance of Dog), the method call will automatically pass the self argument.
#### VVI####
#Every method call associated with a class automatically passes self, which
#is a reference to the instance itself; it gives the individual instance access to
#the attributes and methods in the class.
if __name__ == '__main__':
my_dog = Dog('willie', 6) #When Python reads this line, it calls the __init__() method in Dog with the arguments 'willie' and 6.
#We store that instance in the variable my_dog.
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
| true |
0f4d4cb8f7f45575b5ba4d04757db25a09d0c79e | DrFeederino/python_scripts | /password_randomizer.py | 2,820 | 4.28125 | 4 | """
This module to randomize passwords for your own or user's usages.
Supports for custom or default (8-16) lengths of passwords. Can be used
both as a standalone program or imported to your project.
Example:
For default length:
$ python3 password_randomizer.py
For a variable length:
$ python3 password_randomizer.py 20
Note: if a variable length is not an integer, it would fallback
to either default length (if used as a standalone program) or
0 if imported.
"""
import random, string, sys
list_of_symbols = list(string.ascii_letters + string.digits)
def check_int(num):
"""Check if arguement is integer.
Arg:
num (int): The only arguement.
Returns:
bool: The return value. True if num is indeed an integer, False otherwise.
"""
if num is not None:
try:
int(num)
return True
except ValueError:
return False
else:
return False
def randomize_password():
"""Randomizes password for default length, which is a
random range from 8 to 16.
Returns:
pswd (str): the string of password.
"""
pswd = ""
pswd_length = random.randrange(8, 17)
for random_char in range(pswd_length):
rnd = random.randrange(len(list_of_symbols))
pswd += list_of_symbols[rnd]
return pswd
def randomize_password_custom(length=0):
"""Randomizes password for variable length, which is by default 0.
Returns:
pswd (str): the string of password.
"""
pswd = ""
if check_int(length):
for random_char in range(length):
rnd = random.randrange(len(list_of_symbols))
pswd += list_of_symbols[rnd]
return pswd
else:
print("Length is not an int.")
raise TypeError
def write_to_file(password="", txt="password.txt"):
"""Writes a string to the file. Passowrd and txt arguements,
by default, are set to empty string and password.txt. Can be modified
during call.
Args:
password (str): the string arguement.
txt (str): the string arguement;
"""
with open(txt, 'w') as f:
f.write(password + "\n")
def main (length=None):
"""Main function to tie every part of module if it is used a standalone
program. It checks the length if it was set, otherwise it is None. Then
it randomizes the password and writes it to a file accordingly.
"""
if check_int(length) and int(length) > 0:
pswd = randomize_password_custom(int(length))
else:
print("Length wasn't recognized as a positive int, fallback to default randomizing.")
pswd = randomize_password()
write_to_file(pswd)
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1])
else:
main()
| true |
8a4dcdb0d69d1c5ef779637dab859e3c68bde45f | Ameliarate16/python-programming | /unit-2/homework/highest.py | 220 | 4.28125 | 4 | #Given a list of numbers, find the largest number in the list
num_list = [1, 2, 3, 17, 5, 9, 13, 12, 11, 4]
highest = num_list[0]
for number in num_list:
if number > highest:
highest = number
print(highest) | true |
180727f1c1ed8730bcf31e95b5b36409fe7da25d | Ameliarate16/python-programming | /unit-2/functions.py | 905 | 4.15625 | 4 | '''
def add_two():
result = 5 + 5
print(result)
#passing arguments
def add_two(a, b):
result = a + b
print(result)
#returning the value
def add_two(a, b):
result = a + b
return result
print(add_two(3, 10))
'''
#write a function that returns the sum of the integers in a list
def sum_list(a_list):
running_sum = 0
for num in a_list:
running_sum += num
return running_sum
#print(sum_list([1,-2,3,4,5]))
# write a function that reverses a string
def rev_string(my_string):
reverse = ""
for char in my_string:
reverse = char + reverse
return reverse
#write a function that finds the intersection of two lists
def intersect_list(list_1, list_2):
intersection = []
for item in list_1:
if item in list_2:
intersection.append(item)
return intersection
print(intersect_list([1,2,3,4,5,"c"],[12,4,1,"c",180,3])) | true |
bd947bf7410ca64c210a42e5a278aada8b949131 | HEroKuma/leetcode | /1005-univalued-binary-tree/univalued-binary-tree.py | 1,029 | 4.21875 | 4 | # A binary tree is univalued if every node in the tree has the same value.
#
# Return true if and only if the given tree is univalued.
#
#
#
# Example 1:
#
#
# Input: [1,1,1,1,1,null,1]
# Output: true
#
#
#
# Example 2:
#
#
# Input: [2,2,2,5,2]
# Output: false
#
#
#
#
#
# Note:
#
#
# The number of nodes in the given tree will be in the range [1, 100].
# Each node's value will be an integer in the range [0, 99].
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
set_ = set()
def unique(root, set_):
if root is None:
return set_
set_.add(root.val)
set_ = unique(root.left, set_)
set_ = unique(root.right, set_)
return set_
set_ = unique(root, set_)
print(set_)
return True if len(set_) is 1 else False
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.