blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ffc5c4eb524cd11e8e452e0e75c50b6ac0933e2b | rsp-esl/python_examples_learning | /example_set-3/script_ex-3_6.py | 2,966 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
# Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB)
# Date: 2017-11-17
##############################################################################
from __future__ import print_function # for Python 2.6 or higher
import threading, time
# define the MyThread class as a subclass of threading.Thread
class MyThread(threading.Thread):
def __init__(self, id, lock): # constructor
# call the constructor of its superclass
threading.Thread.__init__(self)
self.id = id # set thread ID
self.lock = lock # set the mutex lock
def run(self): # override the run method() of its superclass
for i in range(10): # repeat for 10 times
with self.lock: # access to the mutex lock
print ('[Thread id=%d (%d)]' % (self.id, i))
time.sleep(0.5) # sleep for 0.5 seconds
if __name__ == '__main__': # test code
lock = threading.Lock() # create a mutex lock
threads = [] # create an empty list
num_threads = 5 # number of threads to be created
for i in range(num_threads):
# create a new thread object
threads.append( MyThread(i,lock) );
for t in threads: # for each thread in the list
# invoke the run() method of this thread
t.start()
for t in threads: # for each thread in the list
# the main thread must wait until this thread exits.
t.join()
print ('Done...')
# Sample output:
#
# [Thread id=0 (0)]
# [Thread id=1 (0)]
# [Thread id=2 (0)]
# [Thread id=3 (0)]
# [Thread id=4 (0)]
# [Thread id=1 (1)]
# [Thread id=2 (1)]
# [Thread id=0 (1)]
# [Thread id=3 (1)]
# [Thread id=4 (1)]
# [Thread id=2 (2)]
# [Thread id=3 (2)]
# [Thread id=1 (2)]
# [Thread id=0 (2)]
# [Thread id=4 (2)]
# [Thread id=2 (3)]
# [Thread id=0 (3)]
# [Thread id=3 (3)]
# [Thread id=1 (3)]
# [Thread id=4 (3)]
# [Thread id=2 (4)]
# [Thread id=0 (4)]
# [Thread id=3 (4)]
# [Thread id=1 (4)]
# [Thread id=4 (4)]
# [Thread id=2 (5)]
# [Thread id=0 (5)]
# [Thread id=3 (5)]
# [Thread id=4 (5)]
# [Thread id=1 (5)]
# [Thread id=1 (6)]
# [Thread id=0 (6)]
# [Thread id=3 (6)]
# [Thread id=2 (6)]
# [Thread id=4 (6)]
# [Thread id=4 (7)]
# [Thread id=1 (7)]
# [Thread id=0 (7)]
# [Thread id=3 (7)]
# [Thread id=2 (7)]
# [Thread id=0 (8)]
# [Thread id=1 (8)]
# [Thread id=3 (8)]
# [Thread id=2 (8)]
# [Thread id=4 (8)]
# [Thread id=0 (9)]
# [Thread id=3 (9)]
# [Thread id=1 (9)]
# [Thread id=4 (9)]
# [Thread id=2 (9)]
# Done...
##############################################################################
| true |
091be1a39775ef12d7eacc6b90c2ab563fddb340 | rsp-esl/python_examples_learning | /example_set-1/script_ex-1_34.py | 1,238 | 4.4375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
# Author: Rawat S. (Dept. of Electrical & Computer Engineering, KMUTNB)
# Date: 2017-11-17
##############################################################################
from __future__ import print_function # for Python 2.6 or higher
## Data structures, Lists, Tuples
num_list = [3,4,5] # create a list of integers
num_tuple = (0,1,2) # creaet a tuple of integers
num_tuple += tuple( num_list ) # convert to tuple and append to a tuple
print (num_tuple) # output: (0,1,2,3,4,5)
str = "10, 20, 30, 40"
tup = tuple( int(i) for i in str.split(',') ) # convert str to tuple
print (tup) # output: (10, 20, 30, 40)
tup = (10,20,30,40)
total = sum( x for x in tup ) # sum all elements of a tuple of integers
print ('total = ', total) # output: total= 100
tup = ('a','b','c','d') # create a tuple of strings
s = ','.join( x for x in tup) # join all elements of a tuple into a string
print (s) # output: a,b,c,d
##############################################################################
| true |
7f2111375c9fde24f8e238a901f59fd2b338c4b1 | theymightbepotatoesafter/School-Work | /CIS 210/p11_quiz_christian_carter.py | 2,320 | 4.3125 | 4 | '''
Prior programming experience quiz.
CIS 210 Project 1-1 Hello-Quiz Solution
Author: Christian Carter
Credits: N/A
Add docstrings to Python functions that implement quiz 1 pseudocode.
(See p11_cricket.py for examples of functions with docstrings.)
'''
def q1(onTime, absent):
'''
(bool, bool) -> string
User inputs boolean values and function returns a tailored message
>>>q1(False, False)
Better late than never.
>>>q1(True, False)
Hello!
'''
if onTime:
return('Hello!')
elif absent:
return('Is anyone there?')
else:
return('Better late than never.')
def q2(age, salary):
'''
(int, int) -> bool
User inputs age and salary and function returns bool based on the set values
>>> q2(13, 1000)
True
>>> q2(27, 10000)
False
>>> q2(27, 10001)
False
'''
return (age < 18) and (salary < 10000)
def q3():
'''
(none) -> int
No input and will return a 6
>>> q3()
6
'''
p = 1
q = 2
result = 4
if p < q:
if q > 4:
result = 5
else:
result = 6
return result
def q4(balance, deposit):
'''
(int/float, int/float) -> (int/float)
User inputs balance and deposit and is returned the balance plus ten times the deposit
>>> q4(300, 20)
500
>>> q4(300, 20.0)
500.0
'''
count = 0
while count < 10:
balance = balance + deposit
count += 1
return balance
def q5(nums):
'''
docstring -
(list of numbers) -> int
User inputs list of number and is returned the number of numbers in the list that are greater or equal to 0
>>> q5([0, 1, 2, 3, 4, 5]) #examples are given
6
>>> q5([0, -1, 2, -3, 4, -5])
3
'''
result = 0
i = 0
while i < len(nums):
if nums[i] >= 0:
result += 1
i += 1
return result
def q6():
'''
(none) -> int
No user input and won't return anything
>>> q6()
'''
i = 0
p = 1
while i < 4:
i = 1 #This is making the while loop infinite. If this was removed then the returned value would be 16
p = p * 2
i += 1
return p
| true |
c42d57a4c634bae031e0dc1085cf88e95f1464d3 | tartlet/CS303E | /DaysInMonth.py | 1,512 | 4.40625 | 4 | # File: DaysInMonth.py
# Student: Jingsi Zhou
# UT EID: jz24729
# Course Name: CS303E
# Unique Number: 50695
#
# Date Created: 09/25/2020
# Date Last Modified: 09/25/2020
# Description of Program: User inputs a month and year in integer form and program
# outputs how many days the month has for any given year. Intended for use with the modern
# calendar but also accepts obscure numbers for the year.
month = eval(input("Enter a month of the year as an integer from 1-12: "))
#display error message if month input is not in the valid range
if month > 12 or month < 1:
print("Please input an integer from 1-12... ;A;")
exit()
year = eval(input("Enter a year: "))
if month == 4:
days = 30
elif month == 6:
days = 30
elif month == 9:
days = 30
elif month == 11:
days = 30
else:
days = 31
if month == 1:
month = "January"
elif month == 2:
month = "February"
#looked up how to find if year is leap year
if (year % 4 == 0 and year % 100 != 0) or (year % 4 == 0 and year % 100 == 0 and year % 400 == 0):
days = 29
else:
days = 28
elif month == 3:
month = "March"
elif month == 4:
month = "April"
elif month == 5:
month = "May"
elif month == 6:
month = "June"
elif month == 7:
month = "July"
elif month == 8:
month = "August"
elif month == 9:
month = "September"
elif month == 10:
month = "October"
elif month == 11:
month = "November"
else:
month = "December"
print(month, year, "has", days, "days")
| true |
dff846be18fcde38c697f81272231da3beccc779 | Johnwei386/Warehouse | /Exercise/Python/2017-09-21.py | 261 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
num = raw_input("please submit a num:");
num = int(num)
if num%2 == 0:
if num%4 == 0:
print "%d can be division by 4" % num
else:
print "%d can be division by 2, is even" % num
else:
print "%d is odd" % num
| false |
6275743572e4abdd7c0a00d5852bb8b58cb4bd8f | anirudhn18/msba-python | /Lab5/Lab5_Ex1.py | 988 | 4.3125 | 4 |
class Point:
""" Represents a point in 2D space """
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __str__(self):
return '({},{})'.format(self.x,self.y)
class Rectangle:
"""Represents a rectangle. attributes: width, height, corner."""
# def __init__(self,width=0.0,height=0.0,corner=Point()):
def __init__(self,width=20.0,height=10.0,corner=Point()):
self.width = width
self.height = height
self.corner = corner
def find_center(self):
center = Point()
center.x = self.corner.x + self.width/2.0
center.y = self.corner.y + self.height/2.0
return center
def __str__(self):
return '{:.1f} by {:.1f}, corner is {:s}'.format(self.width,self.height,self.corner)
a_box = Rectangle(100.0,200.0)
#Start
print a_box
#Next
another_rect = Rectangle()
print another_rect
#Finally
third_rect = Rectangle(30,30,Point(5,5))
print third_rect | true |
a72254ff8fee355dd7d06d31f9a3e30457704777 | tdhawale/Python_Practise | /Swap.py | 1,871 | 4.59375 | 5 | # One method to swap variable is using another variabl
print("--------------------------------------------------------")
print("Using the conventional method for swap")
a = 5
b = 6
print("The value of a before swap is :", a)
print("The value of b before swap is :", b)
temp = a
a = b
b = temp
print("The value of a after swap is :", a)
print("The value of b after swap is :", b)
print("--------------------------------------------------------")
print("Swapping without using extra variable")
a = 5 # 101 value in binary
b = 6 # 110 value in binary
print("The value of a before swap is :", a)
print("The value of b before swap is :", b)
a = a + b # the addition is 11 which will require extra bits 1011
b = a - b
a = a - b
print("The value of a after swap is :", a)
print("The value of b after swap is :", b)
print("--------------------------------------------------------")
print("Swapping without using extra variable and without wasting extra bits")
a = 5
b = 6
print("The value of a before swap is :", a)
print("The value of b before swap is :", b)
a = a ^ b # we are using XOR here
b = a ^ b
a = a ^ b
print("The value of a after swap is :", a)
print("The value of b after swap is :", b)
print("--------------------------------------------------------")
print("Swapping without using ROT_TWO(Swaps the top most stack items)")
a = 5
b = 6
print("The value of a before swap is :", a)
print("The value of b before swap is :", b)
a, b = b, a # this works only if it written in the same line
# the values will be assigned from right to left . i.t right hand side will be solved first
# b(top of stack) will be assigned the value of a(top of stack)
# a(top of stack) will be assigned the value of b(top of stack)
# to get more information on this search for ROT_TWO() in python
print("The value of a after swap is :", a)
print("The value of b after swap is :", b)
| true |
ea9471de778308a17a7a553ab37b9aaf40695b31 | bradszalach/pythonbeginnerscripts | /CurrencyConverter.py | 2,960 | 4.28125 | 4 | #Currency Converter.py
#Scripted by Brad Szalach
#Converts USD to Euro or other way around
#1 USD = .81 Euro
#1 USD = .71 GBP
#1 USD = 106.28 JPY
#1 Euro = 1.23 USD
#1 Euro = .88 GBP
#1 Euro = 131.02 JPY
#1 GBP = 1.40 USD
#1 GBP = 1.14 Euro
#1 GBP = 149.08 JPY
#1 JPY = .0094 USD
#1 JPY = .0076 Euro
#1 JPY = .0067 GBP
#Find out what user wants to convert 1) USD -> Euro or 2) Euro -> USD
def currencyconvert():
userchoice = raw_input("What do you want to convert? \n 1) USD -> Euro \n 2) USD -> GBP \n 3) USD -> JPY \n 4) Euro -> USD \n 5) Euro -> GBP \n 6) Euro -> JPY \n 7) GBP -> USD \n 8) GBP -> Euro \n 9) GBP -> JPY \n 10) JPY -> USD \n 11) JPY -> Euro \n 12) JPY -> GBP \n")
#User choice 1
if(userchoice == '1'):
userUSD = float(raw_input("Enter the amount of USD you want to convert \n"))
Euro = (userUSD * .81)
print("$",userUSD,"=",Euro,"Euro")
#User Choice 2
elif(userchoice == '2'):
userUSD = float(raw_input("Enter the amount of USD you want to convert \n"))
GBP = (userUSD * .71)
print("$",userUSD,"=",GBP,"GBP")
#User Choice 3
elif(userchoice == '3'):
userUSD = float(raw_input("Enter the amount of USD you want to convert \n"))
JPY = (userUSD * 106.28)
print("$",userUSD,"=",JPY,"JPY")
#USer Choice 4
elif(userchoice == '4'):
userEuro = float(raw_input("Enter the amount of Euro you want to convert \n"))
USD = (userEuro * 1.23)
print("$",userEuro,"=","$",USD)
#User Choice 5
elif(userchoice == '5'):
userEuro = float(raw_input("Enter the amount of Euro you want to convert \n"))
GBP = (userEuro * .88)
print("$",userEuro,"=",GBP,"GBP")
#User Choice 6
elif(userchoice == '6'):
userEuro = float(raw_input("Enter the amount of Euro you want to convert \n"))
JPY = (userEuro * 131.02)
print("$",userEuro,"=",JPY,"JPY")
#User Choice 7
elif(userchoice == '7'):
userGDP= float(raw_input("Enter the amount of GBP you want to convert \n"))
USD = (userGDP * 1.40)
print("$",userEuro,"=","$",USD)
#User Choice 8
elif(userchoice == '8'):
userGDP= float(raw_input("Enter the amount of GBP you want to convert \n"))
Euro = (userGDP * 1.14)
print("$",userEuro,"=",Euro,"Euro")
#User Choice 9
elif(userchoice == '9'):
userGDP= float(raw_input("Enter the amount of GBP you want to convert \n"))
JPY = (userGDP * 149.08)
print("$",userEuro,"=",JPY,"JPY")
#User Choice 10
elif(userchoice == '10'):
userJPY = float(raw_input("Enter the amount of JPY you want to convert \n"))
USD = (userJPY * .0094)
print("$",userJPY,"=","$",USD)
#User Choice 11
elif(userchoice == '11'):
userJPY = float(raw_input("Enter the amount of JPY you want to convert \n"))
Euro = (userJPY * .0076)
print("$",userJPY,"=",Euro,"Euro")
#User Choice 12
elif(userchoice == '12'):
userJPY = float(raw_input("Enter the amount of JPY you want to convert \n"))
GBP = (userJPY * .0067)
print("$",userJPY,"=",GBP,"GBP")
#User choice else
else:
print("Error")
currencyconvert() | false |
73cdeadb0220dc1917c47b2e78eacc772f48cb6e | rwedema/BFVP3INF2 | /fixme2.py | 846 | 4.25 | 4 | #!/usr/env python3
"""
Draw a tree using turtle
"""
__author__ = "Fenna Feenstra"
import sys
def tree(branchLen):
""" function that draws the tree with stem and branches upwards"""
if branchLen > 5:
t.backward(branchLen)
t.right(20)
tree(branchLen-16,t)
t.left(40)
tree(branchLen-16,t)
t.right(20)
t.forward(branchLen)
def init_turtle()
""" function that initializes and returns the turtle"""
t = turtle.Turtle()
t.left(90)
t.up()
t.backward(100)
t.down()
t.color("darkgreen")
def main(args=None):
""" main function """
myWin= turtle.Screen
t = init_turtle()
if len(args) < 2:
tree(80, t)
else:
tree(args[2], t)
myWin.exitonclick()
if "__name__" == "__main__":
excode = main(sys.argv)
sys.exit(excode)
| false |
fb7512ed6162e479f0e8b2a669af7d9115171355 | maliaditya/Python-code-snippets | /Algorithms/Sorting/insertionsort.py | 238 | 4.21875 | 4 |
def insertion_sort(arr):
for i in range(1,len(arr)):
for j in range(i):
if arr[j]>arr[i]:
arr[i],arr[j] = arr[j],arr[i]
return arr
arr = [2,1,5,4,3,9,8]
print(arr)
sorted_array = insertion_sort(arr)
print(sorted_array)
| false |
2fae6de3cc45cae76936c8253f9951cfad720848 | tinadotmoardots/learning | /python/RPSv3.py | 1,223 | 4.375 | 4 | # This is a version of rock, paper, scissors that you can plan against a computer opponent
import random
player_wins = 0
computer_wins = 0
print("Rock...")
print("Paper...")
print("Scissors...")
while player_wins < 2 and computer_wins < 2:
print(f"Player Score: {player_wins} Computer Score: {computer_wins}")
player = input("Make your move: ")
if player == "quit" or player == "q":
break
rand_num = random.randint(0,2)
if rand_num == 0:
computer = "rock"
elif rand_num == 1:
computer = "paper"
else:
computer = "scissors"
p = "You win!"
t = "It's a tie!"
c = "Computer wins!"
if player == computer:
print(t)
elif player == "rock":
if computer == "scissors":
print(p)
player_wins += 1
elif computer == "paper":
print(c)
computer_wins += 1
elif player == "paper":
if computer == "rock":
print(p)
player_wins += 1
elif computer == "scissors":
print(c)
computer_wins += 1
elif player == "scissors":
if computer == "rock":
print(c)
computer_wins += 1
elif computer == "paper":
print(p)
player_wins += 1
else:
print("Something went wrong")
print("Thanks for playing!")
print(f"Final score: Player {player_wins} Computer: {computer_wins}")
| true |
dc9fd2bce543366b0a1f196397aeb8ba82c80bea | Tomxp32/Python-proyects | /math_main/clases/Clase1_logica.py | 1,502 | 4.5 | 4 | # CLase 1 Logica
logica = '''
La lógica es la ciencia formal y rama tanto de la filosofía como de las matemáticas que
estudia los principios de la demostración y la inferencia válida, las falacias, las
paradojas y la noción de verdad.
La lógica matemática es la rama más matemática de la lógica, que estudia la inferencia
mediante sistemas formales como la lógica proposicional, la lógica de primer orden y la
lógica modal. La lógica computacional es la aplicación de la lógica matemática a las
ciencias de la computación. La lógica filosófica utiliza los métodos y resultados de la
lógica moderna para el estudio de problemas filosóficos.
Los orígenes de la lógica se remontan a la Edad Antigua, con brotes independientes en
China, India y Grecia. Desde entonces, la lógica tradicionalmente se considera una rama
de la filosofía, pero en el siglo XX la lógica ha pasado a ser principalmente la lógica
matemática, y por lo tanto ahora también se considera parte de las matemáticas, e
incluso una ciencia formal independiente.
'''
def about():
print(logica)
def test1_():
input('\n\tWhat is logic? \n\t:')
input('\n\tWhat studies mathematical logic? \n\t:')
input('\n\tWhat is computational logic? \n\t:')
input('\n\tDescribe some history about logic \n\t:')
def logica_test():
test1 = input('\n\tWelcome to the logic test, do you want to take it? ')
if test1 == 'y':
test1_()
else:
print('\n\tWell take care')
| false |
fe065712a5b6500d9b9a8dc88ce1b7910a3990a6 | Jacob-Bankston/DigitalCrafts-Assignments | /Week1/Week1-Tuesday-Assignments/add-two-numbers.py | 876 | 4.34375 | 4 | #Defining a function to add two numbers together from user input
def add_numbers(input_1, input_2):
total = input_1 + input_2
return print(f"Your two numbers added together are: {total}")
#Seeking user input for the add_numbers function
while 1:
try: #Checking for integer input on the first number's input
first_number = input("Give me your first number to add: ")
first_number = int(first_number)
break
except ValueError:
print("Please enter an integer instead!")
while 1:
try: #Checking for integer input on the second number's input
second_number = input("Give me your second number to add: ")
second_number = int(second_number)
break
except ValueError:
print("Please enter an integer instead!")
#Calling the function to check the integers
add_numbers(first_number, second_number) | true |
bff9e6911ee84b2424d298daa4ded0fd29e417f7 | acrane1995/projects | /Module 1/absolute beginners.py | 2,855 | 4.15625 | 4 | #my_num = 123
#num_intro = "My number is " + str(my_num)
#print(num_intro)
#total_cost = 3 + 45
#print(total_cost)
#45 was represented as a string and therefore could not be executed
#school_num = 123
#print("the street number of Central School is " + str(school_num))
#school_num is an int and needed to be converted to a string to execute
#print(type(3.3))
#print(type(3))
#print(3.3 + 3)
#executes with no problems and result will always be a float unless converted back to an int
#ERRORS
#print('my socks do not match")
#and neither do your quotation marks
#print("my socks do not match")
#pront("my socks match now")
#but print is misspelled
#print("my socks match now")
#print"Save the notebook frequently
#first parentheses is missing
#print("Save the notebook frequently")
#student_name = "Alton"
#print(STUDENT_NAME)
#recalling the variable incorrectly... either capitalize the variable or lower case the recall
#print(student_name)
#total = 3
#print(total + " students are signed up for tutoring")
#total is an int and must be converted to a string
#print(str(total) + " students are signed up for tutoring")
#ASCII ART
#print(" *")
#print(" * *")
#print(" *****")
#print(" * *")
#print(" * *")
#print()
#print("_ _")
#rint(" \ /")
#print(" \ . . /")
#print(" V")
#print()
#print("eeeeeee")
#print("e")
#print("eeee")
#print("e")
#print("eeeeeee")
#print()
#INPUTS
#print("enter a small integer")
#small_int = input()
#print("Small int: ")
#print(small_int)
#student_name = input("Enter the student name: ")
#print("Hi " + student_name)
#type(student_name)
#city_name = input("What is the name of your city? ")
#print("The city name is " + city_name + "!")
#name = input("Name: ")
#age = input("Age: ")
#email = input("Receive Emails? Yes/No? ")
#print("Name = " + name)
#print("Age = " + age)
#print("Wants email = " + email)
#FORMATTED PRINT
#name = "Colette"
#print("Hello " + name + "!")
#print("Hello",name,"how are you?")
#print("I will pick you up @", 6,"for the party!")
#number_errors = 0
#print("An integer of", 14, "combined with strings causes",number_errors,"TypeErrors in comma formatted print!")
#print("I am",24,"years old in the year",2020,".")
#st_name = input("Enter street name: ")
#st_num = int(input("Enter house number: "))
#print("You live at",st_num,st_name)
#min_early = 15
#owner = input("Name for reservation: ")
#num_people = input("Number of people attending: ")
#training_time = input("Training session start time: ")
#print(owner,"your training for",num_people,"people is set to begin @",training_time,"please arrive",min_early,"minutes prior. Thank you!")
#"Hello".isalpha()
#length = "33"
#length.isalnum()
#name = "skye homsi"
#name_1 = name.title()
#name_2 = name_1.swapcase()
#print(name_2)
#name = "SKYE HOMSI"
#print("y" in name.lower()) | true |
b36975217050a1e3a8af54e7e7a4d1d0e7ae3e1a | divyansh1235/Beta-Algo | /python/tree/PostorderTraversal.py | 2,087 | 4.375 | 4 | #POSTORDER BINARY TREE TRAVERSAL
# In this algorithm we print the value of the nodes present in the binary tree in postorder
# fashion.
# Here we first traverse the left subtree and then traverse the right subtree and finally we
# print the root
# The sequence is as follows -
# Left->Right->Root
class node (): #node class
def __init__(self,val): #constructor that takes the node value as parameter
self.left=None
self.right=None
self.val=val
class Tree(): # Tree class
def __init__(self):
self.root=None
def buildtree(self): #method to take the nodes of the trees as input
root=int(input())
if root==-1:
return
root=node(root)
left=self.buildtree() #building the left subtree
right=self.buildtree() #building the right subtree
root.left=left #Assigning the left and the right subtree to the root
root.right=right
return root
def postorder(self,root): #postorder traversal method
if root is None: #in case the root is empty we return from there
return
self.postorder(root.left)
self.postorder(root.right)
print(root.val)
# Starting with the main code
def main():
tree=Tree() #creating the Tree object
print("Enter the values of the tree :")
tree.root=tree.buildtree() #buiding the tree
print("The order of the elements in postorder fashion is given as :")
tree.postorder(tree.root)
main()
"""
EXAMPLE TEST CASES
1
1) / \
2 3
Enter the values ot the tree :
1
2
-1
-1
3
-1
-1
The order of the elements in postorder fashion is given as :
2
3
1
2) 1
/ \
2 3
/ \ \
4 5 6
Enter the values of the tree :
1
2
4
-1
-1
5
-1
-1
3
-1
6
-1
-1
The order of the elements in postorder fashion is given as :
4
5
2
6
3
1
Time Complexity: O(n)
Space Complexity: O(1) or O(h) if size of stack of function calls is considered
Here, h is the height of the tree
"""
| true |
41c9233b4165f4da13629a007e24dfbc248cff9d | jasonluocesc/CS_E3190 | /P4/shortest_cycle/solution.py | 1,791 | 4.34375 | 4 | # coding: utf-8
def get_length_of_shortest_cycle(g):
"""Find the length of the shortest cycle in the graph if a cycle exists.
To run doctests:
python -m doctest -v solution.py
>>> from networkx import Graph
>>> get_length_of_shortest_cycle(Graph({1: [2, 3], 2: [], 3: []}))
>>> get_length_of_shortest_cycle(Graph({1: [3], 2: [1], 3: [2]}))
3
Parameters
----------
g : Graph
Returns
-------
length : int or None
Length of the shortest cycle, or None if there is no cycle.
"""
# Write your code here.
# Hint! If you'd like to test out these commands without
# writing a full-fledged program, you might want to familiarise
# yourself with the Python interactive shell or IPython (available
# on at least some Aalto IT computers)
# Create a simple line graph g: "(1)->(2)->(3)"
# (The creation parameter is a dict of {node: list_of_neighbors},
# but this is not something you will be needing in your code.)
# >>> from networkx import Graph
# >>> g = Graph({1: [2], 2: [3]})
# >>> g.number_of_nodes()
# 3
# Example. Iterate over the nodes and mark them as visited
# >>> visited = set()
# >>> for node in g.nodes_iter(): # There is also g.nodes(), which returns a list
# ... # do some work here
# ... visited.add(node)
# Example. Given a Node v, get all nodes s.t. there is an edge between
# v and that node
# >>> g.neighbors(1)
# [2]
# Example. Get the edges of the graph:
# >>> e.edges() # as with nodes, there is also g.edges_iter()
# [(1, 2), (2, 3)]
# For more information, consult the NetworkX documentation:
# https://networkx.github.io/documentation/networkx-1.10/tutorial/tutorial.html
| true |
aca7b1cf5d55a62b67f6156c9b633b7bc811e1ab | hansrajdeshpande18/geeksforgeeksorg-repo | /printreverse.py | 206 | 4.28125 | 4 | #Print first and last name in reverse order with a space between them
firstname = (input("Enter your first name:"))
lastname = (input("Enter your last name:"))
print("Hello " +lastname + " " +firstname) | true |
839102579223d22c81a0f54a816f585f7c70262e | skrall3119/prg105 | /MyProject/Practice 9.1.py | 2,704 | 4.5625 | 5 | import pickle
def add(dic): # adds a new entry to the dictionary
name = input('Enter the name you wish to add: ')
email = input('Enter the email you wish to associate with this name: ')
dic[name] = email
print(dictionary)
def remove(dic): # removes the entry of the dictionary
name = input('Enter the name of the person you want removed from your emails: ')
del dic[name]
print(dictionary)
def change(dic): # allows the user to change the name or email when specified.
option = input('Do you want to change the name or the email?: ').lower()
if option == 'name':
name = input('Enter the name you want to change: ')
if name not in dic:
name = input("That name is not in the list, please enter a name in the list. or use the 'add' command to add a \
new email address\n")
while name not in dic:
name = input('Enter the name you want to change: ')
new_name = input('Enter the new name: ')
dic[new_name] = dic[name]
del dic[name]
print('\n')
print(dic)
elif option == 'email':
name = input('Enter the name of the persons email you want to change: ')
if name not in dic:
name = input('That name is not in the list, please enter a name in the list, or use the add command to add \
a new name and email combo.: ')
new_email = input('Enter the new email address: ')
dic[name] = new_email
print('\n')
print(dic)
def show_dic(dic): # prints the dictionary
print(dic)
# beginning of main code. opens the file if it exists or creates a new one otherwise.
try:
dictionary = pickle.load(open('save.p', 'rb'))
except EOFError:
dictionary = {}
print(dictionary)
commands = 'List of commands: ' + '\n' + 'add' + '\n' + 'remove' + '\n' 'print' + '\n' + 'quit' + '\n' + 'save' + '\n'
print(commands)
user = input("Enter a command: ").lower()
while user != 'quit':
if user == 'add':
add(dictionary)
user = input('Enter a command: ')
elif user == 'remove':
remove(dictionary)
user = input('Enter a command: ')
elif user == 'change':
change(dictionary)
user = input('Enter a command: ')
elif user == 'print':
print(dictionary)
user = input('Enter a command: ')
elif user == 'save':
pickle.dump(dictionary, open('save.p', 'wb'))
print('Progress saved!')
user = input('Enter a command: ')
else:
print('Invalid command.' + '\n' + commands)
user = input('Enter a command:')
else:
pickle.dump(dictionary, open('save.p', 'wb'))
| true |
8611ef35c047b7362cb965eb1d07c713cf327d3e | LaxmanMaharjan/Python | /venv/Codes/Polymorphism/Operator_Overloading.py | 1,060 | 4.15625 | 4 | """
The purpose of these so-called “magic methods” is to overload Python operators or built-in
methods.
"""
class Polynomial:
def __init__(self,*args):
self.coeffs = args
def __add__(self, other): #overloading +
return Polynomial(*(x+y for x,y in zip(self.coeffs,other.coeffs)))
def __sub__(self, other): #overloading -
return Polynomial(*(x-y for x,y in zip(self.coeffs,other.coeffs)))
def __iadd__(self, other): #overloading +=
return Polynomial(*(x+y for x,y in zip(self.coeffs,other.coeffs)))
def __isub__(self, other): #overloading -=
return Polynomial(*(x-y for x,y in zip(self.coeffs,other.coeffs)))
def __eq__(self, other): #overloading ==
if self.coeffs == other.coeffs:
return True
else:
return False
def __str__(self): #it is invoked when print on the polynomial type is called
return f"Poynomial*{self.coeffs}"
p1 = Polynomial(1,2,3) #x^2 + 2x + 3
p2 = Polynomial(1,2,3) #x^2 + 2x + 3
p3 = p1 + p2
print(p1 + p2 + p3) | false |
d8ca1f9146fa6dad6de66701e10e45f054f37c39 | dgervais19/Eng74_Python | /dictionaries.py | 1,694 | 4.65625 | 5 | # What is a dictionary
# Dictionary (arrays) is another way managing data more Dynamically
# Key value pairs to store and manage data
# Syntax : {"name": "James"}
# a = {"key": "value"}
# what type of data can store/manage
# Let's create one
devops_student_data = {
"key": "value",
"name": "james",
"stream": "tech",
"completed_lessons": 4,
"completed_lesson_names":["operators", "data types", "variables"] # In order to put more than one value to the key you have to create a list
}
# print(type(devops_student_data))
# display the data by fetching the key "name"
# print(devops_student_data["completed_lessons"])
# print(devops_student_data["name"])
# print(devops_student_data.keys())
# print(devops_student_data["completed_lesson_names"])
# How can I change the value of specific key
# devops_student_data["completed_lessons"] = 3
# print(devops_student_data)
# print(devops_student_data.items())
# How can we fetch the value called "data types"
# print(devops_student_data["completed_lesson_names"][1])
# Task
# create a New dictionary to store user details
user_details = {
"key": "value",
"name": "Dono",
"DOB": "12/02/1940",
"course:": "Devops",
"hobbies": ["basketball", "Piano", "Gym", "Socialising", "data types"]
}
print(user_details)
# Managing the list within the dictionary
user_details["hobbies"].append("running")
user_details["hobbies"].remove("data types")
# all the details that you utilised in the last task
# methods of dictionary to remove, add, replace, display the type of items
user_details["age"] = "40"
print(user_details)
# create a list of hobbies of at least 3 items
# display data in reverse order of hobby list
| true |
8d8a4983bc39fb8c6870cb7e7f275b43d160baea | bhawnabhatt2012/python_lab_exp | /2.b.py | 497 | 4.21875 | 4 | index = 0
string = input("Enter the string: ")
substring = input("Enter the substring: ")
if substring in string:
print(substring," is present in ",string)
while index < len(string):
index = string.find(substring, index)
if index == -1:
break
print(substring, ' found at', index)
index += len(substring)
print('No. of occurences of',substring,': ',string.count(substring))
else:
print(substring," is not present in ",string) | true |
edc8eefa43d0a05859412b8ca21107af71e8237c | lanaelsanyoura/CommentedPythonIntermediateWorkshop | /Person.py | 1,226 | 4.25 | 4 | from datetime import date, datetime #for date
class Person:
"""
A person class
==== Attributes ====
firstname: str
lastname: str
birthdate: date YEAR, MONTH, DAY
address: str
"""
def __init__(self): #, firstname, lastname, birthdate, address):
#self.firstname = firstname
#self.lastname = lastname
#self.birthdate = birthdate
#self.address = address
def __str__(self):
"""
Return the string in a human-readable manner
@return: string
"""
#return "{} {}".format(self.firstname, self.lastname)
def age(self):
"""
Given the current date, return the age of this person
:return: int age
"""
#today = date.today()
#age = today.year - self.birthdate.year
#if today < date(today.year, self.birthdate.month, self.birthdate.day):
# age -= 1
#return age
pass
def getInfo(self):
"""
Return the information of this user to showcase overriding
:return:
"""
#print("I am a generic person")
pass
# Example Build
#person = Person("Joane", "Do", date(1997, 4, 20), "50 st george str")
| true |
13c0b258a492922a560d61c522efd7d6217fc045 | michaelkemp2000/vader | /ex20.py | 1,186 | 4.375 | 4 | from sys import argv
# Pass in an argument from command line
script, input_file = argv
# Function to print the whole file
def print_all(f):
print f.read()
# Function to go the the begining of a file
def rewind(f):
f.seek(0)
#Function to print a line of the file that you pass in
def print_a_line(line_count, f):
print line_count, f.readline()
#Open file passed from the command line
current_file = open(input_file)
#Prints some text and print the whole file by passing calling the function that reads the whole file.
print "First let's print the whole file:\n"
print_all(current_file)
#Prints some text and calls the function that allows you to go the the begining of the file.
print "Now let's rewind, kind of like a tape."
rewind(current_file)
#Prints some text and then calls the functions that allow you to print one line of the file by passing the line of the file that you specify
#current line 1
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
#current line 2
current_line = current_line + 1
print_a_line(current_line, current_file)
#current line 3
current_line = current_line + 1
print_a_line(current_line, current_file)
| true |
d6edafab430c4d6585a2edc62ca1336901199f95 | michaelkemp2000/vader | /ex3.py | 1,104 | 4.375 | 4 | # Print the text
print "I will now count my chickens."
# Print test and the sum answer after the comma
print "Hens", 25.645 + 30.5943 / 6
# Print test and the sum answer after the comma
print "Roosters", 100 - 25 * 3 % 4
# Print the text
print "Now I will count the eggs."
# Prints the answer to the sum. Not sure what the % is doing????
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Print the text
print "Is it true that 3 + 2 < 5-7?"
# checks if total of left sum is less that right some, if so - True, if not false.
print 3 + 2 < 5 - 7
# Print test and the sum answer after the comma
print "What is 3 + 2?", 3+ 2
# Print test and the sum answer after the comma
print "What is 5 - 7?", 5 - 7
#Text
print "Oh, that's why its False."
#Text
print "How about some more."
# Print test and the sum answer after the comma ( this will be boolean)
print "Is it greater?", 5 > -2
# Print test and the sum answer after the comma ( this will be boolean)
print "Is it greater or equal?", 5 >= -2
# Print test and the sum answer after the comma ( this will be boolean)
print "Is it less or equal?", 5 <= -2 | true |
210c5757a96f915bfdcba3d80cda9a7dddae74c1 | miguelgaspar24/BoardgamePrices | /utilities.py | 728 | 4.65625 | 5 | #!/usr/bin/env python
# coding: utf-8
def convert_chars(string):
'''
Converts problematic characters. Usually, tend to be accented vowels.
Takes the following parameters:
string (str): a string where one or more characters raise a UnicodeEncodeError.
Returns a modified string.
'''
if 'â\x80\x93' in string:
string = string.replace('â\x80\x93', '-')
if 'ä' in string:
string = string.replace('ä', 'ä')
if 'ù' in string:
string = string.replace('ù', 'ù')
if 'Å\x8d' in string:
string = string.replace('Å\x8d', 'ō')
if 'Ã\xa0' in string:
string = string.replace('Ã\xa0', 'à')
return string
| true |
71eca0bfe16eb700afb7dc2b38bea1977e7ab911 | oliverxudd/pytorch-gist | /numpy_basics.py | 1,398 | 4.1875 | 4 | """basics of numpy"""
# 1. deep copy of numpy arrays
B = numpy.empty_like(A)
B[:] = A
# 2. rearrange axes for numpy array
np.transpose(A, axes=[2,0,1])
A.transpose(2,0,1)
# 3. set elements to 0 if element meet some condition
out = np.where(A<3, A, 0) # 将矩阵A中小于3的元素置为0
# 4. show nonzero elements of numpy array
A = np.random.randint(0, 100, (10, 10))
(coords0, coords1) = numpy.nonzero(A)
# 5. unique elements of an array.
A = np.array([[0,0], [0,0], [1, 0]])
np.unique(A, axis=0) # output: array([[0, 0],[1, 0]])
# 6. common mistake. read image as uint8 and +- operation with it.
x = np.array([-1]).astype('uint8')
print(x)
# out: np.array([255], dtype=np.uint8)
# Convert to float before arithmetic operation with unsigned data.
# 7. 从numpy数组中按照索引取值. / take elements from an array along an axis.
# np.take(a, indices, axis=None)
a = [4, 3, 5, 7, 6, 8]
np.take(a, [[0, 1], [2, 3]])
# out: [[4, 3], [5, 7]] # output.shape=indices.shape
# 8. 给numpy数组增加长度为1的维度 / 去除numpy数组中长度为1的维度
y = numpy.expand_dims(x, axis=0)
# or
y = x[np.newaxis, ...]
y = numpy.squeeze(x)
# 9. 复制:沿着某个轴对numpy数组做复制
x = np.array([[1,2],[3,4]])
x = np.repeat(x, 3, axis=1)
# [[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]
# 10. concat: 沿着某个新的轴对数组做cat
A = np.stack(arrays, axis=0)
| false |
ee8549863440f5c92a6abc80b55c7e0d4eb3b05f | brinquisruben/evaluacion1 | /par y multiplo3.py | 395 | 4.15625 | 4 | # -*- coding: cp1252 -*-
def par_y_divisble_para_tres():
a= input("introduzca n: ")
if(a%2==0):
if(a%3==0):
print "multiplo de 2 y 3"
else:
print "par y no multiplo de 3"
else:
if(a%3==0):
print "impar y multiplo de 3"
else:
print "impar y no multiplo de 3"
par_y_divisble_para_tres()
| false |
ecccdec592c1cccb123c9ab92170438df90e8fed | jeffkt95/ProjectEuler | /problem0005.py | 945 | 4.15625 | 4 | import sys
import os
import math
def main():
highestNumber = 20
maxCheck = highestNumber * 100000000
# Starting with highestNumber, go up by multiples of highestNumber
# e.g. if your highestNumber was 10, check 10, 20, 30, 40, etc.
for numForCheck in range(highestNumber, maxCheck, highestNumber):
#Assume it's evenly divisible by all until proven otherwise
evenlyDivisibleByAll = True
for i in range(highestNumber, 0, -1):
if numForCheck % i != 0:
evenlyDivisibleByAll = False
break
#If you get through all the numbers and evenlyDivisibleByAll is still true,
# then you've found the answer
if evenlyDivisibleByAll:
print(str(numForCheck) + " is evenly divisible by all numbers from 1 to " + str(highestNumber))
return
print("Unable to find any number evenly divisible by all numbers from 1 to " + str(highestNumber))
print("I checked up to " + str(maxCheck))
if __name__ == "__main__":
main()
| true |
60cfdeffffb011a932a51daf21ddfb9d42c50bb4 | gvnaakhilsurya/20186087_CSPP-1 | /cspp1-pratice/m10/biggest Exercise/biggest Exercise/biggest_exercise.py | 1,025 | 4.125 | 4 | #Exercise : Biggest Exercise
#Write a procedure, called biggest, which returns the key corresponding to the entry with the largest number of values associated with it. If there is more than one such entry, return any one of the matching keys.
def biggest(aDict):
'''
aDict: A dictionary, where all the values are lists.
returns: The key with the largest number of values associated with it
'''
maxm=0
res=0
for i in aDict:
if type(aDict[i])==list or type(aDict[i])==tuple:
if len(aDict[i]) > maxm:
maxm = len(aDict[i])
res = i
if res==0 and maxm==0:
res=i
maxm=1
return (res,maxm)
def main():
# aDict={}
# s=input()
# l=s.split()
# if l[0][0] not in aDict:
# aDict[l[0][0]]=[l[1]]
# else:
# aDict[l[0][0]].append(l[1])
aDict = {1:[1,2,3],2:[1,5,3,4],4:[8,9,7,8]}
print((biggest(aDict)))
if __name__== "__main__":
main() | true |
f3b2c0443d86d4b7deedc30384e3a0aa7868b4c0 | gvnaakhilsurya/20186087_CSPP-1 | /cspp1-pratice/m3/hello_happy_world.py | 234 | 4.125 | 4 | '''
@author : gvnaakhilsurya
Write a piece of Python code that prints out
the string 'hello world' if the value of an integer
variable, happy,is strictly greater than 2.
'''
HAPPY = int(input())
if HAPPY > 2:
print("hello world")
| true |
68cc3286321708fcf077d10f169acfbe5e326715 | dineshagr/python- | /multiDimentionalLists.py | 641 | 4.40625 | 4 | # this is a one dimentional list
x = [2,3,4,5,6,7,8]
# this is a 2 dimentional list
y = [[5,4], [3,4], [7,9], [2,8]]
# 0 1 0 1 0 1 0 1 these are the individual positions of inner lists
# 0 1 2 3 these are the positions of outer lists
print(y)
print(y[3][1])
# this is a multidimentional list
y = [[[5,4], [3,4]], [[7,9], [2,8,3]], [4,6]]
# 0 1 2 outer lists index
# 0 1 0 1 inner lists index
# 0 1 0 1 0 1 0 1 2 0 1 inner most lists index
print(y[1][1][2]) the output will be three here
| true |
cf108fc7d5b54022363eb5d5ced17ec540c0256d | mfirmanakbar/python | /operators/comparation_operators.py | 270 | 4.21875 | 4 | a = 5
b = 10
print("a == b is", a == b)
print("a != b is", a != b)
print("a > b is", a > b)
print("a < b is", a < b)
print("a >= b is", a >= b)
print("a <= b is", a <= b)
'''
a == b is False
a != b is True
a > b is False
a < b is True
a >= b is False
a <= b is True
''' | false |
04acf60a4d97dc23ddc43b30798db72ccdbbc549 | mfirmanakbar/python | /data_types/string_operations.py | 968 | 4.375 | 4 | my_str = "welcome to the tutorial"
my_str_2 = "this is my string"
print(my_str)
print(my_str_2, end="\n\n")
print("print all: ", my_str[:])
print("from index 2 until index 9 and skip index 10: ", my_str[2:10])
print("from index 0 until index 13 and skipping 1 element: ", my_str[0:14:1])
print("from index 0 until index 13 and skipping 2 elements: ", my_str[0:14:2])
print("my_str[::-1]: ", my_str[::-1])
print("my_str[-7:-1]: ", my_str[-7:-1], end="\n\n")
# other function
my_str = "welcome to the tutorial"
print("length: ", len(my_str))
print("count `t`: ", my_str.count("t"))
print("lower: ", my_str.lower())
print("upper: ", my_str.upper())
print("find `l`: ", my_str.find("l")) # return index of the element found
print("partition `to`: ", my_str.partition("to")) # breaks the string into tuple for the element passed
print("split space: ", my_str.split(" "))
print("replace `welcome` to `hi, welcome`: ", my_str.replace("welcome", "hi, welcome"), end="\n\n")
| false |
03ed3c22fe20ae1738041d24a62001328a870734 | mfirmanakbar/python | /data_types/tuple_operations.py | 1,200 | 4.46875 | 4 | # initialize tuples
my_tuple = ()
my_tuple_2 = tuple()
print("empty my_tuple:", my_tuple)
print("empty my_tuple_2:", my_tuple_2)
my_tuple = my_tuple + (1, 2, 3)
print("init my_tuple from plus: ", my_tuple, end="\n\n")
# initialize elements to the tuple
my_tuple = (1, 2, 3)
my_tuple_2 = tuple(("python", "for", "firman"))
print("data type: ", type(my_tuple))
print("my_tuple_2: ", my_tuple_2, end="\n\n")
# accessing element of tuple
my_tuple = (1, 2, 3)
my_tuple_2 = ("python", "for", "firman")
my_tuple_3 = (4, 5, 6, ["golang", "ruby"])
print("get index 0 -> my_tuple[0]", my_tuple[0])
print("get all -> my_tuple_2[:]", my_tuple_2[:])
print("get ruby -> my_tuple_3[3][1]", my_tuple_3[3][1], end="\n\n")
# changing element of tuple
my_tuple_3 = (4, 5, 6, ["golang", "ruby"])
my_tuple_3[3][1] = "java"
print("change ruby to java -> my_tuple_3: ", my_tuple_3)
'''
empty my_tuple: ()
empty my_tuple_2: ()
init my_tuple from plus: (1, 2, 3)
data type: <class 'tuple'>
my_tuple_2: ('python', 'for', 'firman')
get index 0 -> my_tuple[0] 1
get all -> my_tuple_2[:] ('python', 'for', 'firman')
get ruby -> my_tuple_3[3][1] ruby
change ruby to java -> my_tuple_3: (4, 5, 6, ['golang', 'java'])
''' | false |
e90cfacd47c60099592b03dba2948da5dca2d141 | jarehec/holbertonschool-webstack_basics | /0x01-python_basics/101-print_diagonal.py | 261 | 4.15625 | 4 | #!/usr/bin/python3
"""
module containing print_diagonal function
"""
def print_diagonal(n):
"""
draws a diagonal line
@n: integer:q
"""
if n <= 0:
print()
else:
[print(' ' * i + '\\') for i in range(n)]
print()
| false |
b689d8c576b9731b116d987bb1282437803f63a9 | onatsahin/ITU_Assignments | /Artificial Intelligence/Assignment 2/block_construction_constraint.py | 2,980 | 4.125 | 4 | #Onat Şahin - 150150129 - sahino15@itu.edu.tr
#This code include the Block class and the constraint function that is used for the csp problem.
#This code is imported from csp_str_1.py and csp_str_2.py which create the model and solve the problem.
blocklist = [] #A list that holds block objects. Filled in the other codes.
class Block: #Block class to define blocks
def __init__(self, orientation, top, bottom):
self.orientation = orientation #Vertical of horizontal
self.top = top #Top part of the block in coordinates (block itself if horizontal)
self.bottom = bottom #Bottom part of the block in coordinates (block itself if horizontal)
#For the coordinates, I assumed that the height of a horizontal block is 1 and its width is 6.
#The height of a vertical block is 3 and its width is 2. I put the whole structure in a coordinate system
#where left and downmost point of the structure is the point 0,0
def horizontal_center_check(block, placed): #Checks if the below of a horizontal block's center is filled
return ( (block[2][0] - 1, block[2][1]) in placed ) and ( (block[3][0] - 1, block[3][1]) in placed )
def horizontal_two_over_three_check(block, placed): #Checks if at least 2/3 of a horizontal block's below is filled
count = 0
for piece in block:
if (piece[0] - 1, piece[1]) in placed:
count += 1
return count >= (len(block) / 3 * 2)
def vertical_bottom_check(block_bottom, placed): #Checks if a vertical block's below is filled
return ((block_bottom[0][0]-1, block_bottom[0][1]) in placed) and ((block_bottom[1][0]-1, block_bottom[1][1]) in placed)
#The function below uses the functions above to implement the constraints given in the assignment. Every variable's value
#comes to this function in argv list. The order of this list corresponds to the order of blocks in blocklist
def is_order_valid(*argv):
block_count = len(argv)
list_to_check = []
for i in range(block_count): #For every block
if blocklist[i].bottom[0][0] == 0: #If a block touches the ground, continue since it satisfies the constraints
continue
del list_to_check[:] #clear the checklist
for j in range(block_count):
if argv[j] < argv[i]: #If a block j is placed before the block i, add block j to the checklist
list_to_check = list_to_check + blocklist[j].top
if blocklist[i].orientation == 'h': #Perform horizontal check if the block i is horizontal
if not (horizontal_center_check(blocklist[i].bottom, list_to_check) or horizontal_two_over_three_check(blocklist[i].bottom, list_to_check)):
return False
elif blocklist[i].orientation == 'v': #Perform vertical check if the block i is vertical
if not vertical_bottom_check(blocklist[i].bottom, list_to_check):
return False
return True #If no False is returned, the structure can be built with the given order. Return True.
| true |
41eec34b60ce8f0152543d9464e064039a974cae | sebutz/python101code | /Chapter 4 - Conditionals/conditionals.py | 2,148 | 4.34375 | 4 | # a simple if statement
if 2 > 1:
print("This is a True statement!")
# another simple if statement
var1 = 1
var2 = 3
if var1 < var2:
print("This is also True")
# some else
if var1 > var2:
print("This should not be printed")
else:
print("Ok, that's the good branch")
# -1 -----0 -------1
if var1 < -1:
print("not reachable")
elif var1 < 0:
print("not reachable also")
elif var1 < 1:
print("almost there")
else:
print("at last")
if var1 < -1:
print("not reachable")
elif var1 < 0:
print("not reachable also")
elif var1 <= 1:
print("right there")
else:
print("not reachable ")
# let's make it dynamic
user_says = input("give a price:")
user_says_int = int(user_says)
#simplified
if 0 < user_says_int <= 10:
print("you got the right price, boss")
elif 10 < user_says_int <= 20:
print("that's a lot")
elif user_says_int >= 20:
print("are you nuts?")
else:
print("what?")
# and, or, not
if (user_says_int > 0 and
user_says_int <= 10):
print("good price")
elif user_says_int > 10 and user_says_int < 20:
print("that's a lot")
elif user_says_int >= 20:
print("are you nuts?")
else:
print("what?")
if not False:
print("ola")
x = 4
if x != 2:
print("boom")
else:
print("kboom")
# in list checking
my_list = [1, 2, 3, 4]
x = 10
if x in my_list :
print("gotcha")
else:
print("keep looking")
# checking for Nothing
# different types (they are evaluated differently !!!!)
empty_list = []
empty_map = {}
empty_string = ""
nothing = None
# for ex:
print(empty_list == None) # False
if empty_list == []:
print("empty list")
else:
print("something")
# same as
if empty_list:
print(empty_list)
else:
print("something")
if not empty_list:
print("something")
else:
print("empty")
if not nothing:
print("some value exists")
else:
print("absolutely nothing")
'''
# execute this code only if this program is executed as standalone file
if __name__ == "__main__":
#whatever
'''
| true |
1d76d63c49fba58705754cb77cc6228a3bb891c0 | isaiahb/youtube-hermes-config | /python_publisher/logs/logger.py | 957 | 4.1875 | 4 | """This module creates a logger that can be used by any module to log information
for the user. A new logger is created each time the program is run using a timestamp
to ensure a unique name.
"""
import logging
from datetime import datetime
class Logger():
"""Creates a timestamped log file in the logs/ directory
and prints the systems errors in the log.
"""
def __init__(self):
self.logger = logging.getLogger()
self.logger.setLevel(logging.ERROR)
timestamp = str(datetime.now().strftime("%Y-%m-%d:%H:%M"))
file_title = "logs/" + "log-" + timestamp + ".log"
output_file_handler = logging.FileHandler(file_title)
self.logger.addHandler(output_file_handler)
def log(self, error_message):
"""Log an error message using the logger.
Args:
error_message (str): the error message to print in the log
"""
error_message = str(datetime.now()) + " " + error_message
self.logger.error(error_message)
| true |
c3298fa7e323160b821295148c7e7094e9d47364 | lradebe/simple_programming_problems | /largest_element.py | 219 | 4.1875 | 4 | def largest_element(mylist):
largest_element = 0
for element in mylist:
if element >= largest_element:
largest_element = element
print(largest_element)
largest_element([1, 2, 3, 4, 5])
| true |
0177a475d7829b46e61a98456b99d438e3250bb8 | lradebe/simple_programming_problems | /find_intersection.py | 726 | 4.375 | 4 | def find_intersection(Array):
'''This function takes in a list with two strings \
it must return a string with numbers that are found on \
both list elements. If there are no common numbers between \
both elements, return False'''
first = list(Array[0].split(', '))
second = list(Array[1].split(', '))
string = ''
both = []
for number in first:
if number in second:
both.append(number)
sorted(both)
if len(both) == 0:
return False
for number in both:
if not number == both[-1]:
string += f'{number}, '
else:
string += f'{number}'
print(string)
Array = ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
find_intersection(Array)
| true |
361d5439ded4c00ad770618c6c99cf927c8117a7 | Harsh-Modi278/dynamic-programming | /Fibonacci Sequence/solution.py | 534 | 4.3125 | 4 | # Initialising a dictionary to store values of subproblems
memo_dict = {}
def fibonacci(n):
# If answer to the nth fibonacci term is already present in the dictionary, return the answer
if(n in memo_dict):
return(memo_dict[n])
if n <= 2:
return (1)
else:
# Store the answer to the nth fibonacci term to the dictionary for further use
memo_dict[n] = (fibonacci(n-1)+fibonacci(n-2))
return(memo_dict[n])
if __name__ == '__main__':
n = int(input())
print(fibonacci(n))
| true |
ff45174dacc0319d4cb1faa28984f5ed10cf6662 | TheBrockstar/Intro-Python | /src/days-1-2/fileio.py | 468 | 4.1875 | 4 | # Use open to open file "foo.txt" for reading
foo = open('foo.txt', 'r')
# Print all the lines in the file
print(foo.read())
# Close the file
foo.close()
# Use open to open file "bar.txt" for writing
bar = open('bar.txt', 'w')
# Use the write() method to write three lines to the file
bar.write('''"To be, or not to be, that is the question:
Whether 'tis nobler to suffer the sling and arrows of outrageous fortune..."
--Hamlet
''')
# Close the file
bar.close() | true |
f1acef2e2802c79c6ffd74b1b357fb84aeaf2d26 | Kyrylo-Kotelevets/NIX_python | /Trainee/9.py | 762 | 4.46875 | 4 | """
создайте функцию-генератор, которая принимает на вход два числа, первое - старт, второе - end.
генератор в каждом цикле должен возвращать число и увеличивать его на 1
при итерации генератор должен начать с числа start и закончить итерации на числе end
т.е. при вызове
for i in my_generator(1, 3):
print(i)
в консоли должно быть:
1
2
3
"""
def my_generator(start, end):
"""Function-generator with range of numbers"""
for item in range(start, end + 1):
yield item
for i in my_generator(1, 3):
print(i)
| false |
899ff27333c1927fc535d670fd4cf0dd4754ed9e | Kyrylo-Kotelevets/NIX_python | /Beginner/4.py | 615 | 4.34375 | 4 | """
Дан список из строк. Создайте однострочное решение (при помощи list comprehension),
которое приведёт к верхнему регистру все строки, содержащие слово 'price')
"""
strings = ["Given a list of strings",
"Create a one line solution",
"(with a list comprehension)",
"which will convert",
"all lines containing",
"the word \'price\'",
"to uppercase"]
strings = [line.upper() if 'price' in line else line for line in strings]
print(strings)
| false |
ac3e0974a676ea2cec4025da88171668aafa7062 | mukesh25/python-mukesh-codes | /pattern/pattern9.py | 332 | 4.1875 | 4 | # 1
# 2 2
# 3 3 3
# 4 4 4 4
# No. of spaces in every row:(n-i-1)
# which symbol: (i+1)
# How many times: (i+1)
# with in each row same symbol are taken
# inside row symbol are not changing that's why nested loop is not required.
n= int(input('Enter n value: '))
for i in range(n):
print(' '*(n-i-1)+(str(i+1)+' ')*(i+1))
| true |
55c3bccfa073b942813d86a3764aa4237e55486c | mukesh25/python-mukesh-codes | /stringpattern/strpattern5.py | 333 | 4.21875 | 4 | # write a program to REVERSE internal content of each word?
# input = mukesh software solutions
# output = hsekum erawtfos snoitulos
s = input('enter some string to reverse: ')
l = s.split()
print(l) #['mukesh','software','solutions']
l1=[]
for word in l:
l1.append(word[::-1])
print(l1)
output = ' '.join(l1)
print(output)
| false |
90ee5d614355f201a11e5a5f8d64dd2632427dac | urskaburgar/python-dn | /naloga-8/calculator/calculator.py | 417 | 4.21875 | 4 | first_number = int(input("Enter the first number: "))
second_number = int(input("Enter the second number: "))
operation = input("Choose operation (+, -, *, /): ")
if operation == "+":
print(first_number + second_number)
elif operation == "-":
print(first_number - second_number)
elif operation == "*":
print(first_number * second_number)
elif operation == "/":
print(first_number / second_number)
| true |
f0eb2816abe1464ed57b923664a5a97737c8f1f0 | dgampel/passion-learn | /examples/binary_search.py | 908 | 4.28125 | 4 | def binary_search(array,first,last,x):
array.sort()
if last >= 1: #base case
middle = 1 + (last - 1) // 2
if array[middle] == x: #if element is present at middle
return middle
if array[middle] > x: #if element is in left half
return binary_search(array,first,middle-1,x)
else: #if element is in right half
return binary_search(array,middle+1,last,x)
else: #if element is not present in array
return -1
array = [1, 21, 14, 3, 2, 18, 10, 3, 47, 7] # test array
x = 10 #test element
first = 0
last = len(array)
answer = binary_search(array,first,last,x)
if answer != -1:
print("Element is present at index", str(answer))
else:
print("Element is not present in array")
| true |
182ea9db6515bbed025a04d7cca1bef7bbac5c2c | Anshul-Swarnkar/Oops | /InheritanceSuperMethod.py | 465 | 4.34375 | 4 | class BaseClass:
def hello_world(self):
print("Hello Python from Base")
def Bye(self):
print("Bye Bye")
class ChildClass(BaseClass):
def hello_world(self):
#BaseClass.hello_world(self) #here we are calling same method of BaseClass
super().hello_world() # here you can use Super method instead of above line of code
super().Bye()
print("Hello Python from Child")
obj1=ChildClass()
obj1.hello_world()
| false |
e89644f9ae975b08815394c47a0669ee65627f07 | gopalanand333/Python-Basics | /dictionary-basic.py | 333 | 4.71875 | 5 | #! /usr/bin/env python03
# a dictionary is searchable item with key-value pair
x = {"one": 1, "two":2, "three":3, "four":4,"five":5} # a dictionary
for key in x:
print(key) # this will print the keys
for key, v in x.items():
print('key: {} , value:{}'.format(key, v)) # this will return the key value pair
| true |
cd93ecfa1c20132aa72909ed314b4ba3d2fe177b | blakexcosta/Unit3_Python_Chapter5 | /main.py | 1,208 | 4.3125 | 4 |
def main():
# booleans
number1 = 1
number5 = 5
# boolean values are written as True and False
if (number1 > number5):
print("this statement is true")
else:
print("this statement is false")
# list of comparison operators
# https://education.launchcode.org/lchs/chapters/booleans-and-conditionals/boolean-expressions.html
#len() example
text = "Don't panic"
if(len(text) >= 10):
print("{} has more than 10 character".format(text))
# logic operators (and, or, etc.)
name = "Bob"
if (len(name)>5 and len(name)<10):
print("{} is between 5 and 10 characters".format(name))
else:
print("{} is either less than 5 characters or greater than 10".format(name))
# table of operations for operators
# https://education.launchcode.org/lchs/chapters/booleans-and-conditionals/truth-tables.html
# chained conditionals, (elif)
num = 10
other_num = 20
if num > other_num:
print(num, "is greater than", other_num)
elif num < other_num:
print(num, "is less than", other_num)
else:
print(num, "is equal to", other_num)
if __name__ == "__main__":
main()
| true |
ba025910735dc60863ef5b6525cc20bace3675cb | CAWilson94/MachineLearningAdventures | /ex2/python/iris.py | 2,446 | 4.4375 | 4 | # Charlotte Wilson
# SciKit learn example
# How starting from the original problem data
# can shaped for consumption in scikit-learn.
# importing a dataset
from sklearn import datasets
# data member is an n_sample and n_features array
iris = datasets.load_iris();
digits = datasets.load_digits();
# digits.data accesses the features that can be used to classify the digit samples
# data --> features
# These features each belong to a class
print(iris.data);
print("\n");
print(digits.data);
# digits.target gives ground truth for the data set
# i.e. the number corresponding to each digit we are trying to learn
# target --> class
print("digits target yo!");
print(digits.target);
# Shape of the data arrays
# The data is always a 2d array
# shape(n_samples,n_features)
# Although the original data may have a different shape.
# Each original sample in an image of shape (8,8) can
# be accessed using:
print("\nShape of data arrays \n");
print(digits.images[0]);
###########LEARNING AND PREDICTING#########################
# The task here is to predict, given an image, what digit it represents
# Given samples of each of the ten classes (digits 0-9)
# We fit an ESTIMATOR on each of these, which is able to predict
# the classes to which unseen samples belong
# In scikit-learn: an estimator for classification is a python object that implements the method fit(x,y) and predict(T)
# Estimator for classification --> python object implementing fit(x,y) and predict(T)
# sklearn.svm.SVC is an estimator class that implements support vector classification
# Consider the estimator as a black box for now
from sklearn import svm
# Choosing the paramaters for the model:
# In this case we have selected the value of gamma manually
# Possible to select good values automatically using tools
# Tools for auto selection: grid search, cross validation
# Call our estimator clf, since it is a classifier
# Must now be fitted to the model
# i.e. it must learn from the model
clf = svm.SVC(gamma=0.001, C=100);
# We pas our training set to fit the method
# So we use all images in our dataset bar the last one, as a training set.
# We select this training set with the [:-1] python syntax,
# which produces a new array that contains all but the last entry of digits.data
something = clf.fit(digits.data[:-1], digits.target[:-1]);
print("\nclassifier shit...\n");
print(something);
array = clf.predict(digits.data[:-1])
(array[8]);
| true |
42733c4983449b3967f4b450f35c6b319f8cbd9b | alexgneal/comp110-21f-workspace | /exercises/ex01/hype_machine.py | 273 | 4.15625 | 4 | """Use concantonations to build up strings and print them out using my name."""
__author__ = "730332719"
name: str = input("What is your name? ")
print(name + ", you are awesome!")
print("You're killing it, " + name)
print("Wow, " + name + ", you are an absolute queen!") | true |
617bcc056e3011b6b303ab1c1de87d3e9af49417 | Benneee/PythonTrips | /Assignment_Wk4_Day1_QuadRoots_App.py | 2,135 | 4.34375 | 4 | #The Quadratic Roots Programme
#ALGORITHM
#1 Introduce the program to the user
#2 Give the required instructions to run program appropriately
#3 Request values for a, b, c
#4 Define a variable for the discriminant
#- Solve the discriminant
#- Solve the square root of the discriminant
#- import math module and do the print thingy
#5 Define variables for r1 and r2
#6 Define the conditional statements;
#- discriminant > 0
#- discriminant < 0
#- discriminant == 0
#- Implement the calculation for the two roots when discriminant > 0
#The Program
#1 Introduce the program to the user
greeting = 'welcome to the quadratic roots programme'
print(greeting.title())
#2 Give the required instructions to run program appropriately
instruction = 'please provide values where required'
print(instruction.title())
#3 Request values for a, b, c
a = float(int(input('Please provide a value for a: ')))
b = float(int(input('Please provide a value for b: ')))
c = float(int(input('Please provide a value for c: ')))
#4 Define a variable for the discriminant
d = 'discriminant'
#- Solve the discriminant
d = float(int((b ** 2) - (4 * a * c)))
print('The discriminant is ' + str(d))
#- Solve the square root of the discriminant
#- import math module and do the print thingy
import math
print('The square root of the discriminant is ' + str(math.sqrt(abs(float(d)))))
#The abs function returns the absolute value of d which can be negative depending on the values of a, b and c.
#The python math module sqrt method has a problem with negative values.
#5 Define variables for r1 and r2
r1 = float((-b) + (d) / (2 * a))
r2 = float((-b) - (d) / (2 * a))
#6 Define the conditional statements;
#- discriminant > 0
if d > 0:
print('The equation has two real roots: ' + str(r1) + ' and ' + str(r2))
#- Implement the calculation for the two roots when discriminant > 0
#- discriminant == 0
elif d == 0:
print('The equation has only one real root')
#- discriminant < 0
else:
print('The equation has no real root')
print('Thank you for using this app')
| true |
b70d695f70fc311d4e81a1c0461d6638711f011b | jerthompson/au-aist2120-19fa | /1000-B/calc.py | 468 | 4.125 | 4 | running_total = 0 # accumulator
running_prod = 1
while True:
print("The total so far is", running_total)
print("The prod so far is", running_prod)
num = int(input("enter a number: "))
# num = input("enter a number: ")
# num = int(num)
if num == 0:
break
else:
running_total = running_total + num
running_prod = running_prod * num
print("The final total is", running_total)
print("The final prod is", running_prod)
| false |
c76cf6d1d8d193a0f2a9036d06558344caf2f066 | jerthompson/au-aist2120-19fa | /1130-A/0903-primeA.py | 300 | 4.25 | 4 | n = 2
max_factor = n//2
is_prime = True # ASSUME it is prime
for f in range(2, max_factor + 1): # INCLUDE max_factor by adding 1
if n % f == 0:
print(n, "is not prime--it is divisible by", f)
#exit()
is_prime = False
break
if is_prime:
print(n, "is prime")
| true |
f28949cd50fe4a1d5e80c4f0fad20d6172a0531a | hbinl/hbinl-scripts | /Python/C5 - MIPS/T3 - new_power.py | 1,762 | 4.21875 | 4 | """
FIT1008 Prac 5 Task 3
@purpose new_power.py
@author Loh Hao Bin 25461257, Derwinn Ee 25216384
@modified 20140825
@created 20140823
"""
def binary(e):
"""
@purpose: Returns a binary representation of the integer passed
@parameter: e - The integer to be converted to binary
@precondition: A positive integer value is passed
@postcondition: A list of integers representing binary value of the integer,
@Complexity:
Best Case: O(1) if e is 0
Worst Case: O(e + log e) because the algorithm cuts e into half in the second loop
"""
if e > 0:
rev_binary = [0] * e
length = 0
while e > 0:
rev_binary[length] = int(e%2)
e = int((e - e%2) / 2)
length += 1
return rev_binary[0:length]
else:
return [0]
def power(b, e):
"""
@purpose: Using a binary list to calculate power of two integers
@param:
b: The base number
e: The exponent
@precondition: A valid positive base and exponent are input
@postcondition: The power of b^e is print out
@Complexity:
Best Case: O(1) if exponent < 0
Worst Case: O( )
"""
if e < 0:
return "Please input positive exponents"
else:
rev_binary = binary(e)
result = 1
idx = len(rev_binary) - 1
while idx >= 0:
result = result * result
if rev_binary[idx]:
result = result * b
idx -= 1
return result
if __name__ == "__main__":
try:
b = int(input("Please input a positive integer: "))
e = int(input("Please input a positive integer: "))
print(power(b,e))
except:
print("Please input a valid positive integer.") | true |
6f5abd237c95b6590f222c0e5c2dbaf1c7243e99 | itsformalathi/Python-Practice | /iteratingdictionery.py | 473 | 4.78125 | 5 | #No method is needed to iterate over a dictionary:
d = {'A': 'Apple', 'B': 'Ball', 'C': 'Cat'}
for Key in d:
print(Key)
#But it's possible to use the method iterkeys():
for key in d.iterkeys():
print(key)
#The method itervalues() is a convenient way for iterating directly over the values:
for val in d.itervalues():
print(val)
#The above loop is of course equivalent to the following one:
for key in d:
print(d[key])
| true |
8beb44bb1abf99b16cc7b4a05f3dca7b6b3f6c93 | derekyang7/WSIB-Coding-Challenge | /code-obfuscation.py | 811 | 4.15625 | 4 | def myfunction():
num = input("Enter string:")
a = ""
b = num
while len(b) > 0:
if len(b) > 0:
c = b[-1]
b = b[:-1]
a += c
else:
break
if a == num:
return True
else:
return False
"""Function that reverses the order of the words in a sentence, but not the words themselves"""
def reverse_sentence(sentence: str) -> str:
# lst = split list by whitespace
reversed_list = lst[::-1]
res = ""
for item in reversed_list:
res += item
res += " "
return res
def reverse_sentence2(sentence: str) -> str:
reversed_list = list(filter(reverse, sentence))
res = ""
for item in reversed_list:
res += item
res += " "
return res
print(myfunction())
| true |
a086ad53f58f18ede70ba9eff3eb6d474ec49457 | hrd005/lab3_inf | /lab_03_01.py | 1,142 | 4.375 | 4 | ''' Кортежи '''
# создание кортежа
a1 = tuple()
a2 = 1, 2, 3, "abc"
a3 = (1, 2, 3, "abc")
print("Tuple a1 = ", a1)
print("Tuple a2 = ", a2)
print("Tuple a3 = ", a3)
# создание кортежа из других структур данных
l = [1, 2, 3, "abc"]
# из списка
a4 = tuple(l)
print("Tuple a4 from list l = ", a4)
a5 = tuple("Hello, World!")
# из строки
print("Tuple a5 from string = ", a5)
# вложенность кортежей
a6 = a2, a3
print("Tuple a6 formed by a2 and a3 = ", a6)
# объединение кортежей
a7 = a2 + a3
print("Tuple a7 by combining a2 and a3 = ", a7)
# доступ к элементам кортежей
print("a6[0]: ", a6[0])
print("a6[0][3]: ", a6[0][3])
# a6[0][3] = "cba" // it causes an error because cortege is inmodifiable, so you can't assign value to element
print("\n")
# task 3
k1 = (int(input()), int(input()), int(input()))
k2 = (input(), input(), input())
k3 = k1 + k2
print(k3)
print("\n")
# task 4
k4 = k1, k2
print(k4)
print(k4[1][1])
print("\n") | false |
6fd271c5a9306bbd737e223d2d0236547ba033a2 | tvrt0001/CodeWars-Python | /SolutionsByTobi/challenges_6kyu/tribonacci.py | 846 | 4.15625 | 4 | #####################################################################################
# #
# NAME: Tribonacci Sequence #
# RANK: 6kyu #
# URL: https://www.codewars.com/kata/556deca17c58da83c00002db/train/python #
# #
#####################################################################################
# works like fibonacci only with a base length of 3
def tribonacci(signature, n):
while len(signature) < n:
signature.append(signature[-1] + signature[-2] + signature[-3])
return signature[:n]
print(tribonacci([0, 0, 1], 2))
| false |
b1e254e649b83072a1ea2a09f3e40d5a7f6b5a5d | siggij91/TileTraveller | /tile_traveller.py | 2,353 | 4.1875 | 4 | ##Project 5 Tile Traveler https://github.com/siggij91/TileTraveller
#Create tile structure and label it
#Append allowable moves to file structure
#N = +1 in second index and S = -1
#E = +1 in first index and W = -1
#Once in new tile, show the allowable moves
#Once player enters 3, 1 show them that they win.
def can_move(current_square):
prt_str = 'You can travel: '
length = len(current_square)
for char in current_square:
if char == 'N' and length == 1:
prt_str += '(N)orth.'
elif char == 'N':
length -= 1
prt_str += '(N)orth or '
if char == 'E' and length == 1:
prt_str += '(E)ast.'
elif char == 'E':
length -= 1
prt_str += '(E)ast or '
if char == 'S' and length == 1:
prt_str += '(S)outh.'
elif char == 'S':
length -= 1
prt_str += '(S)outh or '
if char == 'W' and length == 1:
prt_str += '(W)est.'
elif char == 'W':
length -= 1
prt_str += '(W)est or '
return print(prt_str)
def select_move(current_square, x, y):
loop_continue = True
while loop_continue:
move = str(input('Direction: '))
for char in current_square:
if move.upper() == 'N' and move.upper() == char:
y += 1
loop_continue = False
break
elif move.upper() == 'E' and move.upper() == char:
x += 1
loop_continue = False
break
elif move.upper() == 'S' and move.upper() == char:
y -= 1
loop_continue = False
break
elif move.upper() == 'W' and move.upper() == char:
x -= 1
loop_continue = False
break
else:
print('Not a valid direction!')
return x, y
SQ = [['N','N','N'],
['NES','SW','NS'],
['ES','EW','SW']]
x = 1
y = 1
current_square = SQ[y-1][x-1]
while True:
can_move(current_square)
x, y = select_move(current_square, x, y)
current_square = SQ[y-1][x-1]
if x == 3 and y == 1:
print('Victory!')
break
| true |
4a578dd7fcd9cc12e0a6e28051f5641d2a9c22fe | vijaypal89/algolib | /ds/linkedlist/intro2.py | 593 | 4.125 | 4 | #!/usr/bin/python
import sys
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print temp.data,
temp = temp.next
def main():
#create link list and node
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
#now combine nodes
llist.head.next = second
second.next = third
llist.printList()
if __name__ == '__main__':
main()
| true |
9114541f1b9aa4b177fafd0ac50ef8b81ce76da0 | AlreadyTakenJonas/pythonBootCamp2021 | /easyExercise_12_regression/easyExercise_12_regression.py | 2,208 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 14 17:20:35 2021
@author: jonas
"""
# IMPORT MODULES
# Handling linear regression
from sklearn.linear_model import LinearRegression
# Handling exponential regression
from scipy.optimize import curve_fit
# Handling numbers and arrays
import numpy as np
# Handling plots
from matplotlib import pyplot as plt
# Create some data to fit and plot
dummyData = { "x": np.array([ 0 , 1 , 2 , 3 , 4 ]),
"y": np.array([ 1.11, 2.23, 7.39, 29.96, 49.40]) }
# Perform a linear regression on the data
linearFit = LinearRegression().fit( dummyData["x"].reshape(-1,1),
dummyData["y"] )
# Perform an exponential regression on the data
# Define exponential function
expFct = lambda x, A, b : A*np.exp(b*x)
# Perform the fit
expFit = curve_fit(f = expFct,
# Training Data
xdata = dummyData["x"],
ydata = dummyData["y"],
# Initial values for fitting parameter
p0 = [1, 1])
# Compute the exponential curve to plot the fitting model
# Get sequence of x values in the interval of the training data
expCurve = {"x": np.arange( min(dummyData["x"]), max(dummyData["x"])+0.1, 0.1 )}
# Compute y values
expCurve["y"] = [ expFct(x, expFit[0][0], expFit[0][1]) for x in expCurve["x"] ]
#
# PLOT DATA AND MODELS
#
# Plot data
plt.plot("x", "y",
"o", # Plot the data as scatter plot
data=dummyData,
# Add label for legend and coloring
label="data")
# Plot linear model
plt.plot(dummyData["x"],
# Predict training data with linear model
linearFit.predict( dummyData["x"].reshape(-1,1) ),
# Add label for legend and coloring
label="linear model")
# Plot exponential model
plt.plot("x", "y",
"", # Add empty format string. There is a warning if this parameter is not passed.
data=expCurve,
# Add label for legend and coloring
label="exp model")
# Add legend to the plot
plt.legend()
# Add axis labels
plt.xlabel("x")
plt.ylabel("y")
# Save the plot as an image file
plt.savefig("regression.png") | true |
7736bd8f305be6ea6e633d1fd34a7fe4e3ec33e3 | missweetcxx/fragments | /segments/sorting/d_insert_sort.py | 2,061 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class InsertSort:
"""
Insert Sort
divide list into two lists: sorted one and unsorted one;
each time insert an element from unsorted list into sorted one at correct position;
Complexity: O(n^2) in worst case
Memory: O(1)
"""
@staticmethod
def solution(my_list):
for r in range(1, len(my_list)):
l = r - 1
if my_list[r] < my_list[l]:
temp = my_list[r]
my_list[r] = my_list[l]
l = l - 1
while l >= 0 and my_list[l] > temp:
my_list[l + 1] = my_list[l]
l = l - 1
my_list[l + 1] = temp
return my_list
@staticmethod
def solution_2(my_list):
for r in range(1, len(my_list)):
l = r - 1
point = r
while l >= 0:
if my_list[l] > my_list[point]:
my_list[l], my_list[point] = my_list[point], my_list[l]
point = l
l -= 1
return my_list
@staticmethod
def solution_3(my_list):
for i in range(len(my_list)):
for j in range(1, i + 1)[::-1]:
if my_list[j] < my_list[j - 1]:
my_list[j - 1], my_list[j] = my_list[j], my_list[j - 1]
else:
break
return my_list
@staticmethod
def solution_4(my_list):
for i in range(1, len(my_list)):
cur = my_list[i]
j = i - 1
while j >= 0 and my_list[j] > cur:
my_list[j + 1] = my_list[j]
j = j - 1
my_list[j + 1] = cur
return my_list
@staticmethod
def solution_5(my_list):
for i in range(1, len(my_list)):
cur = my_list[i]
for j in range(0, i):
if my_list[i] < my_list[j]:
my_list = my_list[:i] + my_list[i + 1:]
my_list.insert(j, cur)
return my_list
| true |
25d5e2d5f13b3580b96f8a8496ba1377b28171a6 | missweetcxx/fragments | /segments/binary_tree/binary_tree.py | 1,895 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from segments.binary_tree.node import Node
class BinaryTree(object):
"""
generate binary tree
"""
def __init__(self):
self.root = None
pass
# create a binary tree with nodes
def _add_node(self, val):
# create root node of binary tree
nodeStack = [self.root, ]
# if root node hasn't been created
if self.root is None:
self.root = Node(val)
print("Successfully add root node as {0}!".format(self.root.val))
return
while len(nodeStack) > 0:
# pop node stack
p_node = nodeStack.pop()
# if left child node not exist
if p_node.left is None:
p_node.left = Node(val)
print("Add left node as {0} ".format(p_node.left.val))
return
# if right child node not exist
if p_node.right is None:
p_node.right = Node(val)
print("Add right node as {0} ".format(p_node.right.val))
return
nodeStack.insert(0, p_node.left)
nodeStack.insert(0, p_node.right)
def gen_tree(self, nums):
for x in nums:
self._add_node(x)
# def __init__(self):
# self.root = Node(None)
# self.myQueue = []
#
# def add_node(self, elem):
# node = Node(elem)
# if self.root.val is None:
# self.root = node
# self.myQueue.append(self.root)
# else:
# tree_node = self.myQueue[0]
# if tree_node.left is None:
# tree_node.left = node
# self.myQueue.append(tree_node.left)
# else:
# tree_node.right = node
# self.myQueue.append(tree_node.right)
# self.myQueue.pop(0)
| true |
c6028097760cbb32a3c9a52d82dd94d8fd23dccc | tunnelview/Sandbox | /Prac_03/password_check.py | 729 | 4.1875 | 4 |
def main():
MINIMUM_LENGTH = 16
get_password(MINIMUM_LENGTH)
def get_password(MINIMUM_LENGTH):
get_password = input("Enter Password of at least {} characters: ".format(MINIMUM_LENGTH))
while len(get_password) < MINIMUM_LENGTH:
print(f"please enter password of {MINIMUM_LENGTH} characters")
get_password = input("Enter Password of at least {} characters: ".format(MINIMUM_LENGTH))
print_pwd(get_password)
def print_pwd(get_password):
print("*" * len(get_password))
# if len(get_password) < 10:
#
# elif len(get_password) > 10 :
# print("Your password is too long, try again!")
# else:
# print("Your password length is correct")
# print("Your password is masked")
main()
| false |
6779b061c38dfb54b977a2bee0f34ca70a86ddc7 | qadaidi/tp01-qadaidi-python | /tp01_ex1.py | 1,697 | 4.15625 | 4 | """
Programme permettant de convertir une quantité en plusieurs unités d'énergie.
1J = 0.738 ft-lb = 0.239 cal = 6.24*10^18 eV
Unités : joule, calorie, Ft-lb et eV
Données : Une valeur et une unité
Indications:
Selon l'unité entrée par l'utilisateur, afficher la conversion
dans les 3 autres unités.
Résultats : Affichage des conversions
"""
### Déclaration et initialisation des variables
joule: float= 1
ftlb: float= 0.738
cal: float= 0.239
ev: float= 6.24*10**18
qnt_energie :float = float(input("Quelle est la quantité d'énergie à convertir ? : "))
unite :str = str(input("Unité (J, ft-lb, cal ou eV) ? : "))
### Séquence d'opération
if unite == "J":
ftlbs = qnt_energie * ftlb
cals = qnt_energie * cal
evs = qnt_energie * ev
print("En ft-lb : ", ftlbs)
print("En calories : ", cals)
print("En eV : ", evs)
elif unite == "ft-lb":
joules = qnt_energie / ftlb
cals = qnt_energie * cal / ftlb
evs = qnt_energie * ev / ftlb
print("En joules : ", joules)
print("En calories : ", cals)
print("En éléctro-Volt : ", evs)
elif unite == "cal":
joules = qnt_energie / cal
cals = qnt_energie * ftlb / cal
evs = qnt_energie * ev /cal
print("En joules : ", joules)
print("En calories : ", cals)
print("En éléctro-Volt : ", evs)
elif unite == "eV":
joules = qnt_energie * joule / ev
cals = qnt_energie * cal / ev
ftlbs = qnt_energie * ftlb / ev
print("En joules : ", joules, "J")
print("En calories : ", cals, "cal")
print("En ft-lb : ", ftlbs, "ft-lb")
| false |
d238ca151039d1ef380bd4ea71ba2d6eab10afdb | catarcatar/cursopython | /ejercicio07.py | 493 | 4.46875 | 4 | ''' Ejercicio 7
Escribe una función llamada hola que reciba un parámetro (una cadena de texto) y retorne "Hola " seguido del argumento y un signo de exclamación.
# escribe la función hola acá
# código de prueba
print(hola("Pedro")) # "Hola Pedro!"
print(hola("Juan")) # "Hola Juan!"
print(hola("")) # "Hola !" '''
def hola(una_cadena_de_texto):
return "Hola "+una_cadena_de_texto+"!"
print(hola("Pedro")) # "Hola Pedro!"
print(hola("Juan")) # "Hola Juan!"
print(hola("")) # "Hola !" | false |
3db4db9c93004441a249355b1a923a8439e78aa8 | jgerity/talks | /2016/computing_workgroup/intro-to-python/firstclassfunctions_example.py | 1,431 | 4.59375 | 5 | #!/usr/bin/env python
def makeAddFunction(x):
"""
This function represents breaking the operation x+y into two steps, by
returning a function F(y) that "knows" what value of x to use. In more
specific terms, the value of x is stored in the "closure" of the function
that is created.
"""
def newFunc(y):
""" This function 'carries' knowledge about x with it """
return x+y
# Having defined newFunc, let's spit it out to whoever wants it
# Notice that we are *not* calling newFunc with parentheses
return newFunc
addOne = makeAddFunction(1)
addTwo = makeAddFunction(2)
print(addOne(1)) # 1 + 1 = 2
print(addOne(2)) # 1 + 2 = 3
print(addTwo(1)) # 2 + 1 = 3
print(addTwo(2)) # 2 + 2 = 4
def addManyTimes(addFunc):
"""
We can even pass functions as arguments to other functions. This function
calls the given function with the arguments [0,1,...,10]
"""
for num in range(0, 11):
print("addManyTimes: Adding %i, result is %i" % (num, addFunc(num)))
addManyTimes(addOne) # Notice that we're not calling addOne here, either
addManyTimes(addTwo)
# Python has a special type of function called a lambda that allows us to
# define a short function in-line
addManyTimes(lambda y: 3+y)
# Here, the lambda expression is a function that takes one argument (y) and
# returns the result of 3+y. This lambda is equivalent to makeAddFunction(3)
| true |
3efd34ad76ac8bc585692de0f0868b0a8c124001 | Lguo0128/helloPython | /practice/chapter4/ex04_02.py | 622 | 4.5 | 4 | # 4-2 动物:想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用 for 循环将每种动物的名称都打印出来。
# 修改这个程序,使其针对每种动物都打印一个句子,如“A dog would make a great pet”。
# 在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any of these animals would make a great pet!”这样的句子
animals = ['cat','dog','rabbit','bird']
for animal in animals:
print('A ' + animal + ' would make a great pet' )
print('Any of these animals would make a great pet!') | false |
0be16c108fc4361fddf8fe0117804e88d4aa4adc | LucasMonteiroBastos/python3_mundo01 | /ex028.py | 611 | 4.28125 | 4 | '''Exercício Python 28:
Escreva um programa que faça o computador “pensar”
em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir
qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu ou perdeu.'''
import random
a = int(input('Em que numero estou pensando? '))
b = random.randint(0,5)
if a == b:
print('Parabéns, você acerto! Você disse que pensei no número {} e eu pensei no número {}.'.format(a,b))
else:
print('Você errou, você disse eu pensei no número {}, mais na verdade eu pensei no número {}.'.format(a,b)) | false |
0062eb73333fbb36791f164a7d3743691eb36490 | vbanurag/python_set1 | /set_1/Ques_2.py | 687 | 4.125 | 4 | a=[1,1,2,3,5,8,13,21,34,55,98]
#part 1
#prints all elements of the list which are less than 5
print "\nThe no. are less than 5 is : ",[x for x in a if x<5]
#part 2
#print a seperate list and stored a no which is less than 5
new_a=[]
for x in a:
if x<5:
new_a.append(x)
print "\n New list is ",new_a
#part 3
#part 2 convert in one line code
new_single_line=[]
[new_single_line.append(x) for x in a if x<5]
print "\n New list using list comprehension is ",new_single_line
#part 4
#user input of number x and prints all elements which are less than that the orignal list
user_num=int(raw_input("\nEnter a number : "))
for x in a:
if user_num>x:
print x
| true |
aed55c61659e5efbc2c9330ca54947651c00bb67 | KareliaConsolidated/CodePython | /Basics/08_Functions.py | 1,431 | 4.125 | 4 | # Create variables var1 and var2
var1 = [1, 2, 3, 4]
var2 = True
# Print out type of var1
print(type(var1))
# Print out length of var1
print(len(var1))
# Convert var2 to an integer: out2
out2 = int(var2)
# Create lists first and second
first = [11.25, 18.0, 20.0]
second = [10.75, 9.50]
# Paste together first and second: full
full = first + second
# Sort full in descending order: full_sorted
full_sorted = sorted(full, reverse=True)
# Print out full_sorted
print(full_sorted)
# string to experiment with: place
place = "poolhouse"
# Use upper() on place: place_up
place_up = place.upper()
# Print out place and place_up
print(place)
print(place_up)
# Print out the number of o's in place
print(place.count("o"))
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Print out the index of the element 20.0
print(areas.index(20.0))
# Print out how often 9.50 appears in areas
print(areas.count(9.50))
# append(), that adds an element to the list it is called on,
# remove(), that removes the first element of a list that matches the input, and
# reverse(), that reverses the order of the elements in the list it is called on.
# Create list areas
areas = [11.25, 18.0, 20.0, 10.75, 9.50]
# Use append twice to add poolhouse and garage size
areas.append(24.5)
areas.append(15.45)
# Print out areas
print(areas)
# Reverse the orders of the elements in areas
areas.reverse()
# Print out areas
print(areas) | true |
23ce14c416b32d4aa28e7c342c9ab201b8f640df | KareliaConsolidated/CodePython | /Basics/49_Functions_Ex_09.py | 312 | 4.25 | 4 | # Write a function called multiply_even_numbers. This function accepts a list of numbers and returns the product all even numbers in the list.
def multiply_even_numbers(li):
total = 1
for num in li:
if num % 2 == 0:
total *= num
return total
print(multiply_even_numbers([1,2,3,4,5,6,7,8,9,10])) # 3840
| true |
873d59c466d5d1b9820cfb3ce30d8fce24f74876 | KareliaConsolidated/CodePython | /Basics/17_Conditional_Statements.py | 1,008 | 4.25 | 4 | # Conditional logic using if statements represents different paths a program can take based on some type of comparison of input.
name = "Johny Stark"
if name == "Johny Stark":
print("Hello, " +name)
elif name == "John Fernandes":
print("You are not authorized !" +name)
else:
print("Calling Police Now !")
# In Python, all conditional checks resolve to True or False
x = 1
x is 1 # True
x is 0 # False
# We can call values that will resolve to True "truthy", or values that will resolve to False "falsy".
# Besides False conditional checks, other things that are naturally falsy include: empty objects, empty strings, None, and Zero.
# is vs "=="
# In Python, "==" and "is" are very similar comparators, however they are not the same.
a = 1
a == 1 # True
a is 1 # True
a = [1,2,3] # A List of Numbers
b = [1,2,3]
a == b # True # Checking, if values are the same.
a is b # False # Checking, if values are stored in the same place in memory.
# "is" is only truthy, if the variables reference the same item in memory. | true |
4dac05e28d6efd9441100f9d70a9f61318e8bb65 | KareliaConsolidated/CodePython | /Basics/21_Loops.py | 613 | 4.34375 | 4 | # In Python, for loops are written like this:
for item in iterable_object:
# do something with item
# An iterable object is some kind of collection of items, for instance; a list of numbers, a string of characters, a range etc.
# item is a new variable that can be called whatever you want
# item references the current position of our iterator within the iterable. It will iterate over(run through) every item of the collection and then go away when it has visited all items.
for num in range(1,8):
print(num)
for letter in "coffee":
print(f"{letter}" * 10)
# A Range is just a slice of the number line. | true |
f6f144ae9939c97e2f3ee45dff82029100277512 | KareliaConsolidated/CodePython | /Basics/166_Python_Ex_27.py | 443 | 4.21875 | 4 | # nth
# Write a function called nth, which accepts a list and a number and returns the element at whatever index is the number in the list. If the number is negative, the nth element from the end is returned.
# You can assume that number will always be between the negative value of the list length, and the list length minus 1
def nth(lst, ind):
return lst[ind]
print(nth(['a','b','c','d'], 1)) # 'b'
print(nth(['a','b','c','d'], -2)) # 'c' | true |
84dea473a9911b96684c54d1f339a442ecac41a6 | KareliaConsolidated/CodePython | /Basics/158_Python_Ex_19.py | 400 | 4.25 | 4 | # Vowel Count
# Write a function called vowel_count that accepts a string and returns a dictionary with the keys as the vowels and values as the count of times that vowel appears in the string.
def vowel_count(string):
lower_string = string.lower()
return {letter:lower_string.count(letter) for letter in lower_string if letter in 'aeiou'}
print(vowel_count('awesome')) # {'a': 1, 'e': 2, 'o': 1} | true |
c06f926ba0c3bf416e403eed81a0497605ab1eeb | KareliaConsolidated/CodePython | /Basics/160_Python_Ex_21.py | 781 | 4.375 | 4 | # Write a function called reverse_vowels. This function should reverse the vowels in a string. Any characters which are not vowels should remain in their original position. You should not consider "y" to be vowel.
def reverse_vowels(s):
vowels = 'aeiou'
string = list(s)
i, j = 0, len(s) - 1
while i < j:
if string[i].lower() not in vowels:
i += 1
elif string[j].lower() not in vowels:
j -= 1
else:
string[i], string[j] = string[j], string[i]
i += 1
j -= 1
return "".join(string)
print(reverse_vowels('Hello!')) # Hello!
print(reverse_vowels('Tomatoes!')) # Tomatoes!
print(reverse_vowels('Reverse Vowels In A String!')) # Reverse Vowels In A String!
print(reverse_vowels('aeiou')) # ueioa
print(reverse_vowels('why try, shy fly?')) # why try, shy fly? | true |
bbbb95519e1f58642b25b4642b7ef20bc0bbbf05 | neoguo0601/DeepLearning_Python | /Python_basic/python_basic/python_basic_1.py | 2,066 | 4.5 | 4 | days = 365
print(days)
days = 366
print(days)
#Data Types
#When we assign a value an integer value to a variable, we say that the variable is an instance of the integer class
#The two most common numerical types in Python are integer and float
#The most common non-numerical type is a string
str_test = "China"
int_test = 123
float_test = 122.5
print(str_test)
print(int_test)
print(float_test)
print(type(str_test))
print(type(int_test))
print(type(float_test))
str_eight = str(8)
print (str_eight)
print (type(str_eight))
eight = 8
str_eight_two = str(eight)
str_eight = "8"
int_eight = int(str_eight)
int_eight += 10
print (type(int_eight))
str_test = 'test'
str_to_int = int(str_test)
"""
Addition: +
Subtraction: -
Multiplication: *
Division: /
Exponent: **
"""
china=10
united_states=100
china_plus_10 = china + 10
us_times_100 = united_states * 100
print(china_plus_10)
print(us_times_100)
print (china**2)
#LIST
months = []
print (type(months))
print (months)
months.append("January")
months.append("February")
print (months)
months = []
months.append(1)
months.append("January")
months.append(2)
months.append("February")
print (months)
temps = ["China", 122.5, "India", 124.0, "United States", 134.1]
countries = []
temperatures = []
countries.append("China")
countries.append("India")
countries.append("United States")
temperatures.append(30.5)
temperatures.append(25.0)
temperatures.append(15.1)
print (countries)
print (temperatures)
china = countries[0]
china_temperature = temperatures[1]
print (china)
print (china_temperature)
int_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
length = len(int_months) # Contains the integer value 12.
print (length)
int_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
index = len(int_months) - 1
last_value = int_months[index] # Contains the value at index 11.
print (last_value)
print (int_months[-1])
#Slicing
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"]
# Values at index 2, 3, but not 4.
two_four = months[2:4]
print (two_four)
three_six = months[3:]
print (three_six)
| true |
d78a38eb6e954225d81984b05cd5cc782b5b93b8 | bitlearns/TurtleGraphics | /Assignment14_RegularPolygonsWithTurtleGraphics.py | 2,672 | 4.9375 | 5 | #Program Description: The following program will use turtle graphics to draw
#polygons based on the user's input of how many sides it will have.
#Author: Madeline Rodriguez
#Imports turtle graphics and random
from turtle import *
import random
#The sides function will take in the user's input of number of sides and check to
#see if it is more than 3 or less than 3
def main():
numSides = int(input('Enter the number of sides, less than 3 to exit: '))
#This loop will call the polygon function if the number of sides is greater
#than 3, if not it will display a thank you message
while numSides >= 3:
polygon(numSides)
numSides = int(input('Enter the number of sides, less than 3 to exit: '))
else:
print('Thanks for using the polygon generator program.')
#The polygon function will calculate the polygon's side length and border width
#using the number of sides inputted along with the line(border) and fill(shape)
#color
def polygon(x):
#Calculates the polygon's side length
sidelength = 600/x
# Specify the colors list to choose the line color and fill color.
colors = ['coral', 'gold', 'brown', 'red', 'green', 'blue', 'yellow',
'purple', 'orange', 'cyan', 'pink', 'magenta', 'goldenrod']
#Randomly selects the color of the fill(shape)
shapecolor = random.choice(colors)
#Randomly selects the color of the fill(border)
bordercolor = random.choice(colors)
#Calculates the size of the border width
bordersize = (x%20) + 1
#Calls the makePolygon function to draw the shape
makePolygon(x, sidelength, bordercolor, bordersize, shapecolor)
# The makePolygon function draws a polygon with the number of sides,
# side length, border color, border width, and fill color as specified.
def makePolygon (sides, length, borderColor, width, fillColor):
#Clears the window for any previous drawing
clear()
#Calculates the angles of the polygon
angle = 360/sides
#Gives the the shape of the turtle to be a turtle
shape("turtle")
#Assigns the pen it's color
pencolor(borderColor)
#Assigns the color that the shape will be fill in with
fillcolor(fillColor)
#Assigns the pen it's width size
pensize(width)
#Using the length and angle sizes specified it will begin to draw the shape
begin_fill()
while True:
if sides != 0:
forward(length)
left(angle)
sides -= 1
else:
break
end_fill()
#Displays to user what the program will create
print('This program will draw a polygon with 3 or more sides.' + '\n')
#Call the main function
main()
| true |
7c2660f87a6b9ebe8e1151867c3d72328fc755fd | JoA-MoS/Python-DeckOfCards | /card.py | 2,338 | 4.125 | 4 | # -*- coding: utf-8 -*-
# Check this out for cards display https://en.wikipedia.org/wiki/Playing_cards_in_Unicode
# Create a Suit Class???
SUITS = {1: {'Suit': 'Clubs',
'Symbol': '♣'},
2: {'Suit': 'Diamonds',
'Symbol': '♦'},
3: {'Suit': 'Hearts',
'Symbol': '♥'},
4: {'Suit': 'Spades',
'Symbol': '♠'}}
class Card(object):
def __init__(self, suit, number):
self.suit = suit
self.number = number
def __str__(self):
num_result = ""
if self.number == 1:
num_result += "Ace"
elif self.number == 11:
num_result += "Jack"
elif self.number == 12:
num_result += "Queen"
elif self.number == 13:
num_result += "King"
else:
num_result += str(self.number)
return num_result + " of " + SUITS[self.suit]['Suit']
# Override Operators <, <=, >, >=, ==, != will allow cards
# to be compared ignoring the suit
# TODO: check other to ensure it is type card and implement
# alternate comparison if int or float it would look like:
# def __le__(self, other):
# if isinstance(other, Card):
# return self.number <= other.number
# elif isinstance(other, (int, float)):
# return self.number <= other
# else:
# return NotImplemented
def __lt__(self, other):
return self.number < other.number
def __le__(self, other):
return self.number <= other.number
def __gt__(self, other):
return self.number > other.number
def __ge__(self, other):
return self.number >= other.number
def __eq__(self, other):
return self.number == other.number
def __ne__(self, other):
return self.number != other.number
class CardSet(object):
def __init__(self):
self.cards = []
def __str__(self):
out = ''
for c in self.cards:
out += str(c) + '\r\n'
return out[:-1]
def remove(self):
return self.cards.pop()
def add(self, card):
self.cards.append(card)
return self
def displayCards(self):
for c in self.cards:
print c
return self
@property
def count(self):
return len(self.cards)
| false |
a64fee29b65474879949c905b005046e61298a8e | Isaac-Tait/Deep-Learning | /Python/scratchPad4.py | 893 | 4.15625 | 4 | # Exponent functions
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
print(raise_to_power(3, 2))
# 2D list
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10]
]
print(number_grid[2][2])
print("It is time to move on to nested for loops!")
# Nested for loop
for row in number_grid:
for element in row:
print(element)
# A translator that dislikes vowels and prefers the letter "G"
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
| true |
e5dfd182fe3810d77335f56d8d73ff6d26603be0 | paulram2810/Python-Programs | /armstrong.py | 265 | 4.125 | 4 | num = eval(input("Enter number to check for armstrong : "))
x = num
flag = 0
while x!=0 :
temp = x%10
flag = flag+(temp**3)
x = x//10
if flag==num:
print(num," is an armstrong number.")
else:
print(num," is not an armstrong number.")
| true |
3be02701f737d06284c9a26f1c719cdab2c721d1 | bmlegge/CTI110 | /P3T1_AreasOfRectangles_Legge.py | 737 | 4.15625 | 4 | #CTI-110
#P3T1: Areas of Rectangles
#Bradley Legge
#3/3/2018
print("This program will compare the area of two rectangles")
recOneLength = float(input("Enter the length of rectangle one: "))
recOneWidth = float(input("Enter the width of rectangle one: "))
recOneArea = float(recOneLength * recOneWidth)
recTwoLength = float(input("Enter the length of rectangle two: "))
recTwoWidth = float(input("Enter the width of rectangle two: "))
recTwoArea = float(recTwoLength * recTwoWidth)
if recOneArea == recTwoArea:
print("The rectangles have the same area.")
elif recOneArea > recTwoArea:
print("Rectangle one has the greater area.")
elif recOneArea < recTwoArea:
print("Rectangle two has the greater area.")
| true |
f4757eb581419b63362df05cbdebee759ec302d3 | flerdacodeu/CodeU-2018-Group7 | /lizaku/assignment2/Q2.py | 2,129 | 4.15625 | 4 | from Q1 import Node, BinaryTree, create_tree
def find_lca(cur_node, node1, node2):
result = find_lca_(cur_node, node1, node2)
if not isinstance(result, int):
raise KeyError('At least one of the given values is not found in the tree')
return result
def find_lca_(cur_node, node1, node2):
# This algorithm is designed as follows: I start with the root and
# try to check whether one node is present in the left subtree and other node
# is present in the right subtree. If this is the case, then the current node
# is LCA. If the traversal reaches the leaves and the value is not found, the recursion step
# returns None. If required values are not found in the right subtree,
# Then LCA should be found in the left subtree, and I start to inspect it.
# Otherwise, I start to inspect the right subtree.
if cur_node is None:
#return None
raise KeyError('At least one of the given values is not found in the tree')
if cur_node.value == node1 or cur_node.value == node2: # reached one of the values
#print(cur_node.value, cur_node.left.value, cur_node.right.value)
return cur_node
try:
left_subtree = find_lca_(cur_node.left, node1, node2)
except KeyError:
left_subtree = None
#return None
try:
right_subtree = find_lca_(cur_node.right, node1, node2)
except KeyError:
right_subtree = None
#return None
if left_subtree is not None and right_subtree is not None: # found the node which has both values in the subtrees -- lca
return cur_node.value
elif right_subtree is None and left_subtree is not None:
return left_subtree
elif left_subtree is None and right_subtree is not None:
return right_subtree
else:
raise KeyError('At least one of the given values is not found in the tree')
if __name__ == '__main__':
data = [7, 3, 2, 1, 6, 5, None, None, 4, None, None, None, 8, None, None]
tree = BinaryTree()
tree.root = create_tree(data)
#tree.print_tree(tree.root)
print(find_lca(tree.root, 12, 11))
| true |
b93f8ec573992e03b78f890fc8218ff4404ed435 | flerdacodeu/CodeU-2018-Group7 | /EmaPajic/assignment4/assignment4.py | 1,923 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: EmaPajic
"""
def count_islands(rows,columns,tiles):
"""
I am assuming that we can change tiles (set some values to false).
If we couldn't do that, we could just make another matrix where
we would store flags so that we don't visit same tile twice.
In this function we are just going through matrix and if we find a part of island
we call function find_all_parts_of island to set all parts of that island to false
"""
numOfIslands = 0
for i in range(0,rows):
for j in range(0,columns):
if tiles[i][j] == True:
numOfIslands += 1
find_all_parts_of_island(rows,columns,i,j,tiles)
return numOfIslands
def valid_index(rows,columns,i,j):
# check if index is out of range
return not (i < 0 or i >= rows or j < 0 or j >= columns)
def find_all_parts_of_island(rows,columns,i,j,tiles):
#I am using dfs to find all connected tiles to one we found before we called this function from count_islands
tiles[i][j] = False
for move in [-1,1]:
if valid_index(rows,columns,i+move,j):
if tiles[i+move][j] == True:
find_all_parts_of_island(rows,columns,i+move,j,tiles)
if valid_index(rows,columns,i,j+move):
if tiles[i][j+move] == True:
find_all_parts_of_island(rows,columns,i,j+move,tiles)
def main():
#main class if we want to test something that is not in the tests
rows = int(input())
columns = int(input())
tiles = [0] * rows
for i in range(0,rows):
tiles[i] = [0] * columns
for i in range(0,rows):
for j in range(0,columns):
tmp = int(input())
if tmp == 0:
tiles[i][j] = False
else:
tiles[i][j] = True
num = count_islands(rows,columns,tiles)
print(num)
| true |
c318ca570f5bffa95560fc13a6db502472133dc5 | oskarmampe/PythonScripts | /number_game/program.py | 538 | 4.15625 | 4 | import random
print("----------------------------------")
print(" GUESS THAT NUMBER GAME ")
print("----------------------------------")
the_number = random.randint(0, 100)
while True:
guess_text = input("Guess a number between 0 and 100: ")
guess = int(guess_text)
if the_number > guess:
print("Your guess of {0} was too LOW.".format(guess))
elif the_number < guess:
print("Your guess of {0} was too HIGH.".format(guess))
else:
print("Congratulations! You won!")
break
| true |
8ed2ee72189b451698cfbc5b861cdbe5136cd3bc | StefGian/python-first-steps | /teenagerStory.py | 588 | 4.375 | 4 | #first method with or
age = input("How old are you?")
if(int(age)> 18 or int(age)<13) :
print("you are not a teenager")
else:
print("you are a teenager")
#second method with and
age = input("How old are you?")
if(int(age)< 18 and int(age)>=13) :
print("you are a teenager")
else:
print("you are not a teenager")
#third method using if
age = input("how old are you?")
age = int(age)
if age >=13:
if age <=18:
print("you are a teenager")
else:
print("you are not a teenager")
else:
print("you are not a teenager")
| false |
3049443c9a563cdcecd50556ecd1aeb8e1db0e6b | StefGian/python-first-steps | /maxOfThree.py | 370 | 4.40625 | 4 | #Implement a function that takes as input three variables,
#and returns the largest of the three. Do this without using
#the Python max() function!
a = int(input("Type the first number: "))
b = int(input("Type the second number: "))
c = int(input("Type the thrid number: "))
if a>b and a>c:
print(a)
elif b>a and b>c:
print(b)
else:
print(c)
| true |
412a520a55edcaa026306556a477ff4fe01bed4a | Akhichow/PythonCode | /challenge.py | 632 | 4.125 | 4 | vowels = set(["a", "e", "i", "o", "u"])
print("Please enter a statement")
sampleText = input()
finalSet = set(sampleText).difference(vowels)
print(finalSet)
finalList = sorted(finalSet)
print(finalList)
# [' ', 'I', 'c', 'd', 'm', 'n', 'r', 's']
# My solution -
# finalList = []
#
# while True:
# print("Please enter a statement")
# text = input()
#
# for alphabet in text:
# if (alphabet not in vowels) and (alphabet != " "):
# finalList.append(alphabet)
#
# print(sorted(finalList))
# print()
# break
# ['I', 'c', 'c', 'd', 'd', 'm', 'n', 'r', 's']
| true |
60d00c0a404a950786d0f83affd95e35f8fe00f3 | JasmineEllaine/fit2004-algs-ds | /Week 1/Tute/8-problem.py | 623 | 4.25 | 4 | # Write code that calculates the fibonacci numbers iteratively.
# F(1) == F(2) == 1
def fibIter(x):
seq = [1, 1]
# Return fib(x) immediately if already calculated.
if (x <= len(seq)):
return 1
for i in range(1, x-1):
seq.append(seq[i]+ seq[i-1])
return seq[-1]
"""
Time complexity:
O(n)
Space complexity:
O(1)
"""
# Write code that calculates the fibonacci numbers recursively.
def fibRec(x):
if (x == 0):
return 0
elif (x == 1):
return 1
else:
return fibRec(x-1) + fibRec(x-2)
"""
Time complexity:
O(2^n)
Space complexity:
O(n)
""" | true |
1693a547bd0278f0675a13ee34e1fa63ee86a00c | davidcotton/algorithm-playground | /src/graphs/bfs.py | 1,790 | 4.1875 | 4 | """Breadth-First Search
Search a graph one level at a time."""
from collections import deque
from typing import List, Optional
from src.graphs.adjacencylist import get_graph
from src.graphs.graph import Graph, Vertex
def bfs_search(start: Vertex, goal: Vertex) -> Optional[List[Vertex]]:
"""Search for the goal vertex within a graph in a breadth-first manner.
Graph must have no loops and no edge weights to work.
Returns the path as a list of vertices if goal is found else None."""
frontier: deque[Vertex] = deque([start])
paths: deque[List] = deque([[]])
while frontier:
vertex = frontier.popleft()
path = paths.popleft()
path.append(vertex.key())
if vertex is goal:
return path
for neighbour in vertex.neighbours():
frontier.append(neighbour)
paths.append(path[:])
return None
def bfs(root: Vertex) -> List[List]:
"""Search a graph via Breadth-First-Search from a vertex.
Returns a tree describing every vertex that is reachable from the source vertex.
"""
frontier: deque[Vertex] = deque([root])
paths: deque[List] = deque([[]])
while frontier:
vertex = frontier.popleft()
path = paths.popleft()
path.append(vertex.key())
if vertex.neighbours():
for neighbour in vertex.neighbours():
frontier.append(neighbour)
paths.append(path[:])
else:
paths.append(path)
return list(paths)
if __name__ == '__main__':
graph: Graph = get_graph()
vertices: List[Vertex] = graph.vertices()
shortest_path = bfs_search(vertices[0], vertices[4])
print('shortest path', shortest_path)
all_paths = bfs(vertices[0])
print('all paths', all_paths)
| true |
7e64e845366f95123d34c8c766064cc6dcb42c6c | girishf15/Python-Data-Structures | /Data_Structures/Sorting/bubble.py | 829 | 4.125 | 4 |
def bubble_sort(arr):
swapped = True
while swapped:
swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
# print(arr)
return arr
arr = [5, 7, 2, 47, 11, 10, 2, 3, 4, 5]
#print("Sorted --- >", bubble_sort(arr))
def bubble_sort_2(arr):
n = len(arr)
counter = 0
print(n)
for i in range(n):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print('-- {} - Swap {} and {}'.format(arr, arr[j+1], arr[j]))
else:w
print('-- {} - No Swap'.format(arr))
counter += 1
print(counter)
return arr
print("arr", bubble_sort_2(arr))
| false |
ef9d8af15889c4cd8c9a4105b5022dbcfa43feed | girishf15/Python-Data-Structures | /Data_Structures/Stack/stack_using_list.py | 755 | 4.21875 | 4 | # __author__ : girish
'''
Stack in Python can be implemented using following ways:
list
collections.deque
queue.LifoQueue
'''
class StackTest:
def __init__(self, stack=[], length=0):
self.stack = []
self.stack_length = length
def push(self, element):
if len(self.stack) == self.stack_length:
print("Stack is Full")
else:
self.stack.append(element)
def pop(self):
if len(self.stack):
return self.stack.pop()
else:
print("Stack is Empty")
def __repr__(self):
return str(self.stack)
ss = StackTest(length=3)
ss.push(10)
ss.push(20)
ss.push(30)
ss.push(410)
print(ss)
ss.pop()
ss.pop()
ss.pop()
print(ss)
ss.pop()
| false |
1cb441682be90079d43c9de98d42e4e4c0393725 | raulmogos/uni-projects | /FP/labs/tema lab 01/set_A_p1.py | 1,275 | 4.15625 | 4 | '''
PROGRAM THAT GENERATES THE FIRTS PRIME NUMBER AFTER A NUMBER N
INPUT: N - a natural number
OUTPU: P - THE FIRTS PRIME NUMBER AFTER N
'''
def e_prim(x):
'''
FUNCTION THAT CHECKS IF X PRIME OR NOT
INPUT: X - a number
OUTPUT: TRUE - IF X IS PRIEM
FALSE - OTHERWISE
'''
if x<2 :
return False
if x==2:
return True
if x%2==0:
return False
i=3
while i*i<=x :
if x%i==0: return False
i+=2
return True
def gen(n):
'''
FUNCTION THAT GENERATE THE FIRST PRIME NUMBER AFTER n
'''
if e_prim(n)==True:
n+=1
if n%2==0:
n+=1
while e_prim(n)==False:
n+=2
return n
def run_ui():
while True:
N = input("Enter a number : ")
N = int(N)
P = gen(N)
print("the first prime number larger than ",N," is : ",P)
def test_e_prim():
assert e_prim(13)==True
assert e_prim(0)==False
assert e_prim(-2)==False
assert e_prim(1)==False
assert e_prim(-5)==False
assert e_prim(2)==True
assert e_prim(4)==False
def test_gen():
assert gen(10)==11
assert gen(14)==17
test_e_prim()
test_gen()
run_ui()
| false |
99f0af8b882d96b8f8bc6df1aa35110b17cbcea7 | MihirMalani1712/PPL_LAB | /Assignment/Assignment6/shapes.py | 1,190 | 4.15625 | 4 | import turtle
s = turtle.getscreen()
t = turtle.Turtle()
class shape:
def __init__(self, sides = 0, length = 0) :
self.sides = sides
self.length = length
class polygon(shape):
def info(self):
print("In geometry, a polygon can be defined as a flat or plane, two-dimensional with straight sides.")
class square(polygon):
def show(self):
t.fd(self.length)
t.rt(90)
t.fd(self.length)
t.rt(90)
t.fd(self.length)
t.rt(90)
t.fd(self.length)
t.rt(90)
class pentagon(polygon):
def show(self):
for i in range(5):
t.forward(self.length)
t.right(72)
class hexagon(polygon):
def show(self):
for i in range(6):
t.forward(self.length)
t.right(60)
class octagon(polygon):
def show(self):
for i in range(6):
t.forward(self.length)
t.right(45)
class triangle(polygon):
def show(self):
t.forward(self.length)
t.left(120)
t.forward(self.length)
t.left(120)
t.forward(self.length)
sq1 = square(4, 100)
sq1.info()
sq1.show()
| false |
660aea75a1024b16e007b6dcdef4aca6cdf6ae77 | blane612/for_loops | /tertiary.py | 470 | 4.40625 | 4 | # -------------------- Section 3 -------------------- #
# ---------- Part 1 | Patterns ---------- #
print(
'>> Section 3\n'
'>> Part 1\n'
)
# 1 - for Loop | Patterns
# Create a function that will calculate and print the first n numbers of the fibonacci sequence.
# n is specified by the user.
#
# NOTE: You can assume that the user will enter a number larger than 2
#
# Example Output
#
# >> size... 6
#
# 1, 1, 2, 3, 5, 8
#
# Write Code Below #
| true |
44db8f0a764a4af6a94741f114a801c6c3ab5de9 | JJBarata/python3oo | /fatorial.py | 392 | 4.21875 | 4 | # Calculando o fatorial de um número:
def fatorial(num):
if num < 0:
print('Não existe fatorial de número negativo. tente novamente!')
elif num == 1:
return 1
else:
fact = 1
while num > 1:
fact *= num
num -= 1
return fact
num = int(input('Digite um número: '))
print(f'O fatorial de {num} é {fatorial(num)}')
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.