blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
8ac16563cee211e7c1113b4f1d1b3c48a9bfa826
|
samuelluo/practice
|
/reverse_linked_list/reverse_linked_list.py
| 1,395
| 4.125
| 4
|
"""
Given the head of a singly linked list, reverse it in-place.
"""
# ---------------------------------------------------------
class Node:
def __init__(self, val, next_=None):
self.val = val
self.next_ = next_
def build_linked_list(vals):
head = Node(vals[0])
curr_ = head.next_
prev_ = head
for val in vals[1:]:
curr_ = Node(val)
prev_.next_ = curr_
prev_ = curr_
curr_ = curr_.next_
return head
def print_linked_list(head):
print("[", end="")
while head is not None:
print(head.val, end="")
head = head.next_
if head is not None:
print(", ", end="")
print("]")
def reverse_linked_list(head):
prev_ = None
curr_ = head
next_ = None
while curr_ is not None:
next_ = curr_.next_ # move next
curr_.next_ = prev_ # reverse curr
prev_ = curr_ # move prev
curr_ = next_ # move curr
head = prev_
return head
# ---------------------------------------------------------
vals = [1,2,3,4]
head = build_linked_list(vals)
print_linked_list(head)
head = reverse_linked_list(head)
print_linked_list(head)
head = reverse_linked_list(head)
print_linked_list(head)
print()
vals = [1]
head = build_linked_list(vals)
print_linked_list(head)
head = reverse_linked_list(head)
print_linked_list(head)
print()
| false
|
ae9973f853a110f61828cc9302089d194db527ba
|
lynnemunini/TurtleCrossingGame
|
/player.py
| 788
| 4.1875
| 4
|
from turtle import Turtle
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
UP = 90
# Create a turtle player that starts out at the bottom of the screen and listen for the "Up" keypress to move the
# turtle north
class Player(Turtle):
def __init__(self):
super().__init__()
self.shape("turtle")
self.color("seaGreen")
self.left(90)
self.penup()
self.go_to_start()
def go_up(self):
if self.heading() == UP:
new_y = self.ycor() + MOVE_DISTANCE
self.goto(self.xcor(), y=new_y)
def go_to_start(self):
self.goto(STARTING_POSITION)
def is_at_finish_line(self):
if self.ycor() > FINISH_LINE_Y:
return True
else:
return False
| false
|
620369233f7cb25553ec58246c922b11cca6bbd4
|
msznajder/allen_downey_think_python
|
/ch3_ex.py
| 2,743
| 4.6875
| 5
|
"""
Exercise 1
Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
"""
def right_justify(s):
print((70 - len(s)) * " " + s)
right_justify("abba")
"""
Exercise 2
A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:
def do_twice(f):
f()
f()
Here’s an example that uses do_twice to call a function named print_spam twice.
def print_spam():
print('spam')
do_twice(print_spam)
Type this example into a script and test it.
Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
Copy the definition of print_twice from earlier in this chapter to your script.
Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.
Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.
"""
def print_spam():
print("spam")
def print_anything(val):
print(val)
def do_twice(f, val):
f(val)
f(val)
def do_four(f, val):
do_twice(f, val)
do_twice(f, val)
do_twice(print_anything, "ha!")
do_four(print_anything, "hi!")
"""
Exercise 3
Write a function that draws a grid like the following:
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
Hint: to print more than one value on a line, you can print a comma-separated sequence of values:
print('+', '-')
By default, print advances to the next line, but you can override that behavior and put a space at the end, like this:
print('+', end=' ')
print('-')
The output of these statements is '+ -'.
A print statement with no argument ends the current line and goes to the next line.
"""
def print_square():
print("+" + " -" * 4 + " +" + " -" * 4 + " +")
print("/" + " " * 9 + "/" + " " * 9 + "/")
print("/" + " " * 9 + "/" + " " * 9 + "/")
print("/" + " " * 9 + "/" + " " * 9 + "/")
print("/" + " " * 9 + "/" + " " * 9 + "/")
print("+" + " -" * 4 + " +" + " -" * 4 + " +")
print("/" + " " * 9 + "/" + " " * 9 + "/")
print("/" + " " * 9 + "/" + " " * 9 + "/")
print("/" + " " * 9 + "/" + " " * 9 + "/")
print("/" + " " * 9 + "/" + " " * 9 + "/")
print("+" + " -" * 4 + " +" + " -" * 4 + " +")
print_square()
| true
|
3eeb1e6de050f71bc4ddbfb76b9c4e111f917c8c
|
adekunleayodele/test
|
/venv/Scratch2.py
| 503
| 4.15625
| 4
|
# num1 = float(input("Enter first number: "))
# oper = input("Enter operation: ")
# num2 = float(input("Enter second number: "))
inport pexpert
num1 = input("Enter first number: ")
oper = input("Enter operation: ")
num2 = input("Enter second number: ")
import re
import pexpect
if oper == "+":
print(num1 + num2)
elif oper == "-":
print(num1 - num2)
elif oper == "*":
ans = str(num1) + str(num2)
print(ans)
elif oper == "/":
print(num1 / num2)
else:
print("Invalid operator")
| false
|
3cf8c28b06e50bf446701066958e4e04079e777d
|
evural/hackerrank
|
/cracking/chapter1/is_unique_bitwise.py
| 535
| 4.15625
| 4
|
# 1. Initialize a checker variable to 0
# 2. For each character in the text, shift left bits of 1
# 3. If bitwise AND of this value returns a number other than 0, return False
# 4. Bitwise OR this value with the checker variable
def is_unique(text):
checker = 0
for c in text:
val = ord(c) - ord("a")
shifted = 1 << val
if checker & shifted != 0:
return False
checker = checker | shifted
return True
if __name__ == "__main__":
text = raw_input()
print is_unique(text)
| true
|
70e9075afd47443a993e4be807274629de87329d
|
Kevin8523/scripts
|
/python/python_tricks/class_v_instance_variables.py
| 1,110
| 4.15625
| 4
|
# Class vs Instance Variable Pitfalls
# Two kind of data attributes in Python Objects: Class variables & instance variables
# Class Variables - Affects all object instance at the same time
# Instance Variables - Affects only one object instance at a time
# Because class variables can be “shadowed” by instance variables of the same name,
# it’s easy to (accidentally) override class variables in a way that introduces bugs
class Dog:
num_legs = 4 # <- Class Variable
def __init__(self,name):
self.name = name # <- Instance Variable
jack = Dog('Jack')
jill = Dog('Jill')
jack.name, jill.name
jack.num_legs, jill.num_legs
#Error Example: This will change the Class
Dog.num_legs = 6
jack.num_legs, jill.num_legs
Dog.num_legs = 4
jack.num_legs = 6
jack.num_legs, jack.__class__.num_legs
# Another example of good vs bad implementation
# Good
class CountedObject:
num_instances = 0
def __init__(self):
self.__class__.num_instances += 1
# Bad
# WARNING: This implementation contains a bug
class BuggyCountedObject:
num_instances = 0
def __init__(self):
self.num_instances += 1 # !!!
| true
|
701c22b62921af1315710489d3f1935a28079b07
|
burgonyapure/cc1st_siw
|
/calc.py
| 494
| 4.28125
| 4
|
def f(x):
return {
'+': int(num1) + int(num2),
'-': int(num1) - int(num2),
'*': int(num1) * int(num2),
'/': int(num1) / int(num2)
}.get(x, "Enter a valid operator (+,-,*,/)")
while True:
num1 = input("\nEnter a number,or press a letter to exit\n")
if num1.isdigit() != True:
break
y = input("Enter the operator\n")
num2 = input("Enter the 2nd number\n")
if num2.isdigit() != True:
print("The 2nd NUMBER has to be a NUMBER as well")
continue
print("Result:", f(y))
| true
|
0e76971f4c57f194f05cbccf3803771fa24c9e02
|
hack-e-d/codekata
|
/sign.py
| 216
| 4.25
| 4
|
#to find if positive ,negative or zero
n=int(input())
try:
if(n>0):
print("Positive")
elif(n<0):
print("Negative")
else:
print("Zero")
except:
print("Invalid Input")
| true
|
a8c28d2602f9400fae0baad00135c1612187f4f9
|
tasnimz/labwork
|
/LAB 3.py
| 1,934
| 4.1875
| 4
|
##LAB 3
##TASK 1
##TASK 2
##TASK 3
st = [];
# Function to push digits into stack
def push_digits(number):
while (number != 0):
st.append(number % 10);
number = int(number / 10);
# Function to reverse the number
def reverse_number(number):
# Function call to push number's
# digits to stack
push_digits(number);
reverse = 0;
i = 1;
# Popping the digits and forming
# the reversed number
while (len(st) > 0):
reverse = reverse + (st[len(st) - 1] * i);
st.pop();
i = i * 10;
# Return the reversed number formed
return reverse;
# Driver Code
number = 39997;
# Function call to reverse number
print(reverse_number(number));
# This code is contributed by mits
##TASK 4
def check(my_string):
brackets = ['()', '{}', '[]']
while any(x in my_string for x in brackets):
for br in brackets:
my_string = my_string.replace(br, '')
return not my_string
# Driver code
string = "{[]{()}}"
print(string, "-", "Balanced"
if check(string) else "Unbalanced")
##TASK 5
##TASK 6
from queue import Queue
# Utility function to print the queue
def Print(queue):
while (not queue.empty()):
print(queue.queue[0], end = ", ")
queue.get()
# Function to reverse the queue
def reversequeue(queue):
Stack = []
while (not queue.empty()):
Stack.append(queue.queue[0])
queue.get()
while (len(Stack) != 0):
queue.put(Stack[-1])
Stack.pop()
# Driver code
if __name__ == '__main__':
queue = Queue()
queue.put(10)
queue.put(20)
queue.put(30)
queue.put(40)
queue.put(50)
queue.put(60)
queue.put(70)
queue.put(80)
queue.put(90)
queue.put(100)
reversequeue(queue)
Print(queue)
| true
|
56a99d737a1ae86f6b31a180c5bc9a319bf06461
|
Alenshuailiu/Python-Study
|
/first.py
| 202
| 4.1875
| 4
|
num=input('Enter a number ')
print('The number you entered is ',num)
num=int(num)
if num > 10:
print('you enter a number > 10')
elif num > 5:
print('you enter a number >5 <10')
else:
print('Others')
| true
|
0501089bafc9bc2a488e9c4cf2e0689e26db6ff7
|
jenyton/Sample-Project
|
/operators.py
| 551
| 4.34375
| 4
|
##Checking the enumerate function
print "##Checking the enumerate function##"
word="abcde"
for item in enumerate(word):
print item
for item in enumerate(word,10):
print item
mylist=["apple","mango","pineapple"]
print list(enumerate(mylist))
##Checking the Zip function
print "##Checking the Zip function##"
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]
roll_no = [ 4, 1, 3, 2 ]
marks = [ 40, 50, 60, 70 ]
zipped=zip(name,roll_no,marks)
print "zipped value"
print zipped
print "Unzipped value"
n,r,m=zip(*zipped)
print n
print r
print m
| true
|
915927d8c4cbf8a7e3637850d3b9d87b98be6c29
|
mithrandil444/Make1.2.3
|
/song.py
| 2,076
| 4.28125
| 4
|
#!/usr/bin/env python
"""
This is a Python script that will display the lyrics of a song
"""
# IMPORTS
__author__ = "Sven De Visscher"
__email__ = "sven.devisscher@student.kdg.be"
__status__ = "Finished"
# CONFIGURING I/O
def main():
class Song: # Define class Song
def __init__(self, lyrics):
self.lyrics = lyrics # Deifine lyrics
def sing(self): # Define the song (de_aarde)
return de_aarde.lyrics # Return the song
de_aarde = Song("""De aarde is een grote bol
Met planten en met beestjes vol
En ze draait al heel lang in het rond
En wat ik haast niet kan geloven
Soms lopen we ondersteboven
En toch lijven onze voeten op de grond
En al de wolkjes boven ons
Die lijken wel 1 grote spons
Ze brengen ons de water van de zee
En als de aarde drinken wil
Dan haalt de wind de wolkjes stil
En dan valt al dat water naar beneeeee
Oooh grote wereldbol, ik snap er niet veel van
Het is gewoon een wonder wat je allemaal kan
Je vliegt maar, je vliegt maar zonder te verdwalen
Je draait maar en je draait maar zonder moter of bedalen
Als de zand dan weer verdwijnt
En de zon haar zonnenstraaltjuh schijnt
Lekker op de rug van onze poes
Dan valt aan de andere kant de nacht
Daarist janneke maan die lacht
Naar de ingeslapen kangoeroes!
En als jezuke zijn bedje maakt
En al zijn pluimjes kwijt geraakt
Dan begind het hier bij ons te sneeuwen
Toch brand de zon in afrika
De negertjes tot chocola
Maar bijt ze niet want anders gaan ze schreeuwen
En van waar dit allemaal komt:
De lucht, het water en de grond
Dat kan tot nu toe niemand vertellen
De aarde draait hier niet alleen
Er zijn nog meer bollen om haar heen
Veel meer dan de mensen kunnen tellen
Want als je straks een lichtje ziet
Dat plotseling door de hemel schiet
Dan kan dat een marsmannetje zijn
Da heel gewoon aan jou komt vragen
Of je een van deze dagen
Met hem mee vliegt in zijn mars konijn""")
print(de_aarde.lyrics) # Print the song
if __name__ == '__main__': # code to execute if called from command-line
main()
| false
|
c2fbe51a4c53f968c64cf470c86ac1cf6b4b448d
|
TardC/books
|
/Python编程:从入门到实践/code/chapter-10/cats&dogs.py
| 361
| 4.15625
| 4
|
def print_file(filename):
"""Read and print a file."""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
# msg = "The file " + filename + " does not exist!"
# print(msg)
pass
else:
print(contents)
print_file('cats.txt')
print_file('dogs.txt')
| true
|
b295d0857648ad8e09a8a484e58d4745ebe74b69
|
ChastityAM/Python
|
/Python-sys/runner_up.py
| 561
| 4.15625
| 4
|
#Given participants score sheet for University, find the runner up score
#You're given n scores, store them in a list and find the score of the
#runner up.
list_of_numbers = [2, 3, 6, 6, 5]
print(sorted(list(set(list_of_numbers)))[-2])
#or
list2 = [2, 3, 6, 6, 5]
def second_place(list2):
list2.sort(reverse=True)
first_place_score = list2[0]
for elem in list2:
if elem < first_place_score:
return_string = "Congrats for second place with score of {}".format(elem)
return return_string
print(second_place(list2))
| true
|
9673488c7cfc5abd1e0339bd5815615780fa8b07
|
ChastityAM/Python
|
/Python-sys/lists.py
| 721
| 4.21875
| 4
|
list_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8]
a = list_of_numbers[5] #selecting an index
b = list_of_numbers[2:5] #slicing the list
#doesn't include last index given in printout
print(a)
print(b)
list_of_numbers[5] = 77
list_of_numbers.append(10)
list_of_numbers.pop(4) #removes at this index, if not indicated, will remove last one
list_of_numbers.reverse()
print(list_of_numbers)
fruits = ["apple", "blueberry", "cherry", "mango", "banana"]
print(fruits)
fruits[3] = "pineapple" #reassigning slot 3
print(fruits)
first_element = fruits[0]
print(first_element)
last_element = fruits[-1]
print(last_element)
print(len(fruits))
fruits.insert(2, "guava")#add to list at the index you chose
print(fruits)
| true
|
c4c1bc5ac2c4e5d28656af5dc987968d34c2feaa
|
ChastityAM/Python
|
/Python-sys/sqrt.py
| 231
| 4.25
| 4
|
import math
#Create a function that takes a number n from the user.
#Return a list containing the square of all numbers between 1 and n
num1 = int(input("Please enter a number: "))
def sq_root(num1):
return math.sqrt(num1)
| true
|
0005a28c25142263623a6c52686bd0d1ef6def3f
|
afcarl/PythonDataStructures
|
/chapter4/exercise_7.py
| 410
| 4.25
| 4
|
def is_divisible_by_n(x,n):
if type(x) == type(int()) and type(n)==type(int()):
if x % n == 0:
print "yes,"+str(x)+" is divisible by "+ str(n)
else:
print "no,"+str(x)+" is not divisible by "+str(n)
else:
print "invalid input"
num1 = input("Please input a number to check:")
num2 = input("Please input a divisor to check:")
is_divisible_by_n(num1,num2)
| true
|
4a118fbc0b36030195ebc7067b6feb98de8c4945
|
afcarl/PythonDataStructures
|
/chapter6/exercise_3.py
| 606
| 4.3125
| 4
|
def print_multiples(n, high):
#initialize and iterator
i = 1
#while the iterator is less than high, print n*i and a tab
while i <= high:
print n*i, '\t',
i += 1
print #print a new line
def print_mult_table(high):
#initialize an interator
i = 1
#while the iterator is less than high, do print_multiples
while i <= high:
print_multiples(i, high)#start from i=1 to high
i += 1 #increment high
#print_mult_table will start on line 1 and then it will continue to print out lines of integers until it reaches high.
print print_mult_table(7)
| true
|
4bad22567b2966e77af73848c19bb95542360a1a
|
gadi42/499workspace
|
/Lab4/counter.py
| 916
| 4.46875
| 4
|
def get_element_counts(input_list):
"""
For each unique element in the list, counts the number of occurrences of the element.
:param input_list: An iterable of some sort with immutable data types
:return: A dictionary where the keys are the elements and the values are the corresponding
number of occurrences.
"""
unique_elements = set(input_list)
elem_counts = {}
for elem in unique_elements:
elem_counts[elem] = count_element(input_list, elem)
return elem_counts
def count_element(input_list, target):
"""
Given a list and a target, counts how many times the target element occurs in the input list.
:param input_list: An iterable of some sort
:param target: An immutable data type
:return: A non-negative integer
"""
count = 0
for elem in input_list:
if elem == target:
count += 1
return count
| true
|
1fe469a732a79d1753a0a886cd9aa6273c84a1fa
|
RanjitThakur678/new-
|
/center.py
| 501
| 4.3125
| 4
|
# name = "Ranjit"
# print(name.center(10,"!"))
# name= input("enter your name :")
# print(name.center(len(name)+8,"*"))
def leap(year):
"year -> 1 if leap year, else 0."
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return f"{year} is a leapyear"
return "Not a leap year"
def _days_before_year(year):
"year -> number of days before January 1st of year."
y = year - 1
return y*365 + y//4 - y//100 + y//400
print(leap(2015))
print(_days_before_year(2012))
| false
|
8874c382f717ef3828bda2da5763cb2d833f655b
|
mentekid/myalgorithms
|
/Permutations/permutations.py
| 1,092
| 4.15625
| 4
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Computes all possible permutations of [0...N-1] for a given N
If you need the permutations of another array, just use N = len(alist)
and then print alist[perm] for perm in p
Author: Yannis Mentekidis
Date: April 28, 2015
"""
from time import clock
import sys
def all_permutations(N):
"""Recursively find permutations """
if len(N)==1:
return [N]
permutations = []
for i in range(len(N)):
p = all_permutations(N[0:i]+N[(i+1):])
for per in p:
per.insert(0, N[i])
permutations.append(per)
return permutations
def main():
if len(sys.argv) < 2:
num = 5 #default
else:
if int(sys.argv[1]) > 10:
print "I don't like pain, so I'm only doing up to 10"
num = 10
else:
num = int(sys.argv[1])
N = range(num)
start = clock()
p = all_permutations(N)
time = clock() - start
# print p
print "Found all ", len(p), " permutations of ", N
print "Time: %fs" %(time)
if __name__ == "__main__":
main()
| true
|
567c3c71afd8baa107f1d3a3a9a130edbb2401f9
|
Coder2100/mytut
|
/13_1_input_output.py
| 2,484
| 4.4375
| 4
|
print("7.1. Fancier Output Formatting")
year = 2016
event = 'referendum'
print(f"Result of the {year} {event} was BREXIT.")
print("The str.format()")
yes_votes =42_572_654
no_votes =43_132_495
percentage_yes = yes_votes/(no_votes + yes_votes)
results = '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage_yes)
print(results)
print("The str() function is meant to return representations of values which are fairly human-readable,")
print("while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax).")
s = 'Hello World.'
print(str(s))#str
print(repr(s))# intepretor representation
print(str(1/7))
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
hello = 'hello, world\n'
print(s)
hellos = repr(hello)
print(hellos)
print(repr((x, y, ('spam', 'eggs'))))
import math
print(f"The value of pi is approximately {math.pi:.3f}.")
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print(f"{name:10} ===> {phone:10d}")
animals = 'eels'
print(f'My hovercraft is full of {animals}.')
print(f"My hovercraft is full of {animals!r}.")
print('We are the {} who say "{}!"'.format('knight', 'Ni'))
print('{0} and {1}'.format('spam', 'eggs'))
#spam and eggs
print('{1} and {0}'.format('spam', 'eggs'))
#eggs and spam
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table))
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
for x in range(1, 11):
print('{0:3d} {1:4d} {2:5d}'.format(x, x*x, x*x*x))
print("Manual String Format")
for x in range(1, 11):
print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
print(repr(x*x*x).rjust(4))
#The str.rjust() method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left.
# There are similar methods str.ljust() and str.center().
print("There is another method, str.zfill(), which pads a numeric string on the left with zeros")
# It understands about plus and minus signs:
print('12'.zfill(5))
print("Old string formatting %s,s as placeholder to the right")
import math
print('The value of pi is approxitaley %5.3f.' %math.pi)
| true
|
409f82a86c31c8a4c8d77cf70e817f0c74d64413
|
Ilya18322/Algoritmss
|
/2.1alg.lab.py
| 541
| 4.3125
| 4
|
import math
def example (x, R):
if x >= -4 and x <= -2:
return x + 3
elif x >= -2 and x <= 4:
return -(x/2)
elif x >= 4 and x <= 6:
return -2
elif x >= 6 and x <= 10:
return math.sqrt((R ** 2) - (x - 8) ** 2) - 2
else:
return("Значение не в диапозоне.")
x = float(input("Введите значение x= "))
R = float(input("Введите значение R= "))
print("Значение функции:", example(x,R))
| false
|
46a0a26d0c0ae7ae5eefcf51f5ef47e26d0d175f
|
gstroudharris/PythonAutomateTheBoringStuff
|
/Lessons/lists.py
| 866
| 4.28125
| 4
|
#purpose: place items in a list, put them in a function, then call them
myLists = [['Grant', 'Dana', 'ListItem3'], [10, 20, 35]]
#index evaluates to a single item at a time
print((myLists[0][0]) + str((myLists[1][-2])))
#slice will evaluate to a a whole list
print(myLists[1:2])
#replace an item in the list
myLists[1][0] = 'replaced'
print(myLists)
#extend the list by assigning new entries
myLists[1][1:3] = ['with', 'some', 'new', 'words']
print(myLists)
#de-assign an item with del
del myLists[1][-2]
print(myLists)
#see how long a list is with len function
print(len(myLists))
#multiply the list by two and print
print(myLists * 2)
#list a str
print(list('helloooooo'))
#see if an item is in the list with 'in', or 'not in' for the opposite
searchWord = input('what word should we find in a name list? ')
print(searchWord in ['Grant', 'bagel'])
| true
|
73a636efa993e4df41d2e0d86f14af29d31a8817
|
eshaang/assignments1
|
/y.py
| 1,287
| 4.1875
| 4
|
angle1 = int(input("Enter angle one: "))
angle2 = int(input("Enter angle two: "))
angle3 = int(input("Enter angle three: "))
angletotal = angle1+angle2+angle3
if angletotal == 180:
if angle1 == 60 and angle2 == 60 and angle3 == 60:
print("equilateral")
elif angle1 == angle2 or angle2 == angle3 or angle1 == angle3:
print("isoceles")
else:
print("scalene")
else:
print("Not triangle")
#month = str(input("Enter month "))
#if month == "1" or month == "january":
# print("31")
#elif month == "2" or month == "february":
# print("29")
#elif month == "3" or month == "march":
# print("31")
#elif month == "4" or month == "april":
# print("30")
#elif month == "5" or month == "may":
# print("31")
#elif month == "6" or month == "june":
# Print("30")
#elif month == "7" or month == "july":
# print("31")
#elif month == "8" or month == "august":
# print("31")
#elif month == "9" or month == "september":
# print("30")
#elif month == "10" or month == "october":
# print("31")
#elif month == "11" or month == "november":
# print("30")
#elif month == "12" or month == "december":
# print("31")
#
#
#c = input("Enter the charecter ")
#print(c.isnumeric())
#if c isnumeric() == true:
# print("Number")
#elif c.isalpha() == true:
# print("Aphabet")
#else:
# print("Charecter")
| false
|
802a63767ddf4ac4449b11045c4e5ee1b2f69e04
|
Hoverbear/SPARCS
|
/week4/board.py
| 1,386
| 4.125
| 4
|
def draw_board(board):
"""
Accepts a list of lists which makes up the board.
Assumes the board is a list of rows. (See my_board)
"""
# Draw the column indexes.
print(" ", end="")
for index, col in enumerate(board):
# Print the index of each column.
# Note: sep="", end="" prevent python from creating a new line.
print(" C" + str(index) + " ", sep="", end="")
print("") # Creates a line break.
for index, row in enumerate(board):
# Print the row border.
print(" " + ("+----" * 8) + "+", sep="")
# Print the row index.
print("R" + str(index) + " ", sep="", end="")
# Print each cell
for cell in row:
print("| " + str(cell) + " ", sep="", end="")
print("|") # Finishes the row.
# Print the end border.
print(" " + ("+----" * 8) + "+", sep="")
my_board = [
["br", "bk", "bb", "bq", "bk", "bb", "bk", "br"],
["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"],
["wr", "wk", "wb", "wq", "wk", "wb", "wk", "wr"]
]
print(my_board)
# draw_board(my_board)
| true
|
2157ab6936bd0e03959d122e9cc4a0c6908081fd
|
Hoverbear/SPARCS
|
/week2/2 - Loops.py
| 2,579
| 4.90625
| 5
|
# Loops! Loops! Loops!
# The above is an example of a loop. Loops are for when you want to do something repeatedly, or to work with a list.
# First, some useful things for us to know.
my_range = range(10)
# This creates an "iterator" which is sort of like a list, in fact, we can use a cast to make a list out of it.
print(list(my_range)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# We're not going to get into what iterators actually are quite yet, so lets just think of them as lists.
# A normal range
range(10) # 0 to 10 (Not including 10!)
# Specify a starting point.
range(5,10) # 5 to 10 (Not including 10!)
# By steps.
range(0,10,2) # [0,2,4,6,8] (Again, no 10)
# Okay, now that we know how to use ranges, lets try looping!
for number in range(10):
print(str(number)) # Holy jeez, this prints out 0 to 9!
for number in range(0, 10, 2):
another_list = list(range(number, 10))
print(another_list) # What do you think this prints?
# Ranges are cool, and useful, but what if I wanted to use one of those handy list things?
for item in ["My", "Handy", "List"]:
print("One item of the list is: " + item)
# Well isn't that useful! Lets try some more!
# So loops are handy, but what if we don't know how many times we want to loop? For example, I want to loop until the user inputs "Potato".
# Thankfully, there's something called a "while" loop.
while input("Enter 'Potato' to finish the loop: ") != "Potato":
print("That's not 'Potato', I'll keep going.")
print("You got out of the loop!")
# Okay, that works, our tool box is growing really big now! There's just one more thing about loops that we should talk about: What if I want to finish early?
# For example: We want loop through a list of names and say hi to everyone, except if we see "Selena Gomez", then we should stop, because she's magic.
names = ["Simon", "Andrew", "Frosty", "Oscar", "Fred", "Selena Gomez", "Someone who doesn't get printed"]
for name in names:
if name == "Selena Gomez":
print("OMG IT'S SELENA GOMEZ.")
break
print("Hello there, " + name + "!")
# *** CHALLENGE TIME ***
# Okay, here's a fun problem... Actually, this is an interview question for hiring REAL programmers.
# Here's the problem:
# For all the numbers from 0 to 100 (not including 100),
# If a number is divisible by 3, print out "Fizz"
# If a number is divisible by 5, print out "Buzz"
# Otherwise, just print out the number.
# Hint: You'll want to use the modulo operator we talked about earlier. (4 % 2 == 0, or "The remainder of 4 divided by 2 is zero")
# *** END OF CHALLENGE TIME ***
# Congratulations! Lets cover more about lists!
| true
|
3428bb3e2794381738752bb1a368b196fcebee13
|
14E47/Hackerrank
|
/30DaysOfCode/day9_recursion3.py
| 302
| 4.125
| 4
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(n):
if n<=1:
return 1
else:
fac = n*factorial(n-1)
return fac
n = int(input("Enter factorial no. :"))
result = factorial(n)
print(result)
| true
|
8d5203e99f35aabfa5710bfae36ba6cc47c479b6
|
HebertFB/Curso-de-Python-Mundo-1-Curso-em-Video
|
/Curso de Python 3 - Mundo 1 - Curso em Video/ex010.py
| 342
| 4.125
| 4
|
"""Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar"""
reais = float(input('Informe quantos Reais a ser convertido para Dólar: '))
cotacao = float(input('Informe a cotação atual do Dólar: '))
print(f'R${reais:.2f} Reais convertidos dará US${reais/cotacao:.2f} Dólares!')
| false
|
a9dc59b43b89dc12b5f2887a61e1857e0affaaa6
|
HebertFB/Curso-de-Python-Mundo-1-Curso-em-Video
|
/Curso de Python 3 - Mundo 1 - Curso em Video/ex009.py
| 508
| 4.34375
| 4
|
"""Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada"""
num = int(input('Informe um número: '))
print(f'=' * 11)
print(f'{num} X {1:2} = {num*1}')
print(f'{num} X {2:2} = {num*2}')
print(f'{num} X {3:2} = {num*3}')
print(f'{num} X {4:2} = {num*4}')
print(f'{num} X {5:2} = {num*5}')
print(f'{num} X {6:2} = {num*6}')
print(f'{num} X {7:2} = {num*7}')
print(f'{num} X {8:2} = {num*8}')
print(f'{num} X {9:2} = {num*9}')
print(f'{num} X {10} = {num*10}')
print(f'=' * 11)
| false
|
0d19a01a43ef753af9eb1f9f09817c86e99f0dec
|
jacobbathan/python-examples
|
/ex8.10.py
| 344
| 4.25
| 4
|
# a string slice can take a third index that specifies the 'step size'
# the number of spaced between successive characters
# 2 means every other character
# 3 means every third
# fruit = 'banana'
# print(fruit[0:5:2])
def is_palindrome(string):
print(string == string[::-1])
is_palindrome('racecar')
is_palindrome('apple')
| true
|
e857a43a220a5e158610933d8f478046e6559ae8
|
sheikh210/LearnPython
|
/functions/challenge_palindrome_sentence.py
| 345
| 4.1875
| 4
|
def is_palindrome(string: str) -> bool:
return string[::-1].casefold() == string.casefold()
def is_sentence_palindrome(sentence: str) -> bool:
string = ""
for char in sentence:
if char.isalnum():
string += char
return is_palindrome(string)
print(is_sentence_palindrome("Was it a car, or a cat, I saw"))
| true
|
e4e6df7f0136d45eaa671d592b74fe4767774cfe
|
sheikh210/LearnPython
|
/functions/challenge_fizz_buzz.py
| 1,549
| 4.3125
| 4
|
# Write a function that returns the next answer in a game of Fizz Buzz
# You start counting, in turn. If the number is divisible by 3, you say "fizz" instead of the number
# If the number if divisible by 5, you say "buzz" instead of the number
# If the number is divisible by 3 & 5, you say "fizz buzz" instead of the number
# The function should return the correct word ("fizz", "buzz" or "fizz buzz"), or the number if not
# divisible by 3 or 5
# The function will always return a string
#
# Include a for loop to test your function for values from 1-100, inclusive
def fizz_buzz(number: int) -> str:
"""
Function to return "fizz" if param `number` is divisible by 3 and not divisible by 5.
Function to return "buzz" if param `number` is divisible by 5 and not divisible by 3.
Function to return "fizz buzz" if param `number` is divisible by 3 and divisible by 5.
Else function returns number
:param number: Number to be checked if divisible by 3 and/or 5
:return: "fizz", "buzz", "fizz buzz" or number passed as argument
"""
if number % 15 == 0:
return "fizz buzz"
elif number % 3 == 0:
return "fizz"
elif number % 5 == 0:
return "buzz"
else:
return str(number)
# PLAY FIZZ BUZZ AGAINST THE COMPUTER!
for i in range(1, 101):
if i % 2 != 0:
print(fizz_buzz(i))
else:
user_input = str(input())
if user_input != fizz_buzz(i):
print("YOU LOSE!")
break
else:
print("WELL DONE, YOU REACHED 100!")
| true
|
7f5ade077d195863562b3d90d89cf9bebd1d715b
|
sheikh210/LearnPython
|
/data_structures/sets/sets_intro.py
| 1,506
| 4.25
| 4
|
# Sets are unordered and DO NOT contain any duplicate values - Think of sets like a collection of dictionary keys
# Elements in a set MUST be immutable (hashable)
# DEFINING A SET
# **********************************************************************************************************************
# Method 1 - Declaring a set literal
farm_animals = {'sheep', 'cow', 'hen'}
for animal in farm_animals:
print(animal)
print('*' * 25)
# Method 2 - Passing a tuple literal to the set() constructor
wild_animals = set(['lion', 'tiger', 'panther', 'elephant', 'hare'])
for animal in wild_animals:
print(animal)
print('*' * 25)
# Method 2.1 - Passing a tuple variable to the set() constructor
squares_tuple = (4, 6, 9, 16, 25)
squares = set(squares_tuple)
print(squares)
print('*' * 25)
# Method 2.2 - Passing a range to the set() constructor
even = set(range(0, 40, 2))
print(even)
print('*' * 25)
# ADDING TO A SET
# **********************************************************************************************************************
farm_animals.add('horse')
wild_animals.add('horse')
print(farm_animals)
print(wild_animals)
print('*' * 25)
# REMOVING FROM A SET
# **********************************************************************************************************************
# discard() - Doesn't throw error
farm_animals.discard('horse')
print(farm_animals)
# remove() - Throws exception if value doesn't exist
wild_animals.remove('horse')
print(wild_animals)
print('*' * 25)
| true
|
b56f52a7d452b41506df0b0aba26f8566c2bdc29
|
trahnagrom/controlled-assessment
|
/currency-converter2.py
| 2,102
| 4.3125
| 4
|
currencies= {
"Pound Sterling": 1,
"Euro": 1.2,
"US Dollar": 1.6,
"Japanese Yen": 200
}
short_hand = {
"GBP": "Pound Sterling",
"EUR": "Euro",
"USD": "US Dollar",
"JPY": "Japanese Yen"
}
c_type1 = raw_input("What Currency are you converting from? GBP/EUR/USD/JPY: ")
if c_type1 == "GBP" or "EUR" or "USD" or "JPY":
"You entered %s" %(c_type1)
else:
print c_type1, "is not a valid input"
c_type1 = raw_input("Please enter a valid currency to convert from- GBP/EUR/USD/JPY: ")
c_type2 = raw_input("What Currency are you converting to? GBP/EUR/USD/JPY: ")
if c_type2 != "GBP" or "EUR" or "USD" or "JPY":
"You entered %s" %(c_type1)
else:
print c_type2, "is not a valid input"
c_type2 = raw_input("Please enter a valid currency to convert to- GBP/EUR/USD/JPY: ")
def rate(c_type1, c_type2):
if c_type1 == "GBP":
print "exchange rate is", currencies["Pound Sterling"]
if c_type1 == "EUR":
print "exchange rate is", currencies["Euro"]
if c_type1 == "USD":
print "exchange rate is", currencies["US Dollar"]
if c_type1 == "JPY":
print "exchange rate is", currencies["Japanese Yen"]
if c_type2 == "GBP":
print "to", currencies["Pound Sterling"]
if c_type2 == "EUR":
print "to", currencies["Euro"]
if c_type2 == "USD":
print "to", currencies["US Dollar"]
if c_type2 == "JPY":
print "to", currencies["Japanese Yen"]
rate(c_type1, c_type2)
numb1 = float(raw_input("How much %s do you wish to convert? " %c_type1))
def conversion(fromCurr, toCurr, value):
if fromCurr == "GBP":
answer = value * float(currencies[short_hand[toCurr]])
return answer
elif toCurr == "GBP":
answer = value / float(currencies[short_hand[fromCurr]])
else:
answer = value / float(currencies[short_hand[fromCurr]])
answer = value * float(currencies[short_hand[toCurr]])
return answer
print "%2.f %s is %2.f %s" %(numb1, short_hand[c_type1], conversion(c_type1, c_type2, numb1), short_hand[c_type2])
| false
|
74269318512c52a38151a35698b3d2e711412bf2
|
MATTPostx/First
|
/dat.py
| 775
| 4.1875
| 4
|
y = "John"
print(y)
cars = {"Ford", "Volvo", "BMW"}
cars.append(cars)
for x in cars:
print(x)
def my_name():
print("hello")
my_name()
# print(array)
# for array in cars:
# print(array)
# first_number = int(input('Type the first number:')) ;\
# second_number = int(input('Type the second number: ')) ;\
# print("The sum is: ", first_number + second_number)
# name = input('Enter your name:')
# print (type(name))
# x = 5
# print ('The number is'+ str(x))
# name = "Matt"
# print(name)
# print (x,y) b
# print(type(name))
# timetuple = ("apple", "cherry", "hawkeye")
| false
|
426ed7b6a1db968eac60457221f26c16c3e79887
|
meechaguep/MCOC-Intensivo-de-Nivelacion
|
/21082019/000352.py
| 1,307
| 4.40625
| 4
|
print "Este dia estudiaremos listas"
#intento 1
lista1= [14,21,3,-14,-21,-3]
print "la lista es:"
print lista1
#intento 2
print "agreguemos un numero a la lista"
lista1= [14,21,3,-14,-21,-3]
lista1.append(1313)
print lista1
#intento 3
print "ahora agreguemos una frase a esta lista de numeros"
lista1= [14,21,3,-14,-21,-3,1313] #las defino denuevo simplemente para hacer como codigos nuevos
lista1.append("hola numeros, soy un texto")
print lista1
#intento 4
print "ahora agreguemos una lista nueva dentro de la actual"
lista1= [14, 21, 3, -14, -21, -3, 1313, 'hola numeros, soy un texto']
lista1.append(["yo tambien soy texto",44,55,22])
print lista1
#intento5
#desde ahora llamare a la lista nomas, ya que se entiende que se siguen usando estos valores
print "eliminaremos ahora el ultimo parametro de la lista" #era una lista por lo que se cuenta como parametro de la lista inicial
lista1.pop()
print lista1
print "eliminaremos ahora el siguiente parametro"
lista1.pop()
print lista1
print "eliminaremos el siguiente"
lista1.pop()
print lista1
#intento 6
print "ahora veamos cual es el tercer valor de la lista"
print lista1[2] #le ponemos 2 porque comienza de 0
print "veamos el primer valor de la lista"
print lista1[0]
| false
|
db0254a976f098a879546af4851e65a579cdfa5b
|
meechaguep/MCOC-Intensivo-de-Nivelacion
|
/29082019/014008.py
| 2,592
| 4.1875
| 4
|
import numpy as np
#intro to numerical computing with numpy
l1= [1,3,5,7]
l2= [9,11,13,15]
print l1 + l2 #agrega l2 a l1
suma_entre_elementos= []
for elemento1, elemento2 in zip(l1, l2):
suma_entre_elementos.append(elemento1+elemento2)
print suma_entre_elementos #se suma cada elemento
gg = list(range(100))
print gg
gg_array = np.array(gg)
print gg_array #podemos ver la diferencia entre listas y arreglos y el tiempo en que lo procesa python
#codigo 2
l11 = np.array([2,4,6,8])
l22 = np.array([10,12,14,16])
print l11.ndim #dimension l11
print l11.shape #cantidad de elementos de cada dimension
print("")
#operaciones matematicas
print l11*l22
print l11+100
print l22*100
print np.sin(l22)
print l11.dtype #tipo de arreglos
l33= np.array([2.3,4.2,5.,5]) #float64
print l33.dtype
limg = np.array([1j,5,2j]) #deberia indicar que es complejo
print limg.dtype
lfloat32= np.array([1,2,3,4,5,6,7,8], dtype='float32')
print lfloat32.dtype #definimos float32
l2d = np.array([[22,33,44,55,66],[66,55,44,33,22]])
print l2d.size #tamano
print l2d.nbytes #bytes
#codigo 3
print l11[1:3] #posiciones 1 y 2, la ultima no la imprime
print l11[1:-1] #-1 es la ultima y -2 la antepenultima
print l11[::2] #cada dos pasos
print l11[:3]
print l11[-2:]
l11_lista= [2,4,6,8]
print l11_lista[0]
print l11_lista[:1] #con listas
arreglo6x6_literal= np.arange(36).reshape(6,6)
print "veamos distintos puntos de esta matriz"
print arreglo6x6_literal
print arreglo6x6_literal[:,4]
print arreglo6x6_literal[1::2, :-1:2]
print arreglo6x6_literal[1::2, :3:2]
print arreglo6x6_literal[:, 1::2]
print arreglo6x6_literal[:,2]
print arreglo6x6_literal[1::2, :-2:2]
print arreglo6x6_literal[4, :]
print arreglo6x6_literal[1::2, :4:2]
#codigo 4
arreglo_paso100 = np.arange(100,100000000,100)
negat= np.array([-5,-4,-3,-2,-1,0,1,2,3])
print negat<0 #imprime true si es negativo
negat[negat<0] = 0 #convierte negativos a 0
print negat
print np.nonzero(negat) #posiciones sin 0
laaa = np.array([1,2,3])
lbbb = np.array([1,3,5])
print laaa<lbbb #posicion donde laa es menor que lbb
print laaa
subset = laaa[[0,2]]
print subset
print subset.flags.owndata
#5 ejercicio
ejercicio = np.arange(25).reshape(5,5)
print ejercicio%3==0
mod = ejercicio%3==0
print ejercicio[mod]
output = np.empty_like(ejercicio, dtype='float')
output.fill(np.nan) #asigno que sean nan
mask = ejercicio%3 == 0
output[mask] = ejercicio[mask]
print output, ejercicio
| false
|
82cb1fd257e84ba308a2bcf20d6450cfd8fda462
|
spuentesv/condicionales_python
|
/ejercicios_profunidzacion/profundizacion_2.py
| 1,797
| 4.25
| 4
|
# Condicionales [Python]
# Ejercicios de profundización
# Autor: Inove Coding School
# Version: 2.0
# NOTA:
# Estos ejercicios son de mayor dificultad que los de clase y práctica.
# Están pensados para aquellos con conocimientos previo o que dispongan
# de mucho más tiempo para abordar estos temas por su cuenta.
# Requiere mayor tiempo de dedicación e investigación autodidacta.
# IMPORTANTE: NO borrar los comentarios en VERDE o NARANJA
# Ejercicios de práctica con números
'''
Enunciado:
Realice un programa que solicite el ingreso de tres números
enteros, y luego en cada caso informe si el número es par
o impar.
Para cada caso imprimir el resultado en pantalla.
'''
# Ingreso de numeros
texto1 = input('Ingrese el primer número (ej. 1, 4):\n')
texto2 = input('Ingrese el segundo número (ej. 1, 4):\n')
texto3 = input('Ingrese el tercero número (ej. 1, 4):\n')
numero_1 = int(texto1)
numero_2 = int(texto2)
numero_3 = int(texto3)
# Calculo si numero es par - numero 1
comparacion = ""
resultado = numero_1 % 2
if (resultado == 0):
comparacion = "PAR"
else:
comparacion="IMPAR"
# Imprima en pantalla según corresponda
print('Numero 1:', numero_1, ' es ', comparacion)
# Calculo si numero es par - numero 2
comparacion = ""
resultado = numero_2 % 2
if (resultado == 0):
comparacion = "PAR"
else:
comparacion="IMPAR"
# Imprima en pantalla según corresponda
print('Numero 2:', numero_2, ' es ', comparacion)
# Calculo si numero es par - numero 3
comparacion = ""
resultado = numero_3 % 2
if (resultado == 0):
comparacion = "PAR"
else:
comparacion="IMPAR"
# Imprima en pantalla según corresponda
print('Numero 3:', numero_3, ' es ', comparacion)
print('Ejercicios de práctica con números')
# Empezar aquí la resolución del ejercicio
| false
|
0a24d97defcca7fe24bcaec53337ba790151a76f
|
crystalballz/LearnPythonTheHardWay
|
/ex3.py
| 700
| 4.46875
| 4
|
print "I will now count my chickens:"
# Hens and Roosters are counted separately
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
# Not too many eggs since there are more Roosters than Hens
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5+ 4 % 2 - 1 / 4 + 6
# Verifies if the statement that follows is true or false
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
# These lines below are demonstrating the comparator math equations
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
| true
|
89d5d07376abc2813ef4c5d556aed9c0e55ba21b
|
Chitranshuvarshney/Stone-Paper-Scissor-Game
|
/game.py
| 1,072
| 4.21875
| 4
|
import random
# This is the stone, Paper & Scissor Game!
def gameWin(comp, you):
if comp == you:
return None
elif comp == 'stone':
if you=='paper':
return True
elif you=='scissor':
return False
elif comp == 'paper':
if you=='stone':
return False
elif you=='scissor':
return True
elif comp == 'scissor':
if you=='stone':
return True
elif you=='paper':
return False
print("Comp Turn: stone, paper, scissor? ")
randNo = random.randint(1, 3)
if randNo == 1:
comp = 'stone'
elif randNo == 2:
comp = 'paper'
elif randNo == 3:
comp = 'scissor'
you = input("Your Turn: stone, paper, scissor? ")
a = gameWin(comp, you)
print("Computer Choose:", comp)
print("You Choose:", you)
if you!= "stone" and you!= "paper" and you!= "scissor":
print("You Choose Wrong Input!")
elif a==None:
print("The game is Tie!")
elif a:
print("You Win!")
else:
print("You Lose!")
| false
|
64c14de2c423cebafdbd7cc8b4869bd3724c0a4e
|
ninsamue/sdet
|
/python/act_4.py
| 1,487
| 4.25
| 4
|
print("ROCK PAPER SCISSORS")
print("-------------------")
Name1 = input("Enter Player 1 Name : ")
Name2 = input("Enter Player 2 Name : ")
player1Score=0
player2Score=0
play="Y"
while play=="Y":
player1Choice = input(Name1+"'s choice - Enter rock/paper/scissors : ").lower()
player2Choice = input(Name2+"'s choice - Enter rock/paper/scissors : ").lower()
if player1Choice == player2Choice:
print("It's a tie")
elif player1Choice=="rock" and player2Choice=="paper":
print(Name2, "wins the round")
player2Score+=1
elif player1Choice=="rock" and player2Choice=="scissors":
print(Name1, "wins the round")
player1Score+=1
elif player1Choice=="paper" and player2Choice=="rock":
print(Name1, "wins the round")
player1Score+=1
elif player1Choice=="scissors" and player2Choice=="rock":
print(Name2, "wins the round")
player2Score+=1
elif player1Choice=="paper" and player2Choice=="scissors":
print(Name2, "wins the round")
player2Score+=1
elif player1Choice=="scissors" and player2Choice=="paper":
print(Name1, "wins the round")
player1Score+=1
else:
print("Invalid Input. You have not entered rock/paper/scissors")
play=input("Do you want to continue playing(Y/N) : ")
print("Final Score")
print("-----------")
print(Name1+"'s score ",player1Score)
print(Name2+"'s score ",player2Score)
| true
|
4cc104ae49f21d9ca55166c2aa5149e646dfda4d
|
mrparkonline/ics4u_solutions
|
/10-06-2020/letterHistogram.py
| 1,080
| 4.3125
| 4
|
# Write a program that reads a string and returns a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored.
def letterHistogram(word):
''' letterHistogram tracks the occurance of each alpha characters
argument
-- word : string
return
-- dictionary
'''
cleaned_word = list(map(str.lower, word))
#cleaned_word = sorted(cleaned_word)
cleaned_word.sort()
# print(cleaned_word)
table = {} # empty dictionar
# Key --> each alpha letter
# Value --> the number of occurance
for item in cleaned_word:
if item in table: # item/the alpha character is a key that exist in table
table[item] += 1
else:
if item.isalpha():
table[item] = 1
# end for
return table
# end of letterHistogram
table = letterHistogram("The quick brown fox jumps over the lazy dog")
for character, count in table.items():
print(character, count)
| true
|
5e018f447d9d13832317ee5720012440a9c73c7c
|
mrparkonline/ics4u_solutions
|
/09-14-2020/factoring.py
| 731
| 4.3125
| 4
|
# 09/14/2020
# Factoring Program
num = int(input('Enter a number you want the factors for: '))
# While Loop Solution
divisor = 1
while divisor <= num:
# we are checking all numbers from 1 to inputted num
if num % divisor == 0:
# when num is divided by divisor the remainder is 0
# therefore, divisor is a factor of num
print(divisor, 'is a factor of', num)
divisor += 1
# end of while
print('I am outside of while loop')
# For Loop Solution
for i in range(1, num+1):
if num % i == 0:
print(i, 'is a factor of', num)
# end of for
print('I am now outside of the for loop')
# Thought: which is the better solution?
# Can I program a better solution?
| true
|
78fcf013af9f568d0314b181d721acb49cb0f59a
|
mrparkonline/ics4u_solutions
|
/10-06-2020/numDict.py
| 1,333
| 4.34375
| 4
|
'''
Q4a) Write a Python program to sum all the items in a dictionary
Q4b) Write a Python program to multiply all the items in a dictionary
Q5a) Create a function that sorts a dictionary by key → Create a sorted list of keys.
Q5b) Create a function that sorts a dictionary by value → Create a sorted list of values.
'''
from random import seed
from random import randrange
seed(1) # this allow us to generate the same random numbers
# at every run
test = {randrange(1,1000000) : randrange(1,100) for x in range(20)}
print(test)
# q4a) Sum up all the values in a dictionary
total_sum = sum(test.values())
print('The total_sum is:', total_sum)
# q4b) Multiply all the number
def multiplyDict(table):
''' multiplyDict returns the total product of all values in table
argument
-- table : dictionary
return
-- integer
'''
total_product = 1
for value in table.values():
total_product *= value
return total_product
# end of multiplyDict
print('The total product is:', multiplyDict(test))
# q5a) List of the keys sorted
sorted_test_keys = sorted(test.keys())
print('Keys of test sorted:', sorted_test_keys)
# q5b) List of the values sorted
sorted_test_values = sorted(test.values())
print('Values of test sorted:', sorted_test_values)
| true
|
3c91e7f0397bac3d0f7684e95642afbf6183a74d
|
mrparkonline/ics4u_solutions
|
/10-19-2020/binarySearch.py
| 1,119
| 4.15625
| 4
|
# Binary Search Non recursive
def binSearch(data, target):
left = 0
right = len(data) - 1
while left <= right:
middle = (left + right) // 2
if data[middle] == target:
return middle
elif data[middle] < target:
left = middle + 1
else:
# data[middle] > target:
right = middle - 1
# end of while
return -1
# end of binSearch
# Recursive Binary Search
def r_binSearch(data, target, i=0):
if not data:
return -1
elif len(data) == 1 and data[0] != target:
return -1
else:
middle = (len(data)-1) // 2
if data[middle] == target:
return middle+i
elif data[middle] < target:
return r_binSearch(data[middle+1:], target, middle+i+1)
else:
return r_binSearch(data[:middle], target, i)
# end of r_binSearch
from random import randrange
test = [randrange(-100,100) for i in range(20)]
test.sort()
print('Testing List:', test)
print(binSearch(test, 42))
print(r_binSearch(test, 42))
| true
|
71c8bdc6bf5b8561a8306cf147b782a3266d8bf5
|
ask-ramsankar/DataStructures-and-Algorithms
|
/stack/stack using LL.py
| 1,217
| 4.15625
| 4
|
# creates a node for stack
class Node:
def __init__(self, data, prev=None):
self.data = data
self.prev = prev
self.next = None
class Stack:
# initialize the stack object with the top node
def __init__(self, data):
self.top = Node(data)
# push the data to the stack
def push(self, data):
self.top.next = Node(data, self.top)
self.top = self.top.next
# deletes the top node from the stack
def pop(self):
if self.isEmpty():
return "! Stack is Empty"
self.top = self.top.prev
# To check if stack has a prev node or not
if self.top is not None:
self.top.next = None
# returns the data in the top node
def reveal(self):
if self.isEmpty():
return "! Stack is Empty"
return self.top.data
# To check whether the stack is empty or not
def isEmpty(self):
return not bool(self.top)
if __name__ == "__main__":
stack = Stack(Node(10))
for value in range(20, 101, 10):
stack.push(value)
while not stack.isEmpty():
print(stack.reveal())
stack.pop()
| true
|
6857698560aa61ddccd54c02d71f57b57be8644c
|
ask-ramsankar/DataStructures-and-Algorithms
|
/queue/queue using LL.py
| 1,050
| 4.125
| 4
|
# Node of the queue
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
# Initialize the queue with the first node
def __init__(self, data):
self.first = Node(data)
# add a node to the queue at last
def enqueue(self, data):
current = self.first
if current is None:
self.first = Node(data)
else:
while current.next:
current = current.next
current.next = Node(data)
# deletes first node from the queue
def dequeue(self):
self.first = self.first.next
# return the data in the first node
def reveal(self):
return self.first.data
# check whether the queue is empty or not
def isEmpty(self):
return not bool(self.first)
if __name__ == "__main__":
queue = Queue(10)
for data in range(20, 101, 10):
queue.enqueue(data)
while not queue.isEmpty():
print(queue.reveal())
queue.dequeue()
| true
|
49d736d6ff76a50557fa392b76d059e7f7d3ad92
|
jodr5786/Python-Crash-Course
|
/Chapter 4/4-12.py
| 289
| 4.25
| 4
|
# More Loops
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
for my_food in my_foods:
print("- " + my_food)
print("\nMy friend's favorite foods are:")
for friend_food in friend_foods:
print("- " + friend_food)
| false
|
1d86a1f0c018922cff28368903e4a99a1eea139f
|
jodr5786/Python-Crash-Course
|
/Chapter 4/4-10.py
| 329
| 4.1875
| 4
|
# Slices
my_foods = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'fish', 'lobster']
friend_foods = my_foods[:]
print("\nThe first 3 items in my list are:")
print(my_foods[:3])
print("\nThe items in the middle of my list are:")
print(my_foods[1:5])
print("\nThe last 3 items in the list are:")
print(my_foods[-3:])
| true
|
0fc4f859e6d60da22006879b49579dbeb0dd8f6c
|
noahtigner/InterviewPrep
|
/CrackingTheCodingInterview/2-LinkedLists/2.4-partition.py
| 1,449
| 4.25
| 4
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Singly Linked
def __init__(self):
self.head = None
def insert(self, data):
# O(1)
if not self.head:
self.head = Node(data)
else:
n = self.head
self.head = Node(data)
self.head.next = n
def insert_many(self, data):
for d in data:
self.insert(d)
def print(self):
n = self.head
while n:
print(n.data, end=" -> ")
n = n.next
print("None")
################################################################
# Write code to partition a linked list around a value x such that all nodes less than x come before all nodes greater than or equal to x
# in: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1, partition=5
# out: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
# time: O(n), space: O(1)
def partition(llist: LinkedList, x: int):
head = tail = node = llist.head
while node:
next_node = node.next
if node.data < x: # prepend node
node.next = head
head = node
else: # append node
tail.next = node
tail = node
node = next_node
tail.next = None
llist.head = head
# tests
llist = LinkedList()
llist.insert_many([1, 2, 10, 5, 8, 5, 3])
llist.print()
partition(llist, 5)
llist.print()
| false
|
a144ce02685932552a3379d5b6997b3fa01504b4
|
1411279054/Python-Learning
|
/Data-Structures&Althorithms/力扣算法/四月份算法题/旋转矩阵.py
| 1,679
| 4.15625
| 4
|
## 题目:旋转矩阵()
import pandas
import copy
class Solution:
##利用pandas求解
def rotate(self, matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
matrix2 = pandas.DataFrame(matrix)
num = matrix2[0].size
for i in range(num):
matrix[i] =matrix2[i].values.tolist()
matrix[i].reverse()
print(matrix)
##辅助函数
def rotate2(self, matrix:list):
"""
Do not return anything, modify matrix in-place instead.
"""
num = 0
matrix2 = [[0]*len(matrix) for i in range(len(matrix))] ## 生成相同维度的二维矩阵
while num < len(matrix2):
for i in range(len(matrix)):
matrix2[i][len(matrix)-num-1] = matrix[num][i]
num += 1
matrix[:] = matrix2 #重点
print(matrix)
## 辅助函数+深拷贝
def rotate3(self, matrix: list) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
num = 0
matrix2 = copy.deepcopy(matrix) ## 注意是深拷贝(区别 深拷贝和浅拷贝)
while num < len(matrix2):
for i in range(len(matrix)):
matrix[i][len(matrix) - num - 1] = matrix2[num][i]
print(matrix[i][len(matrix) - num - 1] )
num += 1
print(matrix)
def main():
matrix = [
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
]
Solution().rotate3(matrix)
if __name__ == '__main__':
main()
| false
|
9073f99a3d78244b516d34730f0321e01e80f341
|
ravindra-lakal/Python_new
|
/mak.py
| 912
| 4.3125
| 4
|
###################################
#1 Find the last element of a list.
list = ['a','b','c','d']
#validation list =[]
print list[-1:]
#print "list[4]",list[4]
#2 Find the last but one element of a list.
list =['z','w','e','i','t','l','e','t','z','t','e','s']
#validation list=[1]
print list[-2:-1]
#3 1.03 (*) Find the K'th element of a list.
list = ['a','b','c','d','e','f','g']
print list[3]
#4
somelist = ["a", "b", "c", "d"];
print len(somelist)
#5 reverse the list
list = ['a','b','c','d']
#print list[::-1]
list.reverse()
print list
#5 Addition of 2 numbers
a= input("enter no")
# b=raw_input("enter no")
print a
###################################
#6 check string Find out whether a list is a palindrome
# name = raw_input("Enter a string: ")
# rev_str = reversed(name)
# if list(name) == list(rev_str):
# print("It is palindrome")
# else:
# print("It is not palindrome")
| true
|
78d323b942aa57366d3a8eb4c9f58bb439f7b66d
|
Allegheny-Computer-Science-102-F2020/cs102-F2020-slides
|
/src/fibonacci-generator.py
| 233
| 4.125
| 4
|
def fibonacci_generator(n):
a = 1
b = 1
for i in range(n):
yield a
a, b = b, a + b
print(fibonacci_generator)
for fibonacci_value in fibonacci_generator(10):
print(fibonacci_value, end=" ")
print()
| false
|
000e177fda7bf009742ef757bdd466249e42bd9a
|
nyeddi/Adv-Python
|
/class_method_.py
| 1,745
| 4.46875
| 4
|
class Shape(object):
# this is an abstract class that is primarily used for inheritance defaults
# here is where you would define classmethods that can be overridden by inherited classes
@classmethod
def from_square(cls, square):
# return a default instance of cls
return cls()
class Square(Shape):
def __init__(self, side=10):
self.side = side
@classmethod
def from_square(cls, square):
return cls(side=square.side)
class Rectangle(Shape):
def __init__(self, length=10, width=10):
self.length = length
self.width = width
@classmethod
def from_square(cls, square):
return cls(length=square.side, width=square.side)
class RightTriangle(Shape):
def __init__(self, a=10, b=10):
self.a = a
self.b = b
self.c = ((a*a) + (b*b))**(.5)
@classmethod
def from_square(cls, square):
return cls(a=square.side, b=square.side+2)
class Circle(Shape):
def __init__(self, radius=10):
self.radius = radius
@classmethod
def from_square(cls, square):
return cls(radius=square.side/2)
class Circle1(Shape):
def __init__(self, radius=10):
self.radius = radius
@staticmethod
def from_square(square):
return Circle1(radius=square.side/2)
class Hexagon(Shape):
def __init__(self, side=10):
self.side = side
#https://stackoverflow.com/questions/5738470/whats-an-example-use-case-for-a-python-classmethod
square = Square(3)
for polymorphic_class in (Square, Rectangle, RightTriangle, Circle, Hexagon):
this_shape = polymorphic_class.from_square(square)
print(this_shape.__class__)
| true
|
c21643f5c58676f77da8ffbc14d3dc488c5b0d8e
|
saadkang/PyCharmLearning
|
/basicsyntax/indexvstring.py
| 2,088
| 4.40625
| 4
|
"""
We will see how the index works in python
"""
nameOfAString = "This is for educational purposes only"
# The : in the [] is has no starting and ending index so it will print the whole String
print("There is nothing before or after the : so it will print complete String: "+nameOfAString[:])
# In the example below there is a number in front of the : so the starting index is 1
# There is no number after the : so it will print rest of the index
print("There is 1 in front of : and nothing after, so it will start at index 1 and print everything: "+nameOfAString[1:])
# In the example below there is no starting index so it will print all, but there is an ending index
# We learned previously that the ending index is exclusive so that will not get printed
print("There is nothing in front of the : and 9 after, so It will print all the index and stop at 8: "+nameOfAString[:9])
# So the cool this is the index can be started from either side, if you choose to start from the
# right side then the index will starts from -1, -2, -3,..,-37
# So in the example below the -37 is the first index on the far left hand side "T"
print("Numbering index is a circle starting from left is 0, and starting from right is -1: "+nameOfAString[-37])
print("So now I'm trying to put -1:-1 and what to see what prints: "+nameOfAString[-1:-1])
# Nothing printed on the console, I guess the reason for that is, it did start with -1 index which is the starting
# index and then it looked at the ending index which is also -1 and ending index is exclusive so nothing gets printed
# Now let's talk about the skip part
# The second : is for skipping an index, in the example below there is nothing after the : so nothing will be skipped
print(nameOfAString[::])
# The example below is saying to skip nothing so it is the same thing as above
print(nameOfAString[::1])
# This is skipping two index and printing the third one on the console
print(nameOfAString[::3])
# To reverse the String you can just type -1 after the second :
print("Reverse the value of a String and you get: "+nameOfAString[::-1])
| true
|
445befab60ef2ad7e87ec1b5ce54925ace4977b8
|
saadkang/PyCharmLearning
|
/basicsyntax/tuplesdemo.py
| 1,493
| 4.5
| 4
|
"""
Tuple
Like list but they are immutable
that means you can't change them
"""
# What the above line in green is trying to say is that list (also called Array in Java) can be changed
# Like in the example below:
# The list or Array is defined by the []
my_list = [1, 2, 3]
print(my_list)
my_list[0] = 0
print(my_list)
print('*'*40)
# The tuple is immutable so can't be changed and they are defined by ()
my_tuple = (1, 2, 3)
print(my_tuple)
# So if we try to change the index of a tuple we will get the 'assignment not supported' error
# So I'm not going to try that here, just know you can't change it.
# But you can access different index of the tuple
print('*'*40)
print(my_tuple[0])
# And we can also do slicing or skipping with the tuple
print('*'*40)
print(my_tuple[1:])
print('*'*40)
# We can also find out the index of the items in the tuple
# Let's say we want to find out the index of item or data '2' in the tuple
# we can just type it in the print statement
print("The index of the data '2' in the tuple 'my_tuple' is: %s" % my_tuple.index(2))
# The next thing we can do with the tuple is find how many times a entry is repeated in the tuple
print('*'*40)
print("'1' appeared in the tuple 'my_tuple' exactly %s times" % my_tuple.count(1))
# To understand this count() method let's create a new tuple and use it in examples
print('*'*40)
my_second_tuple = (1, 2, 3, 4, 3, 6, 3, 8, 3)
print("'3' appeared in the tuple 'my_second_tuple' exactly %s times" % my_second_tuple.count(3))
| true
|
0bb7a577e6dc036a4607eaac1f46ebb10d066b54
|
saadkang/PyCharmLearning
|
/basicsyntax/list_demo.py
| 467
| 4.1875
| 4
|
"""
Now, we are going to talk about the list in python
"""
cars = ["BMW", "Honda", "Audi"]
empty_list = []
print(empty_list)
print(cars)
print("*"*20)
print(cars[0])
print("*"*20)
print(cars[1])
print("*"*20)
print(cars[2])
print("*"*20)
numList = [1, 2, 3]
sumList = numList[0] + numList[1]
print(sumList)
print("*"*20)
# Now you can replace the index in the list
more_cars = ["Benz", "Toyota", "Ford"]
print(more_cars)
more_cars[0] = "Volkswagen"
print(more_cars)
| false
|
bf1a776903b0befb342dd7b8a8ea0b26d2b307dd
|
cnrmurphy/python-lessons
|
/exercises/session_1/calc.py
| 2,685
| 4.21875
| 4
|
'''
Exercise: Implement a basic calculator that supports add,subtract,multiply,divide
Basic requirements: four functions that perform the aforementioned operations will suffice.
Extending: Implement a function, calculator, that takes 3 inputs: operation (string), num_a, and num_b.
the function, calculator, should perform the inputed operation as defined in the basic requirements and pass
num_a and num_b to the respective function. I.e. if calculator is called with the arguments: "add", 5, 10
then the add function should be called with 5 and 10 and return 15. If an operation is not recognized i.e "pow" return the
following string: "Operation not recognized!".
Considerations: What happens if you try to divide by 0? Can you figure out a way to handle this case gracefully (without the programming crashing).
Expectations: All tests should pass. If all tests pass you should see your programm output: "All cases pass!"
Tests: the test functions should evaluate to True when called with the respective function
'''
# Program -> your code goes below
# Tests
def test_add(add_function):
expected_output = 15
result = add_function(10,5)
assert (result == expected_output), f'Add does not output the expected sum: 10 + 15 != {result}'
def test_subtract(subtract_function):
expected_output = 5
result = subtract_function(10,5)
assert (result == expected_output), f'Subtract does not output the expected difference: 10 - 5 != {result}'
def test_multiply(multiply_function):
expected_output = 50
result = multiply_function(10, 5)
assert (result == expected_output), f'Multiply does not output the expected product: 10 * 5 != {result}'
def test_divide(divide_function):
expected_output = 2
result = divide_function(10,5)
assert (result == expected_output), f'Divide does not output the expected quotient: 10 / 5 != {result}'
# Add the name of your functions to the respective test arguments below
# I.e. if your add function is called add_nums, call the test like: test_add(add_nums)
# Note for clarification: It may be confusing to be passing a function name as a function parameter.
# This is valid in programming languages and it is called a first class function. When you define a function
# it's almost as if your assinging a block of code to that function namespace, like you would assign some data
# to a variable. So below we pass the name of the function, which is a reference, and we can execute that function
# when we call it with the normal syntax, using paren (), within our test functions.
test_add(add)
test_subtract(subtract)
test_multiply(multiply)
test_divide(divide)
print("All cases pass!")
| true
|
a5c1932418534132648d77c240e64e839244fd70
|
aditparekh/git
|
/python/lPTHW/ex3.py
| 460
| 4.375
| 4
|
print 'I will not count my chickens:'
print "Hens", 25+30/6
print "Roosters", 100-25*3%4
print 'Now I will coung the eggs:'
print 3+2+1-5+4%2-1/4+6
print 4//3
print "is it true that 3+2<5-7"
print 3+2<5-7
print "Waht is 3+2?",3+2
print "Waht is 5-7?",5-7
print "Ph, that's why it's False"
print "How abot some more"
print"Is it greater?",5>-2 #check to see if it true or false
print "Is it greater or equal?",5>=-2
print "Is it less or equal?",5<=-2
| true
|
2badc0380cce0cef6f0b76a76d6164e6f6b51d39
|
aditparekh/git
|
/python/lPTHW/ex25.py
| 837
| 4.28125
| 4
|
def break_words(stuff):
"""This function will break up words for us"""
words = stuff.split(" ")
return words
def sort_words(words):
"""Sorts the words"""
return sorted(words)
def print_first_word(words):
"""Prints the firs word after popping it off"""
word=words.pop(0)
print word
def print_last_words(words):
"""Prints the last words after popping it off"""
word=words.pop(-1)
print word
def sort_sentence(sentence):
"""takes a full sentence and returns the sorted value"""
words=break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""prints the first and last word of the sentnce"""
words=break_words(sentence)
print_first_word(words),print_last_words(words)
def print_first_and_last_sorted(sentence):
words=sort_sentence(sentence)
print_first_word(words),print_last_words(words)
| true
|
d96410728328d7382eefaae6929001873fefa702
|
ajaymatters/scripts-lab
|
/script-lab/python-scripts/PartA7/pa7.py
| 519
| 4.15625
| 4
|
def AtomicDictionary():
atomic = {"H":"Hydrogen", "He":"Helium", "N":"Nitrogen"};
x = input("Enter symbol ")
y = input("Enter element name ")
if x in atomic.keys():
print("Key already exists. Value will be updated")
else:
print("New Key with Value added")
atomic[x] = y
print(atomic)
print("Number of elements in dict:",len(atomic))
x = input("Enter symbol for searching ")
if x in atomic.keys():
print("Element exists in dict with value "+ atomic[x])
else:
print("Element not present in dict")
| true
|
eeef454dbb42b30cc1c25f99d59a4a5ca9719aae
|
voodoopeople42/Vproject
|
/Janus/python-base-unit_11/oop/oop.constructor.test.py
| 896
| 4.1875
| 4
|
# oop.constructor.test.py
# class Person:
# def __init__(self, first_name, last_name):
# self.first_name = first_name
# self.last_name = last_name
# конструктор класса не позволит создать объект без обязательных полей:
# sam = Person("Sam", "Brown")
# print(sam.first_name, sam.last_name)
# class Person:
# def __init__(self, first_name, last_name, favorite=1, note=None, mobile_phone=None, office_phone=None, private_phone=None, email=None):
# self.first_name = first_name
# self.last_name = last_name
# self.favorite = favorite
# self.note = note
# self.mobile = mobile_phone
# self.office = office_phone
# self.private = private_phone
# self.email = email
# sam = Person("Sam", "Brown")
# print(sam.first_name, sam.last_name, sam.favorite)
| false
|
45c036e33d642d8ada09272dec7152a87dea512b
|
Sridhar-S-G/Python_programs
|
/Extract_numbers_from_String.py
| 370
| 4.125
| 4
|
'''
Problem Statement
A string will be given as input, the program must extract the numbers from the string and display as output
Example 1:
Input: Tony Stark's daughter says 143 3000
Output: 143 3000
Example 2:
Input: There4 I think you will be satis5ed with this tutorial
Output: 4 5
'''
#Solution Code
import re
s=input()
results= re.findall(r'\d+',s)
print(*results)
| true
|
3c4f4279850d8e2f0bb240fa3c2703b54f2796bc
|
simiss98/PythonCourse
|
/UNIT_1/Module1.2/MOD01_1-2.2_Intro_Python.py
| 1,583
| 4.21875
| 4
|
#creating name variable
name = "Petras"
# string addition
print("Hello " + name + "!")
# comma separation formatting
print("Hello to",name,"who is from Vilnius.")
print("Hello to","Petras","who is from Vilnius.")
# [ ] use a print() function with comma separation to combine 2 numbers and 2 strings
print("I was born at 1990. After",2,"years I will be",30,"years old.")
# [ ] get user input for a street name in the variable, street
print("enter Steet name")
street= input()
# [ ] get user input for a street number in the variable, st_number
print("enter street number")
st_number=input()
# [ ] display a message about the street and st_number
print("My home address is ",street,st_number,)
# [ ] define a variable with a string or numeric value
company="Bazaarvoice"
# [ ] display a message combining the variable, 1 or more literal strings and a number
print("I am working with",company,"for",3.5,"months.")
# [ ] get input for variables: owner, num_people, training_time - use descriptive prompt text
owner=input("Enter a name for contact person for training group: Python Academy")
num_people = input("Enter the total number attending the course:")
training_time = "5:00 PM"
# [ ] create a integer variable min_early and "hard code" the integer value (e.g. - 5, 10 or 15)
min_early = 10
# [ ] print reminder text using all variables & add additional strings - use comma separated print formatting
print("Reminder:","Python Academy training is scheduled at",training_time,"for",owner,"group of",num_people,"attendees.","Please arrive",min_early,"early for the first class.")
| true
|
9e4156f225546d0808d225b5078af06a872acff6
|
simiss98/PythonCourse
|
/UNIT_1/Module4.1/MOD04_1-6.1_Intro_Python.py
| 1,981
| 4.15625
| 4
|
#Task1
# [ ] Say "Hello" with nested if
# [ ] Challenge: handle input other than y/n
print("Please Say Hello")
hello_decision=input('"y" for yes or "n" for no: ' )
print()
#1st nested if
if hello_decision.lower()=="y":
#select hello type
print("Please select hello type.")
hello_type = input('"hello" for full hello or "hi" for Hi ')
print()
#2nd nested if elif else
if hello_type.lower() =="hello":
print("Say Hello. Thank you.")
elif hello_type.lower() == "hi":
print("Say hi. Thank you.")
else:
print("Sorry there is no such a hello type as ",hello_type, "Thank you.")
# still first nested elif else
elif hello_decision.lower() == "n":
print("Friendly nod")
else:
print("Sorry we do not understand your decision by,", hello_decision, "choice.")
print()
print("Good bye!")
print()
#Task2
# [ ] Create the "Guess the bird" program
print("Hello, guess what bird is my favorite, you have 3 attempts!")
correct_bird="Eagle"
def guess_bird(bird):
if bird.title() == correct_bird:
print("Yes you are right!")
elif bird.title() !=correct_bird:
print("That is incorrect try again, 2 attempts left")
print()
guess_2=input("Enter your 2nd guess").title()
if guess_2 == correct_bird:
print("Yes you are right!")
elif guess_2.title() != correct_bird:
print("Sorry you are wrong, try again")
print()
guess_3= input("3rd and last attempt, Good luck!").title()
if guess_3 == correct_bird:
print("Yes you are right!")
elif guess_3 != correct_bird:
print("You are wrong, but thanks for trying.")
else:
print("I do not understand your input")
else: print("I do not understand your input")
else:
print("I do not understand what you mean")
print(guess_bird(bird=input("You have 3 attempts enter your 1st guess")))
| false
|
6c19170153ee9669fbafe02192606989d031e7a5
|
simiss98/PythonCourse
|
/UNIT_1/Module1.1/MOD01_1-1.4.py
| 2,115
| 4.375
| 4
|
Task1
#creating x,y and z integer variables and then adding then calculating sum of 3 integers.
x=1
y=2
z=3
x+y+z
# displaying sum of float and integer.
65.7+4
#creating string name variable and then using print just for fun to display both strings.
name="Evaldas"
print("This notebook belongs to "+name)
#creating sm_number and big_number as integers, then displaying sum of those variables.
sm_number=4
big_number=5
sm_number+big_number
#creating a string value to the variable first_name and add to the string ", remember to save the notebook frequently.".
first_name="Evaldas"
fn=first_name
#Task2
#adding additional string to the variable new_msg and then printing variable new_msg.
new_msg = "My favorite food is"+" a Brisket, because Brisket is a KING!"
print(new_msg)
#adding additional integers to the variable new_sum and then printing new_sum variable.
new_sum =0+1-(57+23)*6+999
print(new_sum)
#creating 2 string variables and then printing them together.
new_msg="Hello World!"
new_msg_2=new_msg+" Hello Students!!"
print(new_msg_2)
#Task3
#fixing the variable: total_cost in order to print total_cost.
total_cost = 3 + 45
print(total_cost)
#fixing the variable: schoold_num in order to print school_num.
school_num = "123"
print("the street number of Central School is " + school_num)
#Hypothesis - When printing float+integer the outome is printed as float variable.
print(type(3.3))
print(type(3))
print(3.3 + 3)
#Task4
# Opening and closing quotes must be the same in order to print a string, e.g 'text' and "text".
print('my socks do not match')
#pront was miss-spelled to display a variable print should be used instead.
print("my socks match now")
#for printing anything we should add(). Brackets must open and close.
print("Save the notebook frequently")
#print command is case sensitive for printing variables, we must pay extra attention when typing varianles name inside ().
student_name = "Alton"
print(student_name)
#integers cannot be printed with string together, we must use String+String or Int_Int to print something.
total = "3"
print(total + " students are signed up for tutoring")
| true
|
5d22d099a117896b83c84babf34a3916a06504fc
|
Futi7/AnagramChecker
|
/main.py
| 1,949
| 4.1875
| 4
|
class AnagramChecker:
list_of_strings = []
first_string_keys = {}
second_string_keys = {}
list_of_keys = [first_string_keys, second_string_keys]
def __init__(self, first_string, second_string):
self.list_of_strings.append(first_string)
self.list_of_strings.append(second_string)
def check_if_anagrams(self):
for string, keys in zip(self.list_of_strings, self.list_of_keys):
for char in sorted(string):
if char not in keys:
keys[char] = 1
else:
keys[char] = keys.get(char) + 1
if self.list_of_keys[0] == self.list_of_keys[1]:
print("Is anagram")
else:
self.check_required_deletions()
def check_required_deletions(self):
chars_to_delete = [0,0]
first_keys, second_keys = self.list_of_keys
for key in first_keys:
if key in second_keys:
if first_keys[key] > second_keys[key]:
chars_to_delete[0] += (first_keys[key] - second_keys[key])
elif first_keys[key] < second_keys[key]:
chars_to_delete[1] += (second_keys[key] - first_keys[key])
else:
chars_to_delete[0] += first_keys[key]
for key in second_keys:
if key not in first_keys:
chars_to_delete[1] += second_keys[key]
print("remove " + str(chars_to_delete[0]) + " characters from '" + self.list_of_strings[0] + "' and " + str(chars_to_delete[1]) + " characters from '" + self.list_of_strings[1] + "'")
if __name__ == "__main__":
first_string = input("Enter first string:\n")
second_string = input("Enter second string:\n")
anagramChecker = AnagramChecker(first_string, second_string)
print("First:"+anagramChecker.list_of_strings[0]+ "\nSecond:"+anagramChecker.list_of_strings[1])
anagramChecker.check_if_anagrams()
| true
|
9498fe8866498ef6be30b8d8967dad971f09d801
|
charanchakravarthula/python_practice
|
/Baics.py
| 499
| 4.3125
| 4
|
# variable assignment
var = 1
print(var)
# multiple values assignment to a variable
var1,var2 =(1,2)
print(var1,var2)
#ignoring unwanted values
var1,__,__=[1,2,3]
print(var1)
var1=var2=var3=1
print(var1,var2,var3)
# knowing the type of the varible i.e data type of variable
var1=[1,2,3]
var2=('a',"b","c")
var3=1
var4=1.0
var5={'a':1,"b":2}
var6={1,2,3}
print(type(var1),type(var2),type(var3),type(var4),type(var5),type(var6),sep="\n")
# get the memory id of a variable
print(id(var1))
| true
|
e3e76c37ff817bae9836c142f0a7113ede554505
|
bang103/MY-PYTHON-PROGRAMS
|
/PYTHONINFORMATICS/DictDayOfWeek.py
| 871
| 4.25
| 4
|
#Exercise 9.2 in Python for INformatics
#Exercise 9.2 Write a program that categorizes each mail message by which day of
#the week the commit was done. To do this look for lines which start with *From*,
#then look for the third word and then keep a running count of each of the days
#of the week. At the end of the program print out the contents of your dictionary
#(order does not matter).
import string
filename = "mbox-short.txt"
try:
fhand=open(filename,"r")
except:
print "File %s does not exist"%(filename)
exit()
DaysOfWeek=dict()
for line in fhand:
if len(line)== 0: continue
if line.startswith("From:"): continue
if line.startswith("From"):
words=line.split()
day=words[2]
DaysOfWeek[day]= DaysOfWeek.get(day,0)+1
for day in DaysOfWeek:
print day, DaysOfWeek[day]
fhand.close()
| true
|
adc3327fe24e67694446fd98f023306cafd012d2
|
bang103/MY-PYTHON-PROGRAMS
|
/WWW.CSE.MSU.EDU/STRINGS/Cipher.py
| 2,729
| 4.25
| 4
|
#http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/
#implements encoding as well as decoding using a rotation cipher
#prompts user for e: encoding d: decoding or q: Qui
import sys
alphabet="abcdefghijklmnopqrstuvwxyz"
print "Encoding and Decoding strings using Rotation Cipher"
while True:
output=list()
inp=raw_input("Input E to encode, D to decode and Q to quit---> ")
if inp.lower()=="e": #encode
while True: #input rotation
inp2=raw_input("Input the rotation: an integer between 1 and 25 ---> ")
if inp2.isdigit()== False:
print " !!Error: Non digits!! The roatation is a whole number between 1 and 25"
elif int(inp2)>=1 and int(inp2)<=25:
rotation=int(inp2)
break
else:
print " Error! The roatation is a whole number between 1 and 25"
cipher = alphabet[rotation:]+ alphabet[:rotation]
instring=raw_input("Input string to be encoded---> ")
for char in instring:
if char in alphabet:
index=alphabet.find(char)
output.append(cipher[index])
else:
output.append(char)
outputstring = "".join(output)
print "The encoded string---> ",outputstring
elif inp.lower()=="d": #decode and find rotation
instring=raw_input( "Enter string to be decoded---> ")
word=raw_input( "Enter a word in the original(decoded) string ---> ")
rotation=0
found=False
for char in alphabet:
output=list()
rotation +=1
cipher=alphabet[rotation:]+alphabet[:rotation]
#decode encoded text with current rotation
for ch in instring:
if ch not in cipher:
output.append(ch)
elif ch in cipher:
index=cipher.find(ch)
output.append(alphabet[index])
outputstring="".join(output)
if word in outputstring: #IMPORTANT: This statement works only if we join the list into a string
found=True
break
else: continue
if found == True:
print "The rotation is %d"%(rotation)
print "The decoded string is ---> ", outputstring
else:
print "Cannot be decoded with rotation cipher: try another sentence"
elif inp.lower()=="q":
print "Bye! See you soon"
break
| true
|
dc6af3be13be922128409b78b11cec0001d236ae
|
judy1116/pythonDemo
|
/Tester/err_raise.py
| 2,257
| 4.15625
| 4
|
#因为错误是class,捕获一个错误就是捕获到该class的一个实例。因此,错误并不是凭空产生的,而是有意创建并抛出的。Python的内置函数会抛出很多类型的错误,我们自己编写的函数也可以抛出错误。
#如果要抛出错误,首先根据需要,可以定义一个错误的class,选择好继承关系,然后,用raise语句抛出一个错误的实例:
# err_raise.py
class FooError(ValueError):
pass
def foo(s):
n = int(s)
if n==0:
raise FooError('invalid value: %s' % s)
return 10 / n
foo('0')
#只有在必要的时候才定义我们自己的错误类型。如果可以选择Python已有的内置的错误类型(比如ValueError,TypeError),尽量使用Python内置的错误类型。
#最后,我们来看另一种错误处理的方式:
# err_reraise.py
def foo(s):
n = int(s)
if n==0:
raise ValueError('invalid value: %s' % s)
return 10 / n
def bar():
try:
foo('0')
except ValueError as e:
print('ValueError!')
raise
bar()
#在bar()函数中,我们明明已经捕获了错误,但是,打印一个ValueError!后,又把错误通过raise语句抛出去了,这不有病么?
#其实这种错误处理方式不但没病,而且相当常见。捕获错误目的只是记录一下,便于后续追踪。但是,由于当前函数不知道应该怎么处理该错误,所以,最恰当的方式是继续往上抛,让顶层调用者去处理。好比一个员工处理不了一个问题时,就把问题抛给他的老板,如果他的老板也处理不了,就一直往上抛,最终会抛给CEO去处理。
#raise语句如果不带参数,就会把当前错误原样抛出。此外,在except中raise一个Error,还可以把一种类型的错误转化成另一种类型:
###########小结###########
#Python内置的try...except...finally用来处理错误十分方便。出错时,会分析错误信息并定位错误发生的代码位置才是最关键的。
#程序也可以主动抛出错误,让调用者来处理相应的错误。但是,应该在文档中写清楚可能会抛出哪些错误,以及错误产生的原因。
| false
|
0359b15055f14630eac6508c0864216f3ad89225
|
judy1116/pythonDemo
|
/OOPAdvance/create_class_on_the_fly.py
| 2,151
| 4.375
| 4
|
#type()
#动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的。
#比方说我们要定义一个Hello的class,就写一个hello.py模块:
class Hello(object):
def hello(self,name='world'):
print('Hello,%s.'%name)
#当Python解释器载入hello模块时,就会依次执行该模块的所有语句,执行结果就是动态创建出一个Hello的class对象,测试如下:
#from hello import Hello
h=Hello()
print(h.hello())
print(type(Hello))
print(type(h))
#type()函数可以查看一个类型或变量的类型,Hello是一个class,它的类型就是type,而h是一个实例,它的类型就是class Hello。
#我们说class的定义是运行时动态创建的,而创建class的方法就是使用type()函数。
#type()函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义:
def fn(self,name='world'):#先定义函数
print('Hello,%s.'%name)
Hello=type('Hello',(object,),dict(hello=fn))#创建Hello class
h=Hello()
print(h.hello())
print(type(Hello))
print(type(h))
#要创建一个class对象,type()函数依次传入3个参数:
#class的名称;
#继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
#class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
#通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。
#正常情况下,我们都用class Xxx...来定义类,但是,type()函数也允许我们动态创建出类来,也就是说,动态语言本身支持运行期动态创建类,这和静态语言有非常大的不同,要在静态语言运行期创建类,必须构造源代码字符串再调用编译器,或者借助一些工具生成字节码实现,本质上都是动态编译,会非常复杂。
| false
|
a2d0a206f388c10fa50dfc51041efd4fd85bc34b
|
judy1116/pythonDemo
|
/FuncCode/doSorted.py
| 886
| 4.375
| 4
|
#Python内置的sorted()函数就可以对list进行排序:
print(sorted([36,5,-12,9,-21]))
#sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序:
print(sorted([36,5,-12,9,-21],key=abs))
print(sorted(['bob', 'about', 'Zoo', 'Credit']))
#我们给sorted传入key函数,即可实现忽略大小写的排序:
print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower))
#要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True:
print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower, reverse=True))
#练习
#假设我们用一组tuple表示学生名字和成绩:
from operator import itemgetter
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
print(sorted(L,key=itemgetter(0)))
print(sorted(L,key=itemgetter(1),reverse=True))
| false
|
27e4ef0d8bb177a902727eabc24249c933fbb6e2
|
AO-AO/pyexercise
|
/ex8.py
| 653
| 4.4375
| 4
|
"""
Define a function called anti_vowel that takes one string,
text, as input and returns the text with all of the vowels removed.
For example: anti_vowel("Hey You!") should return "Hy Y!".
"""
def anti_vowel(text):
result = ""
lenth = len(text)
for i in xrange(0, lenth):
if i == 0:
result = result + text[i]
elif i == lenth - 1:
result = result + text[i]
elif text[i] == ' ':
result = result + text[i]
elif text[i - 1] == ' ' or text[i + 1] == ' ':
result = result + text[i]
return result
result = anti_vowel("ni hao sunasdlfk kekendfa!")
print result
| true
|
6dad0e0b1ac99cd489e20a297b8b9929a6d8b77e
|
Trollernator/Lesson
|
/app.py
| 929
| 4.25
| 4
|
#variable
#data types int, float, str
#input(), print(), type()
# len() shows the lenght of str
# upper() makes the letters BIG
# lower() makes the letters smol
# capitalize() captitalize the first letter
# replace() replace certain letters
# FirstName="Tom"
# print(FirstName.find("enter search"))
# a=58
# b=108
# if a>b : print("A")
# else: print("B")
# a = int(input("a number:"))
# b = int(input("b number:"))
# if a==b:print("a and b are equal")
# else:print("a and b are NOT equal")
# a = int(input("a number:"))
# # b = int(input("b number:"))
# if a<100: print("a is smaller than 100")
# elif a<1000: print ("a is smaller than 1000")
# else:print("a is greater than 100")
a=int(input("a number:"))
if a>100:print("true")
else:print("false")
# a=int(input("a number:"))
# if a<100 and a>9: #and, or, not
# print("2 digit number")
# else:
# print("not 2 digit number")
if a%3==0:print("true")
else:print("false")
| true
|
df6dc1e87f1a2861224107bbba1c901a0b89e094
|
rajeshvermadav/XI_2020
|
/character_demo.py
| 376
| 4.3125
| 4
|
#program to display indivual character
name = input("Enter any name")
print("Lenght of the string is :", len(name))
print("Location or memmory address of the Character :",len(name)-1)
print("Character is :", name[len(name)-6])
print("Substring is :",name[1])
print("Substring is :",name[-1])
print("Substring is :",name[::1])
print("Reverse string:", name[::-1])
| true
|
841d3b45c6dd57d8fccbfcc984c26677fe96107e
|
rajeshvermadav/XI_2020
|
/relationoper_demo.py
| 414
| 4.1875
| 4
|
#Relational Operator Demo Program
a = int(input("Enter First Number:-"))
b = int(input("Enter Second Number:-"))
print("A>B is :", a>b) #Greater than
print("A<B is :", a<b) #Less than
print("A===B is :", a==b) #Equal to
print("A!=B is :", a!=b) #Not equal to
print("A>=B is :", a>=b) #Greater Than Equal to
print("A<=B is :", a<=b) #Less than equal to
| false
|
4849a377f3eb05b5e074e959b1aaf16793754daf
|
rajeshvermadav/XI_2020
|
/sample3no_if.py
| 498
| 4.15625
| 4
|
#Program to input three numbers calculate sum of numbers and non duplicate numbers
s1 = s2 = 0
a = int(input("Enter first number: "))
b = int(input("Enter Second number: "))
c = int(input("Enter Third number: "))
s1 = a + b + c
if a != b and a != c:
s2= s2 + a
print(a)
if b!= a and b != c:
s2 = s2 + b
if c != a and c != b:
s2 = s2 + c
print(" Numbers are : ",a,b,c)
print(" Sum of three numbers is:", s1)
print(" Sum of non - duplicate number is :", s2)
| false
|
cdc710c7c64c2029fa2b53f210689162fcaf1931
|
acs/python-red
|
/leetcode/two-sum/two-sum.py
| 746
| 4.15625
| 4
|
from typing import List, Tuple
def twoSum(nums, target):
twoSumTargetTuples = []
for (i, number) in enumerate(nums):
for otherNumber in nums[i+1:]:
print(number, otherNumber)
# Move this logic to a function
if (number + otherNumber) == target:
if [number, otherNumber] not in twoSumTargetTuples and [otherNumber, number] not in twoSumTargetTuples:
twoSumTargetTuples.append([number, otherNumber])
return twoSumTargetTuples
if __name__ == '__main__':
listToSum = [1, 2, 1, 0, 3]
listSolution = [(1, 2)]
target = 3
solution = twoSum(listToSum, target)
if solution != listSolution:
print(f'{solution} is not {listSolution}')
| true
|
7f8b3ceeff28f59b0b186d3b3dbd8a7bafd24fdc
|
Environmental-Informatics/building-more-complex-programs-with-python-roccabye
|
/Program_7.1.py
| 2,669
| 4.375
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 09:55:50 2020
Lab Assignment02
ThinkPython 2e, Chapter 7: Exercise 7.1
This program finds the Square Root of a number by using the famous newton's Method approach
and using the function from 'math' library. And compares the absolute values estimated from the two approach.
@author: tiwari13 (Alka Tiwari)
"""
# Importing the required module
import math
# creating a function to compute sqaure root of 'a' using Newton's method.
def mysqrt(a):
x= a/5 #Initial estimate of square root of 'a'
while True:
y=(x + a/x)/2 # equation to estimate square root using newton's method.
if abs(y-x)<0.0000001: # the absolute magnitude difference between 'x' and 'y' is set to 0.0000001
return(x)
break
x=y
def test_square_root():
''' This function tests Newton's method by comparing it with a built in function
math.sqrt(). And prints a table with number ranging from 1 to 9 and second column
gives Newton's method estimate of sqaure root and third column has math.sqrt() estimate
and fourth colum shows the difference in the magnitude of column two and three to compare
the estimates from two methods.
'''
header = ['a', 'mysqrt(a)', 'math.sqtr(a)', 'diff'] # Creates the header of the table
print ('{:<8s}{:<30s}{:<30s}{:<30s}'.format(header[0], header[1], header[2], header[3]))
print ('{:<8s}{:<30s}{:<30s}{:<30s}'.format('-','--------','------------','----')) # to represent --- as shown in table for first row after the header.
for a in range (1,10): # First Column of the table gives vallue of 'a' from 1 to 9
my_sqrt = mysqrt(a) # Second Column - Finding Square root of 'a' Using Newton's method
math_sqrt = math.sqrt(a) # Third Column - Finding Square root of 'a' Using built in function
diff = abs(my_sqrt - math_sqrt) # Fourth Column - to compare the estimates.
lt = [a, math_sqrt, math_sqrt, diff]
print ('{:<8.1f}{:<30s}{:<30s}{:<30s}'.format(lt[0], str(lt[1]), str(lt[2]), str(lt[3])))
test_square_root()
| true
|
1d21943dace332bd3f0e6a601808cdbb9bf9fe72
|
Gchesta/assignment_day_2
|
/fizz_buzz.py
| 341
| 4.1875
| 4
|
def fizz_buzz(entry):
if entry % 3 == 0 and entry % 5 == 0: #tests for numbers that are divisible by both three and five
return "FizzBuzz"
elif entry % 3 == 0: #tests for numbers that are divisible by three
return "Fizz"
elif entry % 5 == 0: #tests for numbers that are divisible by five
return "Buzz"
else:
return entry
| false
|
d6aa20a31894a3f6e94e0d964de05c0e2c232f50
|
RuthieRNewman/hash-practice
|
/hash_practice/exercises.py
| 2,735
| 4.125
| 4
|
#This is a solution that I worked out with a study group hosted by a TA and Al. It was working
#until I made some changes and now I cant seem to figure out what I did or how it was
#really working in the first place. I will continue to work on it but I didnt feel it was worthy
#turning in fully.
def anagram_helper(word1, word2):
if sorted(word1) == sorted(word2):
return True
else:
return False
def grouped_anagrams(strings):
hash_set = {}
temp_array_strings = []
anagrams = []
for i, word1 in enumerate(strings):
if word1 in hash_set:
continue
temp_array_strings.append(word1)
hash_set[word1] = 1
for j, word2 in enumerate(strings):
if anagram_helper(word1, word2):
if word2 not in hash_set:
temp_array_strings.append(word2)
hash_set[word2] = 1
anagrams.append(temp_array_strings)
print(anagrams)
temp_array_strings = []
return anagrams
def top_k_frequent_elements(nums, k):
""" This method will return the k most common elements
In the case of a tie it will select the first occuring element.
Time Complexity: ?
Space Complexity: ?
"""
freq_map = {}
k_freq_elements = []
if nums:
for num in nums:
if num not in freq_map:
freq_map[num] = 1
else:
freq_map[num] += 1
for i in range(0,k):
key_with_max_val = max(freq_map, key=freq_map.get)
k_freq_elements.append(key_with_max_val)
del freq_map[key_with_max_val]
return k_freq_elements
def valid_sudoku(table):
""" This method will return the true if the table is still
a valid sudoku table.
Each element can either be a ".", or a digit 1-9
The same digit cannot appear twice or more in the same
row, column or 3x3 subgrid
Time Complexity: ?
Space Complexity: ?
"""
for row in range(0,9):
row_map = {}
for col in range(0,9):
tile = table[row][col]
if tile == ".":
continue
elif tile not in row_map:
row_map[tile] = 1
else:
return False
for col in range(0,9):
col_map = {}
for row in range (0,9):
tile = table[row][col]
if tile == ".":
continue
elif tile not in col_map:
col_map[tile] = 1
else:
return False
return True
| true
|
f43686010662ea48a1eb685b277f3b991b2d9092
|
angminsheng/python-learn
|
/data-type.py
| 983
| 4.15625
| 4
|
user_age = int(input("What is your age?"))
user_age_month = user_age * 12
print(f"you are {user_age}years old or {user_age_month} months old.")
l = ["bob", "john", "sally"]
t = ("bob", "john", "sally")
h = {"bob", "john", "sally"}
l.append("rosie")
h.add("molly")
friends = {"bob", "ken" , "simon"}
other_friends = {"jasmine", "tom", "jimmy"}
abroad = {"bob", "ken"}
local_friends = friends.difference(abroad)
print(local_friends)
total_friends = friends.union(other_friends)
print(total_friends)
art = {"bob", "tom", "susie"}
science = {"bob"}
both = art.intersection(science)
print(both)
team_a = ["ken", "bob"]
team_b = ["ken", "bob"]
print(team_a == team_b)
print(team_a is team_b)
# if statment
day_of_week = input("Which day of the week is today?").lower()
if day_of_week == "Monday":
print("Have a nice week!")
elif day_of_week == "Tuesday":
print("Full speed ahead!")
else:
print("Almost there!")
fruits = ["apple", "orange", "pear"]
print("apple" in fruits)
| false
|
9958cd212de0d2c36d608a088f100429c95dd6ff
|
jadeaxon/hello
|
/Python/generator.py
| 772
| 4.46875
| 4
|
#!/usr/bin/env python
# Python has special functions called generators.
# All a generator is is an object with a next() method that resumes where it left off each time it is called.
# Defining a function using yield creates a factory method that lets you create a generator.
# Instead of using 'return' to return a value, you use 'yield'.
# That's it!
def g(step, max_steps):
i = 0
steps = 0 # Steps completed.
while True:
if steps >= max_steps: break
yield i
i += step
steps += 1
generator = g(3, 10)
print generator.next()
print generator.next()
print generator.next()
print generator.next()
print generator.next()
print generator.next()
print
# Generators work well in for loops.
for value in g(5, 30):
print value
| true
|
711b0da87e3c90aa3fd25c9d902d2c8433d796ea
|
jadeaxon/hello
|
/Python 3/interview/singly_linked_list.py
| 2,260
| 4.21875
| 4
|
#!/usr/bin/env python3
"""
A singly-linked list class that can be reversed in place.
Avoids cycles and duplicate nodes in list.
"""
class Node(object):
"""A node in a singly-linked list."""
def __init__(self, value):
self.next = None
self.value = value
class SinglyLinkedList(object):
"""A singly-linked list of nodes."""
def __init__(self):
self.head = None
self.tail = None
def append(self, node):
"""Append a node to the end this list. No duplicates or cycles allowed."""
# Do not allow duplicate nodes in the list.
n = self.head
while n:
if n == node: raise ValueError("illegal append of duplicate node")
n = n.next
if self.tail:
self.tail.next = node
self.tail = node
node.next = None # Prevent cycles.
if not self.head:
self.head = node
def reverse(self):
"""Reverse this list in place."""
head = self.head
if head is None: return # Size 0.
if head.next is None: return # Size 1.
new_head = head.next
while new_head:
# A -> B -> C
# h
# n
temp = new_head.next
new_head.next = head
if head == self.head:
head.next = None
head = new_head
new_head = temp
# A <- B C
# t
# h
# n
#----
# A <- B <- C
# t
# h
# n
self.tail = self.head
self.head = head
def __str__(self):
"""Render this list as a string."""
s = ""
n = self.head
s += "s["
while n:
s += n.value
n = n.next
if n: s += " -> "
s += "]"
return s
# Create a list and reverse it.
sll = SinglyLinkedList()
node1 = Node("A")
node2 = Node("B")
node3 = Node("C")
node4 = Node("D")
sll.append(node1)
sll.append(node2)
sll.append(node3)
sll.append(node4)
try:
sll.append(node2)
except ValueError:
print("Okay, not adding duplicate node.")
print(sll)
sll.reverse()
print(sll)
| true
|
ea91e41e939909b6d58f425c36b4f4203ce7de72
|
jadeaxon/hello
|
/Python/LPTHW/example33.py
| 315
| 4.15625
| 4
|
#!/usr/bin/env python
i = 0
numbers = []
while i < 6:
print "At the top, i is %d." % i
numbers.append(i)
# i++ -- Are you joking? No ++ operator!!!
i += 1
print "Numbers now: ", numbers
print "At the bottom, i is %d" % i
print "The numbers: "
for number in numbers:
print number
| true
|
af1558e78172d696613b99a8a110d69ba8751db2
|
SheezaShabbir/Python-code
|
/Date_module.py
| 546
| 4.4375
| 4
|
#Python Dates
#A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
#Example
#Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
print(x)
x = datetime.datetime(2020, 5, 17)
#The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone)
#but they are optional, and has a default value of 0, (None for timezone).
print(x)
| true
|
f07443f0174818f2a9abadcd724ce6b60d9ebdd1
|
SheezaShabbir/Python-code
|
/finaltestithink.py
| 889
| 4.1875
| 4
|
def str_analysis(pass_argument):
if(pass_argument.isdigit()):
int_conversion=int(pass_argument)
if(int_conversion>90):
printvalue=str(int_conversion)+" "+"is pretty big number."
return printvalue
elif(int_conversion<90):
printvalue=str(int_conversion)+" "+"is pretty small number than expected."
return printvalue
else:
printvalue=str(int_conversion)+" "+"is number between expected."
return printvalue
elif(pass_argument.isalpha()):
printvalue=pass_argument+" "+"is all alphabetical characters!"
return printvalue
else:
printvalue=pass_argument+" "+"neither all alpha nor all digit."
return printvalue
while True:
stro=input("enter a word or a digit:")
if(stro!=""):
print(str_analysis(stro))
break
| true
|
6a20b87f76f5e01dab9552208c1a42b197199e9a
|
jmavis/CodingChallenges
|
/Python/DecimalToBinary.py
| 1,796
| 4.3125
| 4
|
#---------------------------------------------------------
# Author: Jared Mavis
# Username: jmavis
# Problem name: Decimal To Binary
# Problem url: https://www.codeeval.com/open_challenges/27/
#---------------------------------------------------------
import sys
import math
#---------------------------------------------------------
# Function definitions
#---------------------------------------------------------
def FindLargestPowerOf2(num):
""" Will find the largest power of 2 that will fit inside
the given number."""
return (math.floor(math.log(num,2)))
# end FindLargestPowerOf2()
def DecimalToBinary(num):
""" Will convert the given decimal number to binary.
*Note bin(num) will give the binary representation
but for fun I made this function. """
currentPower = FindLargestPowerOf2(num)
currentNumber = num
while (currentPower >= 0):
powerOf2 = math.pow(2, currentPower)
currentPower -= 1
if (powerOf2 <= currentNumber):
currentNumber -= powerOf2
sys.stdout.write('1')
else:
sys.stdout.write('0')
print
# end DecimalToBinary()
def ParseLine(line):
""" Reads the line and will call CountNumOneBits
with the appropriate arguments"""
DecimalToBinary(int(line))
# end ParseLine()
def ReadFile(file):
""" Reads in and parses the lines of the given file"""
for line in file.readlines():
line = line.rstrip() #remove endline
ParseLine(line)
#end ReadFile()
#---------------------------------------------------------
# Running Test Cases
#---------------------------------------------------------
test_cases = open(sys.argv[1], 'r')
ReadFile(test_cases)
test_cases.close()
| true
|
b2d2dd3baed364c81e22d193586c21f0abbd56d0
|
jmavis/CodingChallenges
|
/Python/Star.py
| 898
| 4.4375
| 4
|
#------------------------------------------------------------------------------
# Jared Mavis
# jmavis@ucsc.edu
# Programming Assignment 2
# Star.py - Creates an n-pointed star based on user input
#------------------------------------------------------------------------------
import turtle
numPoints = int(input("Enter an odd integer greater than or equal to 3: "))
if (numPoints < 3 or numPoints%2 == 0):
raise ValueError("Enter an odd integer greater that or equal to 3")
angle = (180 - (180 / numPoints))
window = turtle.Screen()
window.title(str(numPoints)+"-pointed star")
drawer = turtle.Turtle()
drawer.pensize(2)
drawer.color("blue", "green")
drawer.backward(150)
drawer.speed(0)
drawer.begin_fill()
for i in range(numPoints):
drawer.forward(300)
drawer.dot(10, "red")
drawer.right(angle)
drawer.end_fill()
drawer.hideturtle()
window.mainloop();
| true
|
daaf1572ef7bf3971cd3a1e27c3397622aa0a172
|
schoentr/data-structures-and-algorithms
|
/code-challanges/401_code_challenges/linked_list/linked_list.py
| 2,852
| 4.25
| 4
|
from copy import copy, deepcopy
class LinkedList():
head = None
def __init__(self, iterable=None):
"""This initalizes the list
"""
self.head = None
if iterable:
for value in iterable:
self.insert(value)
def __iter__(self):
"""This makes the linked list iterable
"""
current = self.head
while current:
yield current.value
current = current._next
def __add__(self, iterable):
"""This makes it able to add an iterable to the linked-list
"""
new_list = deepcopy(self)
for value in iterable:
new_list.insert(value)
return new_list
def __iadd__(self, value):
"""This method makes it able to use "+="to add value to linked list
Arguments:
value -- [data to be added to the linked list]
"""
self.insert(value)
return self
def insert(self, value):
"""This Method inserts a value into the Linked List
Arguments:
value -- the value being expresessed as value in the node
"""
node = Node(value)
if not self.head:
self.head = node
else:
current = self.head
while current._next:
current = current._next
current._next = node
def includes(self, value):
"""[summary]
Arguments:
value -- [the value being expressed as value in the node]
Returns:
[Boolean] -- [True if value is in the Linked list // False if not in list]
"""
current = self.head
while current._next:
if current.value == value:
return True
current = current._next
return True
def print(self):
""" This method prints the values of all nodes in the list
Returns:
[string] -- [ A string containg comma seperated values of the list]
"""
output = ''
current = self.head
while current:
output += current.value + ', '
current = current._next
return output
def find_from_end(self, value):
length = 0
curr = self.head
while curr:
length += 1
curr = curr._next
distance = length - value - 1
curr = self.head
if length > value:
for x in range(0, distance):
curr = curr._next
return curr.value
else:
return 'exception'
class Node():
def __init__(self, value):
"""Creates all nodes for the list
Arguments:
value -- [Any value you want to be held in the node]
"""
self.value = value
self._next = None
| true
|
78a6e7972a8960932922e1aad5982183086a8670
|
schoentr/data-structures-and-algorithms
|
/code-challanges/401/trees/fizzbuzz.py
| 809
| 4.15625
| 4
|
from tree import BinaryTree
def fizzbuzz (self, node = None):
"""
This Method traverses across the tree in Order.
Replacing the value if divisable by 3 to Fizz, if divisibale by 5 to buzz and if divisiable by both 3 and 5 to fizzbuzz
"""
rtn = []
if node is None:
node= self.root
if node.child_left:
rtn += self.fizzbuzz(node.child_left)
if (int(node.value) % 3 == 0) and (node.value % 5 == 0) :
node.value = 'fizzbuzz'
elif int(node.value) % 3 is 0:
node.value = 'fizz'
elif int(node.value) % 5 is 0:
node.value = 'buzz'
rtn.append(node.value)
if node.child_right:
rtn += self.fizzbuzz(node.child_right)
return rtn
| true
|
8e3a079278d9a5c59df34cbbe77c2b10a47449f6
|
schoentr/data-structures-and-algorithms
|
/code-challanges/401_code_challenges/sorts/radix_sort/fooradix_sort.py
| 2,103
| 4.125
| 4
|
def radix_sort(inpt_list, base=10):
"""This sort takes in a list of positive numbers and returns the list sorted in place.
Arguments:
inpt_list {[list]} -- [Unsorted List]
Keyword Arguments:
base {int} -- [description] (default: {10})
Returns:
[list] -- [Sorted List]
"""
if inpt_list == []:
return
def key_factory(digit, base):
"""This fuction creates the keys.
Arguments:
digit {[type]} -- [description]
base {[type]} -- [description]
Returns:
[type] -- [description]
"""
def key(alist, index):
"""This helper function takes in the unsorted list and and index and returns the digit at that location.
Arguments:
alist {list} -- [unsorted list]
index {int} -- [index of list to be evaluated]
Returns:
[int] -- [the digit that is in the place being evaluated]
"""
return ((inpt_list[index]//(base**digit)) % base)
return key
largest = max(inpt_list)
exp = 0
while base**exp <= largest: # checks to see if all values have been covered
inpt_list = count_sort(inpt_list, key_factory(exp, base))
exp = exp + 1
return inpt_list
def count_sort(inpt_list, key):
""" This sorts a list by counting the number of occurances a given digt occurs,
Arguments:
inpt_list {list}
key {int}
list_range {int}
Returns:
[list]
"""
list_range = 9
count_list = [0]*(list_range + 1)
for i in range(len(inpt_list)):
count_list[key(inpt_list, i)] = count_list[key(inpt_list, i)] + 1
count_list[0] = count_list[0] - 1
for i in range(1, list_range + 1):
count_list[i] = count_list[i] + count_list[i - 1]
result = [None]*len(inpt_list)
for i in range(len(inpt_list) - 1, -1, -1):
result[count_list[key(inpt_list, i)]] = inpt_list[i]
count_list[key(inpt_list, i)] = count_list[key(inpt_list, i)] - 1
return result
| true
|
c0a814a1761bd9b11510500386eee4044f4f3d75
|
abhinab1927/Data-structures-through-Python
|
/ll.py
| 1,631
| 4.21875
| 4
|
class Node:
def __init__(self,val):
self.next=None
self.value=val
def insert(self,val):
if self.value:
if self.next is None:
self.next=Node(val)
else:
self.next.insert(val)
else:
self.value=val
def print_ll(self):
if self.value:
while self.next!= None:
print(self.value)
self=self.next
print(self.value)
else:
print("LL is empty")
def delete(self,val):
i=0
while self.value!=val and self.next!=None:
i+=1
self=self.next
if self.next!=None:
print("position is ",i)#find the index of value
self=n1
for j in range(0,i-1): #travel to the node before it
self=self.next
k=self #Store the previous position in a variable
l=self
k=k.next.next #take another variable and store the next value of the element to be deleted
l.next=k
'''Eliminate the current node by pointing the next value of the previous node to the next value of
the element to be deleted'''
else:
print("Element Not found")
n1=Node(5)
n1.insert(12)
n1.insert(4)
n1.insert(6)
n1.insert(15)
print("Before deleting")
n1.print_ll()
n1.delete(6)
print("After deleting")
n1.print_ll()
n1.delete(163)
| true
|
e556737d693fb598ee89751696aa05ff4b791e9a
|
moemaair/Problems
|
/stacks/python/sort_stack.py
| 2,680
| 4.1875
| 4
|
from Stack import Stack
from Stack import build_stack_from_list
"""
Sort Stack
Write a method to sort a stack in ascending order
Approaches:
1) 3 stacks - Small, Large, Current
2) Recursive - Sort and Insertion Sort
"""
def sort_stack_recursive(stack):
if len(stack) == 0:
return
elem = stack.pop()
sort_stack_recursive(stack)
insert(stack, elem)
def insert(stack, elem):
"""Insertion Sort for Stacks!"""
if len(stack) == 0:
stack.append(elem)
else:
top = stack.pop()
#To reverse a stack just remove this conditional
if top >= elem:
stack.append(top)
stack.append(elem)
else:
insert(stack, elem)
stack.append(top)
def sort_stack(stack):
large = Stack()
small = Stack()
while not stack.is_empty() or not small.is_empty():
while not stack.is_empty():
value = stack.pop()
if large.is_empty() or small.is_empty():
if stack.peek() is None:
large.push(value)
elif value > stack.peek():
large.push(value)
small.push(stack.pop())
else:
large.push(stack.pop())
small.push(value)
elif value > large.peek():
small.push(large.pop())
large.push(value)
else:
small.push(value)
tmp = stack
stack = small
small = tmp
return large
#Tests
def test_sort_stack():
inputstack = build_stack_from_list([3,4,1])
outputstack = sort_stack(inputstack)
answerstack = build_stack_from_list([4,3,1])
assert answerstack.equals(outputstack) == True
def test_sort_stack_big():
inputstack = build_stack_from_list([3,6,2,9,10,4,1,-4,6])
outputstack = sort_stack(inputstack)
outputstack.display()
answerstack = build_stack_from_list([10,9,6,6,4,3,2,1,-4])
assert answerstack.equals(outputstack) == True
def test_sort_stack_1_element():
inputstack = build_stack_from_list([3])
outputstack = sort_stack(inputstack)
answerstack = build_stack_from_list([3])
assert answerstack.equals(outputstack) == True
def test_sort_stack_empty():
inputstack = build_stack_from_list([])
outputstack = sort_stack(inputstack)
answerstack = build_stack_from_list([])
assert answerstack.equals(outputstack) == True
def test_sort_stack_recursive():
s1 = [8,3,1,4,2,5,9,7,6]
outputstack = [9,8,7,6,5,4,3,2,1]
sort_stack_recursive(s1)
assert s1 == outputstack
if __name__ == "__main__":
test_sort_stack()
test_sort_stack_1_element()
test_sort_stack_empty()
test_sort_stack_big()
test_sort_stack_recursive()
| true
|
176d58d5bd2b5c3148c3882d9010a9be36568071
|
moemaair/Problems
|
/strings/python/is_rotation.py
| 2,181
| 4.375
| 4
|
#Cases
"""
1) Empty string
2) Normal is rotation 1-step
3) Normal is rotation multistep
4) Normal no rotation same chars
5) 1,2,3+ length
6) Strings not same length == False
"""
#Approaches
"""
1) Submethod called "rotate" which rotates string one-place, main method rotates str2 len(str1) times, checks if strings are equal
2) Loop through str1 one time, if str2[i] == str1[i] then increment both and keep going. If you reach a str2[i] that doesn't
match str1[i], you start from beginning, where str1[i] == str2[i+1]. If you reach end of str1 with all equal, return True
"""
def rotate_string(str1):
#rotate 1 place
if len(str1) < 2:
return str1
return str1[-1] + str1[:-1]
def is_rotation(str1, str2):
if len(str1) != len(str2):
return False
if len(str1) == 0:
return True
i = 0
while i < len(str1):
if str1 == str2:
return True
str2 = rotate_string(str2)
i+=1
return False
def is_rotation_loops(str1, str2):
if len(str1) != len(str2):
return False
if len(str1) == 0:
return True
attempts = len(str1)
str1_pos = 0
str2_pos = 0
str2_start = 0
are_rotations = True
while attempts > 0 and str1_pos < len(str1):
are_rotations = True
if str2_pos == len(str1):
str2_pos = 0
if str1[str1_pos] != str2[str2_pos]:
are_rotations = False
str2_start += 1
str2_pos = str2_start
str1_pos = 0
attempts -= 1
else:
str1_pos += 1
str2_pos += 1
return are_rotations
#Tests
def test_rotate_string():
assert rotate_string("ABC") == "CAB"
assert rotate_string("BA") == "AB"
assert rotate_string("") == ""
assert rotate_string("A") == "A"
def test_is_rotation():
assert is_rotation("ABC","CAB") == True
assert is_rotation("ABC","BCA") == True
assert is_rotation("","") == True
assert is_rotation("AABB", "ABAB") == False
assert is_rotation("A","A") == True
def test_is_rotation_loops():
assert is_rotation_loops("ABC","CAB") == True
assert is_rotation_loops("ABC","BCA") == True
assert is_rotation_loops("","") == True
assert is_rotation_loops("AABB", "ABAB") == False
assert is_rotation_loops("A","A") == True
if __name__ == "__main__":
test_rotate_string()
test_is_rotation()
test_is_rotation_loops()
| true
|
e37c22e6e03c1a576b264ae00769edbf084fcc4b
|
moemaair/Problems
|
/graphs/python/pretty_print.py
| 1,411
| 4.125
| 4
|
from Graph import Graph
from Graph import build_test_graph
from Vertex import Vertex
"""
Pretty Print
Starting with a single Vertex, implement a method that prints out a
string representation of a Graph that resembles a visual web
Approach:
1) Using BFS, extract all unique vertices from the graph into set
2) Loop through vertices, plot each vertex into a arbitrary coordinates in matrix
3) Rearrange vertices in matrix until correctly positions
4) Pass matrix into format string method to print output
"""
def extract_vertices(vertex):
"""
Input: starting Vertex, value to find
Output: return closest Vertex that contains value
Graph is a digraph. So it has cycles. Values can repeat.
"""
neighbors = []
visited = set() #all unique elements
neighbors.append(vertex)
while len(neighbors) > 0:
vertex = neighbors.pop(0)
for neighbor in vertex.neighbors:
if neighbor not in visited:
neighbors.append(neighbor)
visited.add(neighbor)
return visited
def plot_to_array(vertices):
return []
def pretty_print(vertices_arr=[]):
print vertices_arr
def test_pretty_print():
graph = build_test_graph()
graph.pretty_print()
vertices = graph.vertices
v1 = vertices[0] #A
v2 = vertices[1] #B
v3 = vertices[2] #C
v4 = vertices[3] #D
v5 = vertices[4] #E
vertices_set = extract_vertices(graph.vertices[0])
print vertices_set
if __name__ == "__main__":
test_pretty_print()
| true
|
469a59d991f878a9a668df228b310a9d633a60f4
|
moemaair/Problems
|
/stacks/python/stacks_w_array.py
| 1,569
| 4.125
| 4
|
from Stack import Stack
from Node import Node
"""
Stacks with Array
Implement 3 stacks using a single array
Approaches
1) Index 0, 3, 6.. first stack. 1, 4, 7.. second stack. 2, 5, 8.. third stack.
"""
class StacksWithArray(object):
def __init__(self):
self.array = [None for x in range(99)]
# Represent next available open position
self.stack_positions = {
0 : 0,
1 : 1,
2 : 2
}
self.INCREMENT = 3
def push(self, stackno, value):
"""
Find the current open position in array
of the stack (0-2) requested by client
Add value, then increment to next open position
"""
index = self.stack_positions[stackno]
self.array[index] = value
self.stack_positions[stackno] += self.INCREMENT
print "stack positions = " + str(self.stack_positions)
print "array values = " + str(self.array)
def pop(self, stackno):
index = self.stack_positions[stackno]
if index > stackno:
self.stack_positions[stackno] -= self.INCREMENT
index = self.stack_positions[stackno]
value = self.array[index]
self.array[index] = None
print "stack positions = " + str(self.stack_positions)
print "array values = " + str(self.array)
return value
#Tests
def test_basic_ops():
stack = StacksWithArray()
stack.push(0,"A")
stack.push(1,"B")
stack.push(2,"C")
stack.push(0,"A")
stack.push(0,"A")
stack.push(0,"A")
stack.pop(0)
stack.pop(0)
stack.pop(0)
stack.push(0,"A")
stack.pop(1)
stack.pop(1)
stack.pop(1)
stack.pop(2)
stack.pop(2)
stack.pop(0)
stack.pop(0)
stack.pop(0)
if __name__ == "__main__":
test_basic_ops()
| true
|
1043391288e9b6b26e2feeff248cee4ebefcc085
|
moemaair/Problems
|
/stacks/python/evaluate_expression.py
| 2,374
| 4.3125
| 4
|
from Stack import Stack
"""
Evaluate Expression
Evaluate a space delimited mathematical that includes parentheses
expression. e.g. "( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )"
== 101
Approaches:
1) Use two stacks, one for operators, one for operands.
If you get to close paren?, then pop last two operands off
and combine using last operator. Pop operator and continue.
At end of string, pop result of operands
Questions:
1) Supported operators?
2) Always balanced parenthesese + equations?
3) Empty or one element equations?
4) Integers only?
Examples:
(1 + 1)
2
___ ___
(1 + (2 * 5) + 3)
14
___ ___
( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
101
___ ___
"""
def evaluate_exp(exp):
SUPPORTED_OPERATORS = "+*-//"
OPERANDS_REGEX = "" #For now we assume if NOT operator, then operand
operators_stack = Stack()
operands_stack = Stack()
exp_list = exp.split() #splits by space default
for char in exp_list:
if char in SUPPORTED_OPERATORS:
operators_stack.push(char)
elif char == ")":
right_operand = operands_stack.pop()
left_operand = operands_stack.pop()
operator = operators_stack.pop()
operands_stack.push(math_mapper(operator, left_operand, right_operand))
elif char == "(":
continue #do nothing
else:
operands_stack.push(int(char)) #assume operand, convert to int
#return final remaining on operands stack
return operands_stack.pop()
def math_mapper(operator, left_operand, right_operand):
if operator == "+":
return left_operand + right_operand
elif operator == "-":
return left_operand - right_operand
elif operator == "*":
return left_operand * right_operand
elif operator == "/":
return left_operand / right_operand
elif operator == "//":
return left_operand // right_operand
elif operator is None: #Only one value left, return right operand
return right_operand
else:
raise Exception("Unknown operator " + operator)
# Tests
def test_evaluate_exp():
exp1 = "( 1 )"
exp2 = "( 1 + 1 )"
exp3 = "( ( 1 + ( 2 * 5 ) ) + 3 )"
exp4 = "( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )"
exp5 = "( ( 1 + ( 2 * 5 ) ) - 3 )"
exp6 = "( ( 1 - ( 10 / 5 ) ) * ( 3 + 6 ) )"
assert evaluate_exp(exp1) == 1
assert evaluate_exp(exp2) == 2
assert evaluate_exp(exp3) == 14
assert evaluate_exp(exp4) == 101
assert evaluate_exp(exp5) == 8
assert evaluate_exp(exp6) == -9
if __name__ == "__main__":
test_evaluate_exp()
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.