blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
06faf22ecd5d6a77af38b0218bdc6b1dcb414a47 | yinyangguaiji/yygg-C1 | /5-2.py | 829 | 4.15625 | 4 | str1 = 'wdnmd'
str2 = 'WdnMd'
print('str1 == str2 ?')
print(str1 == str2)
print('str1 == str2.lower() ?')
print(str1 == str2.lower())
print('5 == 5 ?')
print(5 == 5)
print('5 == 3 ?')
print(5 == 3)
print('5 != 3 ?')
print(5 != 3)
print('5 > 3 ?')
print(5 > 3)
print('5 < 3 ?')
print(5 < 3)
print('5 >= 5 ?')
print(5 >= 5)
print('5 <= 5 ?')
print(5 <= 5)
print('5 >= 6 ?')
print(5 >= 6)
print('5 <= 6 ?')
print(5 <= 6)
print('5 > 6) and (5 > 3) ?')
print((5 > 6) and (5 > 3))
print('(5 > 6) or (5 > 3) ?')
print((5 > 6) or (5 > 3))
numbers = [2,4,7,8]
print('numbers'+str(numbers))
print('Is "2" in numbers ?')
print(2 in numbers)
print('Is "5" in numbers ?')
print(5 in numbers)
print('Is 6 not in numbers ?')
print(6 not in numbers)
print('Is "4" not in nujbers')
print(4 not in numbers)
| false |
ce98303c85ea286d54b8815d68d6b2c32502e220 | ryan-g13/Python | /1PlayerBasicBattleship.py | 2,461 | 4.1875 | 4 | from random import randint
'''This is a 1 player version of Battleship that currently only allows 4 turns to guess on a grid of 5 x 5
Please enjoy responsibly'''
board = [] # empty gameboard list
for x in range(0, 5): # fill in board with "O"s
board.append(["O"] * 5)
def print_board(board):
for row in board:
print (" ".join(row)) # remove commas and brackets from list of lists
print_board(board)
def random_row(board): # methods to generate the random row/column placement of battleship
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board) # generate the random row/column placement of battleship
ship_col = random_col(board)
#print(ship_row) - removing location of ship in order to make game challenging!!!
#print(ship_col)
# Loop that defines the game "Editable" range for turns # and
for turn in range(4):
print("Turn", turn + 1)
guess_row = int(input("Guess Row: "))
guess_col = int(input("Guess Col: "))
if guess_row == ship_row and guess_col == ship_col:
print("Congratulations! You sank my battleship!")
break
else:
if guess_row not in range(5) or guess_col not in range(5): #logic test for out of bounds
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X": #logic test for if already guessed there
print( "You guessed that one already." )
else:
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
if turn == 3: #game over test based on turn count
print("Game Over")
print_board(board)
'''Future enhancements
enhancements—maybe you can think of some more!
Make multiple battleships: you'll need to be careful because you need to make sure that you don’t place battleships on top of each other on the game board. You'll also want to make sure that you balance the size of the board with the number of ships so the game is still challenging and fun to play.
Make battleships of different sizes: this is trickier than it sounds. All the parts of the battleship need to be vertically or horizontally touching and you’ll need to make sure you don’t accidentally place part of a ship off the side of the board.
Make your game a two-player game.
Use functions to allow your game to have more features like rematches, statistics and more!
''' | true |
f4af647f6c19fe3d0fc30784f811bcde0fbaf6d2 | BbillahrariBBr/python | /book2/car2.py | 994 | 4.25 | 4 | class Vehicle:
"""Base class for all Vehicle """
def __init__(self, name, manufacture, color):
self.name = name
self.manufacture = manufacture
self.color = color
def turn(self, direction):
print("Turning ",self.name, "to" , direction)
class Car(Vehicle):
"""Car Class"""
def __init__(self, name, manufacture, color, year, wheels):
self.name = name
self.manufacture = manufacture
self.color = color
self.year = 2017
self.wheels = 4
def change_gear(self,gear_name):
"""Method for changing gear"""
print(self.name, " is changing gear to ", gear_name)
#turn method is overriding
def turn(self, direction):
print("Turning ",self.name, "is turing" , direction)
if __name__ == "__main__":
c = Car ("Mustang 5.0 Gt Coupe", "Ford", "Red",2018, 4)
v = Vehicle("Softail Delux", "Harley-Davidson", "blue")
c.turn("right")
v.turn("left")
| false |
907ac4e323d08fa8d44b9ded6d6353001d3e4ff7 | kiwisquash/automatetheboringstuffwithpython | /Chapter3/collatz.py | 465 | 4.1875 | 4 | from inputValidator import isInteger
def collatz(value):
if value % 2 == 0:
return value // 2
if value % 2 == 1:
return 3*value + 1
print("Please enter an integer:",end=" ")
userInput = input()
while not isInteger(userInput):
print("You didn't enter an integer.")
print("Please enter an integer:",end=" ")
userInput = input()
value = int(userInput)
print(value)
while (value !=1):
value = collatz(value)
print(value)
| true |
4616555e47a266113d6bd47bd3fdf229006af730 | laureanopiotti/python3 | /02_Functions_and_Loops/204_list_comprehension.py | 1,527 | 4.4375 | 4 | # List comprehension
"""
A list comprehension is a Pythonic way of constructing a list.
"""
#for my_number in range(10):
# print(my_number)
numbers = list(range(10))
doubled = [n*2 for n in numbers]
phrases = [f'I am {age} years old' for age in doubled]
names_list = ["John", "Rolf", "Anne"]
lowercase_names = [name.lower() for name in names_list]
## With conditional
numbers = list(range(10))
evens = [n for n in numbers if n % 2 == 0]
friends = ['rolf', 'anna', 'charlie']
guests = ['Jose', 'Rolf', 'ruth', 'Charlie', 'michael']
present_friends = [name.capitalize() for name in guests if name.lower() in friends]
# present_friends = [name.capitalize() for name in guests if name.lower() in [f.lower() for f in friends]]
# Set and dictionary comprehension
"""
In the same way that we do list comprehension, we can do set comprehension
"""
friends = {'rolf', 'anna', 'charlie'}
guests = {'jose', 'rolf', 'ruth', 'charlie', 'michael'}
present_friends = friends & guests
"""
We could capitalize them using set comprehension.
"""
present_friends = {name.capitalize() for name in present_friends}
"""
Dictionary comprehension is also possible! All we have to do is create key-value pairs in the for loop.
"""
names = ['Rolf', 'Anna', 'Charlie']
time_last_seen = [10, 15, 8]
friends_last_seen = {names[i]: time_last_seen[i] for i in range(len(names))}
## EXTRA
"""
This is so popular, that there's a built-in function for it!
"""
friends_last_seen = dict(zip(names, time_last_seen))
print(friends_last_seen) | true |
ac9304b94d7f9443dba51236033049cf3ec32555 | deepaksamuel/python-tutorials | /13-curve-fitting-linear.py | 2,084 | 4.625 | 5 | # In this tutorial we will see how to fit curves to give set of data points
# In the first part, we will see how to make a linear fit
import numpy as np
import matplotlib.pyplot as plt
# lets create an artificial data set of x and y points to which we will fit a straight line
# We will make x=y in which case the slope =1 and intercept will be 0
x = np.arange(0,10,1)
# you can also add some variations to y to simulate an experimental datapoint.
# one way is to add gaussian noise by sampling a number from a gaussian distribution and adding it to y.
# like this:
noise = np.random.normal(0,1,10)# check tutorials 04 to learn about random number generatio
y = x+noise # in case noise is zero, y = x will be a straight line with slope exactly equal to 1 and intercept exaclty 0
plt.scatter(x,y)
fit_res = np.polyfit(x, y, 1) # 1 is the degree of fit, 1 is for linear fit, 2 for quadratic plot and so on
# z contains the results of the fit
# This is how you get the slope and intercept
print("The fit results are:{0}".format(fit_res)) # the first element in the array is the slope and the second element is the intercept
print("The first value is the slope and the second is the intercept")
#Now lets plot the line as estimated by the linear fit:
y_fit = fit_res[0]*x + fit_res[1] # y=mx + c
# enable the line below to see the fitted line
plt.plot(x,y_fit)
plt.show()
# assignments
# # in many cases, one might require the error on the slope and intercept
# in which case one can do the following:
# fit_res, error= np.polyfit(x, y, 1,full=False, cov=True) # 1 is the degree of fit, 1 is for linear fit, 2 for quadratic plot and so on
# print("The error matrix is {0}".format(error))
# print("The diagonal elements are the errors") # The first element in the diagonal is that of slope and the second element in the diagonal is that of the intercept
# Try the above code
# In case you want to fit a second order polynomial change np.polyfit(x,y,1) to np.polyfit(x,y,2)
# Change the mean and sigma in the gaussian distribution and see how the error matrix changes. | true |
22b178bd4b462d63162bdae4f885d76378e2401c | deepaksamuel/python-tutorials | /10-pandas-read-file.py | 1,451 | 4.53125 | 5 | # reading file with pandas
# Pandas is a python module to read files and manipulate its contents (and also plot it)
# the read data is stored in what is called as a dataframe (like excel worksheet, which can be viewed in Spyder)
# This example shows how to read file which we wrote in the previous assignment (09-file-write)
# Pandas can also be used to write files.
import numpy as np
import matplotlib.pyplot as plt
# You must also import pandas and if it is not installed use the anaconda navigator -> environments and search for pandas and install it
# You can also see detailed instructions to install in https://github.com/deepaksamuel/python-tutorials and see the README.md
import pandas as pd
# We have no headers in the file, we name the columns as i and i-squared as shown below. The names will be used while plotting
df = pd.read_csv("out.txt",header=None, names=["i","i-squared"]) # the dataframe will be shown in Spyder IDE
print(df.head()) # this prints out the first 5 elements in the file
# you can also plot from a dataframe
df.plot(x="i",y="i-squared")
plt.show()
# if the file has NO header rows, you must state that explicitly
# more info at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
# if you want to have the full view of the dataframe, go to variable explorer in the Spyder IDE and click on the parameter df.
# A separate window will open show the file in an Excel Sheet like view. | true |
2415e3fd45ba8b8a2090d1ea80c8be7384a93aa8 | armyrunner/CS1400-OOP1 | /TankRainWater.py | 1,528 | 4.1875 | 4 | # Andrew Nelson
# Write a program to do the following
# User input for dimensions of the tank
# User input for the amount of rain water
# Convert inches to feet
# Global Variable for gallons per cubic foot
# Started:9-8-2018
# Revisison 1:
# gcpf stands Gallons per Cubic Foot
gpcf = 7.48
gpcf = float(gpcf)
inchFeet = 12
inchFeet = float(inchFeet)
def main():
print("Welcome to the rainwater tank calculator.")
print("We'll ask you for a few parameters about your rainfall ")
print("and rain catchment area. We assume that your catchment ")
print("area is rectangular.")
print()
rainFall = float(input("How many inches of rain fall in a large storm? -> "))
wideth = float(input("How wide is your catchment area, in feet? -> "))
long = float(input("How long is your catchment area, in feet? -> "))
print()
print("You need a tank with ",gallons(wideth,long,rainFall),"gallon capacity")
print("to capture that much rain at one time")
def conInchFeet(rainFall,inchFeet):
conTotal = 0
conTotal = float(conTotal)
conTotal = rainFall / inchFeet
return conTotal
def volume(wideth,long,rainFall):
boxTotal = 0
boxTotal = float(boxTotal)
boxTotal = wideth * long * conInchFeet(rainFall,inchFeet)
return boxTotal
def gallons(wideth,long,rainFall):
galTotal = 0
galTotal = float(galTotal)
galTotal = volume(wideth,long,rainFall) * gpcf
return galTotal
main()
| true |
df5757765fd87d6e0c87cda2d3bf1f7a6bcf9553 | hunhgun321/Breadth_first_search | /Breadth_first_search.py | 2,917 | 4.21875 | 4 | #Breadth first search (only horizontal or vertical adjacent)
#in this practice, 1s which are horizontally or vertically adjacent to each other are called "river"
#using BFS to see how many "river" in a graph and what are their position
def breadth_first_search(graph):
result = [] #storing the position of ALL river(adjacent 1)
copy_graph = graph
for index1,row in enumerate(copy_graph):
for index2,column in enumerate(row):
if column == 0:
copy_graph[index1][index2] = False #indicate 0 in graph(not part of a river)/it has been evaluated
else:
copy_graph[index1][index2] = True #indicate 1 in graph(part of a river)/it has not been evalutaed
directions = ((-1,0),(1,0),(0,-1),(0,1)) # up down left right
for index1,row in enumerate(copy_graph):
for index2, col in enumerate(row):
if col == True:
#start BFS
copy_graph[index1][index2] = False
pointer = (index1,index2) #for the starting point of the BFS
queue = [] #in form of [(row,col),(row,col),(row,col)]
output = [] #also [(row,col),(row,col)]
output.append(pointer)
for direction in directions: #search for all directions to see whether it is adjacent
dir_row = pointer[0] + direction[0]
dir_col = pointer[1] + direction[1]
if dir_row >= 0 and dir_row < len(graph) and dir_col >= 0 and dir_col < len(graph[0]):
if copy_graph[dir_row][dir_col] == True:
queue.append((dir_row,dir_col))
copy_graph[dir_row][dir_col] = False
while len(queue)>0:
pointer = queue[0]
output.append(queue[0])
queue.pop(0)
for direction in directions: #search for all directions to see whether it is adjacent
dir_row = pointer[0] + direction[0]
dir_col = pointer[1] + direction[1]
if dir_row >= 0 and dir_row < len(graph) and dir_col >= 0 and dir_col < len(graph[0]):
if copy_graph[dir_row][dir_col] == True:
queue.append((dir_row,dir_col))
copy_graph[dir_row][dir_col] = False
result.append(output)
return result
if __name__ == '__main__':
graph = ([0,0,0,0,0], #0 for walkable 1 for unwalkable e.g. wall
[1,0,1,1,1],
[1,0,0,0,1],
[1,1,0,0,1],
[0,0,0,0,0])
result = breadth_first_search(graph)
print(result)
print(f"number of rivers is {len(result)}")
| true |
e436d4994877bff313231c735ef5273d992d3bee | Anna-Pawlewicz/python_and_selenium_practice | /learning_python/circleClass.py | 453 | 4.28125 | 4 | # Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle.
import math
class Circle:
def __init__(self, r):
"""radius in centimeters"""
self.radius = r
def area(self):
return math.pi * (self.radius ** 2)
def perimeter(self):
return 2 * math.pi * self.radius
circle = Circle(5)
print(circle.area())
print(circle.perimeter())
| true |
1faf6c0115f9a71018a806881e9cae440b4b89a7 | Kabson-Innovation/mkabore-python-bc | /script/anagram_remover.py | 1,261 | 4.125 | 4 | #!/usr/bin/env python3
"""
Service to remove anagrams in a list of strings
"""
def are_anagram(str1, str2):
# Get lengths of both strings
n1 = len(str1)
n2 = len(str2)
# If length of both strings is not same, then
# they cannot be anagram
if n1 != n2:
return False
# Sort both strings
str1 = sorted(str1)
str2 = sorted(str2)
# Compare sorted strings
for i in range(0, n1):
if str1[i] != str2[i]:
return False
return True
def script_runner():
input_l = ["poke", "pkoe", "okpe", "ekop"] #["eat", "tea", "tan", "ate", "nat", "bat"]
print(input_l)
size = len(input_l)
print(size)
cp = input_l
for i in range(len(cp)):
if i == len(cp):
break
for j in range(len(cp)):
if i == j:
continue
if j >= len(cp):
break
if i >= len(cp):
break
print(i, j)
s1 = cp[i]
s2 = cp[j]
if are_anagram(s1, s2):
s = s2 if i < j else s1
input_l.remove(s)
print("cp : ", cp)
print("Anagrams removed : ", sorted(input_l))
if __name__ == '__main__':
script_runner() | true |
084b7b383ebe78e82bfaa01e1b3b286f77202fdf | nshahm/learning | /python/variables.py | 2,450 | 4.5625 | 5 | # variables
a = 1;
b = c = d = 2;
e = 1, 2, "John"
f, g, h = e
print (f)
print (g)
print (h)
del b # delete the reference of single or multiple variable
#print (b) # NameError: name 'b' is not defined
#string
name = "Shahm Nattarshah"
print (name[0])
print (name[2:5]) # substring
print (name[5:]) # substring only with start index
# list
list = [1,2,3,4,5,6,7,8,9,0]
tinylist = [1, "John"]
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2)
print (list + tinylist) # concatenated list
list.append(10) # Add anytime dynamically
print (list)
#tuple
# The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
# and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
# and cannot be updated. Tuples can be thought of as read-only lists
# Read only list we cannot update it
tuplee = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuplee) # Prints complete tuple
print (tuplee[0]) # Prints first element of the tuple
print (tuplee[1:3]) # Prints elements starting from 2nd till 3rd
print (tuplee[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuplee + tinytuple) # Prints concatenated tuple
# tuple.append() no such method
#tuple[0] = 'efgh'; # TypeError: 'tuple' object does not support item assignment
# Dictionaries
# Dictionaries are enclosed by curly braces ({ }) and values can be assigned
# and accessed using square braces ([]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
# Cast variables to types
floatvar = 1.05
print (int(floatvar))
intvar = 2
print (float(intvar))
print (str(intvar))
expstr = (1, "shahm", "33", "pollachi")
print (repr(intvar))
print (eval(" intvar > 1")) # Evaluates the expression True
print (tuple("abcdefgh")) #('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
print (list(1,2,3,4,5))
| true |
d35e3d0a50743204fa999ef63edf6aa7bec1bfc8 | nshahm/learning | /python/operators.py | 1,757 | 4.125 | 4 | # bitwise operators
# a = bin(60)
# b = bin(13)
# print (a&b)
# print (a|b)
#Logical Membership operators
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
c=b/a
if ( c in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
# Identity operators
# Identity operators compare the memory locations of two objects
a = 20
b = 20
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")
if ( id(a) == id(b) ):
print ("Line 3 - a and b have same identity")
else:
print ("Line 3 - a and b do not have same identity")
b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is not b ):
print ("Line 5 - a and b do not have same identity")
else:
print ("Line 5 - a and b have same identity")
#
# Operator Description
# ** Exponentiation (raise to the power)
# ~ + - Ccomplement, unary plus and minus (method names for the last two are +@ and -@)
# * / % // Multiply, divide, modulo and floor division
# + - Addition and subtraction
# >> << Right and left bitwise shift
# & Bitwise 'AND'
# ^ | Bitwise exclusive `OR' and regular `OR'
# <= < > >= Comparison operators
# <> == != Equality operators
# = %= /= //= -= += *= **= Assignment operators
# is is not Identity operators
# in not in Membership operators
# not or and Logical operators
| false |
ffb06719ecb87423ca8bb1c3ed27f6059c4c4a1c | cvhs-cs-2017/sem2-exam1-IMissHarambe | /Encrypt.py | 1,454 | 4.15625 | 4 | """Write a code that will remove vowels from a string and run it for the sentence:
'Computer Science Makes the World go round but it doesn't make the world round itself!'
Print the save the result as the variable = NoVowels
"""
def nohaksheer(x):
vowels = "AaEeIiOoUu"
novowels = ""
for y in x:
if y == 'a':
novowels = novowels + " "
elif y == "A":
novowels = novowels + " "
elif y == "E":
novowels = novowels + " "
elif y == "e":
novowels = novowels + " "
elif y == "I":
novowels = novowels + " "
elif y == "i":
novowels = novowels + " "
elif y == "O":
novowels = novowels + " "
elif y == "o":
novowels = novowels + " "
elif y == "U":
novowels = novowels + " "
elif y == "u":
novowels = novowels + " "
else:
novowels = novowels + y
return novowels
#print(nohaksheer('Computer Science Makes the World go round but it doesn\'t make the world round itself!'))
"""Write an encryption code that you make up and run it for the variable NoVowels"""
def hakrssucc(string):
newstring = ""
for ch in string:
a = ord(ch)
a = a + 8
newstring = newstring + chr(a)
return newstring
print (hakrssucc("Computer Science Makes the World go round but it doesn't make the world round itself!"))
| false |
949a8f40fc8b2e9a00f30f9b573db3a084c40e0a | Anshul-GH/freelance_projects | /category_job_evaluation_tests/vanHack/non_prime_generator.py | 1,395 | 4.28125 | 4 | from math import sqrt
# function to check if a given number is prime
def check_prime(n):
is_prime = True
for num in range(2, int(sqrt(n)) + 1):
if n % num == 0:
is_prime = False
break
return is_prime
def manipulate_generator(generator, n):
# flag to ensure that manipulate_generator prints only one value per iteration
printed = False
while not printed:
if n == 1:
# printing 1 by default as its the first non-prime
print(1)
# update the flag to indicate value being printed and exit the while loop
printed = True
else:
# check for the number to be prime
is_prime = check_prime(n)
# if its a non-prime number, print it
if not is_prime:
print(n)
# update the flag to indicate value being printed and exit the while loop
printed = True
else:
# if a prime number is encountered, generate the next number
n = next(generator)
def positive_integers_generator():
n = 1
while True:
x = yield n
if x is not None:
n = x
else:
n += 1
k = int(input())
g = positive_integers_generator()
for _ in range(k):
n = next(g)
# print(n)
manipulate_generator(g, n) | true |
a5bafe575121bb1d38a162321d00d26c38a0cd77 | mcdonagj/Tiptabs | /Tiptabs/UserInterface.py | 2,130 | 4.15625 | 4 | import tkinter as tk
class UserInterface:
user_input = ""
entry_field = None
window = None
calculator = None
def __init__(self, title, calculator):
"""
__init__() - Constructor for the Tiptabs User Interface.
:param title: Title of the UI window.
:param calculator: Tiptabs object.
"""
self.calculator = calculator
# Declare the frame of the UI
self.window = tk.Tk()
# Set the title of the UI frame.
self.window.title(title)
# Create a label for the UI application name.
lbl_name = tk.Label(text="Tiptabs, V3.7")
lbl_name.grid(column=0, row=0)
# Create a entry field for inputting the bill amount.
self.entry_field = tk.Entry()
self.entry_field.grid(column=0, row=1)
# Create a button for calculating the total amount.
btn_calc = tk.Button(self.window, text="Calculate Amount", command=lambda: self.retrieve_input())
btn_calc.grid(column=0, row=2)
# Set the size of the UI frame.
self.window.geometry("400x400")
# Call mainloop() to run the UI window.
self.window.mainloop()
def retrieve_input(self):
"""
retrieve_input() - Helper function for retrieving input from the fields within the UI.
:return: Boolean indicating valid input placed into the calculator.
"""
input_text = str(self.entry_field.get())
valid_input = self.check_input(input_text)
if valid_input:
self.calculator.set_amount(float(input_text.strip()))
return valid_input
def check_input(self, desired_input_text):
"""
check_input(str) - Helper function for verifying input given in the Tkinter GUI.
:param desired_input_text: String containing input from all fields in the GUI input fields.
:return: Boolean condition indicated whether valid input was given.
"""
result = False
check_str_len = len(desired_input_text.strip()) > 0
if check_str_len:
result = True
return result
| true |
0f937aede7c46d49b2bd289af69877c148de9d27 | Cormac88/mywork | /Week03/lab3.3.1-len.py | 240 | 4.125 | 4 | # This program reads in a String and outputs its length
# Author: Cormac Hennigan
inputString = str(input("Please enter a string: "))
lengthOfString = len(inputString)
print("The length of {} is {} characters".format(inputString, lengthOfString)) | true |
044f4068eb04e178088c46cdea117bc54bca6e60 | CursosyPracticasPlatzi/curso_de_python | /prueba_primalidad.py | 1,216 | 4.21875 | 4 | """Vamos a ver si un numero es primo o no mediante un código
un numero primo es uno que solo se puede dividir entre 1 y su mismo numero.
Vamos a ver si el numero es divisible por otros numero diferentes a 1 y al
mismo numero; si es así, ese numero no es primo, de lo contrario, es primo"""
#1) Primero la función principal de inicio
def es_primo(numero): #3) desarrollamos la función ejecutadora
contador = 0
for i in range(1,numero+1):
if numero % i != 0:
continue
else:
contador += 1
if contador == 2:
return True
else:
return False
#!Un nuevo código que funciona!
def run():
numero = int(input("Escribe el numero: "))
if es_primo(numero): #2) identificamos la funcion que va a accionar el resultado: si es primo o no es primo
print("Es un número primo")
else:
print("No es un número primo")
if __name__ == "__main__":
run()
#Pasos para escribir en python:
#1) función principal de inicio __name__
#2) función de definicion- se encarga de dar la respuesta, pero no la ejecuta
#3) funcion ejecutadora- se encarga de ejecutar la operacion, el resultado lo envía a la función de definición. | false |
e74fcaddba60de9510492ef08c43a75d4d1cd367 | RamG007/MuleSoft | /script.py | 1,171 | 4.46875 | 4 | import sqlite3
# define connection and cursor
connection = sqlite3.connect('movies_database.db')
cursor = connection.cursor()
# create movies table
command = """CREATE TABLE IF NOT EXISTS movies( id INTEGER PRIMARY KEY,
movie_name TEXT,
actor TEXT,
actress TEXT,
director TEXT,
release_year INTEGER)"""
cursor.execute(command)
# Insert data into movies table
cursor.execute("INSERT INTO movies VALUES( 1, 'Avatar', 'Sam Worthington', 'Zoe Saldana', 'James Cameron', 2009)")
cursor.execute("INSERT INTO movies VALUES( 2, 'Sherlock Holmes', 'Robert Downey Jr.', 'Rachel McAdams', 'Guy Ritchie', 2009)")
cursor.execute("INSERT INTO movies VALUES( 3, 'Flipped', 'Callan McAuliffe', 'Madeline Carroll', 'Rob Reiner', 2010)")
# get movies
print('All Movies : ')
cursor.execute("SELECT * FROM movies")
print(cursor.fetchall())
print('---------')
print('Movies of Robert Downey Jr.')
cursor.execute("SELECT * FROM movies WHERE actor='Robert Downey Jr.'")
print(cursor.fetchall())
| true |
93b299a97faf312ea93cfbc4f555c50c58178f0e | parsa-kazazi/hashck | /hashmk.py | 1,390 | 4.15625 | 4 | #!/bin/python3
# -*- coding: utf-8 -*-
"""
Hash maker
Convert a string to hash
"""
import hashlib
string = input("\nEnter string : ")
print("\nSelect Hash type")
print("""
1-md5 2-sha1 3-sha224 4-sha256 5-sha384 6-sha512 7-blake2b 8-blake2s
9-sha3_224 10-sha3_256 11-sha3_384 12-sha3_512
""")
hash_type_number = input(": ")
numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
if (hash_type_number not in numbers):
print("\nInvailed input")
exit()
elif (hash_type_number == "1"):
hash_type = "md5"
elif (hash_type_number == "2"):
hash_type = "sha1"
elif (hash_type_number == "3"):
hash_type = "sha224"
elif (hash_type_number == "4"):
hash_type = "sha256"
elif (hash_type_number == "5"):
hash_type = "sha384"
elif (hash_type_number == "6"):
hash_type = "sha512"
elif (hash_type_number == "7"):
hash_type = "blake2b"
elif (hash_type_number == "8"):
hash_type = "blake2s"
elif (hash_type_number == "9"):
hash_type = "sha3_224"
elif (hash_type_number == "10"):
hash_type = "sha3_256"
elif (hash_type_number == "11"):
hash_type = "sha3_384"
elif (hash_type_number == "12"):
hash_type = "sha3_512"
def hashing(hash_type, string):
hash = hashlib.new(hash_type, bytes(string,"utf-8")).hexdigest()
return hash
hash = hashing(hash_type, string)
print("\n" + string + " : " + hash + "\n") | false |
6c433de83eb5fc47fbe24cb6a2400afeec0584c0 | arthurarty/shopping_cart | /db/utils.py | 819 | 4.125 | 4 | def convertTuple(tup):
"""Convert a tuple to a string"""
string = ','.join(tup)
return string
def return_values(values_list):
"""Return string that can be used in sql command"""
string = ''
for value in values_list:
if type(value) is int:
string = string + "," + str(value)
else:
string = string + ",'" + value + "'"
if string[0] == ',':
string = string[1:]
return string
def sql_from_dict(dict_values):
"""Return string that can be used in sql command"""
string = ''
for key, value in dict_values.items():
if type(value) is int:
string = string + f"{key}={value},"
else:
string = string + f"{key}='{value}',"
if string[-1] == ',':
string = string[:-1]
return string
| true |
bbdd06c6de5c7cae1ae8aa960e0ea82e3b12f099 | silviuapostu/project-euler-solutions | /30.py | 986 | 4.1875 | 4 | # Find the sum of all the numbers that can be written
# as the sum of fifth powers of their digits.
def is_sum_of_digit_powers(x, pwr=5):
digits = list(str(x))
powers = [int(d)**pwr for d in digits]
return x == sum(powers)
def digit_powers(pwr=5, n_max=254294):
nums = [x for x in range(n_max, 1, -1) if is_sum_of_digit_powers(x, pwr)]
return sum(nums)
if __name__ == "__main__":
# the biggest value of the sum of digit fifth powers is 9**5 * n_digits
# if n_digits goes beyond 6, the value of the number starts to diverge too
# much from this max value, thus making equality impossible.
# we can thus limit ourselves to searching up to 9**5*6 = 254294
try:
assert is_sum_of_digit_powers(1634, pwr=4)
assert is_sum_of_digit_powers(8208, pwr=4)
assert digit_powers(pwr=4, n_max=9999) == 19316
except AssertionError:
print('Failing tests for numbers with 4 digits')
else:
print(digit_powers())
| true |
cf75b2203060a9f764e18d12926fce17efa4817e | tiggerntatie/Birthday-quiz-1 | /birthday.py | 1,859 | 4.625 | 5 | """
birthday.py
Author: Eric
Credit: me
Assignment:
Your program will ask the user the following questions, in this order:
1. Their name.
2. The name of the month they were born in (e.g. "September").
3. The year they were born in (e.g. "1962").
4. The day they were born on (e.g. "11").
If the user's birthday fell on October 31, then respond with:
You were born on Halloween!
If the user's birthday fell on today's date, then respond with:
Happy birthday!
Otherwise respond with a statement like this:
Peter, you are a winter baby of the nineties.
Example Session
Hello, what is your name? Eric
Hi Eric, what was the name of the month you were born in? September
And what year were you born in, Eric? 1972
And the day? 11
Eric, you are a fall baby of the stone age.
"""
from datetime import datetime
todaydate = datetime.today().day
todaymonth = datetime.today().month
from calendar import month_name
name = input("Hello, what is your name? ")
month = input("Hi {0}, what was the name of the month you were born in? ".format(name))
year = int(input("And what year were you born in, {0}? ".format(name)))
date = int(input("And the day? "))
if month == "October" and date == 31:
print ("You were born on Halloween!")
elif month == month_name[todaymonth] and todaydate == date:
print("Happy birthday!")
else:
decade = "Stone Age"
if year >= 2000:
decade = "two thousands"
elif year >= 1990:
decade = "nineties"
elif year >= 1980:
decade = "eighties"
if month in ["January", "February", "December"]:
season = "winter"
elif month in ["March", "April", "May"]:
season = "spring"
elif month in ["June", "July", "August"]:
season = "summer"
else:
season = "fall"
print("{0}, you are a {1} baby of the {2}.".format(name, season, decade))
| true |
9af4a1c052bd492b2a268032cc794681ec423062 | matiasmasca/python | /ucp_intro/031_strings.py | 2,144 | 4.4375 | 4 | frase = "Curso de Python"
print(frase)
# Es posible realizar operaciones con cadenas. Por ejemplo, podemos "sumar" cadenas añadiendo una a otra. Esta operación no se llama suma, sino concatenación y se representa con el signo +.
# Concatenación
print(frase + " esta muy bueno")
print("muy " + "pero " + "muy " + "bueno!")
# Repetición
# podemos repetir una misma cadena un ciertno numero de veces con el signo *
print("Esto es una prueba. " * 3)
# funciones/métodos para cadenas
# Los métodos son funciones adjuntas a un valor. Por ejemplo, todos los valores de cadena tienen el método lower(), el cuál devuelve una copia de la cadena en minúsculas.
print(frase.lower()) # convertir a minusculas
print(frase.upper()) # convertir a MAYUSCULAS
print(frase.isupper()) # esta todo en mayusculas?
print(frase.upper().isupper()) # podemos convinar funciones
print(len(frase)) # cantidad de caracteres de la cadena
print(frase[0]) # caracter por indice en la cadena
print(frase[0] + frase[6] + frase[9]) # iniciales por indice en la cadena
print(frase.index("C"))
print(frase.replace("Python", "Ruby")) # remplazar una cadena dentro de otra
# Caracteres
# Cuando se comparan cadenas, Python va a usar la tabla ASCII para definir quien esta primero.
# con la funcion ORD nos devuelve el nro. de orden de ese caracter en la tabla
print(ord('a')) # 97
print(chr(64)) # @
print(chr(241)) # ñ
print("abajo" < "arriba")
"""
La tabla ASCII presenta un problema cuando queremos ordenar palabras: las letras mayúscu-
las tienen un valor numérico inferior a las letras minúsculas (por lo que ’Zapata’ precede a
’ajo’) y las letras acentuadas son siempre ((mayores)) que sus equivalentes sin acentuar (’aba-
nico’ es menor que ’ábaco’). Hay formas de solucionar eso, pero ya es otra historia.
"""
# Cadenas Multi-Línea
"""
Hasta ahora todas las cadenas han sido de una sola línea y tenían un carácter de comillas al
principio y al final. Sin embargo, si utiliza comillas triples al comienzo y al final entonces la
cadena puede ir a lo largo de varias líneas
"""
print("""
una cadena
de
varias
lineas""")
| false |
6ed1d86ed58d0d03302f0ab8a77a239383c41d8a | matiasmasca/python | /ucp_intro/22_try_catch_erros.py | 871 | 4.25 | 4 |
# Que hacemos cuando hay errores en nuestros programas?
# cuando potencialmente tenemos más errores?
# lista completa en https://docs.python.org/3/library/exceptions.html
""" v1
numero = int(input("Ingrese un numero:"))
print(numero)
"""
#fin v1
# v2 atrapemos ese error potencial
"""
try:
numero = int(input("Ingrese un numero:"))
print(numero)
except:
print("Ingreso invalido")
"""
# ese except asi como esta, capata solo lo que este adentro del try y no otro error en el programa
# v3
# se pueden dar diferentes tipos de errores.
try:
# value = 10 / 0
numero = int(input("Ingrese un numero:"))
print(numero)
except ZeroDivisionError:
print("Hey! no se puede dividir por 0")
except ValueError:
print("Ingreso invalido")
# IndexError("This is an index error")
# para probar un error podes hacer: raise IndexError("This is an index error")
| false |
4f1e3bb52446d880fa48c287c7754a604b07f6b9 | matiasmasca/python | /5hours/12_control_de_flujo_if.py | 1,910 | 4.34375 | 4 | # sentencia IF
# el programa responde a los datos que tiene, a los valores que se le pasa.
# en el dia a dia, resolvemos este tipo de declaraciones
# donde hay condiciones
# Cuando me levanto
# Si tengo hambre
# me hago el desayuno
# Cuando salgo de mi casa:
# Si esta nublado
# llevo un paraguas
# Sino
# llevo anteojos de sol
# Cuando estoy en un restaurant:
# si Quiero comer carne
# entonces pido un bife de lomo
# de otra manera, si quiero comer pasta
# entonces pido ravioles con boloñesa
# Y sino
# pido una ensalada
# Ahora si, en python
es_humano = False
if es_humano:
print("Usted es un ser humano")
else:
print("Usted no es un ser humano")
# Más de una condicion
# OR: uno u otro o ambos
is_male = True
is_tall = True
if is_male or is_tall:
print("Usted es un hombre o es alto o ambos")
else:
print("Usted no es un hombre ni alto")
# AND ambos tienen que ser verdadero
is_male = True
is_tall = False
if is_male and is_tall:
print("Usted es un hombre y es alto")
else:
print("Usted no es un hombre o no es alto")
# Else if
# AND ambos tienen que ser verdadero
is_male = False
is_tall = True
if is_male and is_tall:
print("Usted es un hombre y es alto")
elif is_male and not(is_tall):
print("Usted es un hombre petiso")
else:
print("Usted no es un hombre o no es alto")
if is_male and is_tall:
print("Usted es un hombre y es alto")
elif is_male and not(is_tall):
print("Usted es un hombre petiso")
elif not(is_male) and is_tall:
print("Usted no es hombre pero es alto")
else:
print("Usted no es un hombre o no es alto")
# Comparaciones: Operadores de comparación.
# operador de comparacion: >, <, >=, <=, ==, !=
def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
resultado = max_num(3,1,9)
print("El mayor es " + str(resultado))
| false |
0a4488fa648962893a1966942da75642d58dfc28 | wleepang/projecteuler | /p7.py | 1,196 | 4.1875 | 4 | #!/usr/bin/env python
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
---
This is a brute force implementation. It gets the job done in a reasonable amount of time
(approx, 5-10s)
"""
def primes(start=0):
N = start
while True:
if N > 1:
for n in range(2, N):
if (N % n) == 0:
break
else:
yield N
N += 1
def nth_prime(N, dot_char='*', primes_per_dot=10, dots_per_line=80):
PRIMES = primes()
n_dots = 0
n_primes = 0
for n in range(N):
p = PRIMES.__next__()
n_primes += 1
if (n_primes % primes_per_dot) == 0:
print(dot_char, end='', flush=True)
n_dots += 1
if n_dots >= dots_per_line:
print('', flush=True)
n_dots = 0
print('')
print('-- done --')
return p
if __name__ == "__main__":
print('test case: find 6th prime (13)')
P = nth_prime(6)
print(P)
assert P == 13
print('objective: find 10_001th prime')
P = nth_prime(10_001)
print(P)
| true |
096f2ccb2922a13fe28f70d947c5adca80f8686e | KbearW/Project-Back_to_office | /Homework/take-home/init.py | 1,173 | 4.15625 | 4 |
class Canvas():
"""Canvas class to render canvas with a specified height and width"""
def __init__(self,height,width):
self.elements = []
self.height=height
self.width=width
class Shape():
"""Shape class render the shape based on input"""
class Rectangle(Shape):
"""A rectangle. """
def __init__(self, start_x: int, start_y: int, end_x: int, end_y: int, fill_char: str):
self.start_x = start_x
self.start_y = start_y
self.end_x = end_x
self.end_y = end_y
self.fill_char = fill_char
# def canvas():
# height = int(input('height (int only): '))
# width = int(input('width (int only): '))
# create_canvas={'height':height, 'width':width}
# def print_reg():
# rows = int(input('height (int only): '))
# cols = int(input('width (int only): '))
# char = input('Please enter a character :')
# for i in range(rows):
# for j in range(cols):
# print(char, end = ' ')
# print()
# print_reg()
# answer = input('Would you like to print another? [y/n]')
# if answer =='y':
# print_reg()
# else:
# print('goodbye')
| true |
cd476ec62a37efc0a5569f6cdc8cfcaf6e5740da | eljefedelrodeodeljefe/node-cpython | /deps/test/py_thread.py | 789 | 4.28125 | 4 | ''' Demonstrate the use of python threading'''
import time
import threading
def ThreadFunc():
for i in range(15):
print '...Printed from my thread.'
time.sleep(1)
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
for i in range(15):
print 'printed from MyThread...'
time.sleep(1)
def createThread():
print 'Create and run MyThread'
background = MyThread()
background.start()
print 'Main thread continues to run in foreground.'
for i in range(10):
print 'printed from Main thread.'
time.sleep(1)
print 'Main thread joins MyThread and waits until it is done...'
background.join() # Wait for the background task to finish
print 'The program completed gracefully.'
return 0 | true |
dc6320c2c600ed196a224ef332578362f82e5cb6 | Alexeiabianna/python-beginner | /sateliteOrbita.py | 370 | 4.21875 | 4 | import math
#
# Cálculo da altura (h) para que um satélite atinga uma órbita geoestacionária.
#
T = float(input("Digite o tempo de órbita: "))
T = T * 60
G = 6.67428e-11
M = 5.97e24
R = 6371e3
pi = math.pi
h = ((G * M * T**2) / (4 * pi ** 2)) ** (1/3) - R
print(R)
print("A altitude que deverá estar o satélite para entrar em órbita circular é de: ", h)
| false |
26a3c4ab14890b7ff86f7760d3f18e3f7689d81f | bbung24/codingStudy | /ctci/myown/python/Chapter6/ch6.py | 1,097 | 4.25 | 4 | #!/usr/bin/env python
'''
This file is for cracking the coding interview Chapter 6 : Math and logic puzzles.
'''
# Examplify, Simplify, Generalize, Pattern matching, and Base Case and build.
#------------------------------------------------------------------------------
def findHeavyBottle():
'''
6.1
You have 20 bottles of pills. 19 bottles have 1.0 gram pills, but one has pills
of weight 1.1 grams. Given a scale that provides an exact measurement, how
would you find the heavy bottle? You can only use the scale once.
'''
"""
Take one pill from first bottle. Take two pills from second bottle and so forth.
If the sum is 20.1, heavy bottle is first bottle. 20.2 = second, 21.0 = 10th,
22.0 = 20th, etc.
CORRECT
"""
"""
6.2 Basketball
You have a basketball hoop and someone says that you can play one of two games.
Game 1: You get one shot to make the hoop.
Game 2: You get three shots and you have to make two fo three shots.
If p is the probability of making a particular shot, for which values of p should
you pick one game or the other?
"""
"""
See Ipad for an answer.
"""
| true |
3816ffec61201a28127e84656baf4720b04e98d8 | lhughes99/Homework1 | /main.py | 1,839 | 4.15625 | 4 | # Author: Lauren Hughes lmh5981@psu.edu
Fgrade = input("Enter your course 1 letter grade: ")
Fcredit = input("Enter your course 1 credit: ")
if Fgrade == "A":
gradepoint1 = 4.0
elif Fgrade == "A-":
gradepoint1 = 3.67
elif Fgrade == "B+":
gradepoint1 = 3.33
elif Fgrade == "B":
gradepoint1 = 3.0
elif Fgrade == "B-":
gradepoint1 = 2.67
elif Fgrade == "C+":
gradepoint1 = 2.33
elif Fgrade == "C":
gradepoint1 = 2.0
elif Fgrade == "D":
gradepoint1 = 1.0
else:
gradepoint1 = 0.0
print(f"Grade point for course 1 is: {gradepoint1}")
Sgrade = input("Enter your course 2 letter grade: ")
Scredit = input("Enter your course 2 credit: ")
if Sgrade == "A":
gradepoint2 = 4.0
elif Sgrade == "A-":
gradepoint2 = 3.67
elif Sgrade == "B+":
gradepoint2 = 3.33
elif Sgrade == "B":
gradepoint2 = 3.0
elif Sgrade == "B-":
gradepoint2 = 2.67
elif Sgrade == "C+":
gradepoint2 = 2.33
elif Sgrade == "C":
gradepoint2 = 2.0
elif Sgrade == "D":
gradepoint2 = 1.0
else:
gradepoint2 = 0.0
print(f"Grade point for course 2 is: {gradepoint2}")
Tgrade = input("Enter your course 3 letter grade: ")
Tcredit = input("Enter your course 3 credit: ")
if Tgrade == "A":
gradepoint3 = 4.0
elif Tgrade == "A-":
gradepoint3 = 3.67
elif Tgrade == "B+":
gradepoint3 = 3.33
elif Tgrade == "B":
gradepoint3 = 3.0
elif Tgrade == "B-":
gradepoint3 = 2.67
elif Tgrade == "C+":
gradepoint3 = 2.33
elif Tgrade == "C":
gradepoint3 = 2.0
elif Tgrade == "D":
gradepoint3 = 1.0
else:
gradepoint3 = 0.0
print(f"Grade point for course 3 is: {gradepoint3}")
gradepoint1 = float(gradepoint1)
gradepoint2 = float(gradepoint2)
gradepoint3 = float(gradepoint3)
Fcredit = int(Fcredit)
Scredit = int(Scredit)
Tcredit = int(Tcredit)
GPA = ((gradepoint1*Fcredit)+(gradepoint2*Scredit)+(gradepoint3*Tcredit))/(Fcredit+Scredit+Tcredit)
print(f"Your GPA is: {GPA}") | false |
1b261bbb8b7e6f520577b0846b63cbafa104ef0e | matrixjoeq/timus_solutions | /1585/slu.py | 1,715 | 4.3125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
1585. Penguins
Time limit: 1.0 second
Memory limit: 64 MB
[Description]
Programmer Denis has been dreaming of visiting Antarctica since his childhood.
However, there are no regular flights to Antarctica from his city. That is why
Denis has been studying the continent for the whole summer using a local cinema.
Now he knows that there are several kinds of penguins:
Emperor Penguins, which are fond of singing;
Little Penguins, which enjoy dancing;
Macaroni Penguins, which like to go surfing.
Unfortunately, it was not said in the cartoons which kind of penguins was
largest in number. Petya decided to clarify this. He watched the cartoons once
more and every time he saw a penguin he jotted down its kind in his notebook.
Then he gave his notebook to you and asked you to determine the most numerous
kind of penguins.
[Input]
The first line contains the number n of entries in the notebook (1 ≤ n ≤ 1000).
In each of the next n lines, there is the name of a kind of penguins, which is
one of the following: “Emperor Penguin,” “Little Penguin,” and “Macaroni Penguin.”
[Output]
Output the most numerous kind of penguins. It is guaranteed that there is only
one such kind.
'''
import sys;
import math;
def calc():
n = int(sys.stdin.readline())
m = { 'Emperor Penguin' : 0, 'Little Penguin' : 0, 'Macaroni Penguin' : 0 }
for line in sys.stdin:
if (n <= 0):
break;
line = line.strip('\r\n')
m[line] = m[line] + 1
n = n - 1
c = 0
r = ''
for k, v in m.items():
if (v > c):
r = k
c = v
print r
if __name__ == '__main__':
calc()
| true |
ccc7c651226fc6da0b23fc2b9878637166d7b27e | 1923851861/Python_Base | /day21/08 继承的应用.py | 1,604 | 4.25 | 4 | #派生:子类中新定义的属性,子类在使用时始终以自己的为准
class OldboyPeople:
school = 'oldboy'
def __init__(self,name,age,sex):
self.name = name #tea1.name='egon'
self.age = age #tea1.age=18
self.sex = sex #tea1.sex='male'
class OldboyStudent(OldboyPeople):
def choose_course(self):
print('%s is choosing course' %self.name)
class OldboyTeacher(OldboyPeople):
# tea1,'egon',18,'male',10
def __init__(self,name,age,sex,level):
# self.name=name
# self.age=age
# self.sex=sex
OldboyPeople.__init__(self,name,age,sex)
self.level=level
def score(self,stu_obj,num):
print('%s is scoring' %self.name)
stu_obj.score=num
stu1=OldboyStudent('耗哥',18,'male')
tea1=OldboyTeacher('egon',18,'male',10)
# print(stu1.__str__())
# print(tea1.__dict__)
#对象查找属性的顺序:对象自己-》对象的类-》父类-》父类。。。
# print(stu1.school)
# print(tea1.school)
# print(stu1.__dict__)
# print(tea1.__dict__)
# tea1.score(stu1,99)
# print(stu1.__dict__)
# 在子类派生出的新功能中重用父类功能的方式有两种:
#1、指名道姓访问某一个类的函数:该方式与继承无关
# class Foo:
# def f1(self):
# print('Foo.f1')
#
# def f2(self):
# print('Foo.f2')
# self.f1()
#
# class Bar(Foo):
# def f1(self):
# print('Bar.f1')
# #对象查找属性的顺序:对象自己-》对象的类-》父类-》父类。。。
# obj=Bar()
# obj.f2()
# '''
# Foo.f2
# Bar.f1
# ''' | false |
796d5bf0a6fdb3bedcf0d65bbe195144b358e05c | 1923851861/Python_Base | /day03/02 与用户交互.py | 585 | 4.3125 | 4 |
# 在python3中的input会将用户输入的任何内容都存成字符串类型
# name=input("请输入您的姓名:") #name='egon'
# pwd=input("请输入您的密码:") #pwd='123'
#
# print(name,type(name))
# print(pwd,type(pwd))
# print('=========>1')
# print('=========>2')
# print('=========>3')
# 在python2中的raw_input用法与python3的input是一摸一样的
# name=raw_input("请输入您的姓名:") #name='egon'
# pwd=raw_input("请输入您的密码:") #pwd='123'
# age=input('age>>>: ') #age='18'
# print(age,type(age))
# age=int(age)
# print(age > 11)
| false |
75bbdb218b15c8eeaf4e5eb782fd6b695ab55153 | 1923851861/Python_Base | /day24/03 自定义内置方法来定制类的功能.py | 949 | 4.125 | 4 | #1、__str__方法
# class People:
# def __init__(self,name,age):
# self.name=name
# self.age=age
# #在对象被打印时,自动触发,应该在该方法内采集与对象self有关的信息,然后拼成字符串返回
# def __str__(self):
# print('======>')
# return '<name:%s age:%s>' %(self.name,self.age)
# obj=People('egon',18)
# obj1=People('alex',18)
# print(obj) #obj.__str__()
# print(obj) #obj.__str__()
# print(obj) #obj.__str__()
# print(obj1) #obj1.__str__()
# d={'x':1} #d=dict({'x':1})
# print(d)
#1、__del__析构方法
# __del__会在对象被删除之前自动触发
class People:
def __init__(self,name,age):
self.name=name
self.age=age
self.f=open('a.txt','rt',encoding='utf-8')
def __del__(self):
# print('run=-====>')
# 做回收系统资源相关的事情
self.f.close()
obj=People('egon',18)
print('主')
| false |
1dd0a75084bc64dd88a451072ffa3e6525509f69 | hylandm/Python_intro | /Unit_converter.py | 2,475 | 4.4375 | 4 | print "Welcome Michael Hyland\'s Unit Converter! :)"
print "You can convert Distances, Weights, Volumes & Times to one another, but only"
print "within units of the same category, which are shown below. E.g.: 1 mi in ft"
print
print "Distances: ft cm mm mi m yd km in"
print "Weights: lb mg kg oz"
print "Volumes: floz qt cup mL L gal pint"
distances = {'ft':3.28084,'cm':100,'m':1,'mm':1000,'mi':.000321371,'yd':1.09361,'km':.001,'in':39.3701}
weights = {'lb':2.20462,'mg':1000000,'kg':1,'oz':35.274}
volumes = {'L':1,'floz':33.814,'qt':1.05669,'cup':4.22675,'mL':1000,'gal':.264172,'pint':2.11338}
while 1:
ipt = raw_input("Convert [AMT SOURCE_UNIT in DEST_UNIT, (q)uit, (h)elp, or (u)nits]:")
if ipt == 'q' or ipt == 'quit':
break
if ipt == 'h' or ipt == 'help':
print 'Type in the following format [<number> "unit which number represents" in "unit to convert to"]'
continue
if ipt =='u' or ipt == 'units':
print 'Acceptable units are...'
print "Distances: ft cm mm mi m yd km in"
print "Weights: lb mg kg oz"
print "Volumes: floz qt cup mL L gal pint"
continue
iptarr = str.split(ipt) #split the input into strings based on whitespace
if len(iptarr) != 4:
print "Incorrect format. Please enter in the format shown below"
continue
amount = float(iptarr[0])
srcunit = iptarr[1]
destunit = iptarr[3]
if distances.has_key(srcunit):
if not distances.has_key(destunit):
print 'Your destination unit is not recognized! type "units" to see list of available units'
continue
print (amount/distances[srcunit])*distances[destunit]
elif weights.has_key(srcunit):
if not weights.has_key(destunit):
print 'Your destination unit is not recognized! type "units" to see list of available units'
continue
print (amount/weights[srcunit])*weights[destunit]
elif volumes.has_key(srcunit):
if not volumes.has_key(destunit):
print 'Your destination unit is not recognized! type "units" to see list of available units'
continue
print (amount/volumes[srcunit])*volumes[destunit]
else:
print 'Source unit not recognized! Please ensure your format is correct and that your unit is listed below.'
print
print "Distances: ft cm mm mi m yd km in"
print "Weights: lb mg kg oz"
print "Volumes: floz qt cup mL L gal pint"
| true |
2e93946188837adbd18e47497eb65fb2fd9361b0 | hogeschool/INFDEV-Homework | /Solutions to homework/Python/CarsAndBikes/Ex1_pygame.py | 994 | 4.125 | 4 | import pygame
# the same Car as part 1 of the exercise
class Car:
def __init__(self):
self.position = 0
def move(self):
self.position += 1
print(self.position)
def __str__(self):
return "the car is at position: ".format(self.position)
def Main():
pygame.init()
size = width, height = 600, 600
white = 255, 255, 255
green = 50, 255, 100
screen = pygame.display.set_mode(size)
offset = 30
board_size = 10
#instantiate a car-object
c = Car()
#start the game-loop
while True:
pygame.event.pump()
screen.fill(white)
# draw the car. Just an ugly green rectangle
# pygame requires 4 parameters to define a rectangle: [x, y, width, height] of which we will only change the x
position_and_size = [10*c.position, 30, 30,30]
pygame.draw.rect(screen, green, position_and_size)
# update the car
c.move()
pygame.display.flip()
Main()
| true |
f792b16dd88f863bcefc2d94143e6f0f0d73d3c2 | Alacdoom97/Python-Programmer-Bootcamp | /8. Big O/Time complexity.py | 2,260 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 15:11:49 2020
@author: Pranav
"""
# -------------------------------------------------------------------------
# Constant Time - O(1) runs at a constant time regardless of input data (n)
# -------------------------------------------------------------------------
# a,b = 2,4
# if a > b:
# print(True)
# else:
# print(False)
# --------------------------------------------------------------------------------------
# Logarithmic Time O(log n) reduces the size of the input data in each step.
# A good example of popular logarithmic time complexity operation is binary search trees
# as shown below.
# --------------------------------------------------------------------------------------
# def binary_search(data, value):
# n = len(data)
# left = 0
# right = n - 1
# while left <= right:
# middle = (left + right) // 2
# if value < data[middle]:
# right = middle - 1
# elif value > data[middle]:
# left = middle + 1
# else:
# return middle
# raise ValueError('Value is not in the list')
# if __name__ == '__main__':
# data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# print(binary_search(data, 8))
# -----------------------------------------------------------
# Linear Time - O(n) inceases linearly as input data increase
# -----------------------------------------------------------
# data = range(1,35,1)
# for value in data:
# print(value)
# ----------------------------------------------------------------------------
# Quadratic Time - O(n^2) occurs when each input needs a linear time operation
# ----------------------------------------------------------------------------
# data = range(20)
# for x in data:
# for y in data:
# print(x, y)
# ----------------------------------------------------------------------------
# Exponential Time - O(2^n) occurs when the growth doubles with each addition
# to the input data set. Usually this is seen in brute-force algorithms like
# below.
# ----------------------------------------------------------------------------
# def fibonacci(n):
# if n <= 1:
# return n
# return fibonacci(n-1) + fibonacci(n-2)
| true |
00645d095fdf86f1289ad9d8965213e8518b2bfe | MigMikael/Practice | /2_list.py | 1,223 | 4.21875 | 4 | # Lists
# A list is the Python equivalent of an array, but is resizeable and can contain elements of different types
print('------------------------------------------')
xs = [3, 1, 2]
print(xs, xs[2])
print(xs[-1])
xs[2] = 'fool'
print(xs)
xs.append('lish')
print(xs)
x = xs.pop()
print(x)
print(xs)
# Slicing
print('------------------------------------------')
nums = list(range(5))
print(nums) # [0, 1, 2, 3, 4]
print(nums[2:4]) # [2, 3]
print(nums[2:]) # [2, 3, 4]
print(nums[:2]) # [0, 1]
print(nums[:]) # [0, 1, 2, 3, 4]
print(nums[:-1]) # [0, 1, 2, 3]
nums[2:4] = [8,9]
print(nums) # [0, 1, 8, 9, 4]
# Loops
print('------------------------------------------')
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx + 1, animal))
# List comprehensions
print('------------------------------------------')
nums = [0, 1, 2, 3, 4]
squares = []
for n in nums:
squares.append(n ** 2)
print(squares)
nums = [0, 1, 2, 3, 4]
squares = [x ** 3 for x in nums]
print(squares)
nums = [0, 1, 2, 3, 4]
squares = [x ** 3 for x in nums if x % 2 == 0]
print(squares)
| true |
8a84084b9aa1ac264e6d070178d2e65b40cdcf55 | chughbhavya/LearnPython | /mysqlConnect.py | 1,000 | 4.3125 | 4 | # Author : Bhavya Chugh
# This program makes a connection with MySql database and inserts data into it.
# Importing the MySQL connector
import mysql.connector
# Setting up a connection
conn = mysql.connector.connect(user = "root", password = "*******", host = "localhost"
,database = "university")
mycursor = conn.cursor()
# Creating a table customer in databse university
mycursor.execute("""Create table if not exists Customer
(
id int primary key,
name varchar(30),
email varchar(30),
city varchar(30),
age int,
gender char(1)
)""")
# Execute the insert statament
mycursor.execute(""" Insert into Customer values
(11, "Bhavya", "chugh.bhavya@gmail.com", "Plano", 25, "F")""")
mycursor.execute(""" Insert into Customer values
(2, "Milind", "chugh.bhavya@gmail.com", "Plano", 25, "F")""")
mycursor.execute(""" Insert into Customer values
(3, "Mansi", "chugh.bhavya@gmail.com", "Plano", 25, "F")""")
conn.commit()
mycursor.execute("Select * from Customer")
mylist = mycursor.fetchall()
for i in mylist:
print(i)
| true |
7544c77fd65dca62229daef209c9e04488d5d81c | joetomjob/PythonProjects | /Quiz 2.py | 877 | 4.1875 | 4 | import turtle as t
def circle(num):
'''
pre:turtle facing east at centre
post:turtle facing east at right end of outer circle
:param num: the nymber of circles to be drawn
'''
for i in range(num):
t.up()
t.back(50 + ((i-1) * 50))
t.left(90)
t.back(50 + ((i) * 50))
t.down()
t.right(90)
t.circle(50+(i*50))
t.up()
t.left(90)
t.back(50)
t.forward(50+((i+1)*50))
t.right(90)
t.forward(50 + ((i) * 50))
def circlenew(num):
for i in range(num):
t.down()
t.circle(50+(i*50))
t.up()
t.left(90)
t.back(50)
t.right(90)
t.left(90)
t.forward(num*50+50)
t.right(90)
t.forward(num * 50)
if __name__ == '__main__':
circlenew(2)
t.mainloop()
| false |
721f5757318716c1da699b140e01771d820bce3f | a-staab/code-challenges | /product_except.py | 1,173 | 4.40625 | 4 | """
You have a list of integers, and for each index you want to find the product of
every integer except the integer at that index. Write a function
get_products_of_all_ints_except_at_index() that takes a list of integers and
returns a list of the products. (Interview Cake)
>>> [1, 7, 3, 4]
[84, 12, 28, 21]
>>> [0, 1, 2, 3]
[6, 0, 0, 0]
"""
def get_products_of_all_ints_except_at_index(nums):
if len(nums) < 2:
raise IndexError("Array must contain two or more integers.")
products_of_all_nums_except_at_index = []
product_so_far = 1
# First loop populates list with products of all numbers before
# corresponding index
for i in xrange(len(nums)):
products_of_all_nums_except_at_index.append(product_so_far)
product_so_far *= nums[i]
product_so_far = 1
j = -1
# Then, we loop again, multiplying each number in the list by the product of
# the numbers after its index, starting from the end of the list
for i in xrange(len(nums)):
products_of_all_nums_except_at_index[j] *= product_so_far
product_so_far *= nums[j]
j -= 1
return products_of_all_nums_except_at_index
| true |
716fb4b6c6199f5407e224abc75269e1eb289bcf | kevine11/DigitalCrafts | /Python101/classworkweek2/HeroRPG.py | 1,421 | 4.1875 | 4 | #!/usr/bin/env python
# In this simple RPG game, the hero fights the goblin. He has the options to:
# 1. fight goblin
# 2. do nothing - in which case the goblin will attack him anyway
# 3. flee
###### SELF NOTES: add crit chance, add defense power, add block
class Hero(object):
def __init__ (self, heroHealth, heroPower):
self.heroHealth = heroHealth
self.heroPower = heroPower
class Goblin(object):
def __int__(self, goblinHealth, goblinPower):
self.goblinHealth = goblinHealth
self.goblinPower = goblinPower
while goblin_health > 0 and hero_health > 0:
print("You have {} health and {} power.".format(hero_health, hero_power))
print("The goblin has {} health and {} power.".format(goblin_health, goblin_power))
print()
print("What do you want to do?")
print("1. fight goblin")
print("2. do nothing")
print("3. flee")
print("> ", end=' ')
raw_input = input()
if raw_input == "1":
# Hero attacks goblin
goblin_health -= hero_power
print("You do {} damage to the goblin.".format(hero_power))
if goblin_health <= 0:
print("The goblin is dead.")
elif raw_input == "2":
pass
elif raw_input == "3":
print("Goodbye.")
break
else:
print("Invalid input {}".format(raw_input))
if goblin_health > 0:
# Goblin attacks hero
hero_health -= goblin_power
print("The goblin does {} damage to you.".format(goblin_power))
if hero_health <= 0:
print("You are dead.")
main() | true |
a060b38babfd07323944d8684ecb951c266c74e7 | mukherjeeritwik3/DrauvaSir | /Python Practices/Python Interview Questions/Assignment1/23.Python program to find uncommon words from two Strings.py | 786 | 4.125 | 4 | """
Given two sentences as strings A and B. The task is to return a list of all uncommon words. A word is uncommon if it
appears exactly once in any one of the sentences, and does not appear in the other sentence.
Note: A sentence is a string of space-separated words. Each word consists only of lowercase letters.
Examples:
Input : A = "Geeks for Geeks"
B = "Learning from Geeks for Geeks"
Output : ['Learning', 'from']
Input : A = "apple banana mango"
B = "banana fruits mango"
Output : ['apple', 'fruits']
"""
# Using Sets Symmetric difference
def uncommon(a,b):
c = a.split(' ')
d = b.split(' ')
k = set(c).symmetric_difference(set(d))
return k
a = "apple banana mango"
b = "banana mango fruits"
print(uncommon(a,b)) | true |
a7d8e3d3a5ac366bb25da52e3f3c617bfc604da1 | mukherjeeritwik3/DrauvaSir | /Python Practices/Python Interview Questions/Assignment1/7.Python Program for Program to find area of a circle.py | 213 | 4.375 | 4 | """
Area of a circle can simply be evaluated using following formula.
Area = pi * radius**2
where r is radius of circle
"""
def areaCircle(r):
area = 3.142*pow(r,2)
return area
print(areaCircle(5)) | true |
5f1e24f72833a36c3e397210b97a64c7a5f9c87d | urban-winter/Playground | /google_evens.py | 1,227 | 4.28125 | 4 | import unittest
#Build an algorithm that returns true when every digit is even. 1234 = false. 2468 = true. Assume the input is a number > 0
# def all_digits_even(n):
# # break down into digits
# num_str = str(n)
# # for each digit
# for i in range(len(num_str)):
# # if digit is odd
# # return False
# # return True
# if (int(num_str[i]) % 2 == 1):
# return False
# return True
def all_digits_even(a_number):
"""return true if all digits are even"""
while a_number > 0:
if a_number % 2 == 1:
return False
a_number /= 10
return True
class TestEvens(unittest.TestCase):
def test_1_is_false(self):
self.assertFalse(all_digits_even(1))
def test_2_is_true(self):
self.assertTrue(all_digits_even(2))
def test_3_is_false(self):
self.assertFalse(all_digits_even(3))
def test_4_is_true(self):
self.assertTrue(all_digits_even(4))
def test_12_is_false(self):
self.assertFalse(all_digits_even(12))
def test_2468_is_true(self):
self.assertTrue(all_digits_even(2468))
def test_1234_is_false(self):
self.assertFalse(all_digits_even(1234))
| true |
31c913906b67515e6587f6996c33932ddc96427c | k-bigboss99/python_algorithm | /Linked List/ch3_8.py | 2,445 | 4.21875 | 4 | # ch3_8.py
# 建立雙向鏈結串列
class Node():
''' 節點 '''
def __init__(self, data=None):
self.data = data # 資料
self.next = None # 向後指標
self.previous = None # 向前指標
class Double_linked_list():
''' 鏈結串列 '''
def __init__(self):
self.head = None # 鏈結串列頭部的節點
self.tail = None # 鏈結串列尾部的節點
def add_double_list(self, new_node):
''' 將節點加入雙向鏈結串列 '''
if isinstance(new_node, Node): # 先確定這item是節點
if self.head == None: # 處理雙向鏈結串列是空的
self.head = new_node # 頭是new_node
new_node.previous = None # 指向前方
new_node.next = None # 指向後方
self.tail = new_node # 尾節點也是new_node
else: # 處理雙向鏈結串列不是空的
self.tail.next = new_node # 尾節點指標指向new_node
new_node.previous = self.tail # 新節點前方指標指向前
self.tail = new_node # 新節點成為尾部節點
return
def print_list_from_head(self):
''' 從頭部列印鏈結串列 '''
ptr = self.head # 指標指向鏈結串列第 1 個節點
while ptr:
print(ptr.data) # 列印節點
ptr = ptr.next # 移動指標到下一個節點
def print_list_from_tail(self):
''' 從尾部列印鏈結串列 '''
ptr = self.tail # 指標指向鏈結串列尾部節點
while ptr:
print(ptr.data) # 列印節點
ptr = ptr.previous # 移動指標到前一個節點
double_link = Double_linked_list()
n1 = Node(5) # 節點 1
n2 = Node(15) # 節點 2
n3 = Node(25) # 節點 3
for n in [n1, n2, n3]:
double_link.add_double_list(n)
print("從頭部列印雙向鏈結串列")
double_link.print_list_from_head() # 從頭部列印雙向鏈結串列
print("從尾部列印雙向鏈結串列")
double_link.print_list_from_tail() # 從尾部列印雙向鏈結串列
| false |
9564a03019e77f240ed8ca6398884de113435d15 | Mr-BYK/Python1 | /oop/class.py | 1,617 | 4.3125 | 4 | # Class
class Person:
# Class Attributes - Sınıf Öznitelikleri
address = 'No Information'
# Constructor(Yapıcı Metod)
def __init__(self, name, year):
# Object Attributes - Nesne Öznitelikleri
self.name = name
self.year = year
# Instance Methods - Metod Örnekleri
def intro(self):
print("Hello There.I am " + self.name)
def calculateAge(self):
return 2020 - self.year
# Object(Instance) - Nesne Örnekleri
p1 = Person(name="Ali", year=1990)
p2 = Person(name="Yağmur", year=1995)
# Updating - Güncelleme
p1.name = "Ahmet"
p1.address = "Manisa"
# Accessing Object Attributes - Nesneye Erişme Öznitelikleri
print(f'p1:name{p1.name} year:{p1.year} adress:{p1.address}')
print(f'p2:name{p2.name} year:{p2.year} adress:{p2.address}')
print(f'adım:{p1.name} ve yaşım {p1.calculateAge()}')
print(f'adım:{p2.name} ve yaşım {p2.calculateAge()}')
p1(intro)
p2(intro)
class Circle:
# Class object attribute - Sınıf nesne öznitelikleri
pi = 3.14
def __init__(self, yaricap=1):
self.yaricap = yaricap
# Methods
def cevre_hesapla(self):
return 2 * self.pi * self.yaricap
def alan_hesapla(self):
return self.pi * (self.yaricap ** 2)
c1 = Circle() # yaricap=1
c2 = Circle(5)
print(f'c1: alanı= {c1.alan_hesapla()} çevre {c1.cevre_hesapla()}')
print(f'c2: alanı= {c2.alan_hesapla()} çevre {c2.cevre_hesapla()}')
| false |
4cbce3bfe2c4ffc0fdb819010ead7f127e4ff9b5 | caoqi95/LeetCode | /Easy/#717- 1-bit and 2-bit Characters.py | 1,247 | 4.25 | 4 | """
We have two special characters. The first character can be represented by one bit 0. The second character
can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return whether the last character must be a one-bit character
or not. The given string will always end with a zero.
Example 1:
Input:
bits = [1, 0, 0]
Output: True
Explanation:
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit
character.
Example 2:
Input:
bits = [1, 1, 1, 0]
Output: False
Explanation:
The only way to decode it is two-bit character and two-bit character. So the last character is NOT
one-bit character.
Note:
1 <= len(bits) <= 1000.
bits[i] is always 0 or 1.
"""
class Solution(object):
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
i = 0
while i < len(bits):
if i == len(bits) - 1: return True
if bits[i] == 1:
i += 2
else:
i += 1
return False
if __name__ == "__main__":
# bits = [1, 0, 0]
bits = [1, 1, 1, 0]
solution = Solution()
print(solution.isOneBitCharacter(bits))
| true |
86279b281ae957f0738bb12ae05247b2e4a6c29d | caoqi95/LeetCode | /Easy/#832-Flipping an Image.py | 1,760 | 4.65625 | 5 | """
Given a binary matrix A, we want to flip the image horizontally, then invert it, and return
the resulting image.
To flip an image horizontally means that each row of the image is reversed. For example,
flipping [1, 1, 0] horizontally results in [0, 1, 1].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
For example, inverting [0, 1, 1] results in [1, 0, 0].
Example 1:
Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
Example 2:
Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Notes:
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1
"""
import numpy as np
class Solution(object):
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
# 逆转矩阵的每行
A_rev = []
for row in A:
row_rev = row[::-1]
A_rev.append(row_rev)
# 矩阵取反
ans = []
for row in A_rev:
for val in row:
if val == 0:
val = 1
else:
val = 0
ans.append(val)
# 转换回 list 类型
ans = np.array(ans).reshape(np.array(A).shape).tolist()
return ans
if __name__ == "__main__":
A = [[1,1,0],[1,0,1],[0,0,0]]
# A = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
solution = Solution()
print(solution.flipAndInvertImage(A)) | true |
bf2eb6848a83298a51c460cfe708228dd91c5a44 | caoqi95/LeetCode | /Easy/#746-Min Cost Climbing Stairs.py | 1,583 | 4.28125 | 4 | """
On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to
reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Example 1:
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
Example 2:
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
Note:
1. cost will have a length in the range [2, 1000].
2. Every cost[i] will be an integer in the range [0, 999].
"""
class Solution(object):
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
"""
p1, p2 = 0, 0
for i in range(2, len(cost)+1):
p1, p2 = p2, min(p2+cost[i-1], p1+cost[i-2])
return p2
"""
# solution 2
if len(cost) == 2:
return min(cost)
for i in range(2, len(cost)):
# 当前的 cost 值与前两个中最小的值累加,然后一直循环判断
cost[i] += min(cost[i-1], cost[i-2])
#print(i, cost[i])
return min(cost[-2], cost[-1])
if __name__ == "__main__":
# cost = [10, 15, 20] # return 15
# cost = [0, 0, 0, 0] # reurn 0
cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] # return 6
solution = Solution()
print(solution.minCostClimbingStairs(cost)) | true |
0f38c051c5f1638ea99cc76590f94f4c968352f1 | YugoNoguchi/study | /introduce.py | 947 | 4.125 | 4 | def main():
print("hello")
if __name__ == "__main__":
main()
"""
pint("hello")
text = "Hello".replace("H","J")
print(text)
print("Hello",10,5.0,sep = "*" )
text = input("入力せよ")
print("あなたが入力したのは" + text)
teika = input("低下を入力せよ")
print(int(teika) * 1.08)
elemental = "nagasyou"
junior = "yamatyuu"
high = "gomi"
courage = "kasd"
sport1 = "swim"
sport2 = "basketball"
sport3 = "inline"
print(elemental)
print(junior)
print(high)
print(courage)
print(sport1)
print(sport2)
print(sport3)
print("elemental school is {},junior high school is {},high school is {},courage is {},sport1 is {},sport2 is {},sport3 is {}".format(elemental,junior,high,courage,sport1,sport2,sport3))
for j in range(0,3):
for i in range(0,3):
print("* ",end="")
print()
"""
| false |
405b2cb31bbb5391936f5d4859bccb2c7e654c7d | CosmicTechie/Coding-Problems | /Fibonacci.py | 867 | 4.375 | 4 | '''
Fibonacci Series
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,.....
First=0
Second=1
Third= 0+1= 1 Sum of Previous 2 values
Fourth= 1+1= 2
Fifth= 1+2= 3
Sixth= 2+3= 5
And so on....
'''
n=int(input("Enter the nth term:"))
def fibonacci(n):
a = 0
b = 1
if n < 0:
print("Incorrect input")
elif n == 1:
return a
elif n == 2:
return b
else:
for i in range(2,n):
c = a + b
a = b
b = c
return b
print(fibonacci(n))
'''
#Python program to generate Fibonacci series until 'n' value
n = int(input("Enter the value of 'n': "))
a = 0
b = 1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
'''
| true |
65fd74f864c56a2a607e402e8d73383315581b14 | heyiwang/PPPPPython | /py5Sample97/py4InputTest.py | 285 | 4.125 | 4 | #get word letter by letter and stop and write to a file if input a #
def letterByLetter():
file1 = open('text1.txt', 'w')
letter = ''
while letter != '#':
letter = raw_input('input a letter\n')
file1.write(letter)
print letter
file1.close()
letterByLetter()
| true |
c60277b46fd10b1e00241d985024529408710992 | rupaku/codebase | /python basics/dictionary.py | 2,032 | 4.1875 | 4 | '''
Dictionary in Python is an unordered collection of data values, used to store data values like a map,
Dictionary holds key:value pair
Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples,
but the key-values can be repeated and be of any type.
'''
dic={1:'geeks',2:'for',3:'geeks'}
print(dic) #{1: 'geeks', 2: 'for', 3: 'geeks'}
Dict = dict([(1, 'Geeks'), (2, 'For')])
print(Dict) #{1: 'Geeks', 2: 'For'}
#nested dictionary
Dict={1:'geeks',2:{3:'for',4:'geeks'}}
print(Dict) #{1: 'geeks', 2: {3: 'for', 4: 'geeks'}}
#add element
Dict={}
Dict[0]='geeks'
Dict[1]='for'
Dict[2]='geeks'
print(Dict) #{0: 'geeks', 1: 'for', 2: 'geeks'}
#Update values of keys
Dict[2]='Hello'
print(Dict) #{0: 'geeks', 1: 'for', 2: 'Hello'}
#access elements
print(Dict[1]) #for
#using get
print(Dict.get(2)) #hello
#delete dic:deletion of keys can be done by using the del keyword
# del Dict[1]
print(Dict)
# Clear:All the items from a dictionary can be deleted at once by using clear() method.
# Dict.clear()
# Dict.pop(2)
#Deleting an arbitrary Key-value pair
# Dict.popitem()
#keys
print(Dict.keys()) #dict_keys([0, 1, 2])
#values
print(Dict.values()) #dict_values(['geeks', 'for', 'Hello'])
#items
print(Dict.items()) #dict_items([(0, 'geeks'), (1, 'for'), (2, 'Hello')])
#update
Dict1={1:'A'}
Dict2={2:'B'}
Dict1.update(Dict2)
print(Dict1) #{1: 'A', 2: 'B'}
Dict1.update(B = 'For', C = 'Geeks')
print(Dict1) #{1: 'A', 2: 'B', 'B': 'For', 'C': 'Geeks'}
#setdefault
#returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary.
Dict1.setdefault('D', 'Geeks')
print(Dict1['D']) #Geeks
#has_keys
# returns true if specified key is present in the dictionary, else returns false.
print(Dict1)
# print(Dict1.has_key('B'))
#fromkeys()
# generate a dictionary from the given keys.
#Syntax : fromkeys(seq, val)
seq = { 'a', 'b', 'c', 'd', 'e' }
res=dict.fromkeys(seq,1)
print(res) #{'a': 1, 'c': 1, 'd': 1, 'e': 1, 'b': 1}
| true |
375f53b6487cc18805c027a6cc151f5a812fed9f | rupaku/codebase | /python basics/higherOrderFunc.py | 710 | 4.25 | 4 | '''
A function is called Higher Order Function if it contains other functions
as a parameter or returns a function as an output i.e, the functions that
operate with another function are known as Higher order Functions.
'''
#Function as object
def shout(text):
return text.upper()
print(shout('hello'))
x=shout
print(x('hello'))
#Passing func as another argument to other functions
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
greeting=func("Hi How are You?")
print(greeting)
greet(shout)
greet(whisper)
#Returning function
def create_adder(x):
def adder(y):
return x+y
return adder
add=create_adder(15)
print(add(10)) #25 | true |
8799376fefb78119153120ebe494df479f04826b | rupaku/codebase | /python basics/generators.py | 1,876 | 4.6875 | 5 | ''' Generators
- generate sequence of value over time
- range is generator
Generator-Function :
- A generator-function is defined like a normal function, but whenever it needs to generate a value,
it does so with the yield keyword rather than return. If the body of a def contains yield,
the function automatically becomes a generator function.
Generator-Object :
- Generator functions return a generator object. Generator objects are used either by calling
the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program).
- Generators are used to create iterators, but with a different approach.
- Generators are simple functions which return an iterable set of items, one at a time, in a special way.
'''
#example 1
def simple_generator():
yield 1
yield 2
yield 3
for i in simple_generator():
print(i)
#output
# 1
# 2
# 3
#example 2
def simple_generator():
yield 1
yield 2
yield 3
x= simple_generator()
print(x.__next__()) #1
print(x.__next__()) #2
print(x.__next__()) #3
''' generator application
Iterators don’t compute the value of each item when instantiated.
They only compute it when you ask for it. This is known as lazy evaluation.
Lazy evaluation is useful when you have a very large data set to compute.
It allows you to start using the data immediately, while the whole data set is being computed.
'''
#fibonacci using generator
def fibo(limit):
a,b=0,1
while a < limit:
yield a
a,b=b,a+b
x=fibo(5)
print(x.__next__()) #0
print(x.__next__()) #1
print(x.__next__()) #1
print(x.__next__()) #2
print(x.__next__()) #3
print(x.__next__()) #stop iteration
#using loop
print("Using for in loop")
for i in fibo(5):
print(i, end=' ')
#output
# Using for in loop
# 0 1 1 2 3
| true |
97e3d82c70b11ba0fcebad072ff33717904d5a67 | Hexexe/Da-Python-2020 | /part04-e02_powers_of_series/src/powers_of_series.py | 369 | 4.34375 | 4 | #!/usr/bin/env python3
import pandas as pd
import numpy as np
def powers_of_series(s, k):
return pd.DataFrame(np.array([x**i for i in range(1,k+1) for x in s]).reshape(k,len(s.index)).T,columns=range(1,k+1),index=s.index)
def main():
s = pd.Series([1, 2, 3, 4], index=list("abcd"))
print(powers_of_series(s, 3))
if __name__ == "__main__":
main()
| false |
44599dc08f8fb9040f90517b38277edcf0929c1e | lduran2/cis106-python-projects | /project5-line-numbers/line-numbers.py | 2,369 | 4.1875 | 4 | '''
./project5-line-numbers/line-numbers.py
<https://github.com/lduran2/cis106-python-projects/blob/master/project5-line-numbers/line-numbers.py>
Numbers the lines in a given text file.
By : Leomar Duran <https://github.com/lduran2>
When : 2020-10-19t21:18
Where : Community College of Philadelphia
For : CIS 106/Introduction to Programming
Version: 1.0
Changelog:
1.0 - Implemented the line numbering.
'''
import filelines
######################################################################
def main():
'''
The program.
'''
# start
# Variables
infile = None # the file to line number
numbered_lines = '' # the file lines after numbering
# Show the intro text.
intro_line_number()
# Get the file from the user.
infile = input_file()
# Number the lines of the file.
try:
numbered_lines = filelines.number(infile)
# Print the result.
print(numbered_lines)
# Always close the file.
finally:
infile.close()
# end finally
print()
# finish
print('Done.')
# end main()
######################################################################
def intro_line_number():
'''
Introduces this program.
'''
print('This program numbers the lines in a file, by 1s starting')
print('with 1 and separated by a colon character.')
print()
# end def intro_sales_tax()
######################################################################
def input_file():
'''
Accepts and validates the name of the file.
@returns
a valid file.
'''
# Variables
filename = '' # name of the file to line number
file = None # the file itself
# Accept the name of the file.
print('Please enter the name of the file.')
filename = input('> ')
# While the file is not found:
while (file == None):
# Try opening the file
try:
file = open(filename, 'r')
# If the file cannot open,
except IOError:
# Print an error message and try again.
print('File not found. Please try again.')
filename = input('> ')
# end except IOError
# end while (file == None)
return file
# end def input_file()
######################################################################
# Execute the main program.
main()
| true |
954f3f0950eaacf1c0d781492dcc5508c3ca75dc | luhu888/SeleniumProject | /base/my_iterator_generator.py | 1,880 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# __author__=luhu
import sys
"""
迭代是Python最强大的功能之一,是访问集合元素的一种方式。
迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。
迭代器有两个基本的方法:iter() 和 next()。
字符串,列表或元组对象都可用于创建迭代器
"""
def iterator():
list = [1, 2, 3, 4]
it = iter(list) # 创建迭代器对象
# for x in it:
# print(x, end=" ")
while True:
try:
print(next(it), end=' ')
except StopIteration:
sys.exit()
"""
在 Python 中,使用了 yield 的函数被称为生成器(generator)。
跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。
在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回yield的值。
并在下一次执行 next()方法时从当前位置继续运行。
"""
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0 # 这里是复合赋值
while True:
if counter > n: # 如果counter值大于n,就停止循环,返回a值
return
yield a
a, b = b, a + b # 这里是复合赋值
counter += 1
def print_fibonacci():
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
try:
print(next(f), end=" ")
except StopIteration:
sys.exit()
if __name__ == '__main__':
# iterator()
print_fibonacci()
| false |
1f0d1b3c1dcea5004f753e32918a75e050fed9cc | sivakrishna2606/jagadish12-python-code | /plain-python/conditional/vowelOrNot.py | 376 | 4.25 | 4 | #!/usr/bin/python
# Input a Char and print if that is vowel or not
print("Enter '0' for exit.");
ch = raw_input("Enter any character: ");
if ch == '0':
exit();
else:
if(ch=='a' or ch=='A' or ch=='e' or ch=='E' or ch=='i' or ch=='I'
or ch=='o' or ch=='O' or ch=='u' or ch=='U'):
print(ch, "is a vowel.");
else:
print(ch, "is not a vowel.");
| true |
ebf60e9949cdd1c106fa0f020e9eb739bb890736 | sivakrishna2606/jagadish12-python-code | /plain-python/conditional/primeOrNot.py | 204 | 4.3125 | 4 | #!/usr/bin/python
# Input a number and write logic to check if that number is prime or not
x = 9
for i in range(2,x):
if i % 2 == 0:
print('not a prime number')
else:
print('prime number')
| true |
ff746579348ee5fb57656d7c5a4ef079c4615c4d | Patricia7sp/Minit_Projeto_Calculadora-com-python | /calculadora.py | 1,089 | 4.25 | 4 | print('--------------------------- Calculadora em python ---------------------------', '\n')
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mult(a, b):
return a * b
def div(a, b):
return a / b
def porct(a, b):
div = a / 100
multi = div * b
return multi
print ("Seleciona a opcao desejada:" '\n')
print("1 = Soma")
print("2 = Subtracao")
print("3 = Multiplicacao")
print("4 = Divisao")
print("5 = Porcentagem")
calc = input("Digite sua opcao (1/2/3/4/5): \n")
n1 = int(input("Digite o numero para operacao: \n"))
n2 = int(input("Digite o segundo numero para operacao: \n"))
if calc == '1' :
print('\n')
print("Resultado", "=", add(n1, n2))
print('\n')
elif calc == '2':
print('\n')
print("Resultado", "=", sub(n1, n2))
print('\n')
elif calc == '3':
print('\n')
print("Resultado", "=", mult(n1, n2))
print('\n')
elif calc == '4':
print('\n')
print("Resultado", "=", div(n1, n2))
print('\n')
elif calc == '5':
print('\n')
print("Resultado", "=", porct(n1,n2))
print('\n')
else:
print("Esta Opcao nao existe, :(")
| false |
e358b83c4b388f996625477bd05b63dfeb7c4362 | jaeyoung-jane-choi/2019_Indiana_University | /Intro-to-Programming/A201-A597-lecture-examples-master/morning-lectures-A201-A597-Fall-2019/20191014-lecture14-morning01.py | 2,090 | 4.46875 | 4 | # strings are immutable!
# e.g.:
morning = "chilli"
# morning[5] = "y" # <-- error: str does not support
# item assignment...
# del morning[5] # <-- error: ... nor deletion!
# a string is a *sequence*, for 2 reasons:
#
# (1) it has multiple elements, e.g.:
print(" morning has " + str(len(morning)) + " characters")
# (2) elements are in a specific order:
if (morning != "chilil") :
print(" the two strings are different ")
# first example at lecture time of ... a tuple!
student1 = ("Jo", "Johnson", 22, "000-11-321")
# an empty tuple:
student2 = ()
student2 = student2 + ("Jill",)
student2 = student2 + ("Jilligan",)
student2 = student2 + (23,)
student2 = student2 + ("999-22-123",)
print("printing out student1 info:")
for element in student1:
print("element = " + str(element))
def printStudentRecord1(r):
""" prints a student1 record stored in a tuple
side effect: printout
r -> None"""
lTuple = ("Name = ", "Last Name = ", \
"Age = ", "SSN = ")
# lecture Task 2:
# implement this function,
# you *must* use a for loop!
counter = 0
for item in lTuple:
print(item + str(r[counter]))
counter = counter + 1
def printStudentRecord2(r):
""" prints a student1 record stored in a tuple
side effect: printout
r -> None"""
lTuple = ("Name = ", "Last Name = ", \
"Age = ", "SSN = ")
# lecture Task 2:
# implement this function,
# you *must* use a for loop!
indices = (0, 1, 2, 3)
for index in indices:
print(lTuple[index] + str(r[index]))
def printStudentRecord3(r):
""" prints a student1 record stored in a tuple
side effect: printout
r -> None"""
lTuple = ("Name = ", "Last Name = ", \
"Age = ", "SSN = ")
# lecture Task 2:
# implement this function,
# you *must* use a for loop!
for index in range(4)
print(lTuple[index] + str(r[index]))
printStudentRecord3(student1)
printStudentRecord3(student2)
| true |
03d356f2f7a7fb0cd618538d9abced02ea56d1a8 | jaeyoung-jane-choi/2019_Indiana_University | /Intro-to-Programming/test01/test_answer.py | 440 | 4.21875 | 4 |
#######PROF ANSWER
#get first user input
#using a counter
num_of_words = 0
total_letters = 0
user_input=''
while num_of_words < 5 and user_input != 'done':
user_input = input('plz enter a word (enter done when done):')
current_length = len(user_input)
total_letters = total_letters + current_length
num_of_words = num_of_words + 1
print('You have entered ' + str(total_letters)+ 'letters')
| true |
7fec131994e27e08a54421ce7241c7bc3bae8fc1 | jaeyoung-jane-choi/2019_Indiana_University | /Intro-to-Programming/A201-A597-lecture-examples-master/morning-lectures-A201-A597-Fall-2019/20190923-lecture08-Morning01.py | 843 | 4.125 | 4 | # printing out a string, 1 char at a time,
#
# version 1: using recursion
#
# defining function print_a_char() :
def print_a_char(i):
"""recursively print 1 char from myString global
Int -> None"""
if i == len(myString):
# base case: end of string, just return
print("debuggin base case ... now i = " + str(i))
return
else:
print("debuggin recursion ... now i = " + str(i))
# recursive case:
# print char at current index
# increment index,
# call itself recursively
print( myString[i] )
i = i + 1
print_a_char(i)
# end of function print_a_char()
#########################################
# main program
#########################################
myString = "abcdefghijklmnopqrstuvwxyz"
print_a_char(0)
| true |
7288852467a454032c1702416ce06f4fc97d8b0a | jaeyoung-jane-choi/2019_Indiana_University | /Intro-to-Programming/A201-A597-lecture-examples-master/afternoon-lectures-A201-A597-Fall-2019/20191002-lecture11-recurTable.py | 805 | 4.15625 | 4 | # using recursion to print
# one row of the multiplication table
# define recursive function
def printRow( i, j ):
# define base case recursion stops here:
# i.e. when end-of-line is reached
if i > 10:
# reached end of line, i.e.:
print()
return
# define recursive case:
else:
# do work for one level of recursion:
n = j * i
print ( "\t" + str(n), end="" )
# prepare recursive call:
i += 1
# call function recursively:
printRow( i, j )
def printTable( j ):
# define base case, i.e. when end-of-table is reached
if j > 10:
return
else:
# do work for 1 level of recursion:
printRow( 1, j)
j = j + 1
# call recursion:
printTable ( j )
| true |
375810f134e1abd50a94516e552bb660bc469da3 | jaeyoung-jane-choi/2019_Indiana_University | /Intro-to-Programming/A201-A597-lecture-examples-master/morning-lectures-A201-A597-Fall-2019/20191016-lecture15-morning02.py | 2,853 | 4.84375 | 5 | # lists - type, multiple values, mutable(*),
# may be used to store any values/types
# as list elements.
# supports indexing - i.e. refer to 1 element
# supports slicing - i.e. refer to multiple elements
# (*) individual values can be referred to,
# as well as changed, reordered, deleted, ...
# create a list by listing its values, in square brackets:
inventory = [ "water", "sunscreen", "flippers" ]
# indexing:
print("I can swim fast because I have "+str(inventory[2]))
# slicing:
print("I'm ready for the beach because I have " + \
str( inventory[0:2]) )
# slicing, again, same slice, different indexing:
print("I'm ready for the beach because I have " + \
str( inventory[:-1]) )
# lists do support changing individual elements:
inventory[0] = "lemonade" # <-- NO Error!
# lists do support changing individual elements, even to a different type!
inventory[2] = 42
# lists do not support assigning individual elements to non-existing positions:
# inventory[3] = 42 # <-- because the index is out of range, I get IndexError!
inventory = inventory + ["flippers"] # <-- concatenation creates new list!
# (from the lists/elements that are concatenated)
# we then re-assign that new list to
# the name inventory
inventory.append("flippers") # <-- appending adds new element(s) to
# existing list, without copying, etc.
# lists do support changing slices of elements:
inventory[0:2] = ["lemonade", "parasol"] # <-- NO Error!
# print out list to see what's in it:
for i in range( len(inventory) ) :
print(" at index " + str(i) + " there is " + str( inventory[i] ) )
print("DANGER: about to delete element 0 from inventory list")
# lists do support deleting elements:
del inventory[0] # <-- NO Type Error!
# lists re-index after element deletion!
# therefore, be CAREFUL about referring to the same elements at new indices!
# also, element deletion is potentially slow, if lots of elements need re-indexing
# print out all elements in list, using:
# for loop - to loop throuh all the elements in the list
# range of indices - to generate all indices for that list
# (this ranges uses len() to obtain lenght of list)
# indexing - uses index i to extract 1 element at a time from the list
for i in range( len(inventory) ) :
print(" at index " + str(i) + " there is " + str( inventory[i] ) )
# print out all elements in list, without indexing, using instead:
# for loop - to loop throuh all the elements in the list
# by extracting 1 element from the list at a time
for elem in inventory:
print(" we have " + str(elem) )
| true |
9b41b5a19ac71feee451e267d938e09e95b9f463 | jaeyoung-jane-choi/2019_Indiana_University | /Intro-to-Programming/lab7/lab07-functions.py | 1,568 | 4.53125 | 5 | #"A201 / Fall 2019" (or "A597 / Fall 2019"), "Lab Task 07", Jane Choi, janechoi
#A
def contains_only_integers(t):
"""Takes a tuple, returns True when all items in the tuple are integers
tuple -> bool"""
#counter is the index of the tuple
counter = 0
#so when the counter is smaller than the length of the tuple,
#the while loop continues
#(the counter should be smaller since it starts at 0
while counter < len(t):
#isinstance is a function that checks the variable if its the type
#so the tuple counter sees if its a integer.
result = isinstance(t[counter] , int)
#if the result is True : meaning that the t[counter] is an integer
if result == True :
#the counter is increased
counter = counter + 1
#if it is False, you can stop seeing other values and break the while loop
else: break
#the def returns the result of bool
return result
###########################################################################
#B
def analyze_tuple_0(pTuple):
"""Takes a tuple and returns the number of items in the tuple, when not tuple returns -1
tuple -> int"""
#when the pTuple is not a tuple returns number -1
if isinstance(pTuple, tuple) == False :
return -1
#when it is a tuple:
else:
#it returns the length of the tuple(number of items in the tuple)
return len(pTuple)
###########################################################################
| true |
b3b09aa93e6dbf412ed7ba720c332082f901103d | abstruso/AES-encryptor | /number_field_arithmetic.py | 2,834 | 4.3125 | 4 | def is_prime(number):
"""
Check if given number is prime
:returns True, False
"""
import math
if number == 0 or number == 1:
return False
for i in range(2, int(math.sqrt(number)) + 1):
if number % i == 0:
return False
return True
def choose_prime():
import Crypto.Util.number
print("Please choose your prime base by direct specification or generation")
number = input("a) specified prime (leave blank for 7): ")
if number == "":
prime = 7
else:
while not is_prime(int(number)):
print(number, "is not a prime")
number = input("try again ")
if number != "":
return int(number)
bits = input("b) number of bits (ec 1024) ")
if bits != "":
print("Number of bits in prime p is", bits)
prime = int(Crypto.Util.number.getPrime(int(bits)))
print("\nRandom n-bit Prime (p): ", prime)
return prime
def modulus_aritmetic(prime):
"""First, most basic element of our program. Does simple operations read from natural notation."""
print("your p = ", prime)
print("\nPlease enter statement to be calculated in modulo p," +
"for example 45242+52435 (only two arguments), or one argument with # " +
"to calculate reverse element in mod p body for example 3#")
statement = input()
if "#" in statement:
calculate_reverse_element(statement, prime)
else:
modulus_aritmetic_operations(statement, prime)
def modulus_aritmetic_operations(statement, prime):
if "+" in statement:
arguments = statement.split('+')
arguments[0] = int(arguments[0])
arguments[1] = int(arguments[1])
result = arguments[0] + arguments[1]
result %= prime
print(result)
if "-" in statement:
arguments = statement.split('-')
arguments[0] = int(arguments[0])
arguments[1] = int(arguments[1])
result = arguments[0] - arguments[1]
result %= prime
print(result)
if "*" in statement:
arguments = statement.split('*')
arguments[0] = int(arguments[0])
arguments[1] = int(arguments[1])
result = arguments[0] * arguments[1]
result %= prime
print(result)
def calculate_reverse_element(statement, p):
"""Calculate reverse element in mod p body."""
arguments = statement.split('#')
a = int(arguments[0])
# reverse element will exists for because p is prime and gcd(a,p)==1
result = gcd_extended(a, p)[1]
if result < 0:
result = p + result
print(result)
def gcd_extended(a, b):
"""Extended Euclidean algorithm"""
if a == 0:
return b, 0, 1
gcd, x1, y1 = gcd_extended(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd, x, y
| true |
688fbec52608cb7ce8fd732b11f80437c36b2f6a | Rajasudhangowda321/HackerRank_SolvedProblems | /lists.py | 1,109 | 4.21875 | 4 | #Consider a list (list = []). You can perform the following commands:
#insert i e: Insert integer e at position i .
#print: Print the list.
#remove e: Delete the first occurrence of integer e .
#append e: Insert integer e at the end of the list.
#sort: Sort the list.
#pop: Pop the last element from the list.
#reverse: Reverse the list.
#Initialize your list and read in the value of n followed by n lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list
#Sample Input
#12
#insert 0 5
#insert 1 10
#insert 0 6
#print
#remove 6
#append 9
#append 1
#sort
#print
#pop
#reverse
#print
N=int(input())
lst=[]
for i in range(N):
g=input().split()
if g[0]=='append':
lst.append(int(g[1]))
elif g[0]=='insert':
lst.insert(int(g[1]),int(g[2]))
elif g[0]=='sort':
lst.sort()
elif g[0]=='remove':
lst.remove(int(g[1]))
elif g[0]=='pop':
lst.pop(int(g[1]))
elif g[0]=='reverse':
lst.reverse()
elif g[0]=='print':
print(lst)
| true |
46637f69f02dc89b6beda456b862b1c6f9fee057 | pratham01tyagi/Python | /Learning Python/python5/python5.8(importing_random).py | 788 | 4.15625 | 4 | ###############################################################################################################
# RANDOM & IMPORT
import random
highest = int(input("enter the highest range :"))
ans = random.randint(0, highest)
#here we are calling "randint" function from "random" module by dot notation.
guess = 0
print(f"enter no betwen 0 to {highest} ")
while guess != ans:
guess = int(input(f"enter no"))
if guess == ans:
print(f"you guessed it right the answer is {ans}")
else:
if ans<guess:
print("guess low")
else:
print("guess high")
| true |
e717546c6d73f85d5aadf12e378b45d2f07eb201 | pratham01tyagi/Python | /Learning Python/python5/python5.4(changingin).py | 1,108 | 4.25 | 4 | #############################################################################################################
# CHECKING IN
'''
name = 'harry'
letter = input("enter your name")
if letter in name:
print("hi")
else:
print("bye")
#output1-
#enter your name hi
#bye
#output2-
#enter your name har
#bye
#output3-
#enter your namehar # here we entered the har without space hence it gave "hi"
#hi
'''
#############################################################################################################
# NOT IN
'''
activity = input("what would you like to do ")
if "cinema" not in activity:
print("bye")
else:
print("welcome")
#output-
#what would you like to do Cinema # as here "C" is in caps hence this is comming to be bye.
#bye
activity = input("what would you like to do ")
if "cinema" not in activity.casefold(): # .casefold() will convert words in caps to lower and then check
print("bye")
else:
print("welcome")
#OUTPUT-
#what would you like to do CINEMA
#welcome
''' | true |
6d18e608ad39cf328e8f49bd50fdb765e83b1971 | flj1860/ranzhji | /51/day1/A_string.py | 2,192 | 4.3125 | 4 | # -*- coding: utf-8 -*-
#这个是单行注释,代码执行时候会忽略注释行
"""
这个是
多行注释
"""
'''
这个也是多行注释
'''
#打印一行字符串到屏幕
print('hello world, 你好, python!')
#什么是变量,以及变量类型
#首先介绍三种类型的变量:
#字符串型(string), 整数型(integer),浮点型(float)
name = "张三" #字符串变量要用引号引起来
age = 25
weight = 75.5678
#造句子的两种方式
#1:直接用+号,来拼接字符串
#字符串是不能直接和整数以及浮点数相加,必须要全部转换为字符串
#变量类型转换函数:str(x):将x转换为字符;int(x):将x转换为整数;float(x):将x转换为浮点型
str1 = "我是:" + name + ",我今年" + str(age) + "了,我的体重是" + str(weight) + "KG"
print(str1)
#2:使用占位符的方式来拼接字符串
# %s:字符串占位符,执行时后面的字符串变量内容会替代这个占位符
# %d 整数占位符, 后面须对应整形变量
# %f 浮点占位符,后面须对应浮点型变量
#\ :转义符,表示斜杠后面的内容仅仅代表它原始的意思,\n : 换行
str2 = "我是:%s,我今年%d了,\n我的体重是%.3fKG"%(name,age,weight)
print(str2)
#%r : 随机占位符, 万能占位符
print("万能占位符:%r"%age)
#下面学习标准输入函数,input:输入
"""
answer = input("请问你的姓名:") #x = input(y) :y:提示信息;x:得到用户的输入
print("哦,你叫:" + answer)
"""
# 模拟苹果的siri的简单回答
myname = 'Siri'
myage = 18
myfavor = "吃饭、喝茶、看电影、旅游..."
x = input("请问你有什么问题吗?")
if "姓名" in x: # if 如果,如果在用户的提问中包含 "姓名" 两个字
print("我叫:%s,很高兴认识你!" %myname)
elif "年龄" in x: # elif 否则如果包含“年龄”
print("我叫:%s,我今年%d!" % (myname, myage))
elif "爱好" in x: # 否则如果包含“爱好”
print("我叫:%s,我今年%d!我喜欢%s" % (myname, myage, myfavor))
else: # 当前面的都没有满足,则执行这个
print("你好,我好像没有听明白,能重复一遍吗?")
| false |
c560d380982cb45872e3c2118534d6fbb621f1e1 | lih627/python-algorithm-templates | /LeetCodeSolutions/LeetCode_0232.py | 1,080 | 4.21875 | 4 | class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self._in = []
self._out = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self._in.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if not self._out:
while self._in:
self._out.append(self._in.pop())
return self._out.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if self.empty():
return None
if not self._out:
return self._in[0]
return self._out[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return self._in == [] and self._out == []
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
| true |
533d08df058803b6942284f4382ccd8eecde7e53 | William-Banquier/WilliamBanquierPersonal | /Cypher/cypher.py | 2,940 | 4.125 | 4 | #This is is a ceaser cipher I made a while ago. I wanted to upgrade it and also practise commenting things out.
#A ceaser cipher is when you get the value of a letter (a = 1, b = 2) then increase the value by the key.
#If the key was 1 a would turn into b, and b into c
#This is technily not a ceaser cipher anymore
#for more parts of a ceaser cipher go to this link: http://practicalcryptography.com/ciphers/caesar-cipher/
#imports
import random
#functions
#encrypt
def encrypt():
#gets unscrabled code and turns into list
caesarCipher = input("Put Code In (You will get random key)")
caesarCipher = list(caesarCipher)
#random key
x = random.randrange(0,26)
#final output
final = ""
#using a while loop like a for loop...
i = 0
while i != len(caesarCipher):
#checks if assii value of the letter of the input is a letter and with x is greater than the letter z
if ord(caesarCipher[i])+x > 122:
#adds x to the assii value of the letter minus 26 then turns the number back into a string.
ncaesarCipher = chr(ord(caesarCipher[i])-26+x)
#adds to final output
final+=(ncaesarCipher)
else:
#if assii value with x is less than z final can just be the number plus x with out -26
final+=(chr(ord(caesarCipher[i])+x))
#sould of made it a for loop
i+=1
#random letters before and after text
#empty string
y = ""
#for loop that runs a random amount of times
for i in range(0,random.randrange(5,25)):
#y gets a random letter from the string at line ****** ADD Line
y+=letterCharSide[random.randrange(0,len(letterCharSide)-1)]
#adds y to the start of final
final = y + final
#exact same thing but adds y to the back of final
y = ""
for i in range(0,random.randrange(5,25)):
y+=letterCharSide[random.randrange(0,len(letterCharSide)-1)]
final += y
print(final, "Your Key Is", x)
#decrypt
def decrypt():
#integer input for key
key = int(input("Put Key In: "))
#str input for the cipher
caesarCipher = input("Put Code In ")
#turns cipher into list
caesarCipher = list(caesarCipher)
#output
final = ""
#should of used for loop
i = 0
while i != len(caesarCipher):
#Checks if the value of the letter minus the key is greater than the value for "a"
if ord(caesarCipher[i])-key < 97:
#makes a new string which is just the letter plus the 26 minus the key.
ncaesarCipher = chr(ord(caesarCipher[i])+26-key)
#adds the letter to the output
final+=(ncaesarCipher)
else:
#adds the letter to the out put. The letters value is subtracted by the key
final+=(chr(ord(caesarCipher[i])-key))
i+=1
#final out put
print(final)
#end of functions
#getting all the characters for later use
letterCharSide = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;?@[]^_`{|}~'
#Checking User Inputs
EorD = input("'e' for encrypt, 'd' for decrypt (no numbers for either): ")
if EorD == 'e':
encrypt()
elif EorD == 'd':
decrypt() | true |
9e8d89be3f8e6a06031c3ad8804134cd1fddab01 | janetbabirye/python-c | /code.py | 1,010 | 4.1875 | 4 | print("i love css2021(upper)".upper()) #this is all upper case
print('i love css2021 (rjust 20)'.rjust(20)) #the second letter is in upper case
print('i love css2021.(capitalize)'.capitalize())#the first letters in upper case
print("i like" + str (" cs_class_cod ") + (" alot "))#adding the whole sentence
print(f'{print}(print function)')#printing the whole function
print(f'{type(229)}(print type)')#data type
#list
list_1 = ["one","two","three"]
list_1.append("four")#adding at the end
list_1.insert(0,"zero")#adding it at the beginning
list_2=[1,2,3]
list_2.extend(list_1)#adding list_1 to list_2
print(list_1)
#dictionary
clan = {"father": "jonathan" , "mother":"christine", "sister":"rena","brother":"ronald"}
#mapping
print(type(clan))
print(list(clan.keys()))
print(len(clan))
#update
clan.update({"father": "matovu"})
print(clan)
clan.update({"friend":"sumayah"})
print(clan)
x = clan.get("brother")
print(x)
print(len(clan))
#iterate
for m in clan.keys():
print(clan[m])
| false |
bea03f4ae7633e976ed58f756b55cc92ad80e8d5 | Mouizuddin/advanced-python | /Decorators And Generators/decorators.py | 2,447 | 4.125 | 4 | def doc():
"""Decorator
is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure
Follows functions first class concept
"""
"""Recap:
first class functions : Allows to treat function like any other objects
"""
def outter_function(logging):
def inner():
print(logging) # free variable
return inner # not executed
# return inner() # executed
# closure gives you access to an outer function's scope from an inner function
hi = outter_function("Hi")
bye = outter_function("Bye")
# hi()
# bye()
# Is a function that takes another function as argument add extra functionality and returns another function without altering the scr code of original function passed in
# def decorator_function(message):
# def wrapper_function():
# return message
# return wrapper_function
#
# output = decorator_function('LOGGING')
# print(output())
def decorator_function(original_function):
def wrapper_functon():
print('Define Decorators?')
return original_function()
return wrapper_functon
def to_display(): # without modifying to_dispaly(), can add extra functionality
return "Decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure"
# () <- EXECUTES THE CODE
abc = decorator_function(to_display)
print(abc())
# @ :
@decorator_function
def original_function():
return to_display()
print('====='*30)
print(original_function())
print('====='*30)
print("WITH ARGUMENT'S")
def decorator_function_2(original_function):
def wrapper_function_2(*args,**kwrags):
print(f"NAME OF THE FUNCTION IS {decorator_function.__name__}")
print(f'ALL DOCUMENTATION GIVEN HERE ARE : {doc.__doc__}')
return original_function(*args,**kwrags)
return wrapper_function_2
@decorator_function_2
def details(a,b):
return f'name {a} age {b} '
print(details("Mohammed mouizuddin",23))
# arguments to decorator
def prefix_decorator(prefix):
def decorator_function_3(original_function):
def wrapper_function_3(*args,**kwargs):
print(f'{prefix} :<- smaple')
return original_function(*args,**kwargs)
return wrapper_function_3
return decorator_function_3
print('======'*10)
@prefix_decorator('GOGGING')
def original_function():
return to_display()
print(original_function()) | true |
a28580e37938ff484599cacda4fef7177aef3652 | yangruihan/practice_7_24 | /PythonPractice/ex25.py | 1,623 | 4.46875 | 4 | # -- coding: utf-8 --
#
#filename:'ex25.py'
#
# 把一句话划分成若干个单词,存在一个list中
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
# 将list中的元素排序(从小到大)
def sort_words(words):
"""Sorts the words."""
return sorted(words)
# 输出list中第一个元素,并删除
def print_first_word(words):
"""Prints the first word after popping it off."""
print words.pop(0)
# 输出list中最后一个元素,并删除
def print_last_word(words):
"""Prints the last word after popping it off."""
print words.pop(-1)
# 先将一句话分成若干个单词,然后将这些单词排序
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
# 打印第一个单词和最后一个单词
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
# 打印第一个单词和最后一个单词(排好序后的list)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
print sort_words(break_words("hello world ni hao a"))
print_first_word(break_words("hello world ni hao a"))
print_last_word(break_words("hello world ni hao a"))
print_first_and_last('This is a good day!')
print sort_sentence("How beatiful you are!")
print_first_and_last_sorted("How beatiful you are!")
| false |
cba584498cf2f9d51bcf187765e0c5e60c83fe29 | yangruihan/practice_7_24 | /PythonPractice/ex_class_instance.py | 930 | 4.125 | 4 | # -- coding: utf-8 --
#
# filename:'ex_class&instance.py'
#
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print self.name, ":", self.score
bart = Student('Yrh', 100)
print bart.name
print bart.score
# result:
# Yrh
# 100
bart.print_score()
# result:
# Yrh : 100
# 在Python中,实例的变量名如果以__开头,
# 就变成了一个私有变量(private),只有内部可以访问,外部不能访问
class Teacher(object):
def __init__(self, name, major):
self.__name = name
self.__major = major
def print_major(self):
print self.__name, ":", self.__major
t = Teacher('YuanSir', 'Data structure')
t.print_major()
# result: YuanSir : Data structure
t.__name = 'Yuan'
t.print_major()
# print t.__major # 会报错
# result: YuanSir : Data structure
# 形如:__xxx__ 这样的变量在类中是可以直接访问的
| false |
268f1f2c5b31176ca44bbb384fe3899497a9c401 | poby123/studyDatastructure | /스택/stack.py | 2,481 | 4.125 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self, val):
self.items.append(val)
def pop(self, msg=None):
try:
return self.items.pop()
except IndexError:
if(msg):
print(msg)
else:
print("Stack is empty")
def top(self):
try:
return self.items[-1]
except IndexError:
print("Stack is empty")
def __len__(self): # len() 으로 호출하면 stack의 item 수를 반환한다.
return len(self.items)
if __name__ == "__main__":
s = Stack()
'''
스택 예1 괄호맞추기
'''
ex1 = "(()())()"
for one in ex1:
if(one == '('):
s.push(one)
else:
s.pop("( 괄호가 부족합니다.")
if(len(s)>0):
print(') 괄호가 부족합니다.')
'''
스택 예2-1 : Infix to Postfix
'''
infix = '3*(2+5)*4'
postfix = []
opStack = Stack()
for item in infix:
if(item.isdigit()):
postfix.append(item)
elif(item == '('):
opStack.push(item)
elif(item == ')'):
while(len(opStack) > 0 and opStack.top() != '('):
postfix.append(opStack.pop())
opStack.pop()
elif(item in '+-'):
while(len(opStack) > 0 and opStack.top() in '+-*/'):
postfix.append(opStack.pop())
opStack.push(item)
elif(item in '*/'):
while(len(opStack) > 0 and opStack.top() in '*/'):
postfix.append(opStack.pop())
opStack.push(item)
# rest operator pop
while(len(opStack) > 0):
postfix.append(opStack.pop())
# print postfix
for i in postfix:
print(i, end=' ')
'''
스택 예2-2 : Postfix 계산
'''
res = Stack()
for item in postfix:
if(item.isdigit()):
res.push(int(item))
elif(item == '+'):
a = res.pop()
b = res.pop()
res.push(a + b)
elif(item == '-'):
a = res.pop()
b = res.pop()
res.push(a - b)
elif(item == '*'):
a = res.pop()
b = res.pop()
res.push(a * b)
elif(item == '/'):
a = res.pop()
b = res.pop()
res.push(a / b)
print()
print('result = ' , res.pop())
| false |
01a387453d4d4e327bafaee4d3a82a607b38f1a1 | BRGoss/Treasure_PyLand | /Puzzles/Completed/palindrome.py | 622 | 4.3125 | 4 | DESCRIPTION: This function determines if a string is a palindrome or not.
ALGORITHM: Strip out any commas, spaces, or periods....could go further, but this is enough
Lowercase the word
Reverse the word
Compare the original with the reverse, return if True, False otherwise
Example: Input = 'A man, a plan, a canal, Panama' Output = 'True'
def is_palindrome(word):
word=string.replace(word,' ','')
word=string.replace(word,',','')
word=string.replace(word,'.','')
word=word.lower()
rev = word[::-1]
if (word == rev):
print 'True'
return 1
else:
print 'False'
return 0
| true |
71c4cc9fbac92125e33c56541860764f2343701b | BRGoss/Treasure_PyLand | /Puzzles/Completed/reverse_words.py | 406 | 4.4375 | 4 | #DESCRIPTION: Reverse the words in a sentence rather than all letters
#ALGORITHM: Define a function called split_words that takes a string
# as its input. The output is the inputs words put in reverse
# order.
#Example: Input = 'A long long time ago' Output = 'ago time long long A'
def split_words(sentence):
words=' '.join(string.split(sentence,' ')[::-1])
return words
| true |
0c3c790f7a00b3cb51f7b4cc1b96c77c7c769e50 | GopalNG/Python_Self_tasks | /intersection_in_two_lists.py | 950 | 4.3125 | 4 | #Here we need to return intersection values
def __intersection__(i,j):
both = list() # an empty list
for a in i: # get all items to a in i (list)
for b in j: # get all items to b in j (list)
if a == b: # if present item a equal b Add to to a list called both
both.append(a)
print("common item : {}".format(both)) #printing a common item
a = ['a','b','c']
b = ['b','d']
In[1]: __intersection__(a,b)
out[1]: common item : ['b']
### other ways to do same ###
Method1:
for x in i: # loop through list i put in x
if x in j: # if items in x are in list j print x is the variable that holds results
print(x)
Method2:
c = [a for a in i if a in j]
print(c)
Method3:
b = list(set(i).intersection(j)) #intersection is an python method | (∩) symbol of intersection
print(b)
Method4:
n = [a for a in i if a in j and(j.pop(j.index(a)) or True)]
print(n)
| false |
04b6bf15cdf11ec57ee9ab383b452d69abba2216 | gucce/advent-of-code | /2017/03-spiral-grid/spiral_grid.py | 1,401 | 4.59375 | 5 | #!/usr/bin/env python3
from itertools import cycle
# definition of spiral movement
move_right = lambda x, y: (x + 1, y)
move_down = lambda x, y: (x, y - 1)
move_left = lambda x, y: (x - 1, y)
move_up = lambda x, y: (x, y + 1)
moves = [move_right, move_up, move_left, move_down]
def manhatten_distance(pos1, pos2):
dist = 0
for i in range(2):
dist += abs(pos1[i] - pos2[i])
return dist
def gen_spiral(end):
"""copied from here: https://stackoverflow.com/questions/23706690/how-do-i-make-make-spiral-in-python"""
_moves = cycle(moves)
n = 1
pos = 0, 0
steps_to_move = 1
yield n, pos
while True:
# we always have to move the same amout of steps two time
# before incrementing the steps
for _ in range(2):
move = next(_moves)
for _ in range(steps_to_move):
if n >= end:
return
pos = move(*pos)
n += 1
yield n, pos
steps_to_move += 1
def distance_for_num(num):
spiral_dict = {entry[0]: entry[1] for entry in gen_spiral(num)}
return manhatten_distance((0,0), spiral_dict.get(num))
def main():
print(distance_for_num(1))
print(distance_for_num(12))
print(distance_for_num(23))
print(distance_for_num(1024))
print(distance_for_num(265149))
if __name__ == '__main__':
main()
| false |
6d91c5b3bfc3a1ef04522a6adc019878469b1472 | tahir24434/py-ds-algo | /src/main/python/pdsa/lib/LinkedLists/singly_linked_list_stack.py | 1,994 | 4.28125 | 4 | """
We demonstrate use of a singly linked list by providing a complete Python
implementation of the stack ADT (see Section 6.1). In designing such an
implementation, we need to decide whether to model the top of the stack at the
head or at the tail of the list. There is clearly a best choice here; we can
efficiently insert and delete elements in constant time only at the head.
Since all stack operations affect the top, we orient the top of the stack at
the head of our list.
Operation Running Time
S.push(e) O(1)
S.pop() O(1)
S.top() O(1)
len(S) O(1)
S.is_empty() O(1)
"""
from nose.tools import assert_equal
class SinglyLinkedListStack(object):
class _Node:
__slots__ = '_element', '_next' # streamline memory usage
def __init__(self, element, nxt=None): # Initialize node fields
self._element = element # Reference to user element
self._next = nxt # Reference to next node
def __init__(self):
self._head = None
self._size = 0
def __len__(self):
return self._size
def is_empty(self):
return self._size == 0
def push(self, e):
self._head = self._Node(e, self._head)
self._size += 1
def pop(self):
if self.is_empty():
raise Exception("Stack is empty")
element = self._head._element
self._head = self._head._next
self._size -= 1
return element
def top(self):
if self.is_empty():
raise Exception("Stack is empty")
return self._head._element
if __name__ == "__main__":
stack = SinglyLinkedListStack()
stack.push(5)
stack.push(7)
assert_equal(stack.top(), 7)
stack.push(4)
stack.push(3)
assert_equal(stack.pop(), 3)
stack.push(3)
assert_equal(stack.pop(), 3)
stack.push(9)
stack.push(0)
assert_equal(stack.pop(), 0)
assert_equal(len(stack), 4)
print('Success ...')
| true |
2621904a551b76b61a9f6a1d94cdca001ec95a17 | JKapple/PRG105 | /Demo_Random.py | 2,186 | 4.8125 | 5 | # In computer programs it is often useful to simulate randomness
# for example, in a game you may need to simulate the roll of a dice or shuffling of cards
#
# programs SIMULATE randomness by using complex mathematical formulas
# these provide a series of pseudo-random numbers
# in python we IMPORT a LIBRARY of functions to provide RANDOM NUMBER GENERATION
#
# the import statement tells python to access a library of code found outside of the program
# python provides several STANDARD LIBRARIES of functions like random and math
import random # gives access to the random library
# print 3 random intergers in the range of 1-10(inclusive)
for num in range(3):
this_guess = random.randint(1, 10) # random.randint() gives access to randint() from random
print(this_guess)
print('')
# to test the "accuracy" of the randomness, calculate an average
total = 0 # set an accumulator variable to 0
n_values = 3000 # how many random numbers to use
for num in range(n_values):
total += random.randint(0, 100) # average should be 50
# outside the loop I can calculate the average
average = total / n_values
print('The average using', n_values, 'values is',format(average, '.2f'))
# more random functions'
# randrange() parallels the range() functions
# it uses the same parameters: randrange (start, limit, step)
# return the random value from the range
print('')
for num in range(10):
print(random.randrange(5, 101, 5)) # start=5, limit=101, step=5
# the random() returns a floating point value starting a 0.0 with a limit of 1.0
print('')
for num in range(10):
print(random.random())
# uniform() function returns floating point numbers in a range you specify (end point included)
print('')
for num in range(10):
print(random.uniform(5.0, 6.5))
# sometimes it is useful to be able to generate the SAME random number pattern
# to do this, we give a SEED value to the random number generator
random.seed(3)
print('')
for num in range(3):
print(random.randint(1, 10))
random.seed(3)
print('')
for num in range(3):
print(random.randint(1, 10))
| true |
0d3a607d3a80bf1d3edf4d5839bf0c01c8200d29 | PabloCoralDev/CoralClassworks10 | /Calculator.py | 1,480 | 4.28125 | 4 | #Simple python calculator
print()
print("Welcome to the simple calculator")
print()
print("Please select the operation: 1 = Add, 2 = Substract, 3 = multiply, 4 = divide")
Operation_Select = int(input("Select operation: "))
print()
if Operation_Select == 1:
while True:
print("Now enter the numbers")
X_Select = int(input("X --> "))
Y_Select = int(input("Y --> "))
Operation_Answer = X_Select + Y_Select
print()
print("The answer is", Operation_Answer)
break
elif Operation_Select == 2:
while True:
print("Now enter the numbers")
X_Select = int(input("X --> "))
Y_Select = int(input("Y --> "))
Operation_Answer = X_Select - Y_Select
print()
print("The answer is", Operation_Answer)
break
elif Operation_Select == 3:
while True:
print("Now enter the numbers")
X_Select = int(input("X --> "))
Y_Select = int(input("Y --> "))
Operation_Answer = X_Select * Y_Select
print()
print("The answer is", Operation_Answer)
break
elif Operation_Select == 4:
while True:
print("Now enter the numbers")
X_Select = int(input("X --> "))
Y_Select = int(input("Y --> "))
Operation_Answer = X_Select / Y_Select
print()
print("The answer is", Operation_Answer)
break
else:
while True:
print()
print("Invalid answer, try again")
break
| true |
81a66e998d83d13122680071386708acc9c0745b | Ignotron/PythonPrograms | /Calculator and number stealer.py | 973 | 4.34375 | 4 | # -*- coding: utf-8 -*-
print("CALCULATOR")
print("")
print("Please enter a number")
num1=int(input())
print("Now enter another number")
num2=int(input())
print("")
print("Do you want to add, subtract, multiply, divide, remainder or exponent?")
print("Answer as any one of the following: Add, Subtract, Multiply, Divide, Remainder, Exponent")
Answer=input()
if(Answer=='Add'):
print("Adding...")
print(num1+num2)
elif(Answer=='Subtract'):
print("Subtracting...")
print(num1-num2)
elif(Answer=='Multiply'):
print("Multiplying...")
print(num1*num2)
elif(Answer=='Divide'):
print("Dividing")
print(num1/num2)
elif(Answer=='Remainder'):
print("Finding remainder...")
print(num1%num2)
else:
print("Finding exponent")
print(num1**num2)
print("This is maths, get good at it")
print("")
print("New Question")
print("")
print("Enter a number")
num=int(input())
print("Ok bye, I stole your number")
| true |
045cc782ff6d019cd7d77e4258ad56b562dc3c78 | zorjak/Algorithms-Design-and-Analysis-Stanford-Coursera | /Part1/inversions_count.py | 1,957 | 4.3125 | 4 | #!/usr/bin/env python3.4
# -*- coding: utf8 -*-
#!/tools/bin/python
# -*- coding: utf8 -*-
'''
Algorithms: Design and Analysis Coursera Stanford, Part I.
Programming Assignment 1:
Sorting an array and counting inversions
@author: Zoran Jaksic
'''
import sys
def sort_and_count_inversions(inp_lst, start, end):
""" sort array and count inversions by using merge sort """
if start == end:
return 0
else:
part_1_inv = sort_and_count_inversions(inp_lst, start, (end+start)//2)
part_2_inv = sort_and_count_inversions(inp_lst, (end+start)//2+1, end)
merged_inv = _merge_and_count_inversions(inp_lst, start, (end+start)//2+1, end)
return part_1_inv + part_2_inv + merged_inv
def _merge_and_count_inversions(lst, start, midle, end):
""" merging two arrays and counting inversions"""
i = start
j = midle
sorted_lst = []
inv_count = 0
while i < midle or j <= end:
if i == midle:
sorted_lst.append(lst[j])
j += 1
elif j > end:
sorted_lst.append(lst[i])
i += 1
elif lst[i] <= lst[j]:
sorted_lst.append(lst[i])
i += 1
else:
inv_count += (midle-i)
sorted_lst.append(lst[j])
j += 1
i = start
while i <= end:
lst[i] = sorted_lst[i-start]
i += 1
return inv_count
def main(int_lst_file_name):
""" main function that reads an input file and creates a list of integers
and calculates number of inversions """
inp_file_h = open(int_lst_file_name, 'r')
inp_lst = []
line = inp_file_h.readline()
while line != '':
inp_lst.append(int(line))
line = inp_file_h.readline()
print('Inversions Number: ' + str(sort_and_count_inversions(inp_lst, 0, len(inp_lst)-1)))
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit(0)
main(sys.argv[1])
print('Finished')
| true |
f1ea13b67c71a786d4ad95efefd3268fa47c238e | shifteight/python | /practical/shrinking_list.py | 302 | 4.21875 | 4 |
def remove_neg(num_list):
'''
Remove the negative numbers from the list num_list.
'''
i = 0
while i < len(num_list):
if num_list[i] < 0:
num_list.pop(i)
else:
i += 1
numbers = [1, 2, 3, -3, 6, -1, -3, 1]
remove_neg(numbers)
print(numbers)
| true |
38268733b3a1eb997bae16a38b311fd4d49aab53 | shifteight/python | /DSA/generator_demo.py | 598 | 4.15625 | 4 | __author__ = 'kevin'
def factors(n):
"""
A generator that computes factors
:param n:
"""
k = 1
while k * k < n:
if n % k == 0:
yield k
yield n // k
k += 1
if k * k == n:
yield k
def fibonacci():
"""
A generator that computes Fibonacci series
:param None:
"""
a = 0
b = 1
while True:
yield a
a, b = b, a + b
def print_first_n_fibs(n):
"""
Print first n fibonacci numbers
:param n:
"""
i = iter(fibonacci())
for j in range(n):
print(next(i))
| false |
466543d557885af3bbdf82636f8faf6410dd8830 | shifteight/python | /project_euler/1.py | 320 | 4.1875 | 4 | ## Problems 1
##
## If we list all the natural numbers below 10 that are multiples of
## 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
##
## Find the sum of all the multiples of 3 or 5 below 1000.
r = []
for n in range(1, 1000):
if n % 3 == 0 or n % 5 == 0:
r.append(n)
#print(n)
print(sum(r)) | true |
62b8d94567f05e8002836222b640780f0fcd00bf | shifteight/python | /PSADS/ch3/hot_potato.py | 967 | 4.34375 | 4 | # Simulation of Hot Potato
# ------------------------
# Assume that the child holding the potato will be at the front of the queue.
# Upon passing the potato, the simulation will simply dequeue and then
# immediately enqueue that child, putting her at the end of the line.
# She will then wait until all the others have been at the front before
# it will be her turn again. After `num`` dequeue/enqueue operations,
# the child at the front will be removed permanently and another cycle
# will begin. This process will continue until only one name remains
# (the size of the queue is 1).
from queue import Queue
def hotPotato(namelist, num):
simqueue = Queue()
for name in namelist:
simqueue.enqueue(name)
while simqueue.size() > 1:
for i in range(num):
simqueue.enqueue(simqueue.dequeue())
simqueue.dequeue()
return simqueue.dequeue()
print(hotPotato(['Bill', 'David', 'Susan', 'Jane', 'Kent', 'Brad'], 7))
| true |
81fd04520bcec9dfa788fe201c1bcb4d09492ed1 | siladikarlo856/learn_python_the_hard_way | /ex5_sd3.py | 1,349 | 4.15625 | 4 | #d Signed integer decimal.
#i Signed integer decimal.
#o Unsigned octal. (1)
#u Unsigned decimal.
#x Unsigned hexadecimal (lowercase). (2)
#X Unsigned hexadecimal (uppercase). (2)
#e Floating point exponential format (lowercase).
#E Floating point exponential format (uppercase).
#f Floating point decimal format.
#F Floating point decimal format.
#g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
#G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
#c Single character (accepts integer or single character string).
#r String (converts any python object using repr()). (3)
#s String (converts any python object using str()). (4)
#% No argument is converted, results in a "%" character in the result.
name = 'Zed A. Shaw'
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s" % name
print "He's %d inches tall." % height
print "He's %r pounds heavy." % weight
print "Actually that's not to heavy."
print "He's hot %r eyes and %s hair" % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to het it exactly right
print "If I add %d, %d, and %d I get %d." % (
age, height, weight, age + weight + height
) | true |
95ec8e9e2bd66b33a3d697a172408c4653ae9f58 | OrevaElmer/MyDataStructure | /myLinearSearchWord.py | 668 | 4.125 | 4 | #This program search a list of names from another list of names:
import sys
from loadNumberString import load_strings
fullname = load_strings(sys.argv[1])
searchNames2 = ["Andrea Bailey","Angela Baker","Anna Ball","Anne Bell","Audrey Berry","Ava Black"]
def linearSearch(collection, target):
i = 0
while i < len(collection):
if collection[i] == target:
return i
i +=1
return None
for name in searchNames2:
indexOfName = linearSearch(fullname,name)
print(indexOfName)
#This is how I called the sorted text or unsorted text:
# c:/xampp/htdocs/pythonLesson/myAlgorithm/myBinaryLinear.py names/unsorted.txt
| true |
a4c29af1985bd0ad5b8199d0411bb64d00cec630 | mt3925/leetcode | /Python/Flatten_Nested_List_Iterator.py | 2,450 | 4.125 | 4 | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
class NestedInteger:
def __init__(self, val=None, val_list=None):
self.val = val
self.val_list = val_list
def isInteger(self) -> bool:
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
"""
return self.val is not None
def getInteger(self) -> int:
"""
@return the single integer that this NestedInteger holds, if it holds a single integer
Return None if this NestedInteger holds a nested list
"""
return self.val
def getList(self):
"""
@return the nested list that this NestedInteger holds, if it holds a nested list
Return None if this NestedInteger holds a single integer
"""
return self.val_list
class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.stack = nestedList[::-1]
def next(self) -> int:
return self.stack.pop(-1).getInteger()
def hasNext(self) -> bool:
if not self.stack:
return False
if self.stack[-1].isInteger():
return True
self.stack.extend(self.stack.pop(-1).getList()[::-1])
return self.hasNext()
# from leetcode Discuss
class NestedIterator(object):
def __init__(self, nestedList):
def gen(nestedList):
for x in nestedList:
if x.isInteger():
yield x.getInteger()
else:
for y in gen(x.getList()):
yield y
self.itr = gen(nestedList)
self.latest = next(self.itr, None)
def next(self) -> int:
temp = self.latest
self.latest = next(self.itr, None)
return temp
def hasNext(self) -> bool:
return self.latest is not None
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
if __name__ == '__main__':
nestedList = [
NestedInteger(val_list=[NestedInteger(1), NestedInteger(1)]),
NestedInteger(2),
NestedInteger(val_list=[NestedInteger(1), NestedInteger(1)]),
]
i, v = NestedIterator(nestedList), []
while i.hasNext():
v.append(i.next())
print(v)
| true |
947ce8d41d27f77bf842ef677c72c0b140a5b5e0 | anthonyhabib10/crypto-assignment-1 | /crypto-assignment-1/arecongruent.py | 402 | 4.125 | 4 | # Anthony Habib - 100662176
# October 4th 2019
# Gets values from user
a = int(input("Enter Value for A:"))
b = int(input("Enter Value for B:"))
n = int(input("Enter Value for N:"))
# Calculates congruency
congruent_A = a % n
congruent_B = b % n
# Checks if A and B are congruent
if congruent_A == congruent_B:
print("True")
else:
print("False")
# prints values
print(a, b, n)
| true |
76d4e6ace6439be0cd8118af652d34487e212b08 | kamilczerwinski22/Advent-of-Code | /main_files/year_2015/day_9/year2015_day9_part1.py | 2,446 | 4.125 | 4 | # --- Day 9: All in a Single Night ---
# Every year, Santa manages to deliver all of his presents in a single night.
#
# This year, however, he has some new locations to visit; his elves have provided him the distances between every
# pair of locations. He can start and end at any two (different) locations he wants, but he must visit each location
# exactly once. What is the shortest distance he can travel to achieve this?
#
# For example, given the following distances:
#
# London to Dublin = 464
# London to Belfast = 518
# Dublin to Belfast = 141
# The possible routes are therefore:
#
# Dublin -> London -> Belfast = 982
# London -> Dublin -> Belfast = 605
# London -> Belfast -> Dublin = 659
# Dublin -> Belfast -> London = 659
# Belfast -> Dublin -> London = 605
# Belfast -> London -> Dublin = 982
# The shortest of these is London -> Dublin -> Belfast = 605, and so the answer is 605 in this example.
#
# What is the distance of the shortest route?
from collections import defaultdict
from itertools import permutations
# Function to build the graph
def find_shortest_route() -> int:
# read file
with open('year2015_day9_challenge_input.txt', 'r', encoding='UTF-8') as f:
routes = f.read().splitlines()
# main logic
possible_places = set()
distances_graph = defaultdict(dict) # create undirected graph with all the routes
for route in routes:
source, _, destination, _, distance = route.split(' ')
possible_places.add(source)
possible_places.add(destination)
# add route distance to the graph (dictionary) from both sides. If connection doesn't exist make it
distances_graph[source][destination] = int(distance)
distances_graph[destination][source] = int(distance)
# create all possible routes using available nodes. Create a list with the sum of the distances between these points
# e.g. permutation: ('Straylight', 'AlphaCentauri', 'Norrath', 'Arbre', 'Tristram', 'Faerun', 'Snowdin', 'Tambi')
# Is the total distance between 'Straylight' and 'Tambi' going through the nodes in order:
# Straylight -> AlphaCentauri -> Norrath -> ... -> Tambi
distances = []
for permutation in permutations(possible_places):
distances.append(sum(map(lambda x, y: distances_graph[x][y], permutation[:-1], permutation[1:])))
return min(distances)
if __name__ == "__main__":
graph = find_shortest_route()
print(graph)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.