blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d1656696811a0a9d02b392c66583e2ef9c01712b | KurskiySergey/Python_Algos | /Урок 1. Практическое задание/task_7.py | 1,709 | 4.53125 | 5 | """
7. По длинам трех отрезков, введенных пользователем,
определить возможность существования треугольника,
составленного из этих отрезков. Если такой треугольник существует,
то определить, является ли он разносторонним, равнобедренным или равносторонним.
"""
try:
LENGTH_1 = float(input("Введите длину первого отрезка\n"))
LENGTH_2 = float(input("Введите длину второго отрезка\n"))
LENGTH_3 = float(input("Введите длину третьего отрезка\n"))
if LENGTH_1 <= 0 or LENGTH_2 <= 0 or LENGTH_3 <= 0:
print("Длины не могут быть отрицательными")
elif LENGTH_1 + LENGTH_2 > LENGTH_3 and \
LENGTH_2 + LENGTH_3 > LENGTH_1 and LENGTH_1 + LENGTH_3 > LENGTH_2:
print(
f"Треугольник со сторонами {LENGTH_1} , {LENGTH_2} , {LENGTH_3} существует\n")
if LENGTH_1 == LENGTH_2 and LENGTH_1 == LENGTH_3:
print("Треугольник равносторонний")
elif LENGTH_1 == LENGTH_2 or LENGTH_1 == LENGTH_3 or LENGTH_2 == LENGTH_3:
print("Треугольник равнобедренный")
else:
print("Треугольник разносторонний")
else:
print("Треугольник с заданными сторонами не существует")
except ValueError:
print("Нужно ввести число")
| false |
7f32e5b9b10dc2808100d1375870e20a731584c4 | yyogeshchaudhary/PYTHON | /4oct/defaultArrgumet.py | 557 | 4.25 | 4 | # /usr/bin/python
'''
Default Arrgument:
def functionName(var1, var2, var3=10)
var3=10 : is called as default arrgument and we can call function with 2 or 3 parameters
if we call the function with 3 parameter then it will override the value of var3 with given value
every default parameter should be trailing param not at middle of function param
'''
def defaultArrgument(strVar, x, y=10):
print("String is : "+strVar)
print("X value is : "+str(x))
print("Y value is : "+str(y))
defaultArrgument('Hello',10)
defaultArrgument('Yogesh', 20,30)
| true |
35bf8abfac68432e60f458c2797b7457216e84f1 | 1907cloudgcp/project-0-MasterKuan | /src/main/python/com/revature/client/controller/settingsmenu.py | 1,512 | 4.125 | 4 | HIDE = 0
# Run until exit
def run_settings_menu():
while True:
print("Hide is " + str(HIDE))
action = settings_menu()
if action == 0:
return 0
elif action == 1:
change_hide_password()
def get_hide():
global HIDE
return HIDE
# Get user input until valid input
def settings_menu():
while True:
print("Main Actions:\n"
" 1) Hide password\n"
" 0) Exit")
user_input = input("Input: ").lower()
action = parse_settings(user_input)
if not action == 999:
return action
def parse_settings(action):
if action == "exit" or action == "0" or action == "e":
print("\nExiting")
return 0
elif action == "hide" or action == "1" or action == "h":
return 1
else:
print("\nInput was not recognized.")
return 999
def answer(display):
while True:
action = input(display + " (y/n)?: ").lower()
if action == "y" or action == "yes":
return 1
elif action == "n" or action == "no":
return 0
else:
print("Invalid input")
def change_hide_password():
global HIDE
if HIDE:
print("Currently, typing a password is being HIDDEN")
if answer("Show password while typing "):
HIDE = 0
else:
print("Currently, typing a password is being SHOWN")
if answer("Hide password while typing "):
HIDE = 1
| false |
2cdf3ee23e4db1ec39810a47d712c50e4cf479ba | iconoeugen/swe | /sorting/select.py | 810 | 4.3125 | 4 | #!/usr/bin/python
"""Selection sort
Time complexity:
Big-Oh: O(n^2)
Big-Omega: O(n^2)
Big-Theta: O(n^2)
Space complexity:
O(1)
"""
def sort(list):
l = len(list)
steps = 0
for i in range(0, l-1):
min_idx = i
for j in range(i+1, l):
if list[min_idx] > list[j]:
min_idx = j
steps += 1
print( "step: {} i: {} j: {} min_idx: {} min: {} List: {}".format(steps, i, j, min_idx, list[min_idx], list))
if list[i] > list[min_idx]:
list[i], list[min_idx] = list[min_idx], list[i]
return steps
if __name__ == "__main__":
list = [4 ,5, 7, 1, 9, 0, 8, 3, 2, 6]
steps = sort(list)
print( "step: {} List: {}".format(steps, list))
assert( list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
| false |
12cb04c632d16225961d5c466e49d7ec10c0c1a6 | mtbottle/mts_project_euler_exercises | /ex9.py | 563 | 4.34375 | 4 | # -*- coding: utf-8 -*-
from math import *
#A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#a^(2) + b^(2) = c^(2)
#For example, 3^(2) + 4^(2) = 9 + 16 = 25 = 5^(2).
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.
if __name__ == "__main__":
for i in range(1,999):
for j in range(1,999):
k = 1000 - i - j
if k > 0:
square = i**2 + j**2
value = sqrt( float(square) )
if i**2 + j**2 == k**2:
print i, j, k
print i*j*k
| false |
1d63d6434cdcacf5cbde78f8be2dbfc2799362d9 | ciaocamilo/ejemplos-python | /condicionales1.py | 1,426 | 4.4375 | 4 | numero = 57
# if numero > 0:
# print("El número es positivo")
# else:
# if numero < 0:
# print("El número es negativo")
# else:
# if numero == 0:
# print("El numero es cero")
# if numero > 0:
# print("El número es positivo")
# elif numero < 0:
# print("El número es negativo")
# elif numero == 0:
# print("El numero es cero")
if numero > 0:
if numero >= 10 and numero <= 99:
print("El número es positivo y tiene dos dígitos")
else:
print("El número es positivo y no tiene dos dígitos")
else:
if numero >= -999 and numero <= -100:
print("El número es negativo y tiene tres dígitos")
else:
print("El número es negativo y no tiene tres dígitos")
print(type(True))
x = 10
if x%2 == 0 :
print('x es par')
else :
print('x es impar')
#Para explicar Try y Except utilizaremos de ejemplo una función que convierte la temperatura en grados Fahrenheit a una temperatura en grados Celsius:
# temperatura_fahr = input('Ingrese la temperatura en grados Fahrenheit: ')
# try:
# fahr = float(temperatura_fahr)
# cel = (fahr - 32.0) * 5.0 / 9.0
# print(cel)
# except:
# print('El dato debe ser un número')
# x = 6
# y = 2
# print(x >= 2 and (x/y) > 2)
# x = 1
# y = 0
# print(x >= 2 and (x/y) > 2)
# x = 6
# y = 0
# print(x >= 2 and (x/y) > 2)
x = 6
y = 0
print(x >= 2 and y != 0 and (x/y) > 2) | false |
9f574d8b2d828a1a8fb24e8c1b67e58216280c0a | ramon-ortega/codigo-python | /CodigoDePractica/CodigoPython/condicionales.py | 1,157 | 4.1875 | 4 | ##x = input('escoge x: ')
##y = input('escoge y: ')
##if x > y:
#print x, "es mas grande que", y
## print('{x} es mas grande que {y}'.format(x=x, y=y))
#otra forma de hacerlo es por posicion, example: print('{0} es mas grande que {1}'.format(x,y))
##else:
## print y, "es mas grande que ", x
##print('-----------------')
##print('Segunda parte del problema')
##print('-----------------')
##if x > y:
## print x, "es mas grande que ", y
##elif x==y:
## print x, " y ", y, "son iguales"
##else:
## print y, "es mas grande que ", x
##print('------------------')
##print('Tercera parte del problema')
##print('------------------')
#if x>2:
# if x<=10:
#print(x es mas grande que 2 pero menor o igual a 10)
#if anidados
#if x>2:
# if x<=10:
# print(x es mas grande que 2 e igual/menor a 10)
#and
#if x > 2 and x <=10:
#print(x es mas grande que 2 e igual / menor a 10)
#or
#if x>2 or x<=10:
#print(x es mas grande que 2 e igual/menor a y)
#if not(x==y)
#print(x no es igual a y)
#Operadores de membresia
numbers=[1,2,3,4,5]
z=5
#in
##if z in numbers:
## print(z in numbers)
#not in
if z not in numbers:
print(z not in numbers)
#is
| false |
e0c552546a75f7badedb0dfb01dc15aeae9e24fc | Omega97/Learning-Python | /_B_Simple/Copy.py | 1,275 | 4.25 | 4 | """
The difference between assignation, shallow copy and deep copy
"""
from utils import title
@title
def no_copy():
""" no copy """
a = [['a', 'a'], ['a', 'a']]
print('old a =', a)
b = a
b[0] = ['b']
b[1][0] = 'b'
b[1][1] = 'b'
print('new a =', a)
print(' b =', b)
print('\n', "Same Id" if id(a) == id(b) else "Different Id")
# conclusion: a and b are the same object
@title
def do_copy():
""" copy """
a = [['a', 'a'], ['a', 'a']]
print('old a =', a)
b = copy(a)
b[0] = ['b']
b[1][0] = 'b'
b[1][1] = 'b'
print('new a =', a)
print(' b =', b)
print('\n', "Same Id" if id(a) == id(b) else "Different Id")
# conclusion: a and b are different objects, but the child objects are the same
@title
def do_deepcopy_copy():
""" deepcopy """
a = [['a', 'a'], ['a', 'a']]
print('old a =', a)
b = deepcopy(a)
b[0] = ['b']
b[1][0] = 'b'
b[1][1] = 'b'
print('new a =', a)
print(' b =', b)
print('\n', "Same Id" if id(a) == id(b) else "Different Id")
# conclusion: a and b are completely different objects
if __name__ == "__main__":
no_copy()
do_copy()
do_deepcopy_copy()
| false |
e68a23472e159c441441ea14858974259091d9ab | Harshsa28/CLRS_exercises_codes | /22_1_3.py | 280 | 4.1875 | 4 | x = {}
x[1] = [2]
x[2] = [4]
x[3] = [1,2]
x[4] = [3]
print(x)
def transpose(adj_list):
y = {}
for i in adj_list:
for j in adj_list[i]:
if j in y:
y[j].append(i)
else:
y[j] = [i]
print(y)
transpose(x)
| false |
d4604f0b95fbedcb2fcec35b8f60974177a84235 | Eraydis/Test-tasks | /test_task1.py | 812 | 4.25 | 4 |
# '''Имеется функция StringChallenge(strArr), использующая параметр StrArr, который содержит только один элемент,
#Возвращая строку true, если это валидное число, которое содержит только цифры с правильно расставленными разделителями и запятыми, а обратном случае возвращает строку false'''
import re
def StringChallenge(strArr):
pat = re.compile(r'^[0-9]*[.,]{0,1}[0-9]*$')
for i in strArr:
if pat.match(i):
return('true')
else:
return('false')
pass
a = input()
print(StringChallenge(a))
| false |
6470c1ac40bdb0694f525f3796da2cd29e6f0950 | yunusarli/Quiz | /questions.py | 1,717 | 4.21875 | 4 | #import sqlite3 module to keep questions in a database.
import sqlite3
# Questions class
class Questions(object):
def __init__(self,question,answer,options=tuple()):
self.question = question
self.answer = answer
self.options = options
def save_question_and_answer(self):
""" save the question and answer that given by user"""
conn = sqlite3.connect("q_and_a.db")
cur = conn.cursor()
table = """ CREATE TABLE IF NOT EXISTS question (
question text NOT NULL,
answer text NOT NULL
); """
values = """INSERT INTO question VALUES ('{}','{}') """.format(self.question,self.answer)
cur.execute(table)
cur.execute(values)
conn.commit()
conn.close()
def save_options(self):
""" save the options that given by user """
conn = sqlite3.connect("q_and_a.db")
cur = conn.cursor()
table = """ CREATE TABLE IF NOT EXISTS options (
option1 text NOT NULL,
option2 text NOT NULL,
option3 text NOT NULL,
option4 text NOT NULL
); """
values = """ INSERT INTO options VALUES (?,?,?,?) """
cur.execute(table)
cur.execute(values,self.options)
conn.commit()
conn.close()
if __name__ == "__main__":
question = Questions("Who is the creator of python","guido van rosum",("melezeki","guido van rosum","mehmet toner","albert einstein"))
question.save_question_and_answer()
question.save_options() | true |
d4bb5a83bf83ed0f3b9b427a45c77dbdd2cf733a | emilypng/python-exercises | /Packt/act11.py | 253 | 4.28125 | 4 |
def fib_recursive(n):
if n<2:
return n
else:
return fib_recursive(n-2)+fib_recursive(n-1)
user_input = eval(input("Enter a number to take the factorial of: "))
input_factorial = fib_recursive(user_input)
print(input_factorial)
| false |
30ed215f931ffdcde9dc2e8853f15a00a66b6e00 | Wajahat-Ahmed-NED/WajahatAhmed | /harry diction quiz.py | 253 | 4.1875 | 4 | dict1={"set":"It is a collection of well defined objects",
"fetch":"To bring something",
"frail":"weak",
"mutable":"changeable thing"}
ans=input("Enter any word to find its meaning")
print("The meaning of ",ans,"is",dict1[ans]) | true |
fd38fc531606f37eb343d17e9ddf100667ea508c | Reena-Kumari20/Dictionary | /w3schoolaccessing_items.py | 870 | 4.28125 | 4 | #creating a dictionary
thisdict={
"brand":"ford",
"model":"mustang",
"year":1964
}
print(thisdict["brand"])
print(thisdict.get("brand"))
#dictionary_length
#to determine how many items a dictinary has,use the len()function.
print(len(thisdict))
#dictionary items-data types
thisdict={
"brand":"ford",
"electric":False,
"year":1964,
"colors":["red","while","blue"]
}
print(type(thisdict))
#accessing items
d={
"brand":"ford",
"model":"mustang",
"year":1964
}
x=d["model"]
print(x)
a=d.get("model")
print(a)
print(d["model"])
print(d.get("model"))
#get keys
print(d.keys())
print(d.values())
#add a new items
car={
"brand":"ford",
"model":"mustang",
"year":1964
}
car["color"]="write"
print(car)
#get values
print(car.values())
print(car.items())
if "model" in car:
print("Yes,'model' is one of the keys in the car dictionary")
| true |
ff6f7c387ee332af8b00b5a819a8572c86750790 | tanglan2009/mit6.00 | /FinalExam/P6.py | 1,336 | 4.34375 | 4 | class Frob(object):
def __init__(self, name):
self.name = name
self.before = None
self.after = None
def setBefore(self, before):
# example: a.setBefore(b) sets b before a
self.before = before
def setAfter(self, after):
# example: a.setAfter(b) sets b after a
self.after = after
def getBefore(self):
return self.before
def getAfter(self):
return self.after
def myName(self):
return self.name
p = Frob('percival')
print p.myName()
def insert(atMe, newFrob):
if newFrob.myName() >= atMe.myName():
newFrob.setBefore(atMe)
atMe.setAfter(newFrob)
return newFrob.getAfter()
if newFrob.myName() < atMe.myName():
newFrob.setAfter(atMe)
atMe.setBefore(newFrob)
return newFrob.getBefore()
eric = Frob('eric')
andrew = Frob('andrew')
ruth = Frob('ruth')
fred = Frob('fred')
martha = Frob('martha')
print insert(eric, andrew)
print insert(eric, ruth)
insert(eric, fred)
insert(ruth, martha)
#
# def findFront(start):
# """
# start: a Frob that is part of a doubly linked list
# returns: the Frob at the beginning of the linked list
# """
# if start.getBefore() == None:
# return start.myName()
# else:
# return findFront(start.getBefore())
| false |
50dd82e6795ef4d215f1da9025bba21609bdedbd | HarshPonia/Python_Programs | /Numbers.py | 782 | 4.4375 | 4 | # In python We have Three numbers
# 1. int
# 2. float
# 3. Complex
# Ex 1:-
a= 25
print(type(a)) #int
b = -30
print(type(b)) #int
# Ex 2:-
c = 1.0
print(type(c)) #float
d = -20.25
print((type(d))) # float
# Ex 3:-
e = 2j
print(type(e)) # complex
f = -4+5j
print(type(f)) # complex
# Convert Numbers
# int into float/complex
# Ex 1:
a = float(a)
print(a) # 25.00
print(type(a)) # float
# Ex 2:-
b = complex(b)
print(b) # 25+0j
print(type(b))
# float into int/complex
# Ex 3:-
c = int(c)
print(c) # 1
print(type(c)) #int
# Ex 4:-
d = complex(int(d))
print(d) # 1+0j
print(type(d)) #complex
# Complex Numbers can not be coverted into float or int
print("Hello,Darkness") | false |
790354fe9432f1cf7a4a6aa7d9db3f68ed2b41b0 | HarshPonia/Python_Programs | /Pattern/Apattern.py | 261 | 4.15625 | 4 | n = 8
for i in range(0,n):
if i == 0:
print(" ",end = "")
print("@",end = "")
print("\r")
for i in range(0,n//2):
print("@ @")
for i in range(0,n+2):
print("@",end = "")
print("\r")
for i in range(0,n//2):
print("@ @") | false |
4f9aab2c40c2bfd8ccae05264fc3243efd3da3f4 | KrShivanshu/264136_Python_Daily | /ProgramsForSubmission/ListIntoNestedDict.py | 221 | 4.125 | 4 | """
Write a Python program to convert a list into a nested dictionary of keys
"""
my_list = ['a','b','c','d','e']
my_dict = current = {}
for ele in my_list:
current[ele] = {}
current = current[ele]
print(my_dict) | false |
3044aa9396d2a3481d652a64f99db78253d88d71 | KrShivanshu/264136_Python_Daily | /Collatz'sHypothesis.py | 420 | 4.125 | 4 | """ Write a program which reads one natural number and executes
the above steps as long as c0 remains different from 1.
We also want you to count the steps needed to achieve the goal.
Your code should output all the intermediate values of c0, too.
"""
c0 = int(input("Enter a number: "))
step = 0
while c0!=1:
if c0%2==1:
c0=3*c0+1
else:
c0=c0/2
print(int(c0))
step=step+1
print(step) | true |
0f46661eb4208c064f2badee1a0322bae583b6fa | johnsogg/play | /py/tree.py | 1,997 | 4.34375 | 4 | class Tree:
"""A basic binary tree"""
def __init__(self):
self.root = None
def insert(self, node):
if (self.root == None):
self.root = node
else:
self.root.insert(node)
def bulk_insert(self, numbers):
for i in numbers:
n = Node(i)
self.insert(n)
def report(self):
if (self.root != None):
self.root.report()
else:
print "No data"
def contains(self, number):
if (self.root != None):
return self.root.contains(number)
else:
return false
class Node:
"""A node in the basic binary tree"""
def __init__ (self, data):
"""Create a node"""
self.data = data
self.left = None
self.right = None
def insert(self, node):
if (self.data > node.data):
if (self.left == None):
self.left = node
else:
self.left.insert(node)
else:
if (self.right == None):
self.right = node
else:
self.right.insert(node)
def report(self):
if (self.left != None):
self.left.report()
print str(self.data)
if (self.right != None):
self.right.report()
def contains(self, number):
if (self.data == number):
return True
else:
if (self.data > number):
if (self.left != None):
return self.left.contains(number)
else:
return False
else:
if (self.right != None):
return self.right.contains(number)
else:
return False
if __name__ == '__main__':
tree = Tree()
tree.bulk_insert([4, 3, 6, 9, 13, 2, 3, 8, 3, 8, 4])
tree.report()
for i in range(1, 15):
print str(i) + ": " + str(tree.contains(i))
| true |
53b033db25faa95074a34e44b1fc095a5abd7824 | ltoshea/py-puzzles | /lowestprod.py | 805 | 4.1875 | 4 | """Create a function that returns the lowest product of 4 consecutive numbers in a given string of numbers
This should only work is the number has 4 digits of more. If not, return "Number is too small".
lowest_product("123456789")--> 24 (1x2x3x4)
lowest_product("35") --> "Number is too small"
lowest_product("1234111")--> 4 (4x1x1x1)"""
def lowest_product(input):
if len(input) < 4:
return 'Number is too small'
else:
smallest = int(input[0])*int(input[1])*int(input[2])*int(input[3])
for i in range(0,len(input)-3):
total = 1
for j in range(i,i+4):
total = total * int(input[j])
if total < smallest:
smallest = total
return smallest
if __name__ == "__main__":
print lowest_product("1234") | true |
625b5c1642c07a17d591b3af07c99cb65ab2070c | DipanshKhandelwal/Unique-Python | /PythonTurtle/turtle_circle/turtle_circle.py | 1,053 | 4.3125 | 4 | import turtle
''' this moves turtle to make a square
even tells us how to configure our turtle like changing its speed ,color
shape etc'''
def turtle_circle():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
''' Inputs be like :
turtle.shape() { gives classic shape }
turtle.shape("turtle") { arrow, turtle, circle,
square, triangle, classic }'''
brad.color("yellow")
'''input formats for turtle.shape:-
fillcolor()
fillcolor(colorstring) { like "red", "yellow", or "#33cc8c" }
fillcolor((r, g, b))'''
brad.speed(1)
'''If input is a number greater than 10 or smaller than 0.5, speed is set to 0. Speedstrings are mapped to speedvalues as follows:
fastest: 0
fast: 10
normal: 6
slow: 3
slowest: 1 '''
brad.circle(120)
window.exitonclick()
turtle_circle()
| true |
ac0b9c7cbd00ba13b6f5409556cafaf60460ba96 | Tabsdrisbidmamul/PythonBasic | /Chapter_9_classes/02 three_restaurant.py | 1,260 | 4.40625 | 4 | class Restaurant:
"""a simple to stimulate a restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""will define what the restaurant is"""
print(self.restaurant_name.title() + ' is a 5 star restaurant.')
print(self.restaurant_name.title() + ' is open 6 times a day.\n')
def open_restaurant(self):
"""stimulate that the restaurant is open"""
print(self.restaurant_name.title() + ' is open!')
# create an instance or set of instructions and store into variable restaurant
# create three different instance
restaurant = Restaurant('Le de familie', 'french')
restaurant_1 = Restaurant('taste of hong kong', 'chinese')
restaurant_2 = Restaurant('Days', 'buffet')
print(restaurant.restaurant_name.title() + ' is really good.')
print('They serve ' + restaurant.cuisine_type.title() + '.')
print()
# call the two methods
restaurant.describe_restaurant()
restaurant.open_restaurant()
print()
# call the three instances, call call method describe_restaurant() for each one
restaurant.describe_restaurant()
restaurant_1.describe_restaurant()
restaurant_2.describe_restaurant()
| true |
35d6f1f370cdf61b6bf1f496e08d0ea329d64995 | Tabsdrisbidmamul/PythonBasic | /Chapter_8_functions/15 import_modules.py | 301 | 4.1875 | 4 | import math as maths # import maths module
def area_of_a_circle(radius):
"""finds area of a circle, argument is radius"""
area = round(pi * radius, 2)
return area
pi = maths.pi
# call function, which will give me the area of a circle
circle_0 = area_of_a_circle(50)
print(circle_0)
| true |
c17a03c48b288270bf1bb671f8dca1fa6fbace24 | Tabsdrisbidmamul/PythonBasic | /Chapter_10_files_and_exceptions/01 learning_python.py | 766 | 4.34375 | 4 | # variable to hold file name
file = 'learning_python.txt'
# use open function to open file, and print the contents three times
with open(file) as file_object:
content = file_object.read()
print(content, '\n')
print(content, '\n')
print(content, '\n')
print('indent\n')
# open the file and read through each line and print it
with open(file) as file_object_2:
for line in file_object_2:
print(line, end="")
# open the file, read and store each line into a list, hold this list in lines
# iterate through lines appending it to indent_string to differentiate it
# from the previous work
with open(file) as file_object_3:
lines = file_object_3.readlines()
print()
print()
indent_string = '(indent) '
for line in lines:
print(indent_string + line, end='')
| true |
0ac565e0d4d3b948dcf0d8767039d6ccb2d9f71d | Tabsdrisbidmamul/PythonBasic | /Chapter_10_files_and_exceptions/04 guest_book.py | 448 | 4.1875 | 4 | # program that asks the user name, once entered print a prompt to say it was
# accepted and append the string onto the file
filename = 'programming.txt'
while True:
userName = str(input('What is your name? '))
print('Welcome ', userName)
with open(filename, 'a') as file_object:
# the \n is required, as the write method doesn't put newlines,
# so it has to be put in manually
file_object.write('\n' + userName + ' has been recorded\n')
| true |
3c5b8e6838f2ebead83149f9e35c12f3c7a9b96c | Tabsdrisbidmamul/PythonBasic | /Chapter_7_user_inputs_and_while_loops/08 dream_vacation.py | 819 | 4.28125 | 4 | # set an empty dictionary to be filled up with polling later
responses = {}
# make a flag set to true
polling_active = True
while polling_active:
# prompt for user's name and their destination
name = input('\nWhat is your name: ')
dream_vacation = input('What place is your dream vacation? ')
# store the user input as key-value pair in the empty dictionary
responses[name] = dream_vacation
# To see if anyone wants to take the poll
loop = input('\nWould you like another person to take this poll? ('
'yes/no) ')
if loop.lower() in ['no', 'n']:
polling_active = False
# print the results from your poll
print('\n\t---Poll Results---')
for name, dream_vacation in responses.items():
print(name.title() + ' would like to go to ' + dream_vacation.title())
| true |
24c95a3ab3e6b6e6a6cfa4ab1fbfc0f43dbf9409 | GudjonGunnarsson/python-challenges | /codingbat/warmup1/9_not_string.py | 884 | 4.40625 | 4 | #!/usr/bin/python3
""" This challenge is as follows:
Given a string, return a new string where
"not" has been added to the front. However,
if the string already begins with "not",
return the string unchanged.
Expected Results:
'candy' -> 'not candy'
'x' -> 'not x'
'not bad' -> 'not bad' """
def not_string(str):
# This part is where the challenge is supposed to be solved
return str if str.split()[0] == "not" else "not " + str
if __name__ == '__main__':
# This part is only to test if challenge is a success
print("Scenario 1: candy : {}".format("success" if not_string('candy') == 'not candy' else "fail"))
print("Scenario 2: x : {}".format("success" if not_string('x') == 'not x' else "fail"))
print("Scenario 3: not bad: {}".format("success" if not_string('not bad') == 'not bad' else "fail"))
| true |
915deca3aed8bb835c8d915589a91e5f02cf3f49 | DocAce/Euphemia | /dicey.py | 2,108 | 4.1875 | 4 | from random import randint
def roll_die(sides):
return randint(1, sides)
def flip_coin():
if randint(0, 1) == 0:
return 'Heads'
else:
return 'Tails'
def generate_coin_flip_output(args):
numflips = 1
# just use the first number we find as the number of coins to flip
for arg in args:
if arg.isdigit():
numflips = int(arg)
break
result = ''
for i in range(numflips):
if i > 0:
result += ', '
result += flip_coin()
return result
def generate_dice_roll_output(args):
numdice = 1
addsgn = 1
add = 0
sides = 6
# evaluate the first argument that contains the letter d
# neither the @ nor the command contain that letter, so this should always work
for arg in args:
index_d = arg.find('d')
if index_d > 0:
rollstring = arg
# the number in front of the d is how many dice to roll (1 by default)
numdice = int(rollstring[:index_d])
rollstring = rollstring[index_d + 1:]
# either + or -, followed by a number, can be at the end
index_operator = rollstring.find('+')
if index_operator == -1:
index_operator = rollstring.find('-')
addsgn = -1
if index_operator != -1:
add = int(rollstring[index_operator + 1:]) * addsgn
rollstring = rollstring[:index_operator]
# if there is a number between the d and the + or - it's the number of sides on the dice (6 by default)
if rollstring != '':
sides = int(rollstring)
break
total = add
result = 'Rolling ' + str(numdice) + 'd' + str(sides)
if add < 0:
result += '-'
else:
result += '+'
result += str(abs(add)) + '\n'
result += 'Rolls: '
for i in range(numdice):
rollresult = roll_die(sides)
total += rollresult
if i > 0:
result += ', '
result += str(rollresult)
result += '\nTotal: ' + str(total)
return result
| true |
fc27b4861ef7c7fcd503acac082b04843a94c665 | Ascarik/PythonLabs | /Ch06/Lab08.py | 638 | 4.21875 | 4 | # Converts from Celsius to Fahrenheit
def celsiusToFahrenheit(celsius):
return (9 / 5) * celsius + 32
# Converts from Fahrenheit to Celsius
def fahrenheitToCelsius(fahrenheit):
return (5 / 9) * (fahrenheit - 32)
print(
format("Celsius", "20s"), "Fahrenheit",
" | ", format("Fahrenheit", "20s"),
format("Celsius", ">10s"), end="\n\n"
)
celsius = 40
fahrenheit = 120
for degree in range(0, 10):
print(format(celsius, "<20.1f"), format(celsiusToFahrenheit(celsius), "10.2f"),
" | ", format(fahrenheit, "<20.1f"), format(fahrenheitToCelsius(fahrenheit), ">10.2f"))
celsius -= 1
fahrenheit -= 10
| false |
6e0ddb0412a5f38c233d513c26492d9ddb5d2a1b | Ascarik/PythonLabs | /Ch04/Lab36.py | 644 | 4.1875 | 4 | import turtle, random
NUM = 200
x1, y1 = 0, 0
radius = random.randint(50, NUM)
x2, y2 = random.randint(-NUM, NUM), random.randint(-NUM, NUM)
# Pull the pen down
turtle.circle(radius)
turtle.penup()
turtle.goto(x2, y2)
turtle.pendown()
turtle.begin_fill()
turtle.color("red")
turtle.circle(3)
turtle.end_fill()
# Display the status
turtle.penup()
# Pull the pen up
turtle.goto(x1 - 70, y1 - radius - 20)
turtle.pendown()
d = ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) ** 0.5
if d <= radius:
turtle.write("The point is inside the circle")
else:
turtle.write("The point is outside the circle")
turtle.hideturtle()
turtle.done()
| false |
71adcc544a902e71d283a4ffefb069622b2a03c6 | vesteinnbjarna/Forritun_Vesteinn | /Lestrarverkefni/Kafli 2/simple_while.py | 251 | 4.15625 | 4 | #simple while
x_int = 0
#test loop-controled variable at the start
while x_int < 10:
print(x_int, end =' ') # print x_each time it loops
x_int = x_int + 1 # changing x_int while in loop
print ()
print ('Final value of x_int: ', x_int)
| true |
94a919169f98db4d533b7b186c3c2c4a49dc491c | vesteinnbjarna/Forritun_Vesteinn | /Lestrarverkefni/Kafli 5/celius_to_farenheit.py | 347 | 4.1875 | 4 |
def celsius_to_farenheit(celsius_float):
""" Convert Celsius to Fahrenheit. """
return celsius_float * 1.8 + 32
print("Convert Celsius to Fahrenheit.")
celsius_float = float(input('Enter degrees in celsius:'))
fahrenheit_float = celsius_to_farenheit (celsius_float)
print(celsius_float," converts to ", fahrenheit_float," Fahrenheit")
| false |
e5dbd401cbb63acdd259b185a02eeee98498734e | vesteinnbjarna/Forritun_Vesteinn | /Hlutapróf 2 undirbúningur/longest_word.py | 682 | 4.40625 | 4 |
def open_file(filename):
file_obj = open(filename, 'r')
return file_obj
def find_longest(file_object):
'''Return the longest word and its length found in the given file'''
max_length = 0
longest_word = ""
for word in file_object:
word = word.strip()
length = len(word)
if length > max_length:
longest_word = word
max_length = length
return longest_word, max_length
def main():
filename = input('Enter filename: ')
file_object = open_file(filename)
longest, length = find_longest(file_object)
print("Longest word is '{:s} of length {:d}".format(longest, length))
file_object.close()
| true |
e9b16fba6e3a93f03f9e0b4950b9f3692f2a8cc8 | vesteinnbjarna/Forritun_Vesteinn | /Tímaverkefni/Assignment 12/Q4.py | 606 | 4.5 | 4 |
def merge_lists(first_list, second_list):
a_new_list = []
for element in first_list:
if element not in a_new_list:
a_new_list.append(element)
for element in second_list:
if element not in a_new_list:
a_new_list.append(element)
a_new_list = sorted(a_new_list)
return a_new_list
# Main program starts here - DO NOT change it
def main():
list1 = input("Enter elements of list separated by commas: ").split(',')
list2 = input("Enter elements of list separated by commas: ").split(',')
print(merge_lists(list1, list2))
main() | true |
e0b0f0b3ec6cfe4adb826d78aadaf9496db112ad | vesteinnbjarna/Forritun_Vesteinn | /Tímaverkefni/Assignment 7/A7.5.py | 699 | 4.1875 | 4 |
import string
# palindrome function definition goes here
def is_palindrom (imported_string):
original_str = imported_string
modified_str = original_str.lower()
bad_chars = string.whitespace + string.punctuation
for char in modified_str:
if char in bad_chars:
modified_str = modified_str.replace(char,'')
if modified_str == modified_str [::-1]:
answer = '"' + original_str + '"'+ " is a palindrome."
else:
answer = '"' + original_str + '"' " is not a palindrome."
return answer
in_str = input("Enter a string: ")
result = is_palindrom(in_str)
print(result)
# call the function and print out the appropriate message | true |
17f31ab18c5d3f2d100c967bb88ca7b399d28278 | vesteinnbjarna/Forritun_Vesteinn | /Tímaverkefni/Assignment 7/A7.3.py | 353 | 4.15625 | 4 | # The function definition goes here
def is_num_in_range(number):
if number > 1 and number < 555:
answer = str(number) + " is in range."
else:
answer = str(number) + " is outside the range!"
return answer
num = int(input("Enter a number: "))
result = is_num_in_range(num)
print (result)
# You call the function here | true |
d4321a075f9540f36673bc598bfc9f1990598094 | vesteinnbjarna/Forritun_Vesteinn | /Skilaverkefni/Skilaverkefni 5/project.py | 1,683 | 4.5625 | 5 | # The program should scramble each word in the text.txt
# with the following instructions:
# 1.The first and last letter of each word are left unscrambled
# 2. If there is punctuation attached to a word it should be left unscrambled
# 3. The letter m should not be scrambled
# 4. The letters between the first and the last letter should swap adjacent
# letter.
# Lastly the user should be able to input the name of the file he wishes to scramble
# If no file contains that name he should get a error message:
# File xxx.txt not found!
#
# Steps to do this:
# 1. Create a function that opens the tries to open the file.
# If it cannot open it it should print a out the error message:
# file not found.
#
#
#
def open_file(file_object):
'''A function that tries to open a file
if the filename is not found it prints a
errorr message'''
file_object = open(file_object, "r")
except FileNotFoundError:
print('File', file_object, 'not found!')
return file_object
#def write_file(file_object):
# out_file = open(file_object,'w')
# sentence = ''
# for line in file_object:
# line = line.strip()
# sentence = sentence + line
# print (sentence)
# return out_file
def read_file(file_object):
new_line =''
for line in file_object:
line = line.strip()
line = line.replace("\n",' ')
new_line = line + new_line
print(new_line)
def main():
valid_input_bool = False
while not valid_input_bool:
file_name =input('Enter name of file: ')
try:
file_object = open_file(file_name)
main ()
| true |
c55af45dee5dd8861b67840741f798d791302b35 | AHoffm24/python | /Chapter2/classes.py | 999 | 4.40625 | 4 | #
# Example file for working with classes
#
#methods are functions in python
#self argument refers to the object itself. Self refers to the particular instance of the object being operated on
# class Person: #example of how to initalize a class with variables
# def __initialize__(self, name, age, sex):
# self.name = name
# self.age = age
# self.sex = sex
class myClass(): #super class
def method1(self):
print("myClass Method1")
def method2(self, someString):
print(someString + " myClass Method2 ")
class anotherClass(myClass): #inherited class allows you to call methods from myClass inside of anotherClass
def method1(self):
myClass.method1(self)
print("another class method1")
def method2(self, someString):
print("another calss method2")
def main():
c = myClass()
c.method1()
c.method2("this is my string for")
c2 = anotherClass()
c2.method1()
c2.method2("This is a string")
if __name__ == "__main__":
main()
| true |
58b14b436e842442e92a12cab3f08992e5f6acb2 | XTremeRox/AI-Lab | /Day1/prog1.py | 405 | 4.21875 | 4 | #!/usr/bin/python3
def print_list_elements(l):
for element in l:
print(element, end=' ')
print()
if __name__=="__main__":
l = []
l = ("Make me wanna say").split()
print_list_elements(l)
#insertion
l.insert(4, "like")
print_list_elements(l)
#appending
l.append("oh")
print_list_elements(l)
#removing
l.remove("like")
print_list_elements(l) | false |
e22f5ff5265d5073eeac203c5a6c8e017babdf23 | rodrigo9000/PycharmProjects | /PlayingWithSeries/Mission3_RollTheDice.py | 513 | 4.34375 | 4 | # User should be able to enter how many dices he wants to roll: 1 ,2 or 3. He should pass this value as a parameter in the
# function RollTheDice(num). Dices should show random numbers from 1 to 6.
import random
def main():
def RollTheDice(num):
if num in [1, 2, 3]:
for turns in range(1, (num + 1)):
print "Dice {} is number: ".format(turns), random.randint(1, 6)
else:
print "Number out of range"
RollTheDice(1)
if __name__== "__main__": main() | true |
b410db6a9ea07a05b7e80afad10bfed4a7d643b6 | 95subodh/Leetcode | /116. Populating Next Right Pointers in Each Node.py | 1,266 | 4.28125 | 4 | #Given a binary tree
#
#struct TreeLinkNode {
# TreeLinkNode *left;
# TreeLinkNode *right;
# TreeLinkNode *next;
#}
#pulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
#
#itially, all next pointers are set to NULL.
#
#te:
#
#u may only use constant extra space.
#u may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
#r example,
#ven the following perfect binary tree,
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
#ter calling your function, the tree should look like:
# 1 -> NULL
# / \
# 2 -> 3 -> NULL
# / \ / \
# 4->5->6->7 -> NULL
# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
stk=[]
if root:
stk=[root]
root=next = None
while stk:
z=stk.pop()
if z.left:
z.left.next=z.right
stk.append(z.left)
if z.right:
if z.next:
z.right.next=z.next.left
else:
z.right.next=None
stk.append(z.right)
| true |
93149f960c8b7d342dde0ea643b3977b3ae35bd3 | 95subodh/Leetcode | /326. Power of Three.py | 240 | 4.34375 | 4 | #Given an integer, write a function to determine if it is a power of three.
from math import *
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return True if n>0 and 3**20%n==0 else False | true |
33fa289bf90d66af8fb90cedcf7d52a4a3613baf | kphillips001/Edabit-Python-Code-Challenges | /usingternaryoperators.py | 380 | 4.34375 | 4 | # The ternary operator (sometimes called Conditional Expressions) in python is an alternative to the if... else... statement.
# It is written in the format:
# result_if_true if condition else result_if_false
# Ternary operators are often more compact than multi-line if statements, and are useful for simple conditional tests.
def yeah_nope(b):
return "yeah" if b else "nope" | true |
36a0f49179f1135a619d1d694fa71974e0ffb71b | jbulka/CS61A | /hw2_solns.py | 2,545 | 4.15625 | 4 | """Submission for 61A Homework 2.
Name:
Login:
Collaborators:
"""
# Q1: Done
def product(n, term):
"""Return the product of the first n terms in a sequence.
We will assume that the sequence's first term is 1.
term -- a function that takes one argument
"""
prod, k = 1, 1
while k <= n:
prod, k = prod * term(k), k + 1
return prod
def factorial(n):
"""Return n factorial by calling product.
>>> factorial(4)
24
"""
return product(n, identity)
def identity(k):
''' returns the value k'''
return k
# Q2: Done
from operator import add, mul
def accumulate(combiner, start, n, term):
"""Return the result of combining the first n terms in a sequence.
"""
total, k = start, 1
while k <= n:
total, k = combiner(total, term(k)), k + 1
return total
def summation_using_accumulate(n, term):
"""An implementation of summation using accumulate."""
return accumulate(add, 0, n, term)
def product_using_accumulate(n, term):
"""An implementation of product using accumulate."""
return accumulate(mul, 1, n, term)
# Q3: Done
def double(f):
"""Return a function that applies f twice.
f -- a function that takes one argument
"""
return lambda x: f(f(x))
# Q4: Done
def repeated(f, n):
"""Return the function that computes the nth application of f.
f -- a function that takes one argument
n -- a positive integer
>>> repeated(square, 2)(5)
625
"""
func = f
k = 1
while k < n :
func = compose1(f,func)
k = k + 1
return func
def square(x):
"""Return x squared."""
return x * x
def compose1(f, g):
"""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h
# Q5 (Extra)
def zero(f):
"""Church numeral 0."""
return lambda x: x
def successor(n):
return lambda f: lambda x: f(n(f)(x))
def one(f):
"""Church numeral 1."""
"*** YOUR CODE HERE ***"
def two(f):
"""Church numeral 2."""
"*** YOUR CODE HERE ***"
def add_church(m, n):
"""Return the Church numeral for m + n, for Church numerals m and n."""
"*** YOUR CODE HERE ***"
def church_to_int(n):
"""Convert the Church numeral n to a Python integer.
>>> church_to_int(zero)
0
>>> church_to_int(one)
1
>>> church_to_int(two)
2
>>> church_to_int(add_church(two, two))
4
"""
"*** YOUR CODE HERE ***"
| true |
215aed3bd3d66a69c49bc841e6dc9011cc8bf156 | QinmengLUAN/Daily_Python_Coding | /wk4_findNumbers.py | 860 | 4.28125 | 4 | """
1295. Find Numbers with Even Number of Digits
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
Example 2:
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.
"""
def findNumbers(nums):
oup = 0
k = 0
for i in range(len(nums)):
nu = nums[i]
while nu > 0:
nu = nu // 10
k += 1
if (k % 2) == 0:
oup += 1
k = 0
return oup
nums = [437,315,322,431,686,264,442]
print(findNumbers(nums)) | true |
9261b5b8c174058a10632b6cbe2a580c0a5e9cba | QinmengLUAN/Daily_Python_Coding | /DailyProblem20_maximum_product_of_three.py | 651 | 4.375 | 4 | """
Hi, here's your problem today. This problem was recently asked by Microsoft:
You are given an array of integers. Return the largest product that can be made by multiplying any 3 integers in the array.
Example:
[-4, -4, 2, 8] should return 128 as the largest product can be made by
multiplying -4 * -4 * 8 = 128.
Here's a starting point:
def maximum_product_of_three(lst):
# Fill this in.
print maximum_product_of_three([-4, -4, 2, 8])
# 128
"""
def maximum_product_of_three(nums):
# Fill this in.
nums.sort()
return max(nums[-1]*nums[-2]*nums[-3], nums[0]*nums[1]*nums[-1])
print(maximum_product_of_three([-4, -4, 2, 8]))
# 128 | true |
99845dad934230a83a99d4e8ac1ab96b24cd0c3f | QinmengLUAN/Daily_Python_Coding | /DailyProblem19_findKthLargest.py | 653 | 4.125 | 4 | """
Hi, here's your problem today. This problem was recently asked by Facebook:
Given a list, find the k-th largest element in the list.
Input: list = [3, 5, 2, 4, 6, 8], k = 3
Output: 5
Here is a starting point:
def findKthLargest(nums, k):
# Fill this in.
print findKthLargest([3, 5, 2, 4, 6, 8], 3)
"""
import heapq
def findKthLargest(nums, k):
# Fill this in.
if len(nums) < 3:
return None
h = []
for i in range(3):
heapq.heappush(h, nums[i])
for j in range(3, len(nums)):
heapq.heappush(h, nums[j])
heapq.heappop(h)
return heapq.heappop(h)
print(findKthLargest([3, 5, 2, 4, 6, 8], 3)) | true |
5ff35f6f7a920113cec07c88e253ad06a9bdcfec | QinmengLUAN/Daily_Python_Coding | /LC354_maxEnvelopes_DP.py | 2,042 | 4.40625 | 4 | """
354. Russian Doll Envelopes
Hard
You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.
What is the maximum number of envelopes can you Russian doll? (put one inside other)
Note:
Rotation is not allowed.
Example:
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
"""
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
if len(envelopes) == 0:
return 0
envelopes.sort(key = lambda x: (x[0], -x[1]))
f = [0] * len(envelopes)
size = 0
for w,h in envelopes:
i, j = 0, size
while i != j:
m = i + (j - i)//2
if f[m] < h:
i = m + 1
else:
j = m
f[i] = h
size = max(size, i + 1)
# print(f)
return size
"""
Trick:
let's suppose the values are given as...
[2,3]
[4,6]
[3,7]
[4,8]
If we Sort this envelopes in a tricky way that Sort the envelopes according to width BUT when the values of height are same, we can sort it in reverse way like this :
[2,3]
[3,7]
[4,8]
[4,6]
Now just Do LIS on the all height values, you will get the answer
Solution:
# only seek height's LIS (longest increasing subsequence), alike Leetcode Question 300.
# https://leetcode.com/problems/longest-increasing-subsequence/
# follow up question, how about 3D cases? since Russian Doll are actually with x,y,z dimensions!
# [2,3], [5,4], [6,4], [6,7], [1,2]
# will be sorted to be: [1,2], [2,3], [5,4], [6,7], [6,4]
# where the answer is: 4 for [1,2], [2,3], [5,4], [6,7]
# [2,3], [5,4], [6,4], [7,1], [8,2], [9,3]
# will be sorted to be: [2,3], [5,4], [6,4], [7,1], [8,2], [9,3]
# where the answer is: 3 for [7,1], [8,2], [9,3]
"""
| true |
dc33830a1d3708345a5d77f6f9dfd86017137e31 | QinmengLUAN/Daily_Python_Coding | /wk2_sqrt.py | 609 | 4.125 | 4 | # Write a function to calculate the result (integer) of sqrt(num)
# Cannot use the build-in function
# Method: binary search
def my_sqrt(num):
left_boundary = 0
right_boundary = num
if num <= 0:
return False
elif num < 1:
return 0
elif num == 1:
return num
while (right_boundary - left_boundary) > 1:
mid_num = (right_boundary + left_boundary) // 2 #Update mid_num
new_num = mid_num * mid_num
if new_num < num:
left_boundary = mid_num
elif new_num > num:
right_boundary = mid_num
elif new_num == num:
return mid_num
return left_boundary
#Input:
a = 15
print(my_sqrt(a))
| true |
7dab89ca1ef40d80b0ea0728cca5126bd021f291 | QinmengLUAN/Daily_Python_Coding | /wk2_MoeList.py | 1,106 | 4.28125 | 4 | # To understand object and data structure
# Example 1: https://www.w3schools.com/python/python_classes.asp
# Example 2: https://www.tutorialspoint.com/python_data_structure/python_linked_lists.htm
# write an object MyList with many methods: MyList, append, pop, print, node
class MyNode:
def __init__(self, value):
self.value = value
self.before = None
self.next = None
class MyList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value):
appended = MyNode(value)
if self.head == None:
self.head = appended
self.tail = appended
else:
curr_tail = self.tail
appended.before = curr_tail
curr_tail.next = appended
self.tail = appended
def print(self):
curr_node = self.head
while curr_node != None:
print(curr_node.value)
curr_node = curr_node.next
def get(self, n):
curr_node = self.head
i = 0
while i < n and curr_node != None:
curr_node = curr_node.next
i = i + 1
if curr_node == None:
return None
else:
return curr_node.value
lis = MyList()
lis.append(1)
lis.append(2)
lis.print()
print(lis.get(1))
| true |
c48afae5e64ef91588c53ce962ea8c326a529d1b | QinmengLUAN/Daily_Python_Coding | /LC1189_maxNumberOfBalloons_String.py | 858 | 4.125 | 4 | """
1189. Maximum Number of Balloons
Easy: String, Counter, dictionary
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1
Example 2:
Input: text = "loonbalxballpoon"
Output: 2
Example 3:
Input: text = "leetcode"
Output: 0
"""
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
cnt = Counter(text)
return min(cnt[ch]//n for ch, n in Counter('balloon').items())
def maxNumberOfBalloons(self, text: str) -> int:
c = Counter("balloon")
c_text = Counter(text)
res = len(text)
for i in c:
res = min(res, c_text[i]//c[i])
return res | true |
24b60cb185dcf1770906a0b042b297aa7ea0784b | QinmengLUAN/Daily_Python_Coding | /LC326_isPowerOfThree_Math.py | 420 | 4.25 | 4 | """
326. Power of Three
Easy: Math
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
Follow up:
Could you do it without using any loop / recursion?
"""
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and 3**19 % n == 0 | true |
ea27a81da0146733e81e51b59fcb87622e5f8cea | QinmengLUAN/Daily_Python_Coding | /DailyProblem04_isValid_String.py | 1,649 | 4.21875 | 4 | """
Hi, here's your problem today. This problem was recently asked by Uber:
Leetcode 20
Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using strings.
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets are closed by the same type of brackets.
- Open brackets are closed in the correct order.
- Note that an empty string is also considered valid.
Example:
Input: "((()))"
Output: True
Input: "[()]{}"
Output: True
Input: "({[)]"
Output: False
class Solution:
def isValid(self, s):
# Fill this in.
# Test Program
s = "()(){(())"
# should return False
print(Solution().isValid(s))
s = ""
# should return True
print(Solution().isValid(s))
s = "([{}])()"
# should return True
print(Solution().isValid(s))
"""
class Solution:
def isValid(self, s):
# Fill this in.
bra_dic = {")":"(", "}": "{", "]":"["}
stack = []
for i in range(len(s)):
if s[i] not in bra_dic:
stack.append(s[i])
else:
if len(stack) == 0 or stack[-1] != bra_dic[s[i]]:
return False
else:
stack.pop()
if len(stack) > 0:
return False
else:
return True
# Test Program
s = "()(){(())"
# should return False
print(Solution().isValid(s))
s = ""
# should return True
print(Solution().isValid(s))
s = "([{}])()"
# should return True
print(Solution().isValid(s)) | true |
7e4c89bc3812a0bf3707b3de2183ca661b693f3d | QinmengLUAN/Daily_Python_Coding | /LC207_canFinish_Graph.py | 2,214 | 4.1875 | 4 | """
207. Course Schedule
Medium: Graph
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
"""
from collections import deque
class Solution:
def canFinish(self, numCourses, prerequisites):
cnext = {}
npre = {}
for i in range(len(prerequisites)):
if prerequisites[i][1] in cnext:
cnext[prerequisites[i][1]].append(prerequisites[i][0])
else:
cnext[prerequisites[i][1]] = [prerequisites[i][0]]
if prerequisites[i][0] not in npre:
npre[prerequisites[i][0]] = 1
else:
npre[prerequisites[i][0]] += 1
if prerequisites[i][1] not in npre:
npre[prerequisites[i][1]] = 0
print(cnext)
print(npre)
if len(npre) == 0 and numCourses == 1:
return True
dq = deque([i for i in npre if npre[i] == 0])
print(dq)
finished = 0
while len(dq) > 0:
c = dq.popleft()
finished += 1
# print(finished)
print(cnext, npre)
if c not in cnext:
continue
for cn in cnext[c]:
npre[cn] -= 1
if npre[cn] == 0:
dq.append(cn)
return finished == len(npre)
numCourses = 4
prerequisites = [[3,0],[0,1]]
s = Solution()
print(s.canFinish(numCourses, prerequisites)) | true |
f27497e9a8acc603807d738e36b3937ad47f1b77 | NkStevo/daily-programmer | /challenge-003/intermediate/substitution_cipher.py | 1,260 | 4.125 | 4 | import json
def main():
with open('ciphertext.json') as json_file:
ciphertext = json.load(json_file)
print("----Substitution Cipher Program----")
choice = input("Input 1 to encode text and 2 to decode text:\n")
if choice == '1':
text = input("Input the text you would like to be encoded:\n")
print(encode(text, ciphertext))
elif choice == '2':
text = input("Input the text you would like to be decoded:\n")
print(decode(text, ciphertext))
else:
print("Invalid input")
def encode(text, ciphertext):
coded_text = ""
for char in text:
char_code = ord(char)
if (char_code >= ord('a') and char_code <= ord('z')) or (char_code >= ord('A') and char_code <= ord('Z')):
coded_text += ciphertext[char]
else:
coded_text += char
return coded_text
def decode(text, ciphertext):
coded_text = ""
inverse_ciphertext = {value: key for key, value in ciphertext.items()}
for char in text:
if char in inverse_ciphertext:
coded_text += inverse_ciphertext[char]
else:
coded_text += char
return coded_text
if __name__ == '__main__':
main()
| true |
505816e71a2df217a36b6dc74ae814e40208b26d | zszinegh/PyConvert | /pyconvert/conversions.py | 1,068 | 4.375 | 4 | """A module to do various unit conversions.
This module's functions convert various units of measurement.
All functions expect a 'float' as an argument and return a 'float'.
'validate_input()' can be used before running any function to
convert the input to a 'float'.
"""
def validate_input(incoming):
"""Convert input to float.
Args:
incoming (str): String probably coming from a 'raw_input()'.
Returns:
result (str or float): Depends on try statement.
"""
try:
result = float(incoming)
except ValueError:
result = incoming
return result
# Conversion functions.
def celsius_fahrenheit(number):
"""Convert celsius to fahrenheit."""
return (number * 9.0 / 5.0) + 32.0
def fahrenheit_celsius(number):
"""Convert fahrenheit to celsius."""
return (number - 32.0) * 5.0 / 9.0
def kms_miles(number):
"""Convert kms to miles."""
return number * 0.62137
def miles_kms(number):
"""Convert miles to kms."""
return number / 0.62137
if __name__ == '__main__':
pass
| true |
61c0658f4299a3175b50d3d2c680ad8ea52d2d4c | cadbane/python-dojo | /tricks/iterating.py | 279 | 4.1875 | 4 | # iterating over list index and value pairs
a = ['Lorem', 'ipsum', 'dorem', 'kolorem']
for i, x in enumerate(a):
print(f'{i}: {x}')
# iterating over dictionary
b = {'apple': 3, 'banana': 7, 'orange': 0}
for f, q in b.items(): # iteritems() for python2
print(f'{f}: {q}') | false |
82be926a6549078edf9b27ea2e56c0993d5e6b3a | isaiah1782-cmis/isaiah1782-cmis-cs2 | /Assignment_Guessing_Game.py | 950 | 4.25 | 4 | import math
import random
Minimum_Number = int(raw_input("What is the minimum number? "))
Maximum_Number = int(raw_input("What is the maximum number? "))
print "I'm thinking of a number from " + str(Minimum_Number) + " to " + str(Maximum_Number) + "."
Guess = str(raw_input("What do you think it is?: "))
def Correct_or_Over_or_under():
x = number = random.randint(Minimum_Number, Maximum_Number)
if int(x) == int(Guess):
print """
The target was {}.
Your guess was {}.
That's correct! You must be psychic!
""".format(str(x), str(Guess))
elif str(x) > str(Guess):
Under = int(x) - int(Guess)
print """
The target was {}.
Your guess was {}.
That's under by {}.
""".format(str(x), str(Guess), Under)
elif str(x) < str(Guess):
Over = int(Guess) - int(x)
print """
The target was {}.
Your guess was {}.
That's over by {}.
""".format(str(x), str(Guess), Over)
Correct_or_Over_or_under()
| true |
27d4d41ca785afa105f59b8420637948d29ea9b0 | kammariprasannalaxmi02/sdet | /python/Activity14.py | 538 | 4.3125 | 4 | #Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
fibo_num = input("Enter the number to get Fibonnaci numbers: ")
def fibonnaci_Num(fib_num):
n1 = 0
n2 = 1
i = 1
n = int(fib_num) - 2
fiba_list = [0,1]
if(int(fib_num)==1):
print([0])
else:
while(i<=n):
sum = n1 + n2
n1 = n2
n2 = sum
fiba_list.append(sum)
i+=1
print(fiba_list)
fibonnaci_Num(fibo_num)
| false |
77069ee92fcb26ff76619058b379d05e8c177153 | kammariprasannalaxmi02/sdet | /python/Activity12.py | 264 | 4.21875 | 4 | #Write a recursive function to calculate the sum of numbers from 0 to 10
def calculate(i):
if i <= 1:
return i
else:
return i + calculate(i-1)
num = int(input("Enter a number: "))
print("The sum of numbers: ", calculate(num))
| true |
26343c2e7d1a57463b71faee58c204afd426b5b8 | noemiko/design_patterns | /factory/game_factory.py | 2,774 | 4.75 | 5 | # Abstract Factory
# The Abstract Factory design pattern is a generalization of Factory Method. Basically,
# an Abstract Factory is a (logical) group of Factory Methods, where each Factory
# Method is responsible for generating a different kind of object
# Frog game
class Frog:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def interact_with(self, obstacle):
act = obstacle.action()
msg = f"{self} the Frog encounters {obstacle} and {act}!"
print(msg)
class Bug:
def __str__(self):
return "a bug"
def action(self):
return "eats it"
class FrogGame:
def __init__(self, name):
print(self)
self.player_name = name
def __str__(self):
return "\n\n\t------ Frog World -------"
def make_character(self):
return Frog(self.player_name)
def make_obstacle(self):
return Bug()
# Wizard game
class Wizard:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def interact_with(self, obstacle):
act = obstacle.action()
msg = f"{self} the Wizard battles against {obstacle} and {act}!"
print(msg)
class Ork:
def __str__(self):
return "an evil ork"
def action(self):
return "kills it"
class WizardGame:
def __init__(self, name):
print(self)
self.player_name = name
def __str__(self):
return "\n\n\t------ Wizard World -------"
def make_character(self):
return Wizard(self.player_name)
def make_obstacle(self):
return Ork()
# Game environment
class GameEnvironment:
def __init__(self, factory):
self.hero = factory.make_character()
self.obstacle = factory.make_obstacle()
def play(self):
self.hero.interact_with(self.obstacle)
def validate_chosen_game(user_name):
print(f"Would you like to play {user_name} in Wizard game?")
print(f"Would you like to play {user_name} in Frog game?")
game_number = input("Wizard game press: 1, From game press: 2 ")
try:
game_number = int(game_number)
if game_number not in (1, 2):
raise ValueError
except ValueError as err:
print("You have chosen the wrong game number")
return False, game_number
return True, game_number
def main():
user_name = input("Hello. What's your name? ")
is_valid_input = False
while not is_valid_input:
is_valid_input, game_number = validate_chosen_game(user_name)
games = {
1: FrogGame,
2: WizardGame
}
chosen_game = games[game_number]
environment = GameEnvironment(chosen_game(user_name))
environment.play()
main()
| true |
5f20f80abf87e9a9b32d0f5b32da197e75b18655 | NeonMiami271/Work_JINR | /Python/Kvadrat_yravn.py | 551 | 4.125 | 4 | #Решение квадратного уравнения
import math
print("Решим квадратное уравнение")
a = float(input("а = "))
b = float(input("b = "))
c = float(input("c = "))
D = b**2 - (4*a*c)
if D < 0:
print("Корней нет")
elif D == 0:
x = -b/(2*a)
print("Корень равен:" + str(x))
elif D > 0:
x1 = (-b - math.sqrt(D))/(2*a)
print("Первый корень равен: " + str(x1))
x2 = (-b + math.sqrt(D))/(2*a)
print("Второй корень равен: " + str(x2)) | false |
cc59404f7b10f79ddbf44dc265083c99c32ad4be | phpdavid/python-study | /home-study/study-code/python-code/ten/one.py | 760 | 4.625 | 5 | # 使用类枚举的方式(python中没有枚举类型)为元祖每个元素命名,提高程序可读性
# 在python中没有真正的枚举类型,我们可以定义一些常量代替
Student = ('david', 19, 'male')
# # 通过下标读取值,可读性很差,时间久了,不知道是什么了
# # name
# Student[0]
# # age
# Student[1]
# # gender
# Student[2]
#
# # 定义常量
# # NAME = 0
# # AGE = 1
# # GENDER = 2
# NAME, AGE, GENDER = range(3)
# Student[NAME]
# Student[AGE]
# Student[GENDER]
# print(Student[NAME])
# 2通过collection中的nametuple定义
from collections import namedtuple
Student = namedtuple('Human', ['name', 'age', 'gender'])
s = Student('david', 16, 'female')
print(s.name) # 以类,对象的形式访问元祖
| false |
95a9f4e25127241ba07696dacca17dfe3740c930 | vladflore/py4e | /course3/week6/extract-data-json.py | 1,396 | 4.40625 | 4 | # In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The
# program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment
# counts from the JSON data, compute the sum of the numbers in the file and enter the sum below: We provide two files
# for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual
# data you need to process for the assignment.
#
# Sample data: http://py4e-data.dr-chuck.net/comments_42.json (Sum=2553) Actual data:
# http://py4e-data.dr-chuck.net/comments_330796.json (Sum ends with 66) The closest sample code that shows how to
# parse JSON and extract a list is json2.py. You might also want to look at geoxml.py to see how to prompt for a URL
# and retrieve data from a URL.
import json
import ssl
import urllib.request
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter URL: ')
if len(url) < 1: url = "http://py4e-data.dr-chuck.net/comments_330796.json"
# context is not needed because the data source link is NOT https
data = urllib.request.urlopen(url, context=ctx).read()
json_data = json.loads(data)
comments = json_data['comments']
s = 0
for comment in comments:
s = s + int(comment['count'])
print(s)
| true |
597416454b410742bc4ac70d165389cd73093c56 | PKpacheco/exec_roman_numerals | /main.py | 826 | 4.1875 | 4 | from int_roman import *
from roman_int import *
def decision_method(number_choice):
if (number_choice == 1):
N = int(input("Input integer number (between 1 and 3000: "))
if (N == 0):
print ("Please enter a number greater than 0")
elif (N > 3000):
print ("Please enter a number less than 3000")
else:
print "Roman number is:", int_to_roman(N)
elif (number_choice == 2):
roman_number = raw_input("Input roman number: ").upper()
print "Integer number is:", roman_to_int(roman_number)
else:
print "--------- Input a valid Number ---------"
if __name__ == '__main__':
print "Please choose a number"
number_choice= int(input("1- Integer to Roman or 2- Roman to Integer: "))
decision_method(number_choice) | false |
f7f87810b50c50b2828e2c404763cdb3f44b08a0 | alindsharmasimply/Python_Practice | /seventySecond.py | 307 | 4.21875 | 4 | def sumsum():
sum1 = 0
while True:
try:
a = input("Enter a valid number to get the sum ")
if a == ' ':
break
sum1 = sum1 + a
print sum1, "\n"
except Exception:
print "Enter a valid number only "
sumsum()
| true |
3a50f698d6a65fafa0c72bfc75b8ec175896b9d8 | SimonFromNeedham/Project_Euler_Problems | /euler16.py | 1,072 | 4.125 | 4 | # 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
# What is the sum of the digits of the number 2^1000?
# I'm aware that this approach is more complex than necessary and that I could just use a long to store the number,
# But I honestly find it a lot more interesting to work through the problem trying to save memory by using an array
if __name__ == '__main__':
# Use an array instead of an int/long to store the number because
# with hundreds of digits, the latter would take up a ton of memory
digits = [1]
for i in range(1000):
digits[0] *= 2
if digits[0] > 9:
digits[0] %= 10
digits.insert(0, 1)
# If the first digit == 1, then the second digit was already doubled because
# the higher digit (> 10) was "carried" over to the next digit --> inserted at index 0
for j in range(1 if digits[0] != 1 else 2, len(digits)):
digits[j] *= 2
if digits[j] > 9:
digits[j] %= 10
digits[j-1] += 1
print(sum(digits))
| true |
c0bdf60e9dd878b032e2372faf6babe022ee1201 | littlejoe1216/Daily-Python-Exercise-01 | /#1-Python-Daily-Exercise/Daily Exercise-1-02082018.py | 290 | 4.1875 | 4 | #Joe Gutierrez - Python Daily Exercise - 2/16/18
# 1. Write a statement that concatenates at least two variables (you can have more than 2 for this practice).
name = input('Enter First name:')
sna = input('Enter Last name:')
joe = name + sna
print ('Is your name ' + str(joe))
| true |
43c9ee7ba7e074a0d37c44e7391d8181d706193d | CSSBO/websystem | /算法分析/fenxingtree.py | 1,203 | 4.28125 | 4 |
import turtle
#画分形树,用的是创建二叉树的算法
def treeoface(length):
#如果枝干长度小于15就不画
if length<15:
return 0
turtle.forward(length)#往前画
turtle.up()#在回退的时候关闭画笔的工作
turtle.backward(length * (1 / 3))#回退到三分之一的地方
turtle.down()#重新打开画笔工作
turtle.left(60)
#time.sleep(1)#画左枝干,长度为主枝干的1/3
treeoface(length*(1/3))
turtle.right(60)
turtle.up()
turtle.backward(length * (1 / 3))
turtle.down()
# 画右枝干,长度为主枝干的2/3
turtle.right(60)
treeoface(length*(2/3))
turtle.left(60)
turtle.up()
turtle.backward(length * (1 / 3))
turtle.down()
return 0
def main():
#画笔一开始是水平向右的,让它左转90度竖直向上
turtle.left(90)
turtle.backward(250)
turtle.pensize(3)
turtle.speed(2)
#设置线条粗细
#设置线条颜色
turtle.color("blue")
# turtle.size(3)
#设定树的最大长度为500
treeoface(500)
#关闭画板
turtle.exitonclick()
main()
| false |
518087b3406afc65b712cee808f5849e98d40197 | palepriest/python-notes | /src/ex32.py | 635 | 4.1875 | 4 | # -*- coding:utf-8 -*-
t_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'bananas', 'Blueberries', 'oranges']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# print a integer list
for number in t_count:
print "The number is %d." % number
# print a string list
for fruit in fruits:
print "The fruit type is %s." % fruit
# print a multi-type list
for i in change:
print "I got %r." % i
elements = []
# use the range function to construcr a list
for i in range(0, 6):
print "Add %d into elements list." % i
elements.append(i)
# the print them out
for element in elements:
print "The element is %d." % element | true |
ca03996c06e344c39557e27a53fd7a4b8d243471 | Nasir1004/assigment-3-python-with-dahir | /lopping numbers from one to ten.py | 235 | 4.1875 | 4 | '''
numbers=1
for i in range (1,10):
print(i)
#this is example of for loop numbers from one to ten
'''
# the whileloop example is
current_number = 1
while current_number <=10:
print(current_number )
current_number += 1
| true |
db42b6acb7d451e412f58c2837e4d1c309a412dc | wbluke/python_dojang | /01_input_output.py | 649 | 4.15625 | 4 | # if you divide integer by integer, result is float.
num = 4 / 2
print(num) # 2.0
# convert float to int(int to float)
num = int(4/2)
print(num) # 2
num = float(1+3)
print(num) # 4.0
# delete variable
del num
# if you want to know class' type
print(type(3.3)) # <class 'float'>
# when save input data on variable
s = input() # string type
a = int(input()) # integer type
# several inputs
b, c = input().split() # two string types
b, c = map(int, input().split()) # two int types by using map()
# control print method
# sep : seperate character
print(1, 2, 3, sep=', ') # 1, 2, 3
# end : end character
print(1, end=' ')
print(2) # 1 2
| true |
1c5ae131528b6e48953212686c066c5a9736a334 | brandonkbuchs/UWisc-Python-Projects | /latlon.py | 2,073 | 4.5 | 4 | # This program collects latitude and longitude inputs from the user and returns
# Information on the location of the quadrant of the coordinate provided
def latlon(latitude, longitude): # Defines function
# Latitude logic tests.
if latitude == 0: # Test if on equator
print "That location is on the equator."
elif latitude > 0 and latitude <= 90: # Test if north of equator
print "That location is north of the equator."
elif latitude < 0 and latitude >= -90: # Test if south of equator.
print "That location is south of the equator."
elif latitude < -90 or latitude > 90: # Invalid entry.
print "That location does not have a valid latitude!"
# Longitude logic tests.
if longitude == 0: # Test if prime meridian
print "That location is on the prime meridian."
elif longitude > 0 and longitude <= 180: # Tests if east of PM.
print "That location is east of the prime meridian."
elif longitude < 0 and longitude >= -180: # Tests if west of PM.
print "That location is west of the prime meridian."
elif longitude < -180 or longitude > 180: # Invalid entry.
print "That location does not have a valid longitude!"
while True:
# Print instructions to the user.
print "This program will tell you where latitude and longitude fall on the Earth."
print "Please follow the instructions. Enter only real numbers."
print "Latitude must be a number between -90 and 90."
print "Longitude must be a number between -180 and 180.\n"
latitude = raw_input("Enter your latitude here.>") # Latitude variable
longitude = raw_input("Enter your longitude here.>") # Longitude variable
try: # Test whether input is real number.
latitude = float(latitude)
longitude = float(longitude)
break
except: # Prints error message, restarts program for all non-real numbers.
print "Please enter a valid number for both latitude and longitude."
latlon(latitude, longitude) # Calls function
| true |
5eea14c56271bb0034e0d80744730fe9bf2ea3ae | vishaldhateria/100daysofcode | /18-August-2020/changedimensions.py | 523 | 4.1875 | 4 | # my__1D_array = numpy.array([1, 2, 3, 4, 5])
# print my_1D_array.shape #(5,) -> 5 rows and 0 columns
# my__2D_array = numpy.array([[1, 2],[3, 4],[6,5]])
# print my_2D_array.shape #(3, 2) -> 3 rows and 2 columns
# change_array = numpy.array([1,2,3,4,5,6])
# change_array.shape = (3, 2)
# print change_array
# print numpy.reshape(my_array,(3,2))
import numpy
def reshapeme(arr):
reshar = numpy.array(arr,int)
return numpy.reshape(reshar,(3,3))
arr = input().strip().split(' ')
print (reshapeme(arr))
| false |
659e981c2f135e1ae4e3db3d62d90d359c787e71 | 21eleven/leetcode-solutions | /python/0673_number_of_longest_increasing_subsequence/lsubseq.py | 1,203 | 4.125 | 4 | """
673. Number of Longest Increasing Subsequence
Medium
Given an integer array nums, return the number of longest increasing subsequences.
Example 1:
Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: nums = [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.
Constraints:
1 <= nums.length <= 2000
-106 <= nums[i] <= 106
"""
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
N = len(nums)
if N <= 1:
return N
lengths = [0]*N
counts = [1]*N
for j, num in enumerate(nums):
for i in range(j):
if nums[i] < nums[j]:
if lengths[i] >= lengths[j]:
lengths[j] = 1 + lengths[i]
counts[j] = counts[i]
elif lengths[i] + 1 == lengths[j]:
counts[j] += counts[i]
longest = max(lengths)
return sum(c for i, c in enumerate(counts) if lengths[i] == longest)
| true |
6a52d60f15ef338e27b8c62ce8c034653c0a0f2f | 21eleven/leetcode-solutions | /python/0605_can_place_flowers/three_slot.py | 1,411 | 4.15625 | 4 | """
605. Can Place Flowers
Easy
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: false
Constraints:
1 <= flowerbed.length <= 2 * 104
flowerbed[i] is 0 or 1.
There are no two adjacent flowers in flowerbed.
0 <= n <= flowerbed.length
"""
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
if len(flowerbed) == 1 and 1 != flowerbed[0]:
return True
left = n
if flowerbed[0] == 0 and flowerbed[1] == 0:
flowerbed[0] = 1
left -= 1
if flowerbed[-1] == 0 and flowerbed[-2] == 0:
flowerbed[-1] = 1
left -= 1
if len(flowerbed) >= 3:
for i in range(1,len(flowerbed)-1):
if flowerbed[i-1] == 0 and flowerbed[i] == 0 and flowerbed[i+1] == 0:
flowerbed[i] = 1
left -= 1
if left < 1:
return True
return False
| true |
a3f61908d09cba128724d0d6a533c59075156091 | 21eleven/leetcode-solutions | /python/1631_path_with_minimum_effort/bfs_w_heap.py | 2,594 | 4.125 | 4 | """
1631. Path With Minimum Effort
Medium
You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
Example 1:
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
Example 2:
Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
Example 3:
Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.
Constraints:
rows == heights.length
columns == heights[i].length
1 <= rows, columns <= 100
1 <= heights[i][j] <= 106
"""
class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
lcol = len(heights[0])
lrow = len(heights)
path_effort = math.inf
q = [(0,0,0)]
visited = set()
while q:
effort, row, col = heapq.heappop(q)
if row == lrow -1 and col==lcol-1:
return effort
if (row,col) in visited:
continue
visited.add((row,col))
up = (row-1, col)
if up[0] < 0:
up = None
if col + 1 < lcol:
right = (row,col+1)
else:
right = None
if row+1 < lrow:
down = (row+1, col)
else:
down = None
if col -1 < 0:
left = None
else:
left = (row, col-1)
here = heights[row][col]
routes = [up,down,left,right]
for d in routes:
if d:
there = heights[d[0]][d[1]]
step_effort = abs(there - here)
heapq.heappush(q,(max(effort,step_effort),d[0],d[1]))
| true |
0790ccdc036798bf7ce9d542345f784dd6009d39 | makhmudislamov/leetcode_problems | /microsoft/arr_and_str/set_matrix_zeroes.py | 2,465 | 4.46875 | 4 | """
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
Youtube solution: https://www.youtube.com/watch?v=6_KMkeh5kEc
"""
def setZeroes(matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
# declaring height and width variables for iteration
# initialize boolean (false)to mark if the first row should be filled with 0s
height = len(matrix)
width = len(matrix[0])
first_row_zero = False
# iterate over the first row
# if it has 0 change the boolean to true
for cell in range(width):
if matrix[0][cell] == 0:
first_row_zero = True
# iterate over each cell
# if the cell contains 0
# mark the corresponding index of first row as zero >> denotes the whole column as 0
for row in range(height):
for col in range(width):
if matrix[row][col] == 0:
matrix[0][col] = 0 # denotes: whole column as 0s
# iterate each cell starting second row
# declare boolean (false) if the cell is 0
# once a cell with 0 is reached change the boolean, break the loop
for row in range(1, height):
cell_has_zero = False
for col in range(width):
if matrix[row][col] == 0:
cell_has_zero = True
break
# iterate over the columns
# if the cell has 0 or (boolean above) or corresponding index of first row is 0
# change this cell to 0
for col in range(width):
if cell_has_zero or matrix[0][col] == 0:
matrix[row][col] = 0
# if the first row has 0 (boolean above)
# iterate over the first row and change each cell to 0
if first_row_zero:
for cell in range(width):
matrix[0][cell] = 0
return matrix
matrix = [
[0, 1, 2, 0],
[3, 4, 5, 2],
[1, 3, 1, 5]
]
print(setZeroes(matrix))
| true |
27a566d6f5312cf2b427d42c1e542d53a1384c21 | makhmudislamov/leetcode_problems | /microsoft/arr_and_str/trapping_rain_water.py | 1,224 | 4.28125 | 4 | """
Given n non-negative integers representing an elevation map where the width of each bar is 1,
compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
In this case, 6 units of rain water (blue section) are being trapped.
Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
"""
# helper func
# at the target index
# expand to two sides until on of the side values is less then previous value - should increase
# in that condition >> max value of one side - min value of another side
# return the value >> cubes of water in each section
def trap(height: [int]):
if height is None or len(height) == 0:
return 0
total = 0
level = 0
left = 0
right = len(height) - 1
while left < right:
if height[left] < height[right]:
lower = height[left]
left += 1
else:
lower = height[right]
right -= 1
level = max(lower, level)
total += level - lower
print("lower", lower)
print("total", total)
return total
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
print(trap(height))
| true |
6842fe3c8db077be3e54baab2058ec882cd7c597 | guyimin/python-tutorial-by-Vamei | /3.5包裹传递.py | 456 | 4.1875 | 4 | # coding=utf-8
#!/usr/bin/env python
#包裹传递用于用户不知道参数个数的情况
def func(*name):
print type(name)
print name
# 按照位置传入tuple
func(1,4,6)
func(5,6,7,1,2,3)
def func1(**dict):
print type(dict)
print dict
#按照关键词传入dic
func1(a=1,b=9)
func1(m=2,n=1,c=11)
#difference between * and **
def func2(a,b,c):
print a,b,c
args = (1,3,4)
func2(*args)
dict = {'a':1,'b':2,'c':3}
func2(**dict) | false |
1e0225bc030d7c718fe15296109c28a0d9c4134b | zhibosheng/6212algorithms | /chapter1/insertionsert.py | 294 | 4.125 | 4 | #Uses python3
def InsertionSert(arr):
length = len(arr)
for j in range(1,length):
key = arr[j]
i = j - 1
while i >= 0 and arr[i] > key:
arr[i+1] = arr[i]
i -= 1
arr[i+1] = key
return arr
if __name__ == "__main__":
arr = [5,6,8,2,3]
result = InsertionSert(arr)
print(result) | false |
5b2f5770e980ebeca8a5944726065bb3dee8c0aa | karandevgan/Algorithms | /RadixSort.py | 971 | 4.125 | 4 | def get_nth_digit(num, n):
'''
This function returns the nth digit of a number num
n = digit which is required
num = number
'''
divisor = 10 ** n
dividend = num
new_dividend = dividend % divisor
return new_dividend / (divisor / 10)
def counting_sort(A, n):
count = [0] * 10
aux_list = [0] * len(A)
for num in A:
count[get_nth_digit(num, n)] += 1
for i in xrange(1,len(count)):
count[i] += count[i-1]
nth_digit = -1
for i in xrange(len(A)-1, -1, -1):
nth_digit = get_nth_digit(A[i], n)
aux_list[count[nth_digit]-1] = A[i]
count[nth_digit] -= 1
return aux_list
def radix_sort(A):
max_num = max(A)
max_digits = 0
while (max_num != 0):
max_digits += 1
max_num = max_num / 10
for i in xrange(1, max_digits+1):
B = counting_sort(A, i)
return B
A = [329, 457, 657, 839, 436, 720, 355]
A = radix_sort(A)
print A
| false |
ff83309a29010223b289355195fad25ac86d36c7 | karandevgan/Algorithms | /LargestNumber.py | 779 | 4.28125 | 4 | def compare(number, number_to_insert):
str_number_to_insert = str(number_to_insert)
str_number = str(number)
num1 = str_number + str_number_to_insert
num2 = str_number_to_insert + str_number
if num1 > num2:
return -1
elif num1 == num2:
return 0
else:
return 1
def largestNumber(A):
'''
Given a list of numbers, return the string arranging the numbers in
the given list forming largest number. Eg: A = [3,30,90,9], the function
should return 990330
'''
isAllZero = True
for num in A:
if num != 0:
isAllZero = False
if (isAllZero):
return '0'
A.sort(cmp=compare)
return ''.join([str(i) for i in A])
A = [3, 30, 34, 5, 9]
print largestNumber(A)
| true |
6b3c9e414503f3b249e372f690c97e6f8cd52d78 | Keikoyao/learnpythonthehardway | /Ex20.py | 881 | 4.25 | 4 | # -- coding: utf-8 --
from sys import argv
script, input_file = argv
#read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中
def print_all(f):
print (f.read())
#seek() 移动文件读取指针到指定位置
def rewind(f):
f.seek(0)
#readline() will read the file line by line as if there is a for next loop automatically vs readlines()一次读取整个文件
def print_a_line(line_count,f):
print (line_count,f.readline())
current_file = open(input_file)
print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")
rewind(current_file)
print("Let's print three lines:")
current_line = 1
print_a_line(current_line,current_file)
current_line += 1
print_a_line(current_line,current_file)
current_line += current_line + 1
print_a_line(current_line,current_file)
| true |
1a0260d0313bdf1d6c79434f2916383d54670312 | yusufcimenci/programlama_lab | /uzaktan_eğitim_hafta_4.py | 2,216 | 4.125 | 4 | #min_heapyfy(array,i) : bir dizinin i indeksindeki elemanı ile o elemanın sağındaki ve solundaki elamanlan büyüklük kıyaslaması yapar. Küçük olanı üste çıkartır. diziyi heap yapısına çevirir
#build_min_heapy(array) : aldığı dizinin yarısından itibaren geriye doğru kontrol edee ve bütün diziyi MinHeap düzenine sokar.
#heapsort(array) : bir heap yapısını küçükten büyüğe sıralar
#insertItemToHeap(MinHeapyArray,i) : Bir heapm in heap algoritmasına uygun bir şekilde eleman ekler.
#removeItemFrom(myheap_1) : Parametre olarak aldığı MinHeap düzenin de ki array'in son elemanını siler.
def min_heapyfy(array,i):
left = 2*i+1
right = 2*i+2
length = len(array)-1
smallest = i
if left<=length and array[i]>array[left]:
smallest = left
if right<=length and array[smallest]>array[right]:
smallest = right
if smallest != i:
array[i],array[smallest] = array[smallest],array[i]
min_heapyfy(array,smallest)
def build_min_heapy(array):
for i in reversed(range(len(array)//2)):
min_heapyfy(array,i)
my_array_1 = [8,10,3,4,7,15,1,2,16]
min_heapyfy(my_array_1,4)
print(my_array_1)
my_array_1 = [8,10,3,4,7,15,1,2,16]
build_min_heapy(my_array_1)
print(my_array_1)
def heapsort(array):
array = array.copy()
build_min_heapy(array)
sorted_array = []
for _ in range (len(array)):
array[0],array[-1] = array[-1],array[0]
sorted_array.append(array.pop())
min_heapyfy(array,0)
return sorted_array
Sorted_Array = heapsort(my_array_1)
print(Sorted_Array)
def insertItemToHeap(MinHeapy_array,item):
MinHeapy_array.append(item)
i = len(MinHeapy_array)-1
if i<=0:
return
parent = (i-1)//2
while parent>=0 and MinHeapy_array[parent] > MinHeapy_array[i]:
MinHeapy_array[parent],MinHeapy_array[i] = MinHeapy_array[i],MinHeapy_array[parent]
i = parent
parent = (i-1)//2
def removeItemFrom(myheap_1):
index = len(myheap_1)
if index<=0:
print("heap zaten boş")
return
myheap_1.pop()
insertItemToHeap(my_array_1,5)
print(my_array_1)
removeItemFrom(my_array_1)
print(my_array_1)
| false |
33e1e11d95b94d22e1fc939c716cd8251d04b034 | TwoChill/Learning | /Learn Python 3 The Hard Way/ex34 - Accessing Elements of Lists.py | 2,096 | 4.21875 | 4 | # Remember, if it says "first," "second," then it's using ORDINAL, so subtract 1.
# If it gives you CARDINAL, like "The animal at 1", then use it directly.
# Check later with Python to see if you were correct.
animal = ['bear','python3.7', 'peacock', 'kangaroo', 'whale', 'platypus']
# Q1. The animal at 1. <-- CARDINAL
# A. The animal at 1 is the 2nd animal and is a python3.7..
# The 2nd animal is at 1 and is a;
# PYTHON3.7
print("Q1: >>:",animal[1] )
# Q2. The third (3rd) animal. <-- ORDINAL
# A. The third (3rd) animal is at 2 and is a peacock.
# The animal at 2 is the 3rd animal and is a;
# PEACOCK
print("Q2: >>:",animal[(3 -1)] )
# Q3. The first (1st) animal. <-- ORDINAL
# A. The first (1st) animal is at 0 and is a bear.
# The animal at 0 is the 1st animal and is a;
# BEAR
print("Q3: >>:",animal[(1 -1)] )
# Q4. The animal at 3. <-- CARDINAL
# A. The animal at 3 is the 4th animal and is a kangaroo.
# The 4th animal is at 3 and is a;
# KANGAROO
print("Q4: >>:",animal[3] )
# Q5. The fifth (5th) animal. <-- ORDINAL
# A. The fifth (5th) animal is at 4 and is a whale.
# The animal at 4 is the 5th animal and is a;
# WHALE
print("Q5: >>:",animal[(5 -1)] )
# Q6. The animal at 2. <-- CARDINAL
# A. The animal at 2 is the 3rd animal and is a peacock.
# The 3rd animal is at 2 and is a;
# PEACOCK
print("Q6: >>:",animal[2] )
# Q7. The sixth (6th) animal. <-- ORDINAL
# A. The sisth (6th) animal is at 5 and is a platypus.
# The animal at 5 is the 6th animal and is a;
# PLATYPUS
print("Q7: >>:",animal[(6 -1)] )
# Q8. The animal at 4. <-- CARDINAL
# A. The animal at 4 is the 5th animal and is a whale.
# The 5th animal is at 4 and is a;
# WHALE
print("Q8: >>:",animal[4] )
| true |
2ffa957733ffcd46c2fd448b75f6bbe9c64043ec | TwoChill/Learning | /Learn Python 3 The Hard Way/ex32 - Loops and Lists.py | 1,770 | 4.5625 | 5 | hair = ['brown', 'blond', 'red']
eye = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print(f'This is count {number}')
# same as above
for fruit in fruits:
print(f'A fruit of type: {fruit}')
# als we can go through mixxed lists too.
# notice we have to use {} since we don't know what's in it
for i in change:
print(f'I got {i}')
# we can also build lists, first start with an empty one.
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0,6):
print(f'Adding {i} to list.')
# append is a function that lists understand.
elements.append(i)
# now we can print them out too
for i in elements:
print(f'Element was: {i}')
# Q. Could you have avoided that for-loop on line 27 and just assigned range(0,6) directly to elements?
# No, that would just show the tekst range(0,6)
# Q. What other operations can you do to lists besides append?
# .append() -> Adds an item to a list.
# .clear() -> Removes all item in a list
# .copy() -> Returns a shallow copy of itself
# .count() -> Return a number of occurrences in a list
# .extend() -> Extend list by appending elements from the iterable.
# .index() -> Return first index of value.
# .insert() -> Insert object before index.
# .pop() -> Remove and return item at index (default last).
# .remove() -> Remove first occurrence of value.
# .reverse() -> Reverse items in a list.
# .sort() -> Sorts items in a list alphabetically.
| true |
545cbfef3ca36549f96c421a54fafc0c0c92d318 | TwoChill/Learning | /Learn Python 3 The Hard Way/ex15 - Reading Files.py | 1,845 | 4.625 | 5 | # This line imports the variable argument argv from the sys module.
from sys import argv
# These are the TWO command line arguments you MUST put in when running the script.
script, filename = argv
# This line opens the filename argument and puts it content in a variable.
txt = open(filename)
print("\n\nTHIS IS THE ARGV METHODE TO OPEN A FILE\n")
# This line prints out the name of the filename.
print(f"Here's your file {filename}:\n ")
# This line prints out the txt variable by calling the .read() function.
print(txt.read())
# # This line asked the user to put in the filename again.
# print("Type the filename again: ")
# #This line creates a variable unnoticable to the user.
# file_again = input('>')
#
# # This line uses the previous variable to open the typed in filename
# # and places this in a second variable.
# txt_again = open(file_again)
#
# # This line prints out the second variable which contains the ex15_sample.txt
# print(txt_again.read())
# txt_again.close()
### EX QUESTION ###
# Remove line 18 to 29
# Use only input and try the script that way.
print("\nTHIS IS THE INPUT METHODE TO OPEN A FILE\n")
file_name = input('What is the name of the txt file?: ')
print("\nHere's your filename:", str(file_name), "\n")
txt = open(file_name) # Here Python makes a "file object"
print(txt.read()) # This is were the file is being read and printed.
txt.close() # This code closes the file,
# Why is one way of getting the filename better that another?
# Michael: I think the use of the input function instead of the arvg
# is better because it only uses the input from a user.
# The user doesn't start this program from a terminal,
# thus it can't put in the filename before the program runs.
# On the other hand I think the agvr METHODE uses less code and probably uses
# less computing power.
| true |
4c7fdd6fe35f53ac8a12e8b3a3c69a64e08b3b28 | cazzara/mycode | /random-stdlib/use-random.py | 2,112 | 4.65625 | 5 | #!/usr/bin/env python3
import random
## Create a random number generator object
# This can be used to instantiate multiple instances of PRNGs that are independent of one another and don't share state
r = random.Random()
## Seed random number generator
# This initializes the state of the PRNG, by default it uses the current system time
# Calling this function isn't entirely necessary because the seed function is called when the Random object is created
r.seed()
print("[+] Initialized a PRNG using default seed (system time)")
## Optionally you can specify the source of randomness (os.urandom) or pass in a str, int or bytes like object
# r.seed('banana')
## randrange(start, stop) -- Select a random element from range(start, stop)
print("[+] Print 5 random numbers between 1 and 10 using r.randrange(1, 11)")
for i in range(5):
print("{} ".format(r.randrange(1, 11)), end='') # Prints a number between 1 and 10
print()
## randint(a, b) -- return a random int N such that a <= N <= b, basically like saying randrange(a, b+1)
print("[+] Print 5 random numbers between 1 and 10 using r.randint(1, 10)")
for i in range(5):
print("{} ".format(r.randint(1, 10)), end='')
print()
flavors = ['apple', 'kiwi', 'orange', 'grape', 'strawberry']
print("[+] List of items (flavors):")
print(flavors)
## choice(seq) -- Returns a random element from a non-empty sequence
print("[+] Select a random element from a list using r.choice(flavors)")
print(r.choice(flavors)) # Prints a random flavor from the list
## shuffle(list) -- shuffles a list in place
print("[+] Use r.shuffle(flavors) to randomly redistribute items in a list")
r.shuffle(flavors)
print(flavors)
## sample(population, k) -- returns a list of k elements from a population, sampling without replacement
print("[+] Select k elements from a range or collection (w/o replacement) using r.sample(l, 10)")
l = range(1, 101)
print(r.sample(l, 10)) # print 10 random numbers from 1 - 100
## random() -- returns a random float in the range [0.0, 1.0)
print("[+] Print 5 random floats using r.random()")
for i in range(5):
print(r.random())
| true |
8068f6de2b10e0d0673a0d96f8a62135223624f7 | cazzara/mycode | /if-test2/if-test2.py | 380 | 4.1875 | 4 | #!/usr/bin/env python3
# Author: Chris Azzara
# Purpose: Practice using if statements to test user input
ipchk = input("Set IP Address: ")
if ipchk == '192.168.70.1':
print("The IP Address was set as {}. That is the same as the Gateway, not recommended".format(ipchk))
elif ipchk:
print("The IP Address was set as {}".format(ipchk))
else:
print("No IP Address provided")
| true |
5eca3115baaf3a1f4d09a92c3e8bef73b5e655e8 | cazzara/mycode | /datetime-stdlib/datetime-ex01.py | 931 | 4.28125 | 4 | from datetime import datetime # required to use datetime
## WRITE YOUR OWN CODE TO DO SOMETHING. ANYTHING.
# SUGGESTION: Replace with code to print a question to screen and collect data from user.
# MORE DIFFICULT -- Place the response(s) in a list & continue asking the question until the user enters the word 'quit'
startTime = datetime.now() # returns the time of right now from the datetime object
# Note that datetime is an object, not a simple string.
## Explore the statrTime object
print('The startTime hour is: ' + str(startTime.hour))
print('The startTime minute is: ' + str(startTime.minute))
print('The startTime day is: ' + str(startTime.day))
print('The startTime year is: ' + str(startTime.year))
print("This is how long it takes Python to count to 50:")
for i in range(50):
pass
## Figure out how long it took to do that something
print('The code took: ' + str(datetime.now() - startTime) + ' to run.')
| true |
1ed15bd4d250bfc4fc373c26226f84f83c40cdcd | shishir7654/Python_program-basic | /listcomprehension1.py | 513 | 4.375 | 4 | odd_square = [x **2 for x in range(1,11) if x%2 ==1]
print(odd_square)
# for understanding, above generation is same as,
odd_square = []
for x in range(1, 11):
if x % 2 == 1:
odd_square.append(x**2)
print( odd_square)
# below list contains power of 2 from 1 to 8
power_of_2 = [2 ** x for x in range(1, 9)]
print (power_of_2 )
string = "my phone number is : 11122 !!"
print("\nExtracted digits")
numbers = [x for x in string if x.isdigit()]
print (numbers )
| true |
c084419e361233b87f85c9a688e29f6471376579 | brennanmcfarland/physics-class | /18-1a.py | 1,469 | 4.125 | 4 | import matplotlib.pyplot as plt
import math
def graphfunction(xmin,xmax,xres,function,*args):
"takes a given mathematical function and graphs it-how it works is not important"
x,y = [],[]
i=0
while xmin+i*xres<=xmax:
x.append(xmin+i*xres)
y.append(function(x[i],*args))
i+=1
return [x,y]
def iterateX(xn,yn,zn,a,b,c,dt):
"iterate for x"
return xn+a*(yn-xn)*dt
def iterateY(xn,yn,zn,a,b,c,dt):
"iterate for y"
return yn+(-yn+b*xn-xn*zn)*dt
def iterateZ(xn,yn,zn,a,b,c,dt):
return zn+(-c*zn+xn*yn)*dt
#HERE IS WHERE THE PROGRAM STARTS:
#iterate 100 times:
iterations = 100
#create our list of n integers and configure the axes:
n = list(range(0,iterations+1))
#plt.axis([0,len(n)-1,0,1])
#give it our initial variables:
x = [0]
y = [10]
z = [0]
dt = .01
a = 10
b = 28
c = 8/3
#for 100 iterations, find the next x and y by iterating:
for i in range(0,iterations):
x.append(iterateX(x[i],y[i],z[i],a,b,c,dt))
y.append(iterateY(x[i],y[i],z[i],a,b,c,dt))
z.append(iterateZ(x[i],y[i],z[i],a,b,c,dt))
#plot the approximation:
plt.plot(n,x)
#reset variables
x = [0]
y = [11]
z = [0]
dt = .01
a = 10
b = 28
c = 8/3
#for 100 iterations, find the next x and y by iterating:
for i in range(0,iterations):
x.append(iterateX(x[i],y[i],z[i],a,b,c,dt))
y.append(iterateY(x[i],y[i],z[i],a,b,c,dt))
z.append(iterateZ(x[i],y[i],z[i],a,b,c,dt))
#plot the approximation:
plt.plot(n,x)
plt.show() | true |
65a294810e1afc9d10fa24f84d8a4d60b5ec02c3 | jle33/PythonLearning | /PythonMasterCourse/PythonMasterCourse/GenetratorExample.py | 1,494 | 4.25 | 4 | import random
#Generator Example
def get_data():
"""Return 3 random integers between 0 and 9"""
print("At get_data()")
return random.sample(range(10), 3)
def consume():
"""Displays a running average across lists of integers sent to it"""
running_sum = 0
data_items_seen = 0
print("At top of consume()")
while True:
print("Calling consume() Yield")
data = yield #Saves current state and sends control back to the caller. Resumes at this spot when a callee calls send #Resumes here
print("At consume() after send({}) was called".format(data))
data_items_seen += len(data)
running_sum += sum(data)
print('The running average is {}'.format(running_sum / float(data_items_seen)))
def produce(consumer):
"""Produces a set of values and forwards them to the pre-defined consumer
function"""
print("At top of produce()")
while True:
data = get_data()
print('Produced {}'.format(data))
print("Before consumer.send({}) is called".format(data))
consumer.send(data) #Saves current state and sends control to consumer
print("Calling produce() Yield") #Resumes here
yield
print("At produce() after next(producer) is called")
if __name__ == '__main__':
consumer = consume()
print("Before consumer.send(none)")
consumer.send(None)
producer = produce(consumer)
for _ in range(10):
print('Producing...')
next(producer) | true |
218254f6a4c1152326423160bebdb9d8461d05a2 | jodaz/python-sandbox | /automate-boring-stuff-python/tablePrinter.py | 1,093 | 4.34375 | 4 | #! python3
# tablePrinter.py - Display a list of lists of strings in
# a well-organized table.
table_data = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def print_table(main_arr):
col_widths = [0] * len(main_arr)
# Look for largest str length and save it in a column
for single_arr in main_arr:
curr_index = main_arr.index(single_arr)
for string in single_arr:
if len(string) > col_widths[curr_index]:
col_widths[curr_index] = len(string)
# Create a table from array `(x, y)` => `(y, x)`
table = []
for x in range(len(main_arr[0])):
temp_arr = []
for y in range(len(main_arr)):
temp_arr.append(main_arr[y][x])
table.append(temp_arr)
temp_arr = []
# Print pretty table
for arr in table:
for string in arr:
str_index = arr.index(string)
print(string.rjust(col_widths[str_index] + 1), end='')
print()
print_table(table_data) | true |
b3bba5c4526cff24bd9b71a60aadddcf6e623228 | jodaz/python-sandbox | /automate-boring-stuff-python/strongPassword.py | 424 | 4.34375 | 4 | #! python3
# strongPassword.py - Find is your password is strong.
import re
password = input('Introduce your password: ')
find_upper = re.compile(r'[A-Z]').findall(password)
find_lower = re.compile(r'[a-z]').findall(password)
find_d = re.compile(r'\d').search(password)
if find_upper and find_lower and find_d and len(password) >= 8:
print('Your password is strong.')
else:
print('Your password is NOT strong.')
| true |
98f72a0486ba5cc22b42028c6bb0cd5e79ca2597 | Peterbamidele/PythonDeitelChapterOneExercise | /2.3 Fill in the missing code.py | 394 | 4.125 | 4 | """(Fill in the missing code) Replace *** in the following code with a statement that
will print a message like 'Congratulations! Your grade of 91 earns you an A in this
course' . Your statement should print the value stored in the variable grade :
if grade >= 90"""
#Solution
grade = 90
if grade >= 90:
#print("Congratulations! Your grade of 91 earns you an A in this course") | true |
201a2cbfa51168e159fae14bf438adb71c2b129e | cmdellinger/Code-Fights | /Interview Practice/01 Arrays/isCryptSolution.py | 1,213 | 4.1875 | 4 | """
Codefights: Interview Prep - isCryptSolution.py
Written by cmdellinger
This function checks a possible solution to a cryptarithm. Given a solution as a list of character pairs (ex. ['A', '1']), the solution is valid of word_1 + word_2 == word_3 once decoded.
See .md file for more information about cryptarithm and problem constraints.
"""
def isCryptSolution(crypt, solution):
''' checks that list of pairs is a solution for 3 word cryptarithm;
see problem for more details '''
# change list of pairs to dictionary
dictionary = dict(solution)
# helper functions for map
def str_decode(string = ''): #-> string
''' changes values in string according to key,value pair '''
return ''.join([dictionary[letter] for letter in string])
def lead_zeros(string = ''): #-> boolean
''' checks if a string of numbers has no lead zero '''
return len(string) == len(str(int(string)))
# decode crypt values
decoded = map(str_decode, crypt)
# check that no leading zeros and word_1+word_2==word_3
return all(map(lead_zeros, decoded)) and int(decoded[0]) + int(decoded[1]) == int(decoded[2])
if __name__ == '__main__':
print(__doc__)
| true |
b3ea4b626b6afb470c37d082edd5a451c4601ae3 | LilCharles/ExamenLP | /EAEXAMEN.py | 254 | 4.15625 | 4 | lista = []
n = int(input(print("ingrese el largo de la lista: ")))
while n < 1:
n = input(print("ingrese el largo de la lista: "))
for i in range(2, n*2, 2):
numero = i**3
lista.append(int(numero))
print(lista[0])
print(lista[1:-1])
print(lista[-1])
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.