blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
22afc903d5165e253d50a10862ba8f994f6b5081 | johnnymcodes/cs131b_python_programming | /5_iteration/print_backwards.py | 275 | 4.15625 | 4 |
string = input('enter a string ')
print(string)
print(type(string))
backwardsString = ''
def print_backwards(string):
n = len(string)-1
while n > -1:
backwardsString += string[i]
n = n-1
print(backwardsString)
print_backwards(string)
| false |
ba5f177e8ed7dff0164f72206401d5dd35ab690a | johnnymcodes/cs131b_python_programming | /4_functions/w10exhand.py | 1,504 | 4.21875 | 4 | # Write a program that expects numeric command line arguments and calls
# functions to print descriptive statistics such as the mean, median,
# mode, and midpoint.
# Week 9 : Severance 4
import sys #expects numeric command line arguments
cmarg = sys.argv[1:] #returns a list of cmd arguments
numlist = list()
for arg in cmarg:
try:
number = float(arg)
numlist.append(number)
# except:
# continue
except Exception as err:
print(arg, ' is not a number')
print(err)
print()
print(numlist)
def mode(numlist):
mode = 0
counts = dict()
for number in numlist:
if number not in counts:
counts[number] = 1
else:
counts[number] += 1
lst = list()
for number, count in list(counts.items()):
lst.append((count, number))
lst.sort(reverse=1)
for count, number in lst[:1]:
mode = number;
print(mode, " is the mode appearing ", count, " times")
return mode;
def median(numlist):
numlist.sort()
middle = int(len(numlist)/2)
median = numlist[middle]
print('The median is : ', median)
return median
def midpoint(numlist):
maxnum = max(numlist)
minnum = min(numlist)
midpoint = (maxnum-minnum)/2
print('The midpoint is : ', midpoint)
def mean(numlist):
sumnum = sum(numlist)
mean = sumnum/len(numlist)
print('The mean is : ', mean)
mode(numlist)
median(numlist)
midpoint(numlist)
mean(numlist) | true |
87f7b24055a392eb6a29a2a72b8b9395b4c083fe | johnnymcodes/cs131b_python_programming | /6_strings/sortuserinput.py | 944 | 4.5625 | 5 | #intro to python
#sort user input
#write a program that prints out the unique command line arguments
#it receives, in alphabetical order
import sys
cmdarg = sys.argv[1:]
cmdarg.sort()
delimiter = ' '
if len(cmdarg) > 1:
joinstring = delimiter.join(sys.argv[1:])
print('this is your command argument ', joinstring)
joinstring = delimiter.join(cmdarg)
print('this is your command argument sorted ! ', joinstring, '\n')
print('this program prints your string in alphabetical order')
string = input('enter a string :')
splitstring = string.split() #creating a list using stirng method split()
print('this is your split string ', splitstring)
joinstring = delimiter.join(splitstring)
print('this is your split string list joined back ', joinstring)
splitstring.sort() #no return value for sorted, modifies data
joinstring = delimiter.join(splitstring)
print('this is your sorted string ! ', joinstring)
| true |
ff6e1c1d4887494c8ae8513f0f3b3e66dd895181 | MaximChernyak98/LP_homework | /lesson2/compare_str_if.py | 1,789 | 4.1875 | 4 | '''
Практика: Сравнение строк
Написать функцию, которая принимает на вход две строки
Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0
Если строки одинаковые, вернуть 1
Если строки разные и первая длиннее, вернуть 2
Если строки разные и вторая строка 'learn', возвращает 3
Вызвать функцию несколько раз, передавая ей разные параметры и выводя на экран результаты
'''
def get_user_str(str_number):
# get str from user
try:
entered_str = input(
f'Введите, пожалуйста, строку номер {str_number}: ')
return entered_str
# Question for Mary: what could be wrong?
# I can't imagine what problems there might be
except KeyboardInterrupt:
print('Прервано пользователем')
return 'Не выполнено'
def compare_two_str(string1, string2):
if type(string1) != str or type(string2) != str:
return 0
else:
if string1 == string2:
return 1
elif string1 > string2:
return 2
elif string1 != string2 and string2 == 'learn':
return 3
else:
return None
if __name__ == "__main__":
while input('Для начала работы нажмите Enter/ для завершения работы введите "хватит": ') != 'хватит':
str1 = get_user_str(1)
str2 = get_user_str(2)
print(compare_two_str(str1, str2))
| false |
8d88e73998d7d8bdfb3d323a963369c44aee27db | aliyakm/ICT_task1 | /3.py | 521 | 4.28125 | 4 | print("Please, choose the appropriate unit: feet = 1, meter = 2.")
unit = int(input())
print("Please, enter width and length of the room, respectively")
width = float(input())
length = float(input())
if unit == 1:
area = width*length
result = "The area of the room is {0} feets"
print(result.format(area))
elif unit == 2:
area = width*length
result = "The area of the room is {0} meters"
print(result.format(area))
else:
print("You didn't write a correct number of unit")
| true |
92827541e986f956574b4c50ae27ba757dc6a9a1 | tarcisiocsn/4epy | /dictionaries02.py | 1,774 | 4.25 | 4 | #Counting Pattern
#the general pattern to count the words in a line of the text is to split the line
#into words, then loop through the words and use a dictionary to track the count of
#each word independently
counts=dict()
print('Enter a line of text: ')
line=input('') #se não colocar a definição de line essa porra dá erro quando for printar
words=line.split() # quer dizer que o texto que foi colocado virá a tona ;)
print('Words: ', words)
print('Counting...')
for word in words:
counts[word]=counts.get(word,0)+1 #isso significa que voce add um novo elemento por isso o 0 ou add um já existente e soma 1 nele - ou seja, no texto terá palavras repetidas e outras que não são repetidas e essa formula se encaixa bem nessa opção
print('Counts',counts) #lembrar que na linha 13 eu to criando um dicionário no loop
#Definite Loops Dictionaries
counts={'fred':42, 'chuck':1, 'jan':100} # this is a dictionary
for key in counts:
print(key, counts[key])
#Even through dictionaries are not stored in order, we can write a 'for' loop that goes
#through all the entries in a dictionary - actually it goes through all of the keys in the
#dictionary and looks up the values.
#output ->
#jan 100
#chuck 1
#fred 42 lembrar que aqui a ordem nÃo importa
jjj={ 'chuck':1, 'fred':42, 'jan':100}
print(list(jjj))
#output -> [ 'jan', 'chuck', 'fred']
print(jjj.keys()) #aqui só printa os keys do dicionario
print(jjj.values()) #aqui só print the values of the dictionary
print(jjj.items()) #[{('jan:100), ('chuck':1 ), ( 'fred':42)}]
# se vc perceber voce faz uma lista com cada item - keys, values e both que é items
#BONUS : TWO ITERATION VALUES
jjj=jjj
for aaa,bbb in jjj items():
print(aaa,bbb)
#jan 100
#chuck 1
#fred 42
# aaa=keys and bbb=values
| false |
2f91d697437a7ae3ffb51c07443634f68505566b | androidgilbert/python-test | /ex33.py | 514 | 4.1875 | 4 |
def test_while(a,b):
numbers=[]
i=0
while i<a:
print "At the top is %d"%i
numbers.append(i)
i=i+b
print "numbers now:",numbers
print "at the bottom i is %d"%i
return numbers
def test_for(a):
numbers=[]
for i in range(0,a,3):
print "at the top is %d"%i
numbers.append(i)
print "numbers now:",numbers
print "at the bottom i is %d"%i
return numbers
tests=test_while(8,3)
abc=test_for(8)
print "the numbers:"
for num in tests:
print num
print "the abc:"
for a in abc:
print a | true |
00cf375c449164d643f12c421ffc3fbbde8a789e | androidgilbert/python-test | /ex30.py | 410 | 4.15625 | 4 | people=30
cars=40
buses=15
if cars>people:
print "we should take the cars"
elif cars<people:
print "we should not take the cars"
else:
print "we can't decide"
if buses>cars:
print "that is too many buses"
elif buses<cars:
print "maybe we could take the buses"
else:
print "we still can not decide"
if people>buses:
print "Alright,let us just take the buses."
else:
print "file,let us stay home then." | true |
3391a8aed49e4335f75ad4b18ac26639b9752b6e | JenySadadia/MIT-assignments-Python | /Assignment2/list_comprehension(OPT.2).py | 714 | 4.125 | 4 | print 'Exercise OPT.2 : List comprehension Challenges(tricky!)'
print '(1)'
print 'find integer number from list:'
def int_element(lists):
return [element for element in lists if isinstance(element, int)]
lists = [52,53.5,"grp4",65,42,35]
print int_element(lists)
print '(2)'
print 'Here the y = x*x + 1 and [x,y] will be:'
print ([[x,x*x+1] for x in range(-5,6) if 0 <= x*x + 1 <=10])
print '(3)'
print 'The posible solutions for [x,y] with radious 5'
print ([[x,y] for x in range (-5,6) for y in range(-5,6) if x*x + y*y == 25])
print '(4)'
print 'List comprehension for Celsius to Fahrenheit'
celsius = [22,28,33,35,42,52]
print ([fahrenhit *(9/5) + 32 for fahrenhit in celsius])
| true |
860251764c96cccf6db12d1695ae1774d9332dc4 | Tanner0397/LightUp | /src/chromosome.py | 2,288 | 4.125 | 4 | """
Tanner Wendland
9/7/18
CS5401
Missouri University of Science and Technology
"""
from orderedset import OrderedSet
"""
This is the class defintion of a chromosome. A chromosome has genetic code that ddetermines the phenotype of the population member (the placement of the bulbs).
The genetic code is a list of integer tuples, each tuple representing a bulb placement with the tupes being (row, col)
While each entry in the genetic code is independed (and unordered) from one another since no bulb placement directly determines the placement of an other bulb on the bulb,
I use an OrderedSet to remove duplicate entries to avoid have redundant genes, and to keep the list in order when remove duplicate genes.
"""
class chromosome:
"""
Chromosme constructor. No Paramaters
"""
def __init__(self):
self.genetic_code = []
"""
Paramaters: object, any object but for this class it will always be a tuple
Return: None
This function will append an object passed to it to the genetic code of the chromosome
"""
def append(self, object):
self.genetic_code.append(object)
"""
Paramters: None
Return: None
This function simply removes any duplicate entires within the chromosome, since no two bulbs can occupy the same panel
"""
def remove_duplicates(self):
#still use a list, but set removes the duplicate entries. Keep in order of list
self.genetic_code = list(OrderedSet(self.genetic_code))
"""functions defined for chromosome so that chromosomes acts similar to a list"""
def __getitem__(self, key):
return self.genetic_code[key]
def __setitem__(self, key, value):
self.genetic_code[key] = value
def __str__(self):
return str(self.genetic_code)
def __len__(self):
return len(self.genetic_code)
def __contains__(self, value):
return value in self.genetic_code
def length(self):
return len(self.genetic_code)
def remove_gene(self, gene):
#Since this fucntion is only used once when trying to remove dummy genes, if the gene is not present then ignore
try:
self.genetic_code.remove(gene)
except:
pass
| true |
3d66b0c6593a83435e0df5d2e132e8b504136e6c | antondelchev/Python-Basics | /Conditional-Statements-Advanced---Exercise/06. Operations Between Numbers.py | 877 | 4.21875 | 4 | number_one = int(input())
number_two = int(input())
action = input()
result = 0
if action == "+" or action == "-" or action == "*":
if action == "+":
result = number_one + number_two
elif action == "-":
result = number_one - number_two
elif action == "*":
result = number_one * number_two
if result % 2 == 0:
print(f"{number_one} {action} {number_two} = {result} - even")
else:
print(f"{number_one} {action} {number_two} = {result} - odd")
if action == "/" or action == "%":
if number_two == 0:
print(f"Cannot divide {number_one} by zero")
elif action == "/":
result = number_one / number_two
print(f"{number_one} {action} {number_two} = {result:.2f}")
elif action == "%":
result = number_one % number_two
print(f"{number_one} {action} {number_two} = {result}")
| false |
a221f1dd62fc93c85c1329c670fe4d330df35caa | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Hard_Problem004.py | 1,069 | 4.125 | 4 | import logging
'''This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.'''
def firstMissingPositiveInt(myArray):
''' Method to return the first positive integer missing from an array'''
myArray.sort()
lowestFound = 1
for i in myArray:
if i >= 1:
if i == lowestFound:
lowestFound = lowestFound + 1
elif i > lowestFound:
return lowestFound
return lowestFound
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
a = [3,4,-1,1]#2
result = firstMissingPositiveInt(a)
logging.debug(result)
a=[1,1,1,1,2,4,0]#3
result = firstMissingPositiveInt(a)
logging.debug(result) | true |
79dacd2b79eb76486bfcb0ad860b01eced6ff016 | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Hard_Problem012.py | 1,032 | 4.53125 | 5 | '''This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
'''
def stair_climb(n,s):
if n == 0: return 1
nums = [0] * (n+1)
nums[0] = 1
for i in range(1,n+1):
total = 0
for j in s:
if i-j >= 0: total += nums[i-j]
nums[i] = total
return nums[n]
if __name__ == '__main__':
print(stair_climb(0, [1,2]))
print(stair_climb(1, [1,2]))
print(stair_climb(2, [1,2]))
print(stair_climb(3, [1,2]))
print(stair_climb(5, [1,2]))
print(stair_climb(10, [1,2])) | true |
b075eaa1eb0118a9f0fd0e112b91f318e4a98a20 | Aifedayo/Logic | /palindrome.py | 346 | 4.375 | 4 | def palindrome(string):
'''
Python function that checks whether a word
or phrase is palindrome or not
'''
new_string = string.replace(' ','')
if new_string == new_string[::-1]:
print(f'{string} is a palindrome')
else:
print(f'{string} is not a palindrome')
palindrome(input('Enter a string here: '))
| true |
2b288e37ceb0c00528623ce6c863597d09aebfb8 | ish-suarez/afs-200 | /week5/function/function.py | 481 | 4.1875 | 4 | def step1():
user_input = []
print(f'I will be asking you for 3 numbers')
for i in range(3):
num = int(input(f'Give me a number: '))
user_input.append(num)
input_max = max(num for num in user_input)
input_min = min(num for num in user_input)
print(f'Your Numbers are: {user_input}. Calculating the max. ')
print(f'The Max from the numbers given is {input_max}')
print(f'The Min from the numbers given is {input_min}')
step1() | true |
affa4eda6861fe0c5a2e31f232d3714fa15d84e8 | ish-suarez/afs-200 | /week2/evenOrOdd/evenOrOdd.py | 1,078 | 4.28125 | 4 | # Getting input to determine if numbers are even or odd
def user_input_eve_or_odd():
number = int(input('Give me a number and I will tell you if it is even or odd? '))
check_if_even_or_odd = number % 2
if check_if_even_or_odd == 0:
print(f"{number} is Even")
else:
print(f"{number} is Odd")
user_input_eve_or_odd()
# Is 'Number' a multiple of 4
def is_number_multiple_of_4():
number = int(input('Give me a number and I will tell you if it is a multiple of 4... '))
if number % 4 == 0:
print(f"Yes, {number} is a multiple of 4")
else:
print(f"No, {number} is not a multiple of 4")
is_number_multiple_of_4()
# Does 'Num' divide evenly into 'Check'
def is_it_divisible():
num = int(input('Give me a number to be divided... '))
check = int(input(f"Give me a number that {num} will be divided by... "))
if num % check == 0:
print(f"The numbers {num} and {check} are Evenly Divisible")
else:
print(f"The numbers {num} and {check} are Not Evenly Divisible")
is_it_divisible()
| true |
4f22ae3685a8024e3a70f7721495510c0ca139db | maayan20-meet/meet2018y1lab5 | /fun2.py | 1,111 | 4.28125 | 4 | import turtle
turtle.goto(0,0)
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
direction = None
def up():
global direction
print("You pressed the up key.")
direction = UP
on_move()
def down():
global direction
print("you pressed the down key")
direction = DOWN
on_move()
def left():
global direction
print("you pressed the left key")
direction = LEFT
on_move()
def right():
global direction
print("you pressed the right key")
direction = RIGHT
on_move()
def space():
if turtle.isdown():
turtle.up()
else:
turtle.down()
turtle.onkey(up, "Up")
turtle.onkey(down, "Down")
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
turtle.onkey(space, "space")
turtle.listen()
def on_move():
x_change = 10
y_change = 10
(x,y) = turtle.position()
if direction == UP:
turtle.goto(x,y + y_change)
if direction == DOWN:
turtle.goto(x,y - y_change)
if direction == RIGHT:
turtle.goto(x + x_change, y)
if direction == LEFT:
turtle.goto(x - x_change, y)
| false |
1ee69b4669c48ad85dd511ae57d7d4125cf6f645 | VimleshS/python-design-pattern | /Strategy pattern/solution_1.py | 2,021 | 4.125 | 4 | """
All the classes must in a seperate file.
Problems in this approch.
Order Class
It is not adhering to S of solid principles
There is no reason for order class to know about shipper.
Shipping Cost
Uses a default contructor.
Uses the shipper type stored in a shipper class to calculate cost(number crunching)
It uses lots of elif..(which means something is wrong)
If we have to add a new shipper we have to add a new elif and write the private helper method to get the cost, which
violates the O in solid principles
In a last section were we instanciate the shippingcost calculator, we are programming to implementation not to a abstraction
which violates the D in solid priciples.
"""
class Order(object):
def __init__(self, shipper):
self._shipper = shipper
@property
def shipper(self):
return self._shipper
#
class Shipper(object):
fedex = 1
ups = 2
postal = 3
class ShippingCost(object):
def shipping_cost(self, order):
if order.shipper == Shipper.fedex:
return self._fedex_cost(order)
elif order.shipper == Shipper.ups:
return self._ups_cost(order)
elif order.shipper == Shipper.postal:
return self._postal_cost(order)
else:
raise ValueError('Invalid shipper %s', order.shipper)
def _fedex_cost(self, order):
return 3.00
def _ups_cost(self, order):
return 4.00
def _postal_cost(self, order):
return 5.00
order = Order(Shipper.fedex)
cost_calulator = ShippingCost() # <-- violates D
cost = cost_calulator.shipping_cost(order)
assert cost == 3.0
# Test UPS shipping
order = Order(Shipper.ups)
cost_calulator = ShippingCost()
cost = cost_calulator.shipping_cost(order)
assert cost == 4.0
# Test Postal Service shipping
order = Order(Shipper.postal)
cost_calulator = ShippingCost()
cost = cost_calulator.shipping_cost(order)
assert cost == 5.0
print('Tests passed') | true |
3947858a10bb6fe6e1f0549d39c60f70de70a696 | UmberShadow/PigLatin | /UmberShadow_Pig Latin.py | 989 | 4.5 | 4 | #CJ Malson
#March 6th, 2021
#Intro to Python Programming
#Professor Wright
#I don't understand pig latin at all. What is this??
#Program requests a word (in lowercase letters) as input and translates the word into Pig Latin.
#If the word begins with a group of consonants, move them to the end of the word and add "ay". For instance, "chip" becomes "ipchay".
#If the word begins with a vowel, add "way" to the end of the word. For instance, "else" becomes "elseway".
#Ask the user to kindly insert a word to translate to Pig.
word = input("Enter word to translate: ")
#vowel and consonant letters
vowel = ['a','e','i','o','u']
consonant = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
#when the first letter of a word is a vowel, add "way" to the end.
if word[0] in vowel:
print(word + "way")
elif word[0] and word[1] in consonant:
print(word[2:] + word[0:2] + "ay")
else:
print(word[1:] + word[0] + 'ay')
| true |
693aa7a983a83814395518f00d68d6345502694b | luqiang21/Hackerrank.com | /Cracking the Coding Interview/Davis'_Staricase.py | 1,891 | 4.1875 | 4 | '''
Davis' staircase, climb by 1, 2 or 3 steps when given n stairs
in a staircase
'''
import numpy as np
def staircase(n):
# this function is written based on discussion of this problem on
# the website
A = [1,2,4]
A.append(sum(A))
A.append(A[1] + A[2] + A[3])
M = np.array([[1,1,0],[1,0,1],[1,0,0]])
An = np.array([[A[4], A[3], A[2]], [A[3],\
A[2], A[1]], [A[2], A[1], A[0]]])
if n < 5:
return A[n-1]
else:
return np.dot(An, np.matrix(M)**(n-5)).item(0)
print staircase(1) # 1
print staircase(30) # 53798080
print staircase(36) # 2082876103
def staircase(n):
# Recursive
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
return staircase(n-1) + staircase(n-2) + staircase(n-3)
# same result, but take much longer time
print 'Recursive Approach'
print staircase(1) # 1
# print staircase(30) # 53798080
# print staircase(36) # 2082876103
memory = {1:1, 2:2, 3:4}
def staircase(n):
if n not in memory.keys():
memory[n] = staircase(n-1) + staircase(n-2) + staircase(n-3)
return memory[n]
# using memory, much more efficient
print staircase(1) # 1
print staircase(30) # 53798080
print staircase(36) # 2082876103
# DP approach
def staircase(n):
if n < 0:
return 0
elif n <= 1:
return 1
paths = [None] * (n + 1)
paths[0] = 1
paths[1] = 1
paths[2] = 2
for i in range(3, n + 1):
paths[i] = paths[i - 1] + paths[i - 2] + paths[i - 3]
return paths[n]
print 'DP'
print staircase(1) # 1
print staircase(30) # 53798080
print staircase(36) # 2082876103
# save space
def staircase(n):
if n < 0:
return 0
elif n <= 1:
return 1
paths = [1,1,2]
for i in range(3, n + 1):
count = paths[0] + paths[1] + paths[2]
paths[0] = paths[1]
paths[1] = paths[2]
paths[2] = count
return paths[2]
print 'Another DP save space version'
print staircase(1) # 1
print staircase(30) # 53798080
print staircase(36) # 2082876103 | true |
e5822481483705f34f2af0672ada9d3e81ed8af7 | jlesca/python-booleans | /values-booleans.py | 633 | 4.125 | 4 | # VALORES BOOLEANOS EN PYTHON
# En Python podemos usar operadores relacionales para comparar dos valores.
print(10 > 9) # Mostrará True
print(10 == 9) # Mostrará False
print(10 < 9) # Mostrará False
# Podemos hacer uso de un IF para comparar dos valores y ejecutar una instrucción si ese IF se cumple.
a = 10 # Creo la variable y su valor int
b = 9 # Creo la variable y su valor int
if a > b: # Si se cumple que A es mayor que B, que haga lo siguiente:
print("A is greater than B") # Que imprima este mensaje.
else: # Si no se cumple, que haga lo siguiente:
print("B is greater than A") # Que muestre este mensaje.
| false |
4bd415c085f450727517e81170243dac251f4643 | danilvr/python-practice | /extra_practice05/part1/doctest/doctest_example.py | 1,154 | 4.1875 | 4 | def p1(a, b, c):
"""
Установление по сторонам (a, b, c) треугольника его типа:
равносторонний, разносторонний, равнобедренный.
Примеры:
>>> p1(1, 1, 1)
'равносторонний'
>>> p1(3, 4, 5)
'разносторонний'
>>> p1(5, 5, 3)
'равнобедренный'
>>> p1(1, 0, -1)
'сторона не может быть меньше 0'
>>> p1(1, 2, 1)
'треугольник не существует'
:param a: первая сторона
:param b: вторая сторона
:param c: третья сторона
:return: тип треугольника
"""
if a <= 0 or b <= 0 or c <= 0:
return 'сторона не может быть меньше 0'
if a == b == c:
return 'равносторонний'
if a + b <= c or b + c <= a or a + c <= b:
return 'треугольник не существует'
if a == b or a == c or b == c:
return 'равнобедренный'
return 'разносторонний'
| false |
321cb60befeebd95889763e272177d7cdfd9f1a0 | sureshrmdec/algorithms | /app/dp/knapsack.py | 1,105 | 4.1875 | 4 | """
Given a weight limit for a knapsack, and a list of items with weights and benefits, find the optimal knapsack
which maximizes the benefit, whilee the total weight being less than the weight limit
https://www.youtube.com/watch?v=ipRGyCcbrGs
eg -
item 0 1 2 3
wt 5 2 8 6
benefit 9 3 1 4
wt limit = 10
soln: best items = 0 + 1 for benefit = 9 + 3 = 12 within a wt of 7
"""
def _find_best_knapsack(remaining_weight, wt_benefit_list, index, optimal_knapsack):
"""
:param remaining_weight integer
:param wt_benefit_tuple: list of tuple
:param index: index of current wt_benefit_list item being processed
:param optimal_knapsack: a tuple of (int[] knapsack_item_indices, benefit)
:return: a tuple of (list[], benefit) where list[] is all the items in the knapsack with total benefit
"""
def find_best_knapsack(weight_limit, wt_benefit_list):
"""
:param weight_limit: integer
:param wt_benefit_list: list of tuple with each tuple being (weight, benefit) pair
:return:
"""
return _find_best_knapsack(weight_limit, wt_benefit_list, 0, ([],0)) | true |
f45faa385782d01190945ab84805c8c3eabb9ad4 | martin-kar/project_euler | /p19_counting_sundays.py | 2,061 | 4.125 | 4 | """
Counting sundays
Problem 19
How many sundays fell on the first of the month during the twentieth
century (1 Jan 1901 to 31 Dec 2000)?
"""
DAYS_PER_WEEK = 7
SUNDAY = 7
DAYS_PER_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
MONTHS_PER_YEAR = 12
def get_days_this_month(month, year):
if is_leap_day(month, year):
return 29
else:
return DAYS_PER_MONTH[month - 1]
def is_leap_day(month, year):
return (month == 2) and (year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0))
def is_synday_the_first_this_month(day_of_week, day_of_month):
return (day_of_week == SUNDAY) & (day_of_month == 1)
def get_next_day_of_week(day_of_week):
if day_of_week == SUNDAY:
next_day_of_week = 1
else:
next_day_of_week = day_of_week + 1
return next_day_of_week
def should_increase_month(day_of_month, days_this_month):
return day_of_month + 1 > days_this_month
def should_increase_year(month):
return month + 1 > MONTHS_PER_YEAR
def get_next_date(year, month, day_of_month):
days_this_month = get_days_this_month(month, year)
if should_increase_month(day_of_month, days_this_month):
next_day_of_month = 1
if should_increase_year(month):
next_year = year + 1
next_month = 1
else:
next_year = year
next_month = month + 1
else:
next_day_of_month = day_of_month + 1
next_month = month
next_year = year
return next_year, next_month, next_day_of_month
def get_number_of_sundays_on_first_of_month():
day_of_week = 2
day_of_month = 1
year = 1901
month = 1
nbr_sundays_on_first_of_month = 0
while year <= 2000:
if is_synday_the_first_this_month(day_of_week, day_of_month):
nbr_sundays_on_first_of_month += 1
day_of_week = get_next_day_of_week(day_of_week)
year, month, day_of_month = get_next_date(year, month, day_of_month)
return nbr_sundays_on_first_of_month
print(get_number_of_sundays_on_first_of_month())
| false |
28d24e0531c3f15a5f79fd0501f8f58662452f0b | joaolrsarmento/university | /courses/CT-213/lab3_ct213_2020/hill_climbing.py | 1,841 | 4.1875 | 4 | from math import inf
import numpy as np
def hill_climbing(cost_function, neighbors, theta0, epsilon, max_iterations):
"""
Executes the Hill Climbing (HC) algorithm to minimize (optimize) a cost function.
:param cost_function: function to be minimized.
:type cost_function: function.
:param neighbors: function which returns the neighbors of a given point.
:type neighbors: list of numpy.array.
:param theta0: initial guess.
:type theta0: numpy.array.
:param epsilon: used to stop the optimization if the current cost is less than epsilon.
:type epsilon: float.
:param max_iterations: maximum number of iterations.
:type max_iterations: int.
:return theta: local minimum.
:rtype theta: numpy.array.
:return history: history of points visited by the algorithm.
:rtype history: list of numpy.array.
"""
# First guess
theta = theta0
history = [theta0]
# Number of iterations
num_iterations = 0
# Check stopping condition
while cost_function(theta) >= epsilon and num_iterations < max_iterations:
num_iterations += 1
# Starts the array best with None
best = np.array([None] * len(theta))
for neighbor in neighbors(theta):
# Checks if the best is None (is this the first attempt?) or
# the neighbor is better than best
if np.all(best == None) or cost_function(neighbor) < cost_function(best):
best = neighbor
# If there isn't a neighbor better than theta, return the answer
if cost_function(theta) < cost_function(best):
return theta, history
# Now, we should test the best
theta = best
# Stores this new theta
history.append(theta)
return theta, history
| true |
95bf38eccb1a70731cc9cc4602a440fdb98043dd | ranjanlamsal/Python_Revision | /file_handling_write.py | 1,891 | 4.625 | 5 | '''In write mode we have attributes such as :
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
'''
'''
in write mode:
.write() : which creates the file is not existed . If existed then override the file content
and replace them with the content given in argument.
'''
f = open("Ranjan1.txt","w")
#Ranjan.txt file doesnot exist in the python folder. It is still not created
f.write("Ranjan is a good boy\n")
#now a new file named Ranjan.txt is created with content passed in argument
f.write("Ranjan is not a good boy\n")
'''
Point to be noted: write attribute create new file if not existed and replace the content of the file
if it is already present in project directory. But if you use .write() attribute again
in the same bunch of code i.e without once closing the file pointer, new contents are appended in the
file rather than replacing the old content.
Now when the program is closed and again the file pointer for the same file is opened in new program
then the write attribute override the old content and replace them
'''
f.close()
'''In append mode
.write() attribute is used to append the content given in argument in the file.
this also creates a file if not existed but if existed then append the content in old contents
'''
f = open("Ranjan1.txt", "a")
f.write("Ranjan is a handsome muscular man.\n")
'''
If the file pointer is closed and then again opened in apend mode then the contents are appended in the file
'''
a = f.write("Hey Buddy")
#if we store this attribute then the nukber of characted passed as argument is stored in object
print(a)
f.close()
| true |
3867392dee2e78d71c9a8bf99e1372a46a0eb726 | beyondvalence/thinkpython | /tp.05.py | 1,537 | 4.15625 | 4 | #! Thinking Python, Chp05, conditionals and recursion
#5.1 modulus operator
print("5.1")
print("156%100=")
print(156%100)
#5.9 E2 stack diagrams for recursive functions
print("5.9 E2")
def do_n(f,n):
if n<=0:
return
f()
do_n(f, n-1)
def print_now(s='now'):
print(s)
do_n(print_now,6)
#5.11 keyboard input
print("5.11")
text=input('type a number here:\n')
print(text)
#5.14 exercises
#5.14 E3, Fermat's Last Theorem
def fermat_check(a=1,b=1,c=1,n=3):
a=int(input('a= '))
b=int(input('b= '))
c=int(input('c= '))
n=int(input('n= '))
if a < 1 or b < 1 or c < 1:
print("a,b,c need to be positive integers")
fermat_check()
elif n < 3:
print("n needs to be greater than 2:")
fermat_check()
left=a**n+b**n
right=c**n
yn = (left==right)
return yn
def fermat_prompt():
result = fermat_check()
if result:
print("Holy smokes, Fermat was wrong!")
return
else:
print("No, that doesn't work. Theorem still holds.")
text = input('Try again? ')
if text=='yes':
fermat_prompt()
else:
return
#5.14 E4, Triangles
def is_triangle(a=3,b=4,c=5):
a=float(input("a= "))
b=float(input("b= "))
c=float(input("c= "))
if a < 1 or b < 1 or c < 1:
print("a,b,c must be positive integers")
is_triangle()
elif (a >= b + c) or (b >= a + c) or (c >= a + b):
print("Sides values not viable")
is_triangle()
else:
print("Sides make a valid triangle!")
return True
if __name__ == "__main__":
print("5.14 E3, Fermat's Last Theorem")
fermat_prompt()
print("5.14 E4, Triangles")
is_triangle() | true |
d59b573a9bc93897e130ad223c08f0b22b99bf0b | ankarn/groupIII_twintrons | /groupIII_3'_motif_search.py | 2,605 | 4.125 | 4 | ################################################################################
#
# Search for Group III twinton 3' motifs
# ______________________________________
#
# A program to to find 3' motifs for group III twintrons, given the external
# intron in FASTA format.
#
# ** Program must be in same location as fasta file. **
#
# Assumption: only one sequence submitted in fasta file.
#
# by: Matthew Bennett, Michigan State University
#
################################################################################
# Function to complement a sequence
def complement(sequence):
complement = ""
for i in sequence:
if i == "A":
complement += "T"
elif i == "T":
complement += "A"
elif i == "C":
complement += "G"
elif i == "G":
complement += "C"
return complement
matches = [] #Blank list for potential 3' matches.
while True:
try:
file_nm = input("FASTA file containg your external intron: ")
file = open(file_nm, "r")
break
except FileNotFoundError:
print ("\n", "FASTA file not found", "\n", sep = "")
#First line in FASTA is sequence name, strip of white space and get rid of ">"
seq_name = file.readline().strip()[1:]
# Second fasta line is sequence, strip of white space
seq = file.readline().strip()
# Strip the first 5 bases and last 5 bases, they only apply to external intron
seq = seq[5:-5]
# Reverse the sequence
rev_seq = seq[::-1]
# iterate through sequence and find an "A" to look for pattern:
# abcdef (3–8 nucleotides) f'e'd' A c'b'a' (four nucleotides)
for i, base in enumerate(rev_seq):
if base == "A":
index = i
search_seq_rev = rev_seq[(index-3):index] + rev_seq[(index+1):(index+4)]
search_area_rev = rev_seq[(index+7):(index + 18)]
search_seq_rc = complement(search_seq_rev)
if len(search_seq_rev) == 6:
search_area = search_area_rev[::-1]
check = search_area.find(search_seq_rc)
if check != -1:
total_area_rev = rev_seq[(index-3):(index + 18)]
total_area = total_area_rev[::-1]
match_area = total_area[check:]
match = (match_area)
matches.append(match)
print ("\n", len(matches), " potential 3' motif(s) found in ",\
file_nm, ":", "\n", sep = "")
for i in matches:
print (i)
if len(matches) > 0:
print ("\n", "*** Remember to add 4 bases to the end of any accepted\
matching sequence ***", "\n", sep = "") | true |
ca55b480b5735b4bc0bcb9feb1bb810de93a1007 | andrewrisse/Exercises | /ArrayAndStringProblems/URLify.py | 1,727 | 4.1875 | 4 | """
URLify.py
Creator: Andrew Risse
Drew heavily from example 1.3 in "Cracking the Coding Interview" in attempt to understand and
write their Java version in Python.
This program replaces spaces in a string with '%20'.
Assumptions: the string has sufficient space at the end to hold the additional characters and we are given
the "true" string length.
"""
def URLify(str, trueLength):
numSpaces = countChar(str, 0, trueLength, ' ') # count number of spaces in string
newLength = trueLength - 1 + (numSpaces * 2) # requires 2 spaces to insert %20 since we already have a ' '
lst = list(str) # convert string into a list because Python strings are immutable
if newLength + 1 < len(str): #if there are extra spaces at the end of the string, don't replace those with %20, replace with null
lst[newLength + 1] = '\0'
oldLength = trueLength - 1 # adjust length for next for loop and the fact tha the first index is 0
# work from end of list to front
for oldLength in range(oldLength, -1, -1):
#replace spaces
if lst[oldLength] == ' ':
lst[newLength] = '0'
lst[newLength - 1] = '2'
lst[newLength - 2] = '%'
newLength -= 3
else: #copy character
lst[newLength] = lst[oldLength]
newLength -= 1
str =''.join(lst) #turn list back into a string
return str
# count how many target characters are in the string
def countChar(str, start, end, target):
count = 0
for i in range(start, end):
if (str[i] == target):
count += 1
return count
#test case
print(URLify ("Mr John Smith ", 13))
print(URLify (" This is a test ", 15))
| true |
ac4be20f003f5e94d72f2251cc53f7ef384d02f0 | chunhuayu/Python | /Crash Course/06. Operators.py | 616 | 4.3125 | 4 | # Multiply 10 with 5, and print the result.
>>> print(10*5)
# Divide 10 by 2, and print the result.
>>> print(10/2)
# Use the correct membership operator to check if "apple" is present in the fruits object.
>>> fruits = ["apple", "banana"]
>>> if "apple" in fruits:
print("Yes, apple is a fruit!")
# Use the correct comparison operator to check if 5 is not equal to 10.
>>> if 5 != 10:
print("5 and 10 is not equal")
# Use the correct logical operator to check if at least one of two statements is True.
>>> if 5 == 10 or 4 == 4:
print("At least one of the statements is true")
| true |
0d303b898e689b0460aecb8d16248106d3a0073e | chunhuayu/Python | /Crash Course/0702. Tuple.py | 2,436 | 4.78125 | 5 | # Tuple is immutable
# A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
# Create a Tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(thistuple)
('apple', 'banana', 'cherry')
# Access Tuple Items: You can access tuple items by referring to the index number, inside square brackets:
# Return the item in position 1:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(thistuple[1])
banana
# Loop Through a Tuple: You can loop through the tuple items by using a for loop.
# Iterate through the items and print the values:
>>> thistuple = ("apple", "banana", "cherry")
>>> for x in thistuple:
print(x)
# Check if Item Exists, To determine if a specified item is present in a tuple use the in keyword:
# Check if "apple" is present in the tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
# Tuple Length : To determine how many items a tuple has, use the len() method:
# Print the number of items in the tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(len(thistuple))
# Add Items: Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
# You cannot add items to a tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> thistuple[3] = "orange" # This will raise an error
>>> print(thistuple)
TypeError: 'tuple' object does not support item assignment
# Remove Items : You cannot remove items in a tuple.
# Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
# The del keyword can delete the tuple completely:
>>> thistuple = ("apple", "banana", "cherry")
>>> del thistuple
>>> print(thistuple) #this will raise an error because the tuple no longer exists
NameError: name 'thistuple' is not defined
# The tuple() Constructor: It is also possible to use the tuple() constructor to make a tuple.
# Using the tuple() method to make a tuple:
>>> thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
>>> print(thistuple)
('apple', 'banana', 'cherry')
>>> t[0] = 'NEW'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-97e4e33b36c2> in <module>()
----> 1 t[0] = 'NEW'
TypeError: 'tuple' object does not support item assignment
| true |
57c29ce26289441922f017c49a645f8cbe9ce17f | rajatpachauri/Python_Workspace | /While_loop/__init__.py | 260 | 4.25 | 4 | # while loop is mostly used for counting
condition = 1
while condition < 10:
print(condition)
condition += 1
# condition -= 1
# to create out own infinite loop
while True:
print('doing stuff')
# for breaking use control+c | true |
1aa840435f3eaabb240f81d193c62b3381f52110 | Aminaba123/LeetCode | /477 Total Hamming Distance.py | 1,306 | 4.1875 | 4 | #!/usr/bin/python3
"""
The Hamming distance between two integers is the number of positions at which
the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the
given numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010
(just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2)
= 2 + 2 + 2 = 6.
Note:
Elements of the given array are in the range of 0 to 10^9
Length of the array will not exceed 10^4.
"""
class Solution:
def totalHammingDistance(self, nums):
"""
Brute force, check every combination O(n^2 * b)
check bit by bit
For each bit, the distance for all is #0 * #1
O(n * b)
:type nums: List[int]
:rtype: int
"""
ret = 0
while any(nums): # any not 0
z, o = 0, 0
for i in range(len(nums)):
if nums[i] & 1 == 0:
o += 1
else:
z += 1
nums[i] >>= 1
ret += z * o
return ret
if __name__ == "__main__":
assert Solution().totalHammingDistance([4, 14, 2]) == 6
| true |
0674b8d7de1b0a1f417b11be2eac016d459c8be5 | Aminaba123/LeetCode | /063 Unique Paths II.py | 1,948 | 4.1875 | 4 | """
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
"""
__author__ = 'Danyang'
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
"""
dp
:param obstacleGrid: a list of lists of integers
:return: integer
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
# trivial
if obstacleGrid[0][0]==1 or obstacleGrid[m-1][n-1]==1:
return 0
path = [[0 for _ in range(n)] for _ in range(m)] # possible to optimize by [[0 for _ in range(n+1)]]
path[0][0] = 1 # start
# path[i][j] = path[i-1][j] + path[i][j-1]
for i in range(m):
for j in range(n):
if i==0 and j==0:
continue
if i==0:
path[i][j] = path[i][j-1] if obstacleGrid[i][j-1]==0 else 0
elif j==0:
path[i][j] = path[i-1][j] if obstacleGrid[i-1][j]==0 else 0
else:
if obstacleGrid[i][j-1]==0 and obstacleGrid[i-1][j]==0:
path[i][j] = path[i-1][j]+path[i][j-1]
elif obstacleGrid[i][j-1]==0:
path[i][j] = path[i][j-1]
elif obstacleGrid[i-1][j]==0:
path[i][j] = path[i-1][j]
else:
path[i][j]=0
return path[m-1][n-1]
if __name__=="__main__":
grid = [[0, 0], [1, 1], [0, 0]]
assert Solution().uniquePathsWithObstacles(grid)==0
| true |
a8e56295e5b3d81fc6b63eb549d4a4d4f51dd7ea | Aminaba123/LeetCode | /433 Minimum Genetic Mutation.py | 2,041 | 4.15625 | 4 | #!/usr/bin/python3
"""
A gene string can be represented by an 8-character long string, with choices
from "A", "C", "G", "T".
Suppose we need to investigate about a mutation (mutation from "start" to
"end"), where ONE mutation is defined as ONE single character changed in the
gene string.
For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
Also, there is a given gene "bank", which records all the valid gene mutations.
A gene must be in the bank to make it a valid gene string.
Now, given 3 things - start, end, bank, your task is to determine what is the
minimum number of mutations needed to mutate from "start" to "end". If there is
no such a mutation, return -1.
Note:
Starting point is assumed to be valid, so it might not be included in the bank.
If multiple mutations are needed, all mutations during in the sequence must be
valid.
You may assume start and end string is not the same.
"""
class Solution:
def is_neighbor(self, p, q):
diff = 0
for a, b in zip(p, q):
if a != b:
diff += 1
if diff > 1:
return False
return True
def minMutation(self, start, end, bank):
"""
BFS, record level and avoid loop
Similar to 127 Word Ladder
:type start: str
:type end: str
:type bank: List[str]
:rtype: int
"""
q = [start]
visited = {start}
lvl = 0
while q:
cur_q = []
for e in q:
if e == end:
return lvl
for t in bank:
if t not in visited and self.is_neighbor(e, t):
visited.add(t)
cur_q.append(t)
lvl += 1
q = cur_q
return -1
if __name__ == "__main__":
assert Solution().minMutation("AACCTTGG", "AATTCCGG", ["AATTCCGG","AACCTGGG","AACCCCGG","AACCTACC"]) == -1
assert Solution().minMutation("AACCGGTT", "AAACGGTA", ["AACCGGTA", "AACCGCTA", "AAACGGTA"]) == 2
| true |
64ebeedfbf3d242316451493e0407916896c2f77 | Aminaba123/LeetCode | /403 Frog Jump.py | 2,164 | 4.28125 | 4 | """
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The
frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river
by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.
If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can
only jump in the forward direction.
Note:
The number of stones is >= 2 and is < 1,100.
Each stone's position will be a non-negative integer < 231.
The first stone's position is always 0.
Example 1:
[0,1,3,5,6,8,12,17]
There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.
Return true. The frog can jump to the last stone by jumping
1 unit to the 2nd stone, then 2 units to the 3rd stone, then
2 units to the 4th stone, then 3 units to the 6th stone,
4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:
[0,1,2,3,4,8,9,11]
Return false. There is no way to jump to the last stone as
the gap between the 5th and 6th stone is too large.
"""
__author__ = 'Daniel'
class Solution(object):
def canCross(self, stones):
"""
F, step table
Let F[i] be stone at position i,
dp with a set as the table cell.
:type stones: List[int]
:rtype: bool
"""
F = {}
for stone in stones:
F[stone] = set()
F[0].add(0)
for stone in stones:
for step in F[stone]:
for i in (-1, 0, 1):
nxt = stone+step+i
if nxt != stone and nxt in F:
F[nxt].add(step+i)
return True if F[stones[-1]] else False
if __name__ == "__main__":
assert Solution().canCross([0, 2]) == False
assert Solution().canCross([0, 1, 3, 5, 6, 8, 12, 17]) == True
assert Solution().canCross([0, 1, 2, 3, 4, 8, 9, 11]) == False
| true |
24ba1fb74133913ff4642b3168f44b775cf64b7c | Aminaba123/LeetCode | /384 Shuffle an Array.py | 1,372 | 4.28125 | 4 | """
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array back to its original configuration [1,2,3].
solution.reset();
// Returns the random shuffling of array [1,2,3].
solution.shuffle();
"""
import random
__author__ = 'Daniel'
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type size: int
"""
self.original = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return list(self.original)
def shuffle(self):
"""
Returns a random shuffling of the array.
like shuffle the poker cards
in-place shuffling and avoid dynamic resizing the list
:rtype: List[int]
"""
lst = self.reset()
n = len(lst)
for i in xrange(n):
j = random.randrange(i, n)
lst[i], lst[j] = lst[j], lst[i]
return lst
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle() | true |
13684394a6e93a3c95c3c7916fcb88113a22e7a0 | Aminaba123/LeetCode | /088 Merge Sorted Array.py | 1,122 | 4.125 | 4 | """
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The
number of elements initialized in A and B are m and n respectively.
"""
__author__ = 'Danyang'
class Solution(object):
def merge(self, A, m, B, n):
"""
array, ascending order.
basic of merge sort.
CONSTANT SPACE: starting backward. Starting from the end.
:param A: a list of integers
:param m: an integer, length of A
:param B: a list of integers
:param n: an integer, length of B
:return:
"""
i = m-1
j = n-1
closed = m+n
while i >= 0 and j >= 0:
closed -= 1
if A[i] > B[j]:
A[closed] = A[i]
i -= 1
else:
A[closed] = B[j]
j -= 1
# either-or
# dangling
if j >= 0: A[:closed] = B[:j+1]
# if i >= 0: A[:closed] = A[:i+1]
| true |
36bd7b053f22dbde6145ee948b168bb114a1bcfe | Aminaba123/LeetCode | /225 Implement Stack using Queues.py | 1,673 | 4.28125 | 4 | """
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is
empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque
(double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
"""
__author__ = 'Daniel'
class Stack:
def __init__(self):
"""
initialize your data structure here.
One queue cannot mimic the stack, then you should use two queues.
"""
self.q = [[], []]
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
t = 0
if not self.q[t]:
t ^= 1
self.q[t].append(x)
def pop(self):
"""
:rtype: nothing
"""
t = 0
if not self.q[t]:
t ^= 1
while len(self.q[t]) > 1:
self.q[t^1].append(self.q[t].pop(0))
return self.q[t].pop()
def top(self):
"""
:rtype: int
"""
popped = self.pop()
t = 0
if not self.q[t]:
t ^= 1
self.q[t].append(popped)
return popped
def empty(self):
"""
:rtype: bool
"""
return not self.q[0] and not self.q[1]
| true |
85068b845fc62bc3ca6b9307072225de0f5d380f | Aminaba123/LeetCode | /353 Design Snake Game.py | 2,043 | 4.4375 | 4 | """
Design a Snake game that is played on a device with screen size = width x height.
"""
from collections import deque
__author__ = 'Daniel'
class SnakeGame(object):
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
:type width: int
:type height: int
:type food: List[List[int]]
"""
self.w = width
self.h = height
self.food = deque(food)
self.body = deque([(0, 0)])
self.dirs = {
'U': (-1, 0),
'L': (0, -1),
'R': (0, 1),
'D': (1, 0),
}
self.eat = 0
def move(self, direction):
"""
Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
:type direction: str
:rtype: int
"""
x, y = self.body[0]
dx, dy = self.dirs[direction]
x += dx
y += dy
fx, fy = self.food[0] if self.food else (-1, -1)
if x == fx and y == fy:
self.food.popleft()
self.eat += 1
else:
self.body.pop()
if (x, y) in self.body or not (0 <= x < self.h and 0 <= y < self.w):
# possible to use set to accelerate check
return -1
self.body.appendleft((x, y))
return self.eat
# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction)
if __name__ == "__main__":
game = SnakeGame(3, 2, [[1, 2], [0, 1]])
for char, expect in zip('RDRULU', [0, 0, 1, 1, 2, -1]):
assert game.move(char) == expect
| true |
0f0c2b71165908b69143488b544ec20e7192961b | jiankangliu/baseOfPython | /PycharmProjects/02_Python官方文档/一、Python初步介绍/03_Python控制流结构/3.2判断结构.py | 1,030 | 4.125 | 4 | #3.2.1 if-else语句
#例1 求较大值
num1=eval(input("Enter the first number: "))
num2=eval(input("Enter the second number: "))
if num1>num2:
print("The larger number is:",num1)
else:
print("The larger number is: ",num2)
#3.2.2 if语句
firstNumber=eval(input("Enter the first number: "))
secondNumber=eval(input("Enter the second number: "))
thirdNumber=eval(input("Enter the third number: "))
max=firstNumber
if secondNumber>firstNumber:
max=secondNumber
if thirdNumber>max:
max=thirdNumber
print("The largest number is: ",max)
#3.2.3 嵌套的if-else语句
#例4 灯标的意义
color=input("Enter a color (BLUE or RED): ")
mode=input("Enter a mode (STEADY or FLASHING): ")
result=""
color=color.upper()
mode=mode.upper()
if color=="BLUE":
if mode=="STEADY":
result="Clear View"
else:
result="Clouds Due"
else:
if mode=="STEADY":
result="Rain Ahead"
else:
result="Snow Ahead"
print("The weather forecast is",result)
| true |
3ba28ea233a3f3736bbcd8d520b3369f33ee379b | chaofan-zheng/tedu-python-demo | /month01/all_code/day09/demo07.py | 819 | 4.46875 | 4 | """
面向对象:软件编程思想
找谁 干嘛?
现实事物 -抽象-> 类(模板) -具体-> 对象
车 class Car: Car(xx,xx,xx)
车牌 京E0001
品牌 奔驰
颜色 白色
"""
# 创建类(抽象化)
class Wife:
"""
自定义类 - 老婆
"""
# 数据
def __init__(self, name, face_score=0, money=0):
self.name = name
self.face_score = face_score
# 创建参数快捷键:atl + 回车
self.money = money
# 行为 - 方法(函数)
def play(self):
print(self.name + "在玩")
# 创建对象(具体化)
jian_ning = Wife("建宁", 93, 10000000)
print(jian_ning.money)
jian_ning.play() # play(jian_ning)
| false |
a04882c6e51ff77d30d39c8f234e46d6f0ae9d75 | chaofan-zheng/tedu-python-demo | /month01/all_code/day04/demo13.py | 873 | 4.21875 | 4 | """
切片:定位多个元素
for number in range(开始,结束,间隔)
"""
message = "我是花果山水帘洞美猴王孙悟空"
# 写法1:容器名[开始: 结束: 间隔]
# 注意:不包含结束
print(message[2: 5: 1])
# 写法2:容器名[开始: 结束]
# 注意:间隔默认为1
print(message[2: 5])
# 写法3:容器名[:结束]
# 注意:开始默认为头
print(message[:5])
# 写法4:容器名[:]
# 注意:结束默认为尾
print(message[:])
message = "我是花果山水帘洞美猴王孙悟空"
# 水帘洞
print(message[5:8])
# 花果山水帘洞美猴王
print(message[2: -3])
# 空
print(message[1: 1])
# 是花果山水帘洞美猴王孙悟空
print(message[1: 100])
# 孙悟空
print(message[-3:])
print(message[:5])
# 特殊:空悟孙王猴美洞帘水山果花是我
print(message[::-1])
# 空孙猴洞水果是
print(message[::-2])
| false |
727b4ee599937e2177ffb98ca6ffe9ed13ae116d | chaofan-zheng/tedu-python-demo | /month01/all_code/day06/demo01.py | 1,504 | 4.34375 | 4 | """
笔试题:
请叙述元组与列表的区别.
答:内存存储机制不同.
元组采用按需分配的存储机制,节省内存.
列表 预留空间 + 自动扩容,操作灵活
面试题:
为什么要有元组(为什么要有不可变).
答:任何数据本质都可以理解为不可变,元组就是不可变数据.(计算机世界)
但是在实际应用中,需要不断存储新数据,所以Python提供了列表.
Python语言有哪些数据类型
答:只可变与不可变2种类型
常用的可变数据:列表...
不可变 :str,元组,数值(int,float),bool...
"""
# 创建
# 语法1: 元组名 = (数据1,数据2,数据3)
tuple01 = ("曹伟伟", "杨德义", "王杰")
# 语法2:元组名 = tuple(可迭代对象)
list01 = [10, 20, 30] # 用于存储计算过程中的数据
tuple02 = tuple(list01) # 用于存储最后结果
print(tuple02)
# 定位(读取)
print(tuple01[-1])
# 通过切片读取数据,会创建新容器
print(tuple01[:2])
# 遍历
for item in tuple01:
print(item)
for i in range(len(tuple01) - 1, -1, -1):
print(tuple01[i])
# 特殊1:如果元组中只有一个元素,必须加逗号
tuple03 = (10,)
print(type(tuple03))
# 特殊2:创建元组的括号,在没有歧义的情况下可以省略.
tuple04 = 10, 20, 30
print(tuple04)
# 特殊3:拆包
a, b, c = tuple04
a, b, c = [10, 20, 30]
a, b, c = "孙悟空"
print(a)
print(b)
print(c)
| false |
4ea129f839988825cb63b8fbb294dd8edadcb662 | chaofan-zheng/tedu-python-demo | /month01/all_code/day07/exercise09.py | 267 | 4.21875 | 4 | # 练习2:创建函数,在终端中打印矩形.
def print_rectangle(number):
for row in range(number):
if row == 0 or row == number - 1:
print("*" * number)
else:
print("*%s*" % (" " * (number - 2)))
print_rectangle(8) | false |
d2bdd6b93d56863575896542acf8995db880c5f4 | chaofan-zheng/tedu-python-demo | /month01/all_code/day11/exercise06.py | 645 | 4.4375 | 4 | """
练习:
创建子类:狗(跑),鸟类(飞)
创建父类:动物(吃)
体会子类复用父类方法
体会 isinstance、issubclass与type的作用.
"""
# 从思想层面讲:先有子再有父,从子 -泛化-> 到父
# 从编码层面讲:先有父再有子,从父 -特化-> 到子
class Animal:
def eat(self):
print("吃")
class Dog(Animal):
def run(self):
print("跑")
class Bird(Animal):
def fly(self):
print("飞")
a01 = Animal()
a01.eat()
d02 = Dog()
d02.eat()
print(isinstance(d02, Animal))
print(issubclass(Dog, Animal))
print(type(d02) == Dog)
| false |
52d27a07d787975725603b50590605b7463fe380 | chaofan-zheng/tedu-python-demo | /month01/all_code/day12/homework/exercise02.py | 645 | 4.125 | 4 | """
需求:小明使用手机打电话
划分原则:
数据不同使用对象区分 -- 小王/小孙...
行为不同使用类区分 -- 手机/卫星电话...
识别对象:
人类 手机
分配职责:
打电话 通话
建立交互:
人类 调用 手机
"""
class Person:
def __init__(self, name=""):
self.name = name
def call(self, communication):
print(self.name, "打电话")
communication.dialing()
class MobilePhone:
def dialing(self):
print("呼叫")
xm = Person("小明")
xm.call(MobilePhone())
| false |
be3e780e2aa09537a6a6df9e65bc5c15eb4da166 | chaofan-zheng/tedu-python-demo | /month01/all_code/day11/homework/exercise03.py | 1,351 | 4.15625 | 4 | """
5. 创建电脑类,保护数据在有效范围内
数据:型号, CPU型号, 内存大小, 硬盘大小
不超过10个字符 大于0 元组长度大于等于1
"""
class Computer:
def __init__(self, model_number="", cpu="", memory=0, hard_disk=()):
self.model_number = model_number
self.cpu = cpu
self.memory = memory
self.hard_disk = hard_disk
@property
def cpu(self):
return self.__cpu
@cpu.setter
def cpu(self, value):
if len(value) <= 10:
self.__cpu = value
else:
raise Exception("cpu星号过长")
@property
def memory(self):
return self.__memory
@memory.setter
def memory(self, value):
if value > 0:
self.__memory = value
else:
raise Exception("cpu星号过长")
@property
def hard_disk(self):
return self.__hard_disk
@hard_disk.setter
def hard_disk(self, value):
if len(value) >= 1:
self.__hard_disk = value
else:
raise Exception("硬盘数量必须大于等于1")
alienware = Computer("外星人ALW17M", "Intel i7", 16, (256, 1024))
print(alienware.model_number)
print(alienware.cpu)
print(alienware.memory)
print(alienware.hard_disk)
print(alienware.__dict__)
| false |
5a391b6015b94af3800dba89cf6ed07e94d1f445 | daniyaniazi/Python | /COLLECTION MODULE.py | 2,510 | 4.25 | 4 | """COLLECTION MODULE IN PYTHON """
#LIST TUPLE DICTIONARY SET ARE CONTAINER
#PYTHON HAS COLLECTION MODULE FOR THE SHORTCOMMING OF DS
#PRVIDES ALTERNATIVES CONTAINER OF BUILTIN DATA TYPES
#specializex collection datatype
"""nametupele(), chainmap, deque, counter, orderedDict, defaultdic , UserDict, UserList,UserString"""
"""** namedtuple()**"""
# return a tuple with named entry there will be named assigned to each value inside tuple to overcome the peoblem of acessing with the index
from collections import namedtuple
a=namedtuple('courses','name,technology')
b=a('machine learning','python')
print(b)
#using list
c=a._make(["artificial intelligence","python"])
print(c)
"""** deque**"""
#pronounced as deck
#is an optimised list to perform insertion and deletion easily
#way to precisely
from _collections import deque
l=['e','d','u','c','a','t','i','o','n']
d=deque(l)
print(d)
d.append("python") #at the end
print(d)
d.appendleft("version") #at the end
print(d)
d.pop()
print(d) #aT THE END REMOVE
d.popleft()
print(d)
"""**chain map **"""
#is a dictionary like class for creating a single view of multiple mapping
#return a list of several other dictionaries
from collections import ChainMap
dic1 ={1:"course",2:"python"}
dic2={3:"collection mpdule",4:"chainmap"}
cm=ChainMap(dic1,dic2)
print(cm)
"""Counter"""
#dictionary subclass for counting hashable objects
from collections import Counter
c1=[1,1,22,2,3,3,4,5,6,6,7,7,3,9]
c2=Counter(c1)
print(c2)
print(list(c2.elements())) #show elements and the times of their occurence
print(c2.most_common())
sub={3:1 , 6:1 , 22:1} #subtrac elemets times
print(c2.subtract(sub))
print(c2.most_common())
""""OrderedDict """
#dict subclass which remembers the order in which entries is done
#postion will not change
from collections import OrderedDict
od=OrderedDict()
od[1]="e"
od[2]="d"
od[3]="u"
print(od)
print(od.keys())
print(od.items())
print(od)
od[1]="k"
print(od)
""" defaultdic"""
#dic subclass which cALLS A FACTORY FUNCTION TO SUPPLY MISSING VALUE
#doesnt show any error when a missing key value is call in a dictionary
from collections import defaultdict
defdic=defaultdict(int)
defdic[1]='python'
defdic[2]='numpy'
defdic[3]='matplotlib'
print(defdic)
print(defdic[4]) #no error 0 o/p
#keyerror
""" UserDict """
#wrapper around dic object for easier dic sub classing
""" Userlist """
#wrapper around list object for easier lisxt sub classing
""" Userstring """
#wrapper around string object for easier string sub classing
| true |
6f6a30c997764bad22985c0a8053c88241f4f499 | themorsten/DataStructures | /DoublyLinkedList/DoublyLinkedList.py | 1,290 | 4.125 | 4 | class DoublyLinkedListNode:
def __init__(self,value):
self.value = value
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value): # добавить в конец
newNode = DoublyLinkedListNode(value)
if self.head: # список непустой
self.tail.next = newNode
newNode.prev = self.tail
self.tail = newNode
else: # список пустой
self.head = newNode
self.tail = newNode
def prepend(self, value): # добавить в начало
newNode = DoublyLinkedListNode(value)
if self.head: # список непустой
self.head.prev = newNode
newNode.next = self.head
self.head = newNode
else:
self.head = newNode
self.tail = newNode
def reverse(self): # разворот
headNode = self.head
while(self.head):
prevNode = self.head.prev
nextNode = self.head.next
self.head.prev = nextNode
self.head.next = prevNode
self.head = nextNode
self.head = self.tail
self.tail = headNode
def print(self):
currentNode = self.head
while(currentNode):
print(currentNode.value)
currentNode = currentNode.next
| false |
aca916cd7150ccdc1dc3ddad48f5b41d53007f7f | StealthAdder/SuperBasics_Py | /functions.py | 2,101 | 4.46875 | 4 | # function is collection of code
# they together work to do a task
# they are called using a function call.
# to create a function we use a keyword called "def"
# --------------------------------------------------
# create a function.
def greetings():
print("Hello Dude!")
greetings() #calling the function
# OUTPUT: Hello Dude!
# ---------------------------------------------------------------------------------------
# passing a parameter
def greetings(name): #here we are telling the function to use the argument "name" while calling the function.
print("Hello " + name)
greetings("StealthAdder") #calling the function with a parameter.
# OUTPUT: Hello StealthAdder
# --------------------------------------------------------------------------------------
# passing multiple parameters
def func1(para1, para2):
print("Going to print the first parameter here " + para1 + " the next over here " + para2)
func1("parameter1", "parameter2")
# OUTPUT: Going to print the first parameter here parameter1 the next over here parameter2
# ----------------------------------------------------------------------------------------------
# useful example printing name of that persons with dob
def greets(name, dob):
print("Hey " + name + ", You Birthday is " + dob)
greets("StealthAdder", "07Aug")
# OUTPUT:Hey StealthAdder, You Birthday is 07Aug
# ----------------------------------------------------------------------------------------------
# Return function in function
# Using return we return some imformation back from the function
# Nothing after return function inside a function will be execute, it just breaks the code.
def cube(num):
return num * num * num
print("Hey") #this is not going to be printed (code is out of reach)
result = cube(3) #value returned from cube() is saved to variable result.
print(result) #prints the value
print(str(result)) #can print even in string format.
# OUTPUT: 27
# ------------------------------------------------------------------------------------------------
| true |
89edd52a8e28902a6331f7d939e3a369e3e14e69 | Aravind-2001/python-task | /4.py | 242 | 4.15625 | 4 | #Python program to divided two numbers using function
def divided_num(a,b):
sum=a/b;
return sum;
num1=int(input("input the number one: "))
num2=int(input("input the number one :"))
print("The sum is",divided_num(num1,num2))
| true |
bf2443eb20578d0e4b5765abc5bd6d3c46fabdc6 | leelaram-j/pythonLearning | /com/test/package/lists.py | 1,231 | 4.125 | 4 | """
List in python
written inside []
sequence type, index based starts from 0
mutable
"""
a = [1, 2, 3, 4, 5]
print(a)
print(type(a))
print(a[1])
# array slicing
print("Slicing")
print(a[0:3])
print(a[2:])
print(a[:3])
print("-------------")
a = [1, "sample", True, 10.45, [1, 2, 3, 4]]
print(a)
print(type(a))
print(type(a[1]))
print(a[4][2])
print("-------------")
b = a.copy()
print(b)
print(a)
a.clear()
print(a)
print("-------------")
a = [10, 20, 30, 10, 20, 40, 50, 10]
print(a.count(10))
print(a.index(20))
print(len(a))
print(max(a))
print(min(a))
print(a)
a.pop(0) # values are removed based on index
print(a)
a.remove(10) # values are removed based on actual value
print(a)
print("-------------")
names = ["Ram"]
print(names)
names.append("Sam")
names.append("Kumar")
print(names)
name2 = ["Sara", "Mike"]
names.extend(name2)
print(names)
names.insert(0, "Kiran")
print(names)
print("-------------")
print(list(range(5)))
print(list("leelaram"))
a = [10,50,100, 25, 85]
print(a)
a.sort()
print(a)
a.sort(reverse=True)
print(a)
a = ["z", "a", "y", "b"]
a.sort()
print(a)
a = ["mango", "zebra", "apple"]
a.sort()
print(a)
a = ["mangoes", "zebra", "apples"]
a.sort(key=len)
print(a)
| true |
934f9b2581ab5fa583aaf274d068448b9cc4f0de | sharpchris/coding352 | /8.py | 2,259 | 4.375 | 4 | # Codebites URL: https://codechalleng.es/bites/21/
cars = {
'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
'Jeep': ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk', 'Hawktrailer']
}
space = '+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+'
# 1. Get all Jeeps
def get_all_jeeps(cars=cars):
#produces a list of jeeps
jeeps = cars['Jeep']
#converts list to string, ref: https://stackoverflow.com/questions/5618878/how-to-convert-list-to-string
jeeps_str = ', '.join(jeeps)
#returns the jeeps string
return jeeps_str
#calls the function
print(get_all_jeeps())
print(space)
# 2. Get the first car of every manufacturer
def get_first_of_type(cars=cars):
# loops through the cars dictionary and grabs the keys
first_cars = []
for key in cars.keys():
first_cars.append(cars[key][0])
return first_cars
print(get_first_of_type())
print(space)
# 3. Get all vehicles containing the string 'Trail' in their names
def get_trails(cars=cars):
# makes an empty string that we'll insert trail cars into
trail_cars = []
# loops through teh values in cars
for v in cars.values():
# loops through v, which is the list containing specific models
for i in v:
# Checks if "Trail" is included in name: ref: https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method
if "Trail" in i:
trail_cars.append(i)
elif "trail" in i:
trail_cars.append(i)
return trail_cars
print(get_trails())
print(space)
# 4. Sort the models (values) alphabetically
def sort_models(cars=cars):
# empty list to store all models
all_cars = []
# loop through car models and grab values
for v in cars.values():
# loop through list of cars and extract specific models
for i in v:
# push all models into single list
all_cars.append(i)
# sort dat list bruh
all_cars.sort()
# return dat shat
return all_cars
print(sort_models())
| true |
037920de71306887635d46953eb21890f00d9593 | yeri96/AlgoritmicaBasica_2018 | /Mayor_Menor/mayor_menor.py | 1,617 | 4.4375 | 4 | # coding: utf-8
numero1 = input("Introduce el primer número: ")
numero2 = input("Introduce el segundo número: ")
numero3 = input("Introduce el tercer número: ")
if numero1 == numero2 and numero1 == numero3:
print "Ha escrito 3 veces el mismo número"
else:
if numero1 == numero2 and numero1 != numero3:
print "Has escrito uno de los números dos veces"
else:
if numero1 != numero2 and numero1 == numero3:
print "has escrito uno de los números dos veces"
else:
if numero2 == numero1 and numero2 == numero3:
print "Ha escrito 3 veces el mismo número"
else:
if numero2 == numero1 and numero2 != numero3:
print "Has escrito uno de los números dos veces"
else:
if numero2 != numero1 and numero2 == numero3:
print "has escrito uno de los números dos veces"
else:
if numero3 == numero1 and numero3 == numero2:
print "Ha escrito 3 veces el mismo número"
else:
if numero3 == numero1 and numero3 != numero2:
print "Has escrito uno de los números dos veces"
else:
if numero3 != numero2 and numero3 == numero1:
print "has escrito uno de los números dos veces"
else:
print "Los tres múmeros que ha escrito son distintos"
| false |
a017de5cb43b53b1f7c796ab015b91a68f09efdf | abhishekratnam/Datastructuresandalgorithmsinpython | /DataStructures and Algorithms/Recursion/Reverse.py | 445 | 4.1875 | 4 | def reverse(S, start, stop):
"""Reverse elements in emplicit slice S[start:stop]."""
if start < stop - 1:
S[start], S[stop-1] = S[stop - 1], S[start]
reverse(S, start+1, stop - 1)
def reverse_iterative(S):
"""Reverse elements in S using tail recursion"""
start,stop = 0,len(S)
while start < stop - 1:
S[start],S[stop-1] = S[stop - 1], S[start]
start,stop = start+1, stop -1
| true |
e03f40711cfe8a26b38de0c63faaee30e1b0e336 | pragatishendye/python-practicecode | /FahrenheitToCelsius.py | 338 | 4.40625 | 4 | """
This program prompts the user for a temperature in Fahrenheit and returns
the Celsius equivalent of it.
Created by Pragathi Shendye
"""
tempInFahrenheit = float(input('Enter a temperature in Fahrenheit:'))
tempInCelsius = (tempInFahrenheit - 32) * (5 / 9)
print('{} Fahrenheit = {:.2f} Celsius'.format(tempInFahrenheit, tempInCelsius)) | true |
23a9baab1b0308bde129e6d01894f56ea79e3c64 | iresbaylor/codeDuplicationParser | /engine/utils/printing.py | 921 | 4.1875 | 4 | """Module containing methods for pretty-printing node trees."""
def print_node_list(node_list):
"""
Print a list of TreeNodes for debugging.
Arguments:
node_list (list[TreeNode]): a list of tree nodes
"""
for node in node_list:
if node.parent_index is None:
print_node(node, "", 0, node_list)
def print_node(node, indent, level, node_list):
"""
Print a TreeNode for debugging.
Arguments:
node (TreeNode): node to print
indent (str): space to print before node
level (int): depth of node within the tree (0 for root)
node_list (list[TreeNode]): list of TreeNodes to reference children of TreeNode
"""
print(indent, "(", level, ")", node)
for index in node.child_indices:
for node in node_list:
if node.index == index:
print_node(node, indent + " ", level + 1, node_list)
| true |
f29ca346f0977a08234ceeb742e13ff1ec31fb11 | upputuriyamini/yamini | /al.py | 211 | 4.15625 | 4 | al=int(input())
if al == 0:
exit();
else:
if((al>='a' and al>='z') or (al>='A' and al>='Z')):
print(al, "is an alphabet.")
else:
print(al,"is not an alphabet")
| false |
433453e34c036cf7b04079f06debd27ba3c31e69 | amarish-kumar/Practice | /coursera/coursera_data_structures_and_algorithms/course_1_algorithmic_toolbox/Week_4/binarysearch/binary_search.py | 2,180 | 4.15625 | 4 | #python3
'''Implementation of the binary search algoritm.
Input will contain two lines. First line will
have an integer n followed by n integers in
increasing order. Second line will have an
integer n again followed by n integers. For
each of the integers in the second line, you
have to perform binary search and output the
index of the integer in the set on the first
line else output -1 if it is not there.
'''
sorted_array = list()
def binary_search(num, l, h):
#value containing the index where num resides.
#it will be -1 in case num is not found.
valueToReturn = -1
#if high end is less than the low end, end
#search and return -1.
if h < l :
return valueToReturn
#get the middle element.
mid = int((l+h)/2)
#if num is equal to be searched, return index
#of middle element.
if int(num) == int(sorted_array[mid]):
valueToReturn = mid
#if num is greater than the middle element,
#implement binary search on the upper half
#of the sorted array.
elif int(num) > int(sorted_array[mid]):
valueToReturn = binary_search(num,mid+1,h)
#if num is smaller than the middle element,
#implement binary search on the lower half
#of the sorted array.
elif int(num) < int(sorted_array[mid]):
valueToReturn = binary_search(num,l,mid-1)
return valueToReturn
#read the first line
first_line = input()
#extract the number and the sorted array from
#the first line.
num_first = first_line.split()[0]
sorted_array = first_line.split()[1:]
#read the second line.Put the numbers to be
#searched in a separate list.
second_line = input()
num_second = second_line.split()[0]
input_array = second_line.split()[1:]
#parse the second list and call binary search
#utility for each of the number in the list.
#Save the output of the binary search for each
#of the number in a separate list.
output_array = list()
for num_to_be_searched in input_array:
#search for the index of the number.
output_array.append(binary_search(num_to_be_searched,0,len(sorted_array)-1))
for element in output_array:
print(element,end='')
print(" ",end='')
| true |
a58e51493d43ad0df89b3836366ef7b729223d57 | jnoriega3/lesson-code | /ch6/printTableFunctions.py | 2,680 | 4.59375 | 5 | # this is the printTable function
# parameter: tableData is a list of lists, each containing a word
# we are guaranteed that each list is the same length of words
# this function will print our table right-justified
def printTable( tableData ):
#in order to be able to right-justify each word, we'll need to know the size of all the words. This creates a placeholder that will hold those lengths
colWidths = [0] * len( tableData )
#this for-loop, cycles through each of the lists, and stores the size of the maximum value on each list in colWodths
for eachList in range( len( tableData ) ):
#this utilizes a helper function I created called getMaxSize of List, you'll see how this function works further down on this code
colWidths[eachList] = getMaxSizeofList( tableData[eachList] )
#the line below has been commented so it won't run, but you can take the comment out if you'd like to see the list of values inside colWidths
#print(colWidths)
#this for-loop cycles through each of the words on each list, and right-justifies each of those words using the information acquired about the lengths of each word
for eachWord in range( len( tableData[eachList]) ):
for eachList in range( len( tableData ) ):
#the end=' ' argument allows us to print more than one word side-by-side rather than forcing a newline
print( tableData[eachList][eachWord].rjust( colWidths[eachList]), end=' ' )
#but at the end of each line, we'll need to add a newline
print()
# this is the getMaxSizeofList function, it was created to help us calculate the maximum size of the words on a given list
# parameter: theList is a single list containing words
# this function will determine the size of the largest word on the given list, it is designed to be called repeatedly with different lists
def getMaxSizeofList( theList ):
#this is a local variable called max, that will hold the maximum length of the word as we look through each word on the list. It is initialized to zero and will be replaced below as we determine the size of each word
max = 0
#this for-loop cycles through each word on the list
for word in range(len(theList)):
#if the length of the word we are examining is greater than max (initially, max is 0, but the value of max will change as this loop gets executed
if len(theList[word]) > max:
#the max value will be replaced with the length of this word, if the length of this word is greater than max
max = len(theList[word]);
#return the final max value to the caller of this function
return max | true |
72218d09cd2c9a05bae3d9a2f22eccba436a554d | jnoriega3/lesson-code | /ch4/1-list-print.py | 638 | 4.46875 | 4 | #this defines a function with one parameter, 'theList'
def printList( theList ):
# this for loop iterates through each item in the list, except the last item
for i in range( len(theList)-1 ): #can you remember what this line does?
#this will add a comma after each list item
print( str(theList[i]) + ',', end=' ')
#the last list item doesn't need to be followed by a comma
print( 'and ' + str(theList[ len(theList)-1 ]) )
#this is the end of what was asked in the question, the following lines are just to test the function we wrote
spam = ['apples', 'bananas', 'tofu', 'cats']
printList( spam ) | true |
db8cc0d6b26b66a57b5db9b2478bedb0b463e5a6 | burakdemir1/BUS232-Spring-2021-Homeworks | /hw7.py | 407 | 4.21875 | 4 | names = ("Ross","Rachel","Chandler","Monica","Joey","Phoebe")
friends_list = set()
for name in names:
names_ = input(f'{name}, enter the names of the friends you invited: ')
name_list = names_.split()
for name in name_list:
friends_list.add(name)
print('This is final list of people invited:')
for count, name in enumerate(friends_list, start=1):
print(count, '.', name) | true |
18290bee33c550d52f7b3133320f40f1f43296ff | edersonlucas/Calculadora_IMC_Python | /calculadoraIMC.py | 2,272 | 4.15625 | 4 | '''
Calculadora IMC
Autor: Ederson Lucas
'''
#Entrada do Nome
nome = input('Qual seu nome? ')
# Laço ano
while True:
idade = input('Qual sua idade? ')
if idade.isdigit() == False or int(idade) <= 0:
print('Digite uma idade valida!')
continue
else:
idade = int(idade)
if idade >= 115:
print('A Calculadora de IMC é somente para menores de 115 anos, porém receba nossos parabéns, com essa idade você é a pessoa mais velha do mundo.')
continue
else:
break
# Laço altura
while True:
altura = input('Qual sua altura? ')
if altura.isalnum() == True and altura.isdigit() == False or float(altura) <= 0.2:
print('Digite uma altura valida!')
continue
else:
altura = float(altura)
if altura >= 2.72:
print('A Calculadora de IMC é somente para pessoas com menos de 2.72 metros de altura, porém receba nossos parabéns, com essa altura você é um gigante.')
continue
else:
break
# Laço peso
while True:
peso = input('Qual seu peso? ')
if peso.isalnum() == True and peso.isdigit() == False or float(peso) <= 0.2:
print('Digite um peso valido!')
continue
else:
peso= float(peso)
break
imc = peso/(altura*altura)
#Imprime na tela
print('-='*35)
print('{}, tem {} anos de idade e seu IMC é {:.2f}'.format(nome, idade, imc,));
print('-='*35)
print('Status do seu IMC')
# Condições
if imc < 16:
print('Você está com Magreza Grave. Consulte um médico.');
elif imc >= 16 and imc < 17:
print('Você está com Magreza Moderada. Consulte um médico.');
elif imc >= 17 and imc < 18.5:
print('Você está com Magreza Leve. Consulte um médico.');
elif imc >= 18.5 and imc < 25:
print('Você está Saudável, Parabéns! Siga assim.');
elif imc >= 25 and imc < 30:
print('Você está com Sobrepeso. Consulte um médico.');
elif imc >= 30 and imc < 35:
print('Você tem Obesidade Grau 1. Consulte um médico.');
elif imc >= 35 and imc < 40:
print('Você tem Obesidade Grau 2(Severa). Consulte um médico.');
elif imc >= 40:
print('Você tem Obesidade Grau 3(Mórbida). Consulte um médico.');
print('-='*35)
| false |
e0c8f24b3fd76f748f8aff3e31c04ec314ab6bba | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/IntroToObjects_List.py | 741 | 4.53125 | 5 | #Lists - An unordered sequence of items
groceryList = ['Greens', 'Fruits', 'Milk']
print("My Grocery list is ", groceryList)
#You can iterate over lists. What's Iterate?
#Iterate means go one by one element traverssing the full list
#We may need to iterate the list to take some action on the given item
#e.g. what is we want to check if the list has 'Carrots'. If not add it.
carrotFound = False
for item in groceryList:
if(item=='Carrots'):
carrotFound = True
break
if(carrotFound == False):
groceryList.append('Carrots')
print('Revised grocery list',groceryList)
#Other operations on a list
groceryList.reverse()
print("remove a item ",groceryList)
groceryList.sort()
print("sort a item ",groceryList)
| true |
19a636342dcb726c0a3c1ac89dab78319e4ca0c7 | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/Files_Reading.py | 1,152 | 4.28125 | 4 | #Opening a file using the required permissions
f = open("data/drSeuss_green_eggs_n_ham.txt","r")
#Reading a file using readline() function
print("== Using for loop to read and print a file line by line ==")
#Default print parameters
for line in f:
print(line)
#Extra new lines after the every line. Why?
#Specify print parameters for exactly printing as in file
#How to fix that - dont need an extra new line after every line
#Specify the end of line for print function. By default its the "newline".
for line in f:
print(line,end='')
f.close()
#Reading a file using readline() function
print("== Read a file using readline() ==")
f = open("data/drSeuss_green_eggs_n_ham.txt","r")
line = f.readline()
print(line)
while(line!=""):
line = f.readline()
print(line,end='')
f.close()
#Reading a file with read() function
print("\n === START Read a file using read() ==")
f = open("data/drSeuss_green_eggs_n_ham.txt","r")
txt = f.read(10)
print(txt)
f.close()
print("=== END Read a file using read() ==\n")
#Detour ;-)
#How to get help within from the programming topics.
#pydocs and help utility in python shell. Demo!
| true |
01dc63ff29161279ab8cb689d375895180efc241 | skoolofcode/SKoolOfCode | /The Geeks/modules/IntroToModule.py | 780 | 4.15625 | 4 |
#introduction to Modules
#Let's create a module hello that has 2 function helloWorld() and helloRedmond()
#Diffirent ways of importing the module
#1. Import module as is with its name. Note the usage <module>.<function>
import hello
hello.helloIssaquah()
hello.helloRedmond()
hello.helloSeattle()
hello.helloBangalore()
#2. Import module and give it name. Usage <module given name>.<function>
import hello as myHello
myHello.helloIssaquah()
myHello.helloRedmond()
myHello.helloSeattle()
myHello.helloBangalore()
#3. Import specific items in a module. Usage <function_name>()
from hello import helloSeattle
helloSeattle()
#4. Import specific items in a module and give it a name. Usage <module_given_name>()
from hello import helloRedmond as angadsHello
angadsHello()
| true |
fac14e0cfee5d22b65ca14fce29909c03c5a4f83 | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/Class_3_2_Live.py | 820 | 4.15625 | 4 | #Print a decimal number as binary
#"{0:b}".format(number)
j = 45
print("The number j in decimal is ",j)
print("{0:b}".format(j))
#Use ord() to get Ascii codes for a given character
storeACharacter = 'a'
print("I am printing a character ", storeACharacter)
print("The ASCII code for a is ", ord(storeACharacter))
#Lets convert a whole sentence to ascii
tmp = "This is a live coding demo"
for m in tmp:
print("Ascii for character ", m , "is ", ord(m))
# Let's write a secret message ;-)
# Part - 1 - Let's just write Ascii
letter = "This is a secret This is a secret This is a secret This is a secret"
count = 0
for m in letter:
print("",10+ord(m),end='')
# Part 2 - Ascii may be too simple and easily infered
# So we will jumble up
# Part 3 - More complex code. Note you have to also decode
| true |
83e14b2a1a0b7d360c9ef3b979b5ac1c6fff630f | skoolofcode/SKoolOfCode | /CodeNinjas/SimplifiedHangMan.py | 1,441 | 4.46875 | 4 | #Simplified Hangman
#Present a word with only first 3 characters. Rest everything is masked
#The user would be asked to guess the word. He/She wins if the word is correctly guessed.
#A user get a total of 3 tires. At every try a new character is shown.
#Let's have a global word list.
worldList = ["batman","jumpsuit", "tennis","horses","skoolofcode"]
def initWordList():
lenghtOfWords = 6 #
print("initiWordList : this function initializes the word list")
# Write the code to initialize the world list
#...
#print("initWordList : The world list is ",worldList)
print("initWordList : The world list is initialized with word of lenght", lenghtOfWords)
def selectWord():
word = "dummyy"
print("selectWord : Selects a word to play with")
# ...
# ...
return word
def creexateWordToDisplay(word,firstN):
wordFirstN = "dum***"
print("This function writes out the given word with N characters hideen with *")
#..
#..
#..
return wordFirstN
def about():
print("about: This function tells the users what the program does")
print("Hey user! Welcome to the Hangman. You are now playing a word guessing game")
print("Guess the word in 3 tries!")
#Main
initWordList()
about()
sWord = selectWord()
print("The selected word for this game is ", sWord)
displayWord = createWordToDisplay(sWord,3)
print("User : Guess the word ", displayWord)
| true |
dbf8ea3834665ffc7df5953b5974455849501e16 | skoolofcode/SKoolOfCode | /The Geeks/list_methods.py | 1,042 | 4.59375 | 5 | # This file we'll be talking about Lists.
#Create a list
print("\n *** printing the list ***")
groceryList = ['Milk', 'Oranges', "Cookies", "Bread"]
print(groceryList)
#Append to the list. This also means add a item to the list
print("\n*** Add pumpkin to the list")
groceryList.append("pumpkin")
print(groceryList)
#Lenght of the list.
print("\n*** Lenght of the list after adding pumpkin")
print(len(groceryList))
#Remove an item from the list
print("\n*** let's remove pumpkin from the list")
groceryList.remove("pumpkin")
print(groceryList)
#Find the position of a given element
print("\n*** Let's find the position of Oranges in the list")
print(groceryList.index("Oranges"))
#Lets access Orange using its position
print("\n*** Lets access Orange using its position")
element = groceryList[1]
print(element)
#Let's use index to find the position of Oranges and then print it
i = groceryList.index('Oranges')
element = groceryList[i]
print("\n*** Let's use index to find the position of Oranges and then print it")
print(element)
| true |
ac998b57fae60f1088db024c902ec8a9994b00d3 | skoolofcode/SKoolOfCode | /TrailBlazers/maanya/practice/caniguessyourage.py | 1,024 | 4.125 | 4 | def thecoolmathgame ():
print("Hello. I am going to guess your age today! I promise I will not cheat :)")
startnum = int(input("Pick a number from 1-10:"))
print("Now I will multiply your chosen number by 2.")
age = startnum * 2
print ("Now I will add 5 to the new number.")
age = age + 5
print("Now I will multiply this total by 50")
age = age * 50
bday = (input("Have you already had your birthday this year? Enter '1 for YES' and '2 for NO':"))
if bday == '1':
age = age + 1768
elif bday == '2':
age = age + 1767
else:
print("Your input is not valid. Go ahead and try again!")
print(bday)
byear = int(input("Enter the year you were born:"))
age = age - byear
print("Okay. Your age is ready. Keep in mind through out this game you have NOT told me your age.")
print(" ")
print("Your number is a three-digit result. The first number (left to right) is the number you choose in the beginning . The second and third numbers (left to right) are your age. ")
print(age)
return
thecoolmathgame()
| true |
315e47a3d80ac5835bb40dcc890b7bc924c08c1e | martyav/algoReview | /pythonSolutions/most_frequent_character.py | 878 | 4.1875 | 4 | # Frequency tables, frequency hashes, frequency dictionaries...
#
# Tomayto, tomahto, we're tracking a character alongside how many times it appears in a string.
#
# One small optimization is to update the most-frequently-seen character at the same time as
# we update the dictionary.
#
# Otherwise, we'd have to write a little more code to loop through the dictionary, to see where
# the most frequent character is.
def most_frequent_character(string):
if len(string) == 0:
return None
if len(string) == 1:
return 1
frequency_dict = {}
most_frequent_so_far = ("", 0)
for char in string:
if char in frequency_dict:
frequency_dict[char] += 1
else:
frequency_dict[char] = 1
if frequency_dict[char] > most_frequent_so_far[1]:
most_frequent_so_far = (char, frequency_dict[char])
return most_frequent_so_far[0]
| true |
07482b5f7f8b1ba25dbedc9a1f4398bb66ebd04a | SamuelNgundi/programming-challenges-with-python | /3.11. Book Club Points.py | 1,264 | 4.21875 | 4 | """
11. Book Club Points
Serendipity Booksellers has a book club that awards points to its customers
based on the number of books purchased each month.
The points are awarded as follows:
- If a customer purchases 0 books, he or she earns 0 points
- If a customer purchases 2 books, he or she earns 5 points
- If a customer purchases 4 books, he or she earns 15 points
- If a customer purchases 6 books, he or she earns 30 points
- If a customer purchases 8 or more books, he or she earns 60 points
Write a program that asks the user to enter the number of books that he
or she has purchased this month and displays the number of points awarded.
Reference:
(1) Starting out with Python, Third Edition, Tony Gaddis Chapter 3
(2) https://youtu.be/1n8T4JOd9s4
"""
# Get the User Input and Convert to int
number_of_books = int(input("Please Enter number of books Purchased " + \
"this month : "))
# now let check all the condition and print the result
if number_of_books < 2:
print("You have earn 0 Point")
elif number_of_books < 4:
print("You have earn 5 Points")
elif number_of_books < 6:
print("You have earn 15 Points")
elif number_of_books < 8:
print("You have earn 30 Points")
else:
print("You have earn 60 Points")
| true |
bb5d1cdeede1ec0a878ad5ee0f023e331f75d2dd | SamuelNgundi/programming-challenges-with-python | /3.2. Areas of Rectangles.py | 1,179 | 4.46875 | 4 | """
2. Areas of Rectangles
The area of a rectangle is the rectangles length times its width.
Write a program that asks for the length and width of two rectangles.
The program should tell the user which rectangle has the greater area,
or if the areas are the same.
Reference:
(1) Starting out with Python, Third Edition, Tony Gaddis Chapter 3
(2) https://youtu.be/7be9HlHRB-E
"""
# Get User Input(the length and width of two rectangles.)
# Convert User input to float
rectangle1_length = float(input("Please Enter the length of Rectangle 1 : "))
rectangle1_width = float(input("Please Enter the Width of Rectangle 1 : "))
rectangle2_length = float(input("Please Enter the length of Rectangle 2 : "))
rectangle2_width = float(input("Please Enter the Width of Rectangle 2 : "))
# Compute Area of Rectangle for both
rectangle1_area = rectangle1_length * rectangle1_width
rectangle2_area = rectangle2_length * rectangle2_width
# check all the conditions
if rectangle1_area > rectangle2_area:
print("Rectangle 1 is Bigger than Rectangle 2")
elif rectangle2_area > rectangle1_area:
print("Rectangle 2 is Bigger than Rectangle 1")
else:
print("the areas are the same")
| true |
afe32f4de9c73b431f8e20694a975a45ae993b34 | SamuelNgundi/programming-challenges-with-python | /3.1. Day of the Week.py | 1,136 | 4.46875 | 4 | """
1. Day of the Week
Write a program that asks the user for a number in the range of 1 through 7.
The program should display the corresponding day of the week, where 1 = Monday,
2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday,
and 7 = Sunday.
The program should display an error message if the user enters a number
that is outside the range of 1 through 7.
Reference:
(1) Starting out with Python, Third Edition, Tony Gaddis Chapter 3
(2) https://youtu.be/jx8y647CMsI
"""
# Get User Input(a number in the range of 1 through 7)
# Convert User input to int
user_number = int(input("Enter a number in the range of 1 through 7 : "))
# check all the conditions
if user_number == 1:
print("Monday")
elif user_number == 2:
print("Tuesday")
elif user_number == 3:
print("Wednesday")
elif user_number == 2:
print("Tuesday")
elif user_number == 4:
print("Thursday")
elif user_number == 5:
print("Friday")
elif user_number == 6:
print("Saturday")
elif user_number == 7:
print("Sunday")
# for all the else cases
else:
print("Error a number is outside the range of 1 through 7")
| true |
7e1205f5489688438da50bb992c737eaaf9504fa | rickydhanota/Powerset_py | /powerset_med.py | 1,006 | 4.15625 | 4 | #Powerset
#Write a function that takes in an array of unique integers and returns its powerset.
#The powerset P(X) of a set X is the set of all the subsets of X. for example, the powerset of [1, 2] is [[], [1], [2], [1, 2]]
#Note that the power sets do not need to be in any particular order
#Array = [1, 2, 3]
#[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
#O(n*2^n) time | O(n*2^n) space
# def powerset(array, idx = None):
# if idx is None:
# idx = len(array) - 1
# if idx < 0:
# return [[]]
# ele = array[idx]
# subsets = powerset(array, idx - 1)
# for i in range(len(subsets)):
# currentSubset = subsets[i]
# subsets.append(currentSubset + [ele])
# return subsets
#O(n*2^n) time | O(n*2^n) space
def powerset(array):
subsets = [[]]
for ele in array:
for i in range(len(subsets)):
currentSubset = subsets[i]
subsets.append(currentSubset + [ele])
return subsets
print(powerset([1, 2, 3]))
| true |
9b010ff1877e1ef42db1fe2f8d630dff72b2c544 | JakobHavtorn/algorithms-and-data-structures | /data_structures/stack.py | 1,975 | 4.1875 | 4 | class Stack(object):
def __init__(self, max_size):
"""Initializes a Stack with a specified maximum size.
A Stack incorporates the LIFO (Last In First Out) principle.
Args:
max_size (int): The maximum size of the Stack.
"""
assert type(max_size) is int and max_size >= 0, '`max_size` must be 0 or large but was {}'.format(max_size)
self._max_size = max_size
self._top = -1
self._stack = [None] * self._max_size
def is_full(self):
"""Checks if the stack is full.
Returns:
bool: Whether or not the stack is full.
"""
return self._top == self._max_size - 1
def is_empty(self):
"""Checks if the stack is empty.
Returns:
bool: Whether or not the stack is empty.
"""
return self._top == -1
def peek(self):
"""Returns the top element of the stack without removing it.
Returns:
[type]: The top element
"""
return self._stack[self._top]
def push(self, data):
"""Pushes an element to the top of the stack.
Args:
data (type): The data to push.
Raises:
IndexError: If the stack is full.
"""
if not self.is_full():
self._top += 1
self._stack[self._top] = data
else:
msg = 'Stack overflow at index {} with max size of {}'.format(self._top + 1, self._max_size)
raise IndexError(msg)
def pop(self):
"""Returns the top element of the stack, removing it from the stack.
Raises:
IndexError: If the stack is empty.
Returns:
[type]: The top element of the stack.
"""
if not self.is_empty():
data = self._stack[self._top]
self._top -= 1
return data
else:
msg = 'Stack is empty'
raise IndexError(msg)
| true |
0cac7a90f5b2e66b12400a09cb98a0028eda2883 | Utkarsh016/fsdk2019 | /day4/code/latline.py | 426 | 4.15625 | 4 | """
Code Challenge
Name:
Last Line
Filename:
lastline.py
Problem Statement:
Ask the user for the name of a text file.
Display the final line of that file.
Think of ways in which you can solve this problem,
and how it might relate to your daily work with Python.
"""
file_name=input("enter the name of text file")
with open(file_name,"r") as fp:
a=fp.readlines()
b=a[-1]
print(b) | true |
e5a23142c19ef32b8bd5afc36370fc733be83284 | gagande90/Simple-Gui-Programs-Python | /Simple/2_adding_widgets.py | 789 | 4.34375 | 4 | import tkinter as tk # alias tkinter as "tk"
from tkinter import ttk # ttk == "themed tk"
gui = tk.Tk() # create Tk() instance and assign to variable
ttk.Label(gui, text="Hello Label").\
grid(row=0, column=0) # create a themed tk label
ttk.Button(gui, text="Click Me!").\
grid(row=0, column=1) # gui is the parent for the widgets
tk.Entry(gui).\
grid(row=0, column=2) # using grid layout manager
gui.mainloop() # start the main event loop to display our gui
| false |
1afcc2281ee5a21f3fc4b7327582d5fb96dd4dcb | Harguna/Python | /calc.py | 1,335 | 4.21875 | 4 | print("Press: 1 for even-odd ")
print("Press: 2 for prime number ")
print("Press: 3 for factorial ")
print("Press: 4 for average ")
print("\n")
opt= int( input ("Enter your option: "))
def even_odd(num1):
if num1==0:
print("Number is neither even nor odd")
if num1%2==0:
print("Number is even")
else:
print("Number is odd")
def prime_no(num2):
count=0
if num2==0|num2==1:
print("Number is neither prime nor composite")
for i in range(2,num2):
if num2%i ==0:
count= count+1
if count>=1:
print("Number is composite")
else:
print("Number is prime")
def fact(num3):
fact =1
while num3!=1:
fact= num3*fact
num3=num3 -1
print("Factorial is: " + str(fact))
def avg(num4):
add=0
arr= []
for j in range(0,elts):
num4= int( input() )
arr.append(num4)
add=add + num4
avg= float (add/elts)
print( "Average is: " + str(avg) )
if opt==1:
num1= int( input("Enter your number: ") )
even_odd(num1)
elif opt==2:
num2= int( input("Enter the number: ") )
prime_no(num2)
elif opt==3:
num3= int( input("Enter the number: ") )
fact(num3)
elif opt== 4:
elts= int( input("Enter the number of elements: ") )
avg(elts)
else :
print("Entered number does not match options !")
input("Press any key to finish")
a=20
def abc(a):
| false |
8662bda8ca8c11a857c90048e588861d7eb475c7 | rshandilya/IoT | /Codes/prac2d.py | 1,523 | 4.3125 | 4 | ############# EXPERIMENT 2.D ###################
# Area of a given shape(rectangle, triangle, and circle) reading shape and
# appropriate values from standard input.
import math
import argparse
import sys
def rectangle(x,y):
"""
calculate area and perimeter
input: length, width
output: dict - area, perimeter
"""
perimeter = 2*(x+y)
area = x*y
return {"area": area, "perimeter": perimeter}
def triangle(a, b, c):
p = a + b + c
s = p/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
return {"area": area, "perimeter": p}
def circle(r):
perimeter = 2*math.pi*r
area = math.pi*r*r
return {"area": area, "perimeter": perimeter}
if __name__ == "__main__":
choices = ["tri", "circ", "rect"]
parser = argparse.ArgumentParser(
description="Calculate Area of Basic geometry")
parser.add_argument("geom", choices=choices, help="Geometry type")
parser.add_argument('para', type=float, nargs='*',
help="parameters for geometry")
args = parser.parse_args()
if args.geom=="tri":
ret = triangle(args.para[0], args.para[1], args.para[2])
print(f"Perimeter: {ret['perimeter']}")
print(f"Area: {ret['area']}")
elif args.geom=="rect":
ret = rectangle(args.para[0], args.para[1])
print(f"Perimeter: {ret['perimeter']}")
print(f"Area: {ret['area']}")
else:
ret = circle(args.para[0])
print(f"Perimeter: {ret['perimeter']}")
print(f"Area: {ret['area']}")
| true |
7bf6f58e13b0f780d83aeadd9893382d68762ab5 | veyu0/Python | /les_6/les_6_task_4.py | 2,470 | 4.1875 | 4 | class Car:
''' Автомобиль '''
_speed = None
_color = None
_name = None
_is_police = False
def __init__(self, name, color):
self.name = name
self.color = color
print(f'Новая машина: {self.name} (цвет {self.color}) {type(self)}')
def go(self):
print(f'{self.name}: Машина поехала.')
def stop(self):
print(f'{self.name}: Машина остановилась.')
def turn(self, direction):
print(f'{self.name}: Машина повернула {"налево" if direction == 0 else "направо"}.')
def show_speed(self, speed):
print(f'{self.name}: Скорость автомобиля: {speed}.')
class TownCar(Car):
''' Городской автомобиль '''
def show_speed(self, speed):
if speed > 60:
print(f'{self.name}: Скорость автомобиля: {speed}. Превышение скорости!')
else:
super().show_speed(speed)
class WorkCar(Car):
''' Грузовой автомобиль '''
def show_speed(self, speed):
if speed > 40:
print(f'{self.name}: Скорость автомобиля: {speed}. Превышение скорости!')
else:
super().show_speed(speed)
class SportCar(Car):
''' Спортивный автомобиль '''
class PoliceCar(Car):
''' Полицейский автомобиль '''
def __init__(self, name, color):
super().__init__(name, color)
self.is_police = True
police_car = PoliceCar('"Полицайка"', 'белый')
police_car.go()
police_car.show_speed(80)
police_car.turn(0)
police_car.stop()
print()
work_car = WorkCar('"Грузовичок"', 'хаки')
work_car.go()
work_car.turn(1)
work_car.show_speed(40)
work_car.turn(0)
work_car.show_speed(45)
work_car.stop()
print()
sport_car = SportCar('"Спортивка"', 'красный')
sport_car.go()
sport_car.turn(0)
sport_car.show_speed(120)
sport_car.stop()
print()
town_car = TownCar('"Малютка"', 'жёлтый')
town_car.go()
town_car.show_speed(50)
town_car.turn(1)
town_car.turn(0)
town_car.show_speed(66)
town_car.stop()
print(f'\nМашина {town_car.name} (цвет {town_car.color})')
print(f'Машина {police_car.name} (цвет {police_car.color})') | false |
7ad247c561871ac54719ae32ad42be206364b6b5 | veyu0/Python | /les_2/les_2_task_2.py | 655 | 4.46875 | 4 | '''Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input().'''
list = list(input('Введите число: '))
print(list)
for i in range(1, len(list), 2):
list[i-1], list[i] = list[i], list[i-1]
print(list) | false |
405b6b42a5524fab2960666eafa33887d7b8447f | antigravitybird/pynet_test | /ex_17_callfunc.py | 888 | 4.25 | 4 | #!/usr/bin/env python
def my_func(x, y, z=20):
return x + y + z
def my_func2(x, y, z=20):
return x, y, z
print
print "Calling with three positional arguments: "
print "Value: ", my_func(10, 20, 30)
print
print "Calling with two named arguments: "
print "Value: ", my_func(x=10, y=20)
print
print "Calling with one positional argument and two named arguments: "
print "Value: ", my_func(10, y=15, z=55)
print
print "Calling with three strings: "
print "Value: ", my_func(x='happy ', y='little ', z='string')
print
print "Calling with three lists: "
print "Value: ", my_func2(x=['water', 'ice', 'snow'], y=['lava', 'fire', 'steam'], z=['grass', 'soil', 'flora'])
print
print "Making that call more readable: "
ret1, ret2, ret3 = my_func2(x=['water', 'ice', 'snow'], y=['lava', 'fire', 'steam'], z=['grass', 'soil', 'flora'])
print " {}\n {}\n {}".format(ret1, ret2, ret3)
print
| false |
3d120963e6082fc867cb0b2266e0f4aa63ff458e | wensheng/tools | /r2c/r2c.py | 1,795 | 4.25 | 4 | #!/bin/env python
"""
Author: Wensheng Wang (http://wensheng.com/)
license: WTFPL
This program change change rows to columns in a ASCII text file.
for example:
-----------
hello
world
!
-----------
will be converted to:
-----------
h w!
e o
l r
l l
o d
-----------
If you specify '-b', vertical bars will be added to non-empty line to fill up spaces,
empty lines will still become empty columns, for example:
-----------
goodbye
world
-------------
will be converted to:
-----------
g w
o o
o r
d l
b d
y |
e |
-----------
By default, output will be printed to screen, use > to redirect output to a file.
If "-o filename" is specified, the output will be saved to the specified file.
"""
import sys
import os
from optparse import OptionParser
usage = "Usage: %prog [options] name"
parser = OptionParser(usage=usage)
parser.set_defaults(columns="",rows="1",delay_type=None)
parser.add_option("-b", "--bars", dest="bars", action="store_true", help="add bars")
parser.add_option("-o", "--output", dest="ofile", help="output file name")
(coptions,cargs) = parser.parse_args()
if len(cargs) == 0:
print("ERROR: Must supply file name.")
sys.exit()
fname = cargs[0]
if coptions.ofile:
ofile = open(coptions.ofile,'w')
else:
ofile = sys.stdout
# lines = [a[:-1] for a in file(fname).readlines()]
f = open(fname)
lines = [a[:-1] for a in f.readlines()]
f.close()
maxlen = max([len(line) for line in lines])
if coptions.bars:
for i in range(len(lines)):
if not lines[i]:
lines[i]=" "*maxlen
else:
lines[i]="%s%s"%(lines[i],'|'*(maxlen-len(lines[i])))
else:
lines = ["%s%s"%(line,' '*(maxlen-len(line))) for line in lines]
for i in range(maxlen):
for j in lines:
ofile.write(j[i])
ofile.write('\n')
ofile.close()
| true |
0b44b64de6e6b1c1e58b40b4d793d4e5bb14cbc2 | zertrin/zkpytb | /zkpytb/priorityqueue.py | 2,082 | 4.25 | 4 | """
An implementation of a priority queue based on heapq and
https://docs.python.org/3/library/heapq.html#priority-queue-implementation-notes
Author: Marc Gallet
Date: 2018-01
"""
import heapq
import itertools
class EmptyQueueError(Exception):
pass
class PriorityQueue:
"""Based on https://docs.python.org/3/library/heapq.html#priority-queue-implementation-notes"""
def __init__(self, name=''):
self.name = name
self.pq = [] # list of entries arranged in a heap
self.entry_finder = {} # mapping of tasks to entries
self.counter = itertools.count() # unique sequence count
self.num_tasks = 0 # track the number of tasks in the queue
def __len__(self):
return self.num_tasks
def __iter__(self):
return self
def __next__(self):
try:
return self.pop_task()
except EmptyQueueError:
raise StopIteration
@property
def empty(self):
return self.num_tasks == 0
def add_task(self, task, priority=0):
'Add a new task or update the priority of an existing task'
if task in self.entry_finder:
self.remove_task(task)
count = next(self.counter)
removed = False
entry = [priority, count, task, removed]
self.entry_finder[task] = entry
heapq.heappush(self.pq, entry)
self.num_tasks += 1
def remove_task(self, task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = self.entry_finder.pop(task)
entry[-1] = True # mark the element as removed
self.num_tasks -= 1
def pop_task(self):
'Remove and return the lowest priority task. Raise KeyError if empty.'
while self.pq:
priority, count, task, removed = heapq.heappop(self.pq)
if not removed:
del self.entry_finder[task]
self.num_tasks -= 1
return task
raise EmptyQueueError('pop from an empty priority queue')
| true |
c73cf61e5a79744a8aaa15c9545bddc5b3b47692 | programmersteven/python_exercise | /prac_05/hex_colours.py | 496 | 4.3125 | 4 | COLOR_TO_CODE = {"AliceBlue": "#f0f8ff","blue1": "#0000ff","black":"#000000","brown":"#a52a2a",
"coral": "#ff7f50","DarkGoldenrod": "#b8860b","DarkOrchid": "#9932cc","DarkSeaGreen": "#8fbc8f",
"DimGray": "#696969","firebrick": "#b22222"}
color = input("Enter the color's name: ")
while color != " ":
if color in COLOR_TO_CODE:
print(COLOR_TO_CODE[color])
else:
print("Invalid color's name")
color = input("Enter the color's name: ")
| false |
ccb58c3b3faee4d0b2a14e600c2881a3d5ecb362 | atravanam-git/Python | /DataStructures/tuplesCodeDemo_1.py | 1,133 | 4.6875 | 5 | """tuples have the same properties like list:
#==========================================================================
# 1. They allow duplicate values
# 2. They allow heterogeneous values
# 3. They preserve insertion order
# 4. But they are IMMUTABLE
# 5. tuple objects can be used as keys in Dictionaries
#==========================================================================
"""
# Declaring empty tuples
tupleA = ()
tupleB = tuple()
# initializing the values using tuple()
tupleA = tuple(range(1, 10, 2))
tupleB = tuple(range(2, 8))
# printing complete tuple data set
print("tupleA values: ", tupleA)
print("tupleB values: ", tupleB)
# tuple' object does not support item assignment
"""tupleA[0] = 'AddnewValue'
tupleB[1] = 2"""
# Mathematical Operator * and + for tuple
tupleA = tupleA + tupleB
tupleB = 3 * tupleB
print("Concatenation Operator - tupleA + tupleB: ", tupleA)
print("Repetition Operator - tupleB * 3: ", tupleB)
# Sorting a tuple
tupleA = sorted(tupleA, key=None, reverse=False)
print("Sorted tupleA: ", tupleA)
tupleA = sorted(tupleA, key=None, reverse=True)
print("Reverse Sorted tupleA: ", tupleA) | true |
0160126d1a2e614c95b844adb1524a6982f50493 | atravanam-git/Python | /FunctionsDemo/globalvarDemo.py | 902 | 4.53125 | 5 | """
#==========================================================================
# 1. global vs local variables in functions
# 2. returning multiple values
# 3. positional args vs keyword args
# 4. var-args, variable length arguments
# 5. kwargs - keyword arguments
#==========================================================================
"""
# any variable defined outside the function is global
a = 10
print("Demo on global vs. Local variables")
# this function has local variable hence local values is taken
def f1():
a = 20
print("Prints local variable ", a)
# this function has No local variable hence global values is taken
def f2():
print("Prints global variable ", a)
# this function has global keyword explicitly mentioned and its value modified
def f3():
global a
a = 100
print("prints modified global value ", a)
# calling functions
f1()
f2()
f3()
f2() | true |
397cf4e1582b4f6e5f30a51a5ef531231fdba1b2 | javatican/migulu_python | /class2/if3.py | 220 | 4.125 | 4 | x=-101
if x%2 and x>0:
print(x,"是正奇數")
elif x%2 and x<0:
print(x,"是負奇數")
elif x%2==0 and x>0:
print(x,"是正偶數")
elif x%2==0 and x<0:
print(x,"是負偶數")
else:
print(x,"是0") | false |
964c6e0588f5e3ca4aabb1cd861357f6d935a595 | cuongdv1/Practice-Python | /Python3/database/create_roster_db.py | 2,652 | 4.125 | 4 | """
Create a SQLite database using the data available in json stored locally.
json file contains the users, courses and the roles of the users.
"""
# Import required modules
import json # to parse json
import sqlite3 # to create sqlite db
import sys # to get coomand line arguments
# Get command line arguments
def print_cmd_line_args():
print(sys.argv)
# print_cmd_line_args()
# Get File name
json_fname = sys.argv[1]
# Open & read json data as string
try:
with open(json_fname, "r") as json_fhand:
json_str = json_fhand.read()
except:
print("[ERROR]", json_fname, ": No such file or directory.")
# print("[DEBUG] JSON Data string :\n---------------------------")
# print(json_str)
# Parse json data
json_data_list = json.loads(json_str)
print(len(json_data_list))
# Create/open database
roster_db = sqlite3.connect("roster.sqlite")
# Get command cursor
curr = roster_db.cursor()
# Drop/Wipe-out existing tables, if exist
curr.executescript(
"""
DROP TABLE IF EXISTS Users;
DROP TABLE IF EXISTS Course;
DROP TABLE IF EXISTS Member;
"""
)
# Create new tables
curr.executescript(
"""
CREATE TABLE Users (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
"""
)
# Fill database with data
for item in json_data_list:
user_name = item[0]
course_title = item[1]
user_role = int(item[2])
# print("[DEBUG]", "{:<15}{:<10}{:}".format(user_name, course_title, user_role))
# Insert user
curr.execute("insert or ignore into Users (name) values (?)", (user_name,))
# Get user ID
curr.execute("select id from Users where name = ?", (user_name,))
user_id = curr.fetchone()[0]
# Insert course
curr.execute("insert or ignore into Course (title) values (?)", (course_title,))
# Get course ID
curr.execute("select id from Course where title = ?", (course_title,))
course_id = curr.fetchone()[0]
# Insert role, user_id & course_id in Member table
curr.execute("insert or replace into Member (user_id, course_id, role) values (?, ?, ?)", (user_id, course_id, user_role))
# Done : End of for loop
# Commit/Save database to Filesystem
roster_db.commit()
# Close cursor
curr.close()
| true |
b0436a9cd1ab679ac92b3fa3bd75786a3cb52067 | spectrum556/playground | /src/homework_1_additional/h_add.7.py | 566 | 4.25 | 4 | __author__ = 'Ihor'
month_num = int(input('enter the number of month\n'))
def what_season(month_num):
if month_num == 1 or month_num == 2 or month_num == 12:
return 'Winter'
elif month_num == 3 or month_num == 4 or month_num == 5:
return 'Spring'
elif month_num == 6 or month_num == 7 or month_num == 8:
return 'Summer'
elif month_num == 9 or month_num == 10 or month_num == 11:
return 'Autumn'
else:
return 'Error. The number of month must be in the range from 1 to 12'
print (what_season(month_num)) | true |
c1e0a3c70cfd90f4753bc9b46c101c2e7ad1227d | wardk6907/CTI110 | /P5T2_FeetToInches_KaylaWard.py | 520 | 4.3125 | 4 | # Feet to Inches
# 1 Oct 2018
# CTI-110 P5T2_FeetToInches
# Kayla Ward
#
# Constant for the number of inches per foot.
inches_per_foot = 12
# Main Function
def main():
# Get a number of feet from the user.
feet = int(input("Enter a number of feet: "))
# Convert that to inches.
print(feet, "equals", feet_to_inches(feet), "inches.")
# The feet_to_inches function convets feet to inches.
def feet_to_inches(feet):
return feet * inches_per_foot
# Call the min function.
main()
| true |
55accbf96df3236d8b55ada121259a0cf95daf99 | PraveenMut/quick-sort | /quick-sort.py | 783 | 4.15625 | 4 | # QuickSort in Python using O(n) space
# tester array
arr = [7,6,5,4,3,2,1,0]
# partition (pivot) procedure
def partition(arr, start, end):
pivot = arr[end]
partitionIndex = start
i = start
while i < end:
if arr[i] <= pivot:
arr[i],arr[partitionIndex] = arr[partitionIndex],arr[i]
partitionIndex += 1
i += 1
else:
i += 1
arr[end],arr[partitionIndex] = arr[partitionIndex],arr[end]
return partitionIndex
# parent Quicksort algorithm
def quickSort(arr, start, end):
if (start < end):
partitionIndex = partition(arr, start, end)
quickSort(arr, start, partitionIndex-1)
quickSort(arr, partitionIndex+1, end)
## testers
n = len(arr)
quickSort(arr, 0, n-1)
for i in range(n): # print the elements in a new line
print arr[i] | true |
ed4bf2d14601305473a0e708b7933c28c679aed5 | bscott110/mthree_Pythonpractice | /BlakeScott_Mod2_TextCount.py | 1,366 | 4.3125 | 4 | import string
from string import punctuation
s = """Imagine a vast sheet of paper on which straight Lines, Triangles, Squares, Pentagons, Hexagons, and other figures,
instead of remaining fixed in their places, move freely about, on or in the surface,
but without the power of rising above or sinking below it, very much like shadows - only hard and with luminous edges -
and you will then have a pretty correct notion of my country and countrymen. Alas, a few years ago, I should have said "my universe":
but now my mind has been opened to higher views of things."""
print("original str: " + s)
s_lower = s.lower()
print("str in all lowercase:")
print(s_lower)
words = list()
words = s_lower.split()
print("str in a list:")
print(words)
print("str word count:")
count = len(words)
print(count)
uni_count = len(set(words))
print("str distinct word count:")
print(uni_count)
j = []
for i in words:
word_count = words.count(i)
j.append((i, word_count))
freq_occur = dict(j)
print("str word freq dict:")
print(freq_occur)
#punctuation_list = list(string.punctuation)
#print(punctuation_list)
w_clean = list()
new=[i.strip(punctuation) for i in s_lower.split()]
w_clean = " ".join(new).split()
print("str list w no punct:")
print(w_clean)
print("str w no punct word count:")
print(len(w_clean))
| true |
b54d309379486f336fcd189b81a9a1df5fba77d0 | AnirbanMukherjeeXD/Explore-ML-Materials | /numpy_exercise.py | 2,818 | 4.28125 | 4 | # Student version : https://tinyurl.com/numpylevel1-280919
# Use the numpy library
import numpy as np
def prepare_inputs(inputs):
# TODO: create a 2-dimensional ndarray from the given 1-dimensional list;
# assign it to input_array
n = len(inputs)
input_array = np.array(inputs).reshape(1,n)
# TODO: find the minimum value in input_array and subtract that
# value from all the elements of input_array. Store the
# result in inputs_minus_min
inputs_minus_min = input_array - np.amin(input_array)
# TODO: find the maximum value in inputs_minus_min and divide
# all of the values in inputs_minus_min by the maximum value.
# Store the results in inputs_div_max.
inputs_div_max = inputs_minus_min / np.amax(inputs_minus_min)
# return the three arrays we've created
return input_array, inputs_minus_min, inputs_div_max
def multiply_inputs(m1, m2):
# TODO: Check the shapes of the matrices m1 and m2.
# m1 and m2 will be ndarray objects.
#
# Return False if the shapes cannot be used for matrix
# multiplication. You may not use a transpose
# TODO: If you have not returned False, then calculate the matrix product
# of m1 and m2 and return it. Do not use a transpose,
# but you swap their order if necessary
if m1.shape[1] == m2.shape[0]:
return np.matmul(m1, m2)
elif m2.shape[1] == m1.shape[0]:
return np.matmul(m2, m1)
else:
return False
def find_mean(values):
# TODO: Return the average of the values in the given Python list
return np.mean(values)
input_array, inputs_minus_min, inputs_div_max = prepare_inputs([-1,2,7])
print("Input as Array: {}".format(input_array))
print("Input minus min: {}".format(inputs_minus_min))
print("Input Array: {}".format(inputs_div_max))
m1 = multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1],[2],[3],[4]]))
m2 = multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1],[2],[3]]))
m3 = multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1,2]]))
print("Multiply 1:\n{}".format(m1))
print("Multiply 2:\n{}".format(m2))
print("Multiply 3:\n{}".format(m3))
print("Mean == {}".format(find_mean([1,3,4])))
def test_module():
score = 0
if np.array_equal(input_array,np.array([[-1,2,7]])):
score += 10
if np.array_equal(inputs_minus_min, np.array([[0,3,8]])):
score += 15
if np.array_equal(inputs_div_max, np.array([[0.,0.375, 1.]])):
score += 15
if not m1:
score += 15
if np.array_equal(m2, np.array([[14],[32]])):
score += 15
if np.array_equal(m3, np.array([[9,12,15]])):
score += 15
if round(find_mean([1,3,4])) == 3:
score += 15
print("--------------------------\nYour Total Score: ", score)
test_module()
| true |
183c214562494a3c9ade3e285d5a68dc8f0ba856 | MikeDiaz93/Problems_VS_Algorithms | /Dutch_National_Flag_Problem/Dutch_National_Flag_Problem.py | 1,949 | 4.15625 | 4 | def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
if input_list == None:
return None
if input_list == []:
return []
aux1 = 0
aux2 = 0
middle = 1
L = len(input_list) - 1
while aux2 <= L:
if input_list[aux2] < middle:
swap(input_list, aux1, aux2)
aux1 += 1
aux2 += 1
elif input_list[aux2] > middle:
swap(input_list, aux2, L)
L -= 1
else:
aux2 += 1
return input_list
def swap(input_list, i, j):
temp = input_list[i]
input_list[i] = input_list[j]
input_list[j] = temp
# original test
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2,
2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
# test 2
print(sort_012([0, 0, 2, 2, 2, 1, 1, 2, 0]))
#expected output: [0, 0, 0, 1, 1, 2, 2, 2, 2]
test_function([0, 0, 2, 2, 2, 1, 1, 2, 0])
print('---------------------------------')
print(sort_012([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2]))
#expected output: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2]
test_function([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2])
print('---------------------------------')
print(sort_012([2,2,2,2,2,2,2]))
#expected output: [2, 2, 2, 2, 2, 2, 2]
test_function([2, 2, 2, 2, 2, 2,])
print('---------------------------------')
print(sort_012([]))
#expected output: []
test_function([])
print('---------------------------------') | false |
f7754142cebe7e721ca0cd13187d4025a625cdba | cbira353/buildit-arch | /_site/writer1.py | 445 | 4.15625 | 4 | import csv
from student import Student
students = []
for i in range(3):
print('name:', end='')
name = input()
print('dorm:', end='')
dorm = input()
students.append(Student(name, dorm))
for student in students:
print("{} is in {}.".format(student.name, student.dorm))
file =open("students.csv", "w")
writer = csv.writer(file)
for student in students:
writer.writerow((student.name, student.dorm))
file.close()
| true |
94908555a5067b29f51bc69eb397cb1f3aace887 | onizenso/College | /classes/cs350/wang/Code/Python/coroutines.py | 1,990 | 4.5 | 4 | #!/usr/bin/env python
# demonstrate coroutines in Python
# coroutines require python 2.5
"""
this simple example is a scheduler for walking dogs
the scheduler subroutine and main() act as coroutines
yield hands off control, next() and send() resumes control
"""
def printdog(name): # auxilliary print function
print "It's %s's turn to go for a walk." % name
"""
this is the scheduler coroutine
'yield stuff' passes control back to main with a message in variable stuff
when control resumes, a message (it may be empty) is available from the caller
as the return value from yield
"""
def scheduler(dogs):
doglist = list(dogs) # create a list object of dogs
current = 0
while len(doglist):
# yield passes control back to caller with a dog name
getRequest = yield doglist[current] # on resume, get a request
current = (current + 1) % len(doglist) # circular traversal of the list
if getRequest:
request, name = getRequest
if request == "add":
doglist.append(name)
elif request == "remove" and name in doglist:
doglist.remove(name)
"""
the code below acts as a coroutine with the scheduler
next resumes control in the schedule with no message passing
send resumes control in the schedule with a message as the parameter
"""
if __name__ == "__main__": # initialize once from main only
dogs = ["spot", "rusty", "bud", "fluffy", "lassie"]
s = scheduler(dogs) # start the scheduler s
for i in range(5):
printdog(s.next()) # next resumes control in s w/ no msg
printdog(s.send(("add", "fifi"))) # send resumes control and passes msg
for i in range(6):
printdog(s.next()) # resume control in s
printdog(s.send(("remove","fluffy"))) # send remove request to s
for i in range(6):
printdog(s.next())
| true |
2696488fbf8a0c27b5c410bdca8fab666eeaa213 | BeniyamL/alx-higher_level_programming | /0x0A-python-inheritance/9-rectangle.py | 1,166 | 4.34375 | 4 | #!/usr/bin/python3
"""
class definition of Rectangle
"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
"""
class implementation for rectangle
"""
def __init__(self, width, height):
"""initialization of rectangle class
Arguments:
width: the width of the rectangle
height: the height of the rectangle
Returns:
nothing
"""
self.integer_validator("width", width)
self.__width = width
self.integer_validator("height", height)
self.__height = height
def area(self):
""" function to find area of the rectanngle
Arguments:
nothing
Returns:
return the area of the rectangle
"""
return (self.__width * self.__height)
def __str__(self):
""" function to print the rectangle information
Arguments:
nothing
Returns:
the string representation of a rectangle
"""
rect_str = "[Rectangle] "
rect_str += str(self.__width) + "/" + str(self.__height)
return (rect_str)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.