blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f28878e88c75381e75a59524d9f1a2a62b39ef09 | Derrick-Guo/Learning | /EPI/EPI12-1.py | 592 | 4.15625 | 4 | # Tip: A string can be permuted to form a palindrome if and only if
# the number of chars whose occurence is odd is at most 1.
import collections
def can_form_palindrome(s):
res=collections.Counter(s)
counter=0
for num in res.values():
if num%2!=0:
counter+=1
if counter>1:
return False
return True
# Optimized version:
def can_form_palindrome(s):
return sum(v%2 for v in collections.Counter(s).values())<=1
# Time complexity: O(n). Space complexity: O(c), which c is the number of distinct chars appearing in the string.
# Test
s='hellooehi'
print(can_form_palindrome(s))
| true |
46afe5aea6c250f16ea65ced3f693900dba39db4 | rastgeleo/python_algorithms | /etc/finding_gcd.py | 403 | 4.125 | 4 | def finding_gcd(a, b):
"""Euclid's algorithm
21 = 1 * 12 + 9
12 = 1 * 9 + 3
9 = 0 * 3 + 0
"""
while (b != 0):
result = b
a, b = b, a % b
print(a, b)
return result
def test_finding_gcd():
number1 = 21
number2 = 12
assert(finding_gcd(number1, number2) == 3)
print('passed')
if __name__ == '__main__':
test_finding_gcd()
| true |
13cb53b4afc73762e4101ea7800b1ee3a81a7c77 | rastgeleo/python_algorithms | /sorting/quick_sort_inplace.py | 1,549 | 4.1875 | 4 | import random
def quicksort(unsorted, start=0, end=None):
"""quicksort inplace"""
if end is None:
end = len(unsorted) - 1
if start >= end:
return
# select random element to be pivot
pivot_idx = random.randrange(start, end + 1) # include idx end
pivot_element = unsorted[pivot_idx]
# swap random element with last element in sub-listay
unsorted[end], unsorted[pivot_idx] = unsorted[pivot_idx], unsorted[end]
# tracks all elements which should be to left (lesser than) pivot
less_than_pointer = start
for i in range(start, end):
# we found an element out of place
if unsorted[i] < pivot_element:
# swap element to the right-most portion of lesser elements
unsorted[i], unsorted[less_than_pointer] = unsorted[less_than_pointer], unsorted[i]
# tally that we have one more lesser element
less_than_pointer += 1
# move pivot element to the right-most portion of lesser elements
unsorted[end], unsorted[less_than_pointer] = unsorted[less_than_pointer], unsorted[end]
# Call quicksort on the "left" and "right" sub-lists
quicksort(unsorted, start, less_than_pointer-1)
quicksort(unsorted, less_than_pointer+1, end)
return unsorted
def test_quick_sort():
my_list = random.sample(range(-100, 100), 10)
assert quicksort(my_list) == sorted(my_list)
print('sorting: {}'.format(my_list))
print('sorted :{}'.format(quicksort(my_list)))
if __name__ == "__main__":
test_quick_sort()
| true |
13ecd9dfd2b1633a3e8788edc632efacfd640e86 | adela8888/CS995-Introduction-To-Programming-Principles | /Library/edevice.py | 2,096 | 4.34375 | 4 | class EDevice:
"""
A class to represent a real-life object with its parameters. In this case
to represent an electronic device
"""
def __init__(self, member = None):
"""
A constructor to initialize the instance members of the class EDevice
"""
self.typeOfDevice = "not set"
self.IPAddress = "not set"
self.location = "not set"
self.availability = True
self.loggedInMember = member
def setTypeOfDevice (self, n):
"""
Sets type of an electronic device
"""
self.typeOfDevice = n
def getTypeOfDevice (self):
"""
Returns type of an electronic device
"""
return self.typeOfDevice
def setIPAddresss(self, i):
"""
Sets IP address of an electronic device
"""
self.IPAddress = i
def getIPAddress(self):
"""
Returns IP address of an electronic device
"""
return self.IPAddress
def setLocation(self, l):
"""
Sets location of an electronic device in the library
"""
self.location = l
def getLocation (self):
"""
Returns location of an electronic device in the library
"""
return self.location
def checkAvailability (self):
"""
Checks if an electronic device is available
"""
if self.loggedInMember is None:
return True
return False
def printEDeviceDetails(self):
"""
Prints details about an electronic device
"""
print("This electronic device is " + self.typeOfDevice + ".")
print ("IP address: " + self.IPAddress)
print("The " + self.typeOfDevice + " is located on the " + self.location + ".")
if self.checkAvailability() == True:
print ("The device is currently available.")
else:
print ("The device is currently unavailable.")
e_device1 = EDevice ()
e_device1.setLocation("floor one")
e_device1.checkAvailability()
e_device1.printEDeviceDetails()
| true |
7817f6ec9f063f74dccb25bf04368acee6671eb7 | gabrypol/Algorithms-and-data-structure-IC- | /nth_fibonacci.py | 2,176 | 4.25 | 4 | '''
Write a function fib() that takes an integer n and returns the nth Fibonacci number.
Let's say our Fibonacci series is 0-indexed and starts with 0. So:
fib(0) # => 0
fib(1) # => 1
fib(2) # => 1
fib(3) # => 2
fib(4) # => 3
...
'''
'''
Solution 1:
Using recursion, I can reduce the given problem to many simpler subproblems.
Time: O(2^n)
Space: O(n) The space complexity is the size of the call stack, which never grows larger than n, because there pops and pushes kinda balance each others (I know, this is not the most scientific explanation!). The linear space complexity is easier to prove drawing the recursion tree and the call stack.
def fib(n):
if n == 0 or n == 1:
return n
return fib(n - 1) + fib(n - 2)
'''
'''
Solution 2:
We store the return values of each call in a dictionary, so that I don't need to make multiple calls with the same argument.
Time: O(n)
Space: O(n)
'''
def fib(n):
if n == 0 or n == 1:
return n
cache = {0: 0, 1: 1}
for i in range(2, n + 1):
# As we are in an ascending for loop (from 2 to n + 1), if i - 1 is in the dictionary also i - 2 will be --> There is no need to formally check that i - 2 is in the dictionary.
if i - 1 in cache:
cache[i] = cache[i - 1] + cache[i - 2]
return cache[n - 1] + cache[n - 2]
'''
Solution 3:
We use a bottom-up approach, starting from 0 until we get to n.
Time: O(n)
Space: O(1)
def fib(n):
if n == 0 or n == 1:
return n
before_prev = 0
prev = 1
# when we don't need the index, in Python we can use _, which means that we don't care about i.
for _ in range(n - 1):
current = prev + before_prev
before_prev = prev
prev = current
return current
'''
print("n = 0, fib =", fib(0))
print("n = 1, fib =", fib(1))
print("n = 2, fib =", fib(2))
print("n = 3, fib =", fib(3))
print("n = 4, fib =", fib(4))
print("n = 5, fib =", fib(5))
# Running the function with a large enough input, like fib(37), we can see the huge difference in runtime between O(n^2) of solution 1 and O(n) of solution 2 and 3.
print("n = 6, fib =", fib(37))
| true |
826cd37957db210480006ac6b14cdba95e906d20 | gabrypol/Algorithms-and-data-structure-IC- | /word_cloud.py | 2,678 | 4.28125 | 4 | '''
You want to build a word cloud, an infographic where the size of a word corresponds to how often it appears in the body of text.
To do this, you'll need data. Write code that takes a long string and builds its word cloud data in a dictionary, where the keys are words and the values are the number of times the words occurred.
Think about capitalized words. For example, look at these sentences:
'After beating the eggs, Dana read the next step:'
'Add milk and eggs, then add flour and sugar.'
What do we want to do with "After", "Dana", and "add"? In this example, your final dictionary should include one "Add" or "add" with a value of 22. Make reasonable (not necessarily perfect) decisions about cases like "After" and "Dana".
Assume the input will only contain words and standard punctuation.
You could make a reasonable argument to use regex in your solution. We won't, mainly because performance is difficult to measure and can get pretty bad.
'''
def word_cloud_data(input_string):
words_list = []
current_word_start_index = 0
current_word_length = 0
for i, char in enumerate(input_string):
if len(input_string) - 1 != i and (char.isalpha() or ((char == "'" or char == "-") and input_string[i - 1].isalpha() and input_string[i + 1].isalpha())):
if current_word_length == 0:
current_word_start_index = i
current_word_length += 1
elif char.isalpha() and len(input_string) - 1 == i:
word = input_string[current_word_start_index:]
words_list.append(word)
else:
word = input_string[current_word_start_index:
current_word_start_index + current_word_length]
words_list.append(word)
current_word_length = 0
# Now I create a list without empty strings and making sure that all characters of the string are lowercase
my_clean_least = []
for string in words_list:
if string != '':
my_clean_least.append(string.lower())
my_dict = {}
for string in my_clean_least:
if string in my_dict:
my_dict[string] += 1
else:
my_dict[string] = 1
return my_dict
my_string = 'After beating the eggs, Dana read the next step'
my_string = 'Add milk and eggs, then add flour and sugar.'
my_string = 'I like cake'
my_string = 'Chocolate cake for dinner and pound cake for dessert-'
my_string = 'Strawberry short cake? Yum!'
my_string = 'Dessert - mille-feuille cake'
my_string = 'Mmm...mmm...decisions...decisions'
my_string = "Allie's Bakery: Sasha's Cakes"
print(word_cloud_data(my_string))
'''
Time: O(n)
Space: O(n)
'''
| true |
62a0c2be9dd1b181e966e60fd515f128499ce34f | whereistanya/toddlerclock | /events.py | 2,502 | 4.3125 | 4 | #!/usr/bin/python3
"""A clock to tell your toddler whether they can wake you."""
import logging
import time
MINUTES_IN_DAY = 1440
class Event(object):
"""A single event on a clock, with a start and stop time."""
def __init__(self, start_time, stop_time, description):
"""Create an event. Can't cross midnight boundaries. Make two events.
Midnight is minute 0. 1am is minute 60. 11:55pm is minute 1435.
Args:
start_time, stop_time: ((int, int)): tuple of hours and minutes.
All times are 24h. Events stop at the beginning
of the stop time, i.e., an event from 10am to
description: (str) Text to display for this event.
"""
logging.info("Adding %s from %s to %s", description, start_time, stop_time)
if len(start_time) != 2 or len(stop_time) != 2:
logging.warning(
"Time looks screwy: start (%s), stop (%s)", start_time, stop_time)
return
self.start_minute = start_time[0] * 60 + start_time[1]
self.stop_minute = stop_time[0] * 60 + stop_time[1]
if self.start_minute > self.stop_minute:
logging.warning(
"Start is after stop: %s vs %s", self.start_minute, self.stop_minute)
return
self.description = description
class EventList(object):
"""Time-bounded daily events."""
def __init__(self):
self.minutes = []
for _ in range(0, MINUTES_IN_DAY):
self.minutes.append("") # initialise every minute with no event.
def add(self, event, overwrite=False):
"""Add an event to the day, optionally overwriting existing ones.
One event at a time. Later maybe I'll come back and make this display
multiple things at a time. One's good for now.
Args:
event: (Event): an event to add
"""
for i in range(event.start_minute, event.stop_minute):
if self.minutes[i] == "" or overwrite == True:
self.minutes[i] = event.description
def current(self):
"""Return the current event description.
Returns:
(str): Whatever should be happening right now or empty string.
"""
now = time.localtime()
return self.event_at_minute(now.tm_hour * 60 + now.tm_min)
def event_at_minute(self, minute):
"""Return the event for any given minute.
Returns:
(str): Whatever should be happening at that minute or empty string.
"""
if minute < 0:
logging.warning("Minute less than zero: %s", minute)
return ""
return self.minutes[minute]
| true |
a2d4f606b729ca27dfea6badcebb27b32d1ed352 | gustavoclay/PythonStudy | /exercices/Lista2/ex1.py | 764 | 4.28125 | 4 | '''Faça um Programa que peça os três lados de um triângulo. O programa deverá informar se os
valores podem ser um triângulo.
Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.
'''
a = float(input('Lado a:'))
b = float(input('Lado b:'))
c = float(input('Lado c:'))
'''
if a != b and b != c and c != a:
print ('Triângulo escaleno')
else:
if a == b or b == c or c == a:
print('Triângulo isósceles')
else:
print('Triângulo equilátero')
'''
if a != b:
if b != c and c != a:
print ('Triângulo escaleno')
else:
print('Triângulo isósceles')
else:
if b != c:
print('Triângulo isósceles')
else:
print('Triângulo equilátero')
| false |
7aa74971b0ac528ac4a3094223fe784cd51b12bb | julianfrancor/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 473 | 4.25 | 4 | #!/usr/bin/python3
"function that prints a square with the character"
def text_indentation(text):
"""Args:
text must be a string
"""
if not isinstance(text, str):
raise TypeError("text must be a string")
delimiters = [".", "?", ":"]
aux = "."
for char in text:
if char is " " and aux in delimiters:
continue
print(char, end="")
if char in delimiters:
print("\n")
aux = char
| true |
d43c9e4d31bc5ae951741f9594919c113573e0e1 | capy-larit/exercicios_python | /exer48.py | 849 | 4.25 | 4 | '''
Elabore um programa em Python que seja capaz de contar a quantidade de
números ímpares existentes entre dois números fornecidos pelo usuário.
'''
numero_1 = int(input('Digite um número: '))
numero_2 = int(input('Digite um número maior: '))
cont = 0
if numero_1 > numero_2 or numero_1 == numero_2:
print(
f'''\nEste error pode ter ocorrido:
1. Ou primeiro número digitado é maior que o segundo.
2. Ou os números digitados sãão iguais.'''
)
elif numero_1 % 2 != 0:
while numero_1 < numero_2 and numero_1 != numero_2 - 1 and numero_1 != numero_2 - 2:
numero_1 = numero_1 + 2
cont += 1
print(numero_1)
elif numero_1 % 2 == 0:
numero_1 += 1
print(numero_1)
while numero_1 < numero_2 and numero_1 != numero_2 - 1 and numero_1 != numero_2 - 2:
numero_1 = numero_1 + 2
cont += 1
print(numero_1)
| false |
bc30941e553d9c705866d8679b140e6d63cf2537 | capy-larit/exercicios_python | /exer73.py | 521 | 4.1875 | 4 | """
Faça um programa que leia um número qualquer e mostre o seu factorial.
"""
# OUTRA FORMA DE FAZER
# from math import factorial
# n = int(input('Digite um número para calcular seu factorial: '))
# f = factorial(n)
# print('O factorial de {} é {}.'.format(n, f))
n = int(input('Digite um número para calcular seu factorial: '))
c = n
f = 1
print('Calculando {}! = '.format(n))
while c > 0:
print('{}'.format(c), end=' ')
print('x' if c > 1 else '=', end=' ')
f *= c
c -= 1
print('{}.'.format(f))
| false |
5f1d4ae6e02e4e33bd1e5716d22ee7da2b0c0cbd | capy-larit/exercicios_python | /exer95.py | 675 | 4.21875 | 4 | """
Faça um programa utilizando um dict (dicionário) que leia dados de entrada do usuário. O
usuário deve entrar com os dados de uma pessoa como nome, idade e cidade onde mora.
Após isso, você deve imprimir os dados como o exemplo abaixo:
nome: João
idade: 20
cidade: São Paulo
"""
def chamar_menu():
nome = input('Digite seu nome: ')
idade = int(input('Digite sua idade: '))
cidade = input('Digite sua cidade: ')
dict[nome]=[idade, cidade]
dict = {}
try:
chamar_menu()
except:
print('A idade deve ser um número inteiro.')
chamar_menu()
for chave, item in dict.items():
print(f'Nome: {chave}\nIdade: {item[0]}\nCidade: {item[1]}')
| false |
f62ed7987da178d089221189ed8889b79e68b26c | capy-larit/exercicios_python | /exer20.py | 205 | 4.21875 | 4 | '''
Faça um algoritmo que calcule a raiz do número recebido.
'''
from math import sqrt
num = int(input('Digite um número: '))
raiz = sqrt(num)
print('A raiz de {} é igual a {:.2f}'.format(num, raiz))
| false |
eb232820f7f73dc4a8cc1d698697cd12853f4649 | capy-larit/exercicios_python | /exer24.py | 391 | 4.1875 | 4 | '''
Faça um programa que leia os nomes recebidos e sorteie uma ordem com esses nomes.
'''
from random import shuffle
nome = input('Digite o primeiro nome: ')
nome_1 = input('Digite o segundo nome: ')
nome_2 = input('Digite o terceiro nome: ')
nome_3 = input('Digite o quarto nome: ')
lista = [nome, nome_1, nome_2, nome_3]
shuffle(lista)
print('A ordem sorteada foi: {}'.format(lista)) | false |
2a62d1f4a3d0d2d8365e6668dafdb44667b35ace | capy-larit/exercicios_python | /exer72.py | 754 | 4.3125 | 4 | """
Crie um algoritmo em que o computador sorteie um número e o usuário tente
acertar qual é esse número. No final diga em quantas tentativas ele acertou.
"""
# Sorteia um número
from random import randint
computador = randint(0, 10)
print('Sou seu computador...\nAcabei de pensar em um número entre 0 e 10.\nSerá que você consegue adivinhar qual foi? ')
acertou = False
cont = 0
while not acertou:
jogador = int(input('Qual é o seu palpite? '))
cont += 1
if jogador == computador:
acertou = True
else:
if jogador < computador:
print('Mais... Tente mais uma vez.')
elif jogador > computador:
print('Menos... Tente mais uma vez.')
print('Acertou com {} tentativas.'.format(cont))
| false |
5a76ee6c5b7edc7959888cb8e08974bc05db2dae | capy-larit/exercicios_python | /exer47.py | 600 | 4.375 | 4 | '''
Faça um programa em Python que solicitei ao usuário dois números inteiros e
mostre na tela a soma dos elementos existentes entre os dois números
informados.
'''
numero_1 = int(input('Digite um número inteiro: '))
numero_2 = int(input(
'Digite outro número inteiro: ')
)
soma = 0
if numero_1 < numero_2:
numero_1 += 1
while numero_1 < numero_2:
soma = soma + numero_1
numero_1 += 1
print(soma)
elif numero_2 < numero_1:
numero_2 += 1
while numero_2 < numero_1:
soma = soma + numero_2
numero_2 += 1
print(soma)
else:
print('Digite números distintos.')
| false |
faa204a805bc22d636100b2d6552e1a82888561d | pdelboca/hackerrank | /Algorithms/Implementation/Utopian Tree/solution.py | 985 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 4 18:06:25 2015
@author: pdelboca
Problem Statement
The Utopian Tree goes through 2 cycles of growth every year.
The first growth cycle occurs during the spring, when it doubles in height.
The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian Tree sapling is planted at the onset of spring.
Its height is 1 meter.
Can you find the height of the tree after N growth cycles?
"""
import sys
def calculate_height(cycles):
height = 1
# Itero por todos los ciclos:
# Si es impar: +1
# Si es par: *2
for i in range(cycles):
if (i % 2) == 1:
height = height + 1
else:
height = 2 * height
return height
def main():
T = int(sys.stdin.readline().strip())
for i in range(T):
cycles = int(sys.stdin.readline().strip())
print calculate_height(cycles)
if __name__ == "__main__":
main() | true |
b8d6894771e59fbb5a43cebeaa0ee02c68c8a47d | MachineLearnWithRosh/Data-Structure-and-Algorithms | /LinkedList/NodeInsertion_LL.py | 1,211 | 4.15625 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
def insertNodeBeg(head, newNode):
newNode.next = head
head = newNode
return head
def insertmiddle(head, targetNode, newNode):
cur = head
while(cur.data != targetNode.data):
cur = cur.next
newNode.next = cur.next
cur.next = newNode
return head
def insertEnd(head, newNode):
cur = head
while(cur.next !=None):
cur = cur.next
newNode.next = None
cur.next = newNode
return head
def printList(head):
temp = head
while (temp):
print(temp.data)
temp = temp.next
head = Node('a')
nodeB = Node('b')
nodeC = Node('c')
nodeD = Node('d')
nodeE = Node('e')
nodeF = Node('f')
head.next = nodeB
nodeB.next = nodeC
nodeC.next = nodeD
nodeD.next = nodeE
nodeE.next = nodeF
printList(head)
head = insertNodeBeg(head, Node('z'))
print("***List after inserting z(In the Beg)***")
printList(head)
print("***List after inserting p(In the middle)***")
head = insertmiddle(head, nodeD, Node('p'))
printList(head)
print("***List after inserting M(In the end)***")
head = insertEnd(head, Node('m'))
printList(head) | false |
9c45711d85c91f82586408a10981442712a571a0 | jlbattle/lpthw_exercises | /ex16/ex16_2.py | 927 | 4.34375 | 4 | #this round, I open the file and read it again after writing to it
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CNTRL-C (^C)"
print "If you do want that, hit RETURN."
raw_input("?")
#Opens the file in write('w') and truncate('+') mode
print "Opening and truncating the file..."
target = open(filename,'w+')
print "Now I will ask you for three lines of input"
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
#close out file (like saving)
target.close()
#re-open file with new content and print to console
print "What did you write?"
newTarget = open(filename)
print newTarget.read()
print "And finally, we close it"
newTarget.close() | true |
5a14c31da8d6a4c2e1c919f3150fb16da884b687 | jlbattle/lpthw_exercises | /ex19/ex19.py | 1,314 | 4.125 | 4 | #define the function, its parameters, and its content
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "That's enought for a party!"
print "Get a blanket. \n"
#These are all different ways we can pass parameters to the function
print "We can just give the function numbers directly:"
cheese_and_crackers(20,30)
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
#My function
def santas_little_helper(jolly_level):
print "Hi Santa's Little Helper!"
print "How jolly is the big guy today?"
print "He is at level %d of jolliness" % jolly_level
for x in range(0, jolly_level-1):
print "Ho! "
print "\nRunning the function with an integer parameter"
santas_little_helper(3)
print "\nLet's run this with a variable parameter"
hohos = 10
santas_little_helper(hohos)
print "\nRunning the function with math in the parameter list"
hohos = 1
santas_little_helper(hohos * 6)
| true |
463d6cacb322a56c27008d668168c46432c389c3 | kitilibup/tasks | /task3.py | 255 | 4.15625 | 4 | x1 = float(input("Введите минимум x: "))
x2 = float(input("Введите максимум x: "))
step = float(input("Введите шаг: "))
while x1<=x2:
y=-1.24 * x1**2 + x1
x1+=step
print ("шаг %s:" % x1, y)
| false |
e3e11669edf28ac80b535942e56fb9637a2b54cb | TmNguyen12/python_algos | /reverse_an_array.py | 1,567 | 4.1875 | 4 | # Given a string, that contains special character together with alphabets (‘a’ to ‘z’ and ‘A’ to ‘Z’),
# reverse the string in a way that special characters are not affected.
# Examples:
# Input: str = "a,b$c"
# Output: str = "c,b$a"
# Note that $ and , are not moved anywhere.
# Only subsequence "abc" is reversed
# Input: str = "Ab,c,de!$"
# Output: str = "ed,c,bA!$
import string
import collections
def reverse_an_array(inputString):
dict_lower = dict.fromkeys(string.ascii_lowercase, 0)
dict_upper = dict.fromkeys(string.ascii_uppercase, 0)
alphabet = list(dict_lower.keys()) + list(dict_upper.keys())
dinput = collections.deque()
result_list = []
for l in inputString:
if l in alphabet:
dinput.appendleft(l)
for idx, l in enumerate(inputString):
if l in dict_lower.keys() or l in dict_upper.keys():
result_list.append(dinput.popleft())
else:
result_list.append(inputString[idx])
print("".join(result_list))
# return result_list.join()
input_string = "Ab,c,de!$"
# reverse_an_array(input_string)
# Output: str = "ed,c,bA!$
def betterReverse(inputString):
wordList = list(inputString)
start = 0
end = len(wordList) - 1
while start < end:
# ignore special characters
if not wordList[start].isalpha():
start += 1
elif not wordList[end].isalpha():
end -= 1
else:
wordList[start], wordList[end] = wordList[end], wordList[start]
start +=1
end -= 1
print("".join(wordList))
betterReverse(input_string)
# Output: str = "ed,c,bA!$
| true |
b026bfb3863229b22bd241c1e7ed3451136f6cd2 | TmNguyen12/python_algos | /reverse_string.py | 508 | 4.53125 | 5 | # Write a program to reverse an array or string
# Given an array (or string), the task is to reverse the array/string.
# Examples :
# Input : arr[] = {1, 2, 3}
# Output : arr[] = {3, 2, 1}
# Input : arr[] = {4, 5, 1, 2}
# Output : arr[] = {2, 1, 5, 4}
def reverseString(word):
start = 0
end = len(word) - 1
wordList = list(word)
while start < end:
wordList[start], wordList[end] = wordList[end], wordList[start]
start += 1
end -= 1
print("".join(wordList))
reverseString('hello') | true |
05a285c72d052f8c832c28d1e110023bd1926e78 | Dylans123/First-Step-Python-Workshops | /Week 1/functions.py | 1,766 | 4.5625 | 5 | """
FUNCTIONS
In programming often times we write code that we want to reuse many times.
It can be difficult if we have to write all of our code together and have
no way of deciding which code we want to execute and when. The way this problem is
solved is by splitting our code up into functions and then calling them wherever we need to
use that little bit of code. This helps us write a lot less code and solve problems that previously
we wouldn't have been able to. Below is an example of declaring a function in Python.
"""
def printMyWords(words):
print(words)
printMyWords("Hello there")
"""
Lets go line by line and explain what's happening above. On line 12 we write def and then
printMyWords(words). Whenever you want to create a function in Python, all you have to do
is write def followed by a space and what you want to call your function. Following def, youll have
the name of your function and what you want to pass into your function (In this case a variable called words).
On line 15, were calling our function by just writing the name of our function and then what we want to pass into
it in parentheses. Just think of this as declaring whats in the parentheses when you call the function to be
the variable thats getting passed in (So in this case we're declaring the varibale words to be equal to the
string hello there).
FUNCTIONS WITH A TWIST
Inside a function, we can do anything that we've already gone over. So that includes loops, conditionals, etc.
Below is an example of using a conditional in a function.
"""
def printTheNumber(number):
if number == 10:
print("The number is 10")
elif number == 11:
print("The number is 11")
else:
print("The number was neither 10 nor 11")
printTheNumber(10) | true |
741f24f3b77be7357709f50d594afdb5bb44b2ca | emeznar/PythonPrograms | /setAlarmClock.py | 379 | 4.3125 | 4 | #ask user to input time in hours
current_time = int(input("What time is it now(hours only please)?"))
#ask user how many hours they want to wait for an alarm
alarm_set = int(input("When do you want to set an alarm(in hours)"))
#compute time with alarm hours added to it
wake_time = (current_time + alarm_set)%24
print ("Your alarm is set for " +str(wake_time) +" hundred hours")
| true |
7ef87965a60157dc1f9c96454319008ff6196c44 | emeznar/PythonPrograms | /functionThatReturnsAreaofaCircle.py | 683 | 4.25 | 4 | import math
# TODO: use def to define a function called areaOfCircle which takes an argument called r
def areaOfCircle(r):
a = r**2 * math.pi
return a
#print (areaOfCircle (5))
# TODO implment your function to return the area of a circle whose radius is r
# below are some tests so you can see if your code is correct. You should not include this part in Vocareum.
from test import testEqual
t = areaOfCircle(0)
testEqual(t, 0)
t = areaOfCircle(1)
testEqual(t,math.pi)
t = areaOfCircle(100)
testEqual(t, 31415.926535897932)
t = areaOfCircle(-1)
testEqual(t, math.pi)
t = areaOfCircle(-5)
testEqual(t, 25 * math.pi)
t = areaOfCircle(2.3)
testEqual(t, 16.61902513749)
| true |
f5d2740548dbbfe5dc486b5f69ce7a8dad4135e2 | emeznar/PythonPrograms | /askUserforNumberofSidestoDrawPolygon.py | 380 | 4.28125 | 4 | import turtle
wn = turtle.Screen()
sides = int(input("How many sides does your figure have?"))
distance = int(input("How long is each side?"))
color = input("What color is your turtle?")
fill = input("What color should it be filled with")
alex = turtle.Turtle()
alex.color(color)
alex.fillcolor(fill)
for i in range(sides):
alex.forward(distance)
alex.left(360/(sides))
| true |
8bd3fe01788ce6558bd822dc58fc186b50c0e5fa | Superdadccs57/The_Ultimate_Fullstack_web_development_Bootcamp | /Python101/lesson400_Comparison.py | 1,200 | 4.28125 | 4 | # can_code = True
# if can_code == True:
# #Do a thing
# print("You can code!")
# else:
# #Do Something Else
# print("You don't know how to code yet!")
# teacher = "Kalob Taulien"
# if teacher == "Kalob Taulien":
# print("Show the teacher portal")
# else:
# print("You are a student. Welcome to Python 101")
# if teacher == "Thomas Fentie":
# print("Show the teacher portal")
# else:
# print("You are a student. Welcome to Python 101")
# name = input("What is your name?")
# if name == "Bob":
# print("Welcome Bob!")
# bring_food ="Pizza"
# elif name == "Thomas":
# print("Welcome Thomas")
# bring_food = "Steak and Lobster"
# else:
# print("You're not Bob get outta here")
# bring_food = "Salmon"
# print(f"You are eating {bring_food}")
# name = input("What is your name?")
# name = name.lower()
# if name != "bob":
# print("Your not Bob, get outta here")
# else:
# print("Welcome Bob")
age = input("What is your age?")
age = int(age)
if age > 20:
print("You can drink in the USA")
elif age == 16:
print("You can get your learners licence!")
elif age >= 18:
print("You can Vote")
elif age < 18:
print("You can not vote")
| true |
dfaa0f21933cb52997fb8b377a439550c849a6fb | Superdadccs57/The_Ultimate_Fullstack_web_development_Bootcamp | /Python101/lesson406_Functions.py | 1,077 | 4.53125 | 5 | print("")
def welcome(name):
print(f"Welcome to Lesson 406 Functions; {name}")
print("________________________________________")
welcome("Thomas")
print("")
print("The welcome message just happens to be the first example of this lesson and is designed to welcome me into the lesson using a function!")
print("")
print("Example 2: Multiple Parameters and a default Parameter")
def somename(name, food="Pizza"):
print(f"Hello {name}. Let's eat some {food}")
somename('Thomas')
print("When I called the function somename I declared 'Thomas' for the name parameter but did not use a parameter for the food. Because I set the food parameter to have a default parameter it printed pizza, below I will run the fuction again but this time I will include food parameter to be different from the default Pizza!")
print('')
somename('Cohen', 'Ribs')
print('')
print('Example 3: Creating a basic exponent Calculator')
print('')
def exp(num1, num2):
total = num1 ** num2
return total
print("33 ** 6 = ")
big_number = exp(33, 6)
print(big_number)
| true |
95eb8152ede1763b246b427fac1225e09df0a0d6 | achkataa/Softuni-Programming-Fundamentals | /Functions/6. Password Validator.py | 750 | 4.125 | 4 | input_password = input()
def validator(password):
is_valid = True
if len(password) < 6 or len(password) > 10:
is_valid = False
print("Password must be between 6 and 10 characters")
for el in password:
if el.isdigit() == False:
if el.isalpha() == False:
is_valid = False
print("Password must consist only of letters and digits")
break
digits = 0
for el in password:
if el.isdigit():
digits += 1
if digits < 2:
is_valid = False
print("Password must have at least 2 digits")
return is_valid
is_valid = validator(input_password)
if is_valid:
print("Password is valid") | true |
2fee2311d86f92deec4ee9296b4e4709ac113933 | kerembalci90/python-challenges | /string_sort.py | 237 | 4.1875 | 4 | # input: string of words seperated by space
# output: string of words order alphabetically
def sort_word_list(full_string):
list_of_words = full_string.split()
list_of_words.sort(key=str.lower)
return ' '.join(list_of_words) | true |
4a5d8339547a50321c779fb411e67a5bedc9da54 | G00398347/pands-problem-sheet | /Week 02/bmi.py | 752 | 4.40625 | 4 | #this is a programme that calculates somebody's Body Mass Index (BMI)
#Author: Ruth McQuillan
strweight = input ('Enter your weight in kilograms: ') # this line asks for the persons weight in kgs
strheight = input ('Enter your height in centimetres: ') # ditto for height in cms
heightinmetres= float(strheight)/100 # converts input string height to float and calculates height in metres
weight = float(strweight) # converts input string weight to float
bmi = round( weight/(heightinmetres ** 2 ),2) # performs bmi calculation and rounds to 2 decimal places
print ('Your BMI is: {}. ' .format (bmi) ) # outputs calculation to screen
| true |
a3106b26c45b9b6d34066b35c8e844d23ea2dc10 | mstiles01/learningpython | /listandfunctions/lists.py | 372 | 4.15625 | 4 | #Value "friends" is a list. String, Number, Boolean
friends = ["Kevin", "Karen", "Jim", "Oscar", "Toby"]
print(friends)
#Indicating the Index
print(friends[0])
#Denotes grabbing element from index one and over
print(friends[1:])
#Grabs range of index, not the last index though
print(friends[1:3])
#Changing index position value
friends[1] = "Pam"
print(friends[1])
| true |
5c3e70ff64c9cb390a629acfaef4397af327dbb4 | rianayar/Python-Projects | /Girls Code Inc./Session2.py | 1,764 | 4.40625 | 4 | # # inputs
# print("What is your name?")
# name = input()
# print("Hello", name)
# print()
# # COMMENT ABOVE CODE BEFORE CONTINUING
# # Conditionals: if, elif, else
# x = 15
# y = -8
# if(x > y):
# print("x is greater than y")
# elif(x == y):
# print("x is equal to y")
# else:
# print("x is less than y")
# # using the same x and y we can check conditions on the same line
# if x < 0 and y < 0:
# print("both number are negative")
# elif x < 0 or y < 0:
# print("one number is negative")
# else:
# print("both numbers are positive")
# print()
# # COMMENT ABOVE CODE BEFORE CONTINUING
# Lists
# List of Strings
movies = ["Frozen", "Harry Potter", "Moana"]
print(movies)
#!! Indexing starts from 0 !!
print(movies[0])
print(movies[1])
print(movies[2])
print(movies[-1])
# Modify the list
movies[2] = "Lion King"
print(movies)
# Append and Insert
movies.append("Matilda")
print(movies)
movies.insert(2, "Hidden Figures")
print(movies)
# Slicing the list
print(movies[0:2])
# Removing an item
movies.remove("Matilda")
print(movies)
# Remove with pop: removes and stores the data
currentMovie = movies.pop(0)
print(movies)
print(currentMovie)
# Combining lists
friendsMovies = ["Soul Surfer", "Coco", "Alladin"]
movies.extend(friendsMovies)
print(movies)
# Length of a list
numMovies = len(movies)
print("Number of movies in the list: ", numMovies)
# # COMMENT ABOVE CODE BEFORE CONTINUING
# print()
# # List of ints
# numbers = [12, 8, 20, 54, 67, 50]
# print(numbers)
# # store a sorted list in numbersSorted
# numbersSorted = sorted(numbers)
# print("New Sorted List: ", numbersSorted)
# print("Original List: ", numbers)
# # sort the original list
# numbers.sort()
# print(numbers)
# # Reverse the order
# numbers.reverse()
# print(numbers) | true |
7d0c33c932809af6af84f92072043db310e283b2 | clemencegoh/Python_Algorithms | /algorithms/HackerRank/level 1/warmups/countingValleys.py | 1,731 | 4.40625 | 4 | """
Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography.
During his last hike he took exactly steps. For every step he took, he noted if it was an uphill, U, or a downhill,
D step. Gary's hikes start and end at sea level and each step up or down represents a unit change in altitude.
We define the following terms:
A mountain is a sequence of consecutive steps above sea level,
starting with a step up from sea level and ending with a step down to sea level.
A valley is a sequence of consecutive steps below sea level,
starting with a step down from sea level and ending with a step up to sea level.
Given Gary's sequence of up and down steps during his last hike,
find and print the number of valleys he walked through.
Input Format
The first line contains an integer n, the number of steps in Gary's hike.
The second line contains a single string s, of n characters that describe his path.
:input: 8, UDDDUDUU
_/\\ _
\\ /
\\/\\/
:output: 1
"""
# Completed
class CountingValleysSolution:
def solve(self, n, s):
"""
Concept:
Starting will always be at sea level.
Idea is thus to determine how many times the steps bring him back up to sea level from a valley
Ignore mountains
"""
state = 0
valleyCounter = 0
for i in range(n):
nextStep = s[i].upper()
if nextStep == "U":
state -= 1
if state == 0:
valleyCounter += 1
if nextStep == "D":
state += 1
return valleyCounter
sol = CountingValleysSolution()
print(sol.solve(8, "UDDDUDUU"))
| true |
8a4f773f11a2f0b9b71728993b190ac71c57b50d | basilwong/coding-problems | /hackerrank/python/easy/exercises/regex-and-parsing/detecting-floating-point-number.py | 642 | 4.21875 | 4 | """
Verifies that the given strings can be converted into float numbers.
Note: A quicker way would have been to use REGEX:
import re
for _ in range(int(input())):
print(bool(re.match(r'^[-+]?[0-9]*\.[0-9]+$', input())))
"""
def check_float(s):
try:
float(s)
except(Exception):
return False
else:
if (s == '0'):
return False
return True
if __name__ == '__main__':
t = int(input())
inputs = list()
for i in range(t):
inputs.append(input())
for inp in inputs:
if (check_float(inp)):
print("True")
else:
print("False")
| true |
127ea566e279a49376fdba651b1c8086e5e3dee9 | ArjunBisen/assignments | /calculator.py | 481 | 4.15625 | 4 | #!usr?bin/env python
"""this program defines four functions (multiply, add, subtract, and divide)"""
# This part of the code defines a multiply function
def multiply(a,b):
return a * b
def add(a,b):
return a + b
def subtract(a,b):
return a - b
def divide(a,b):
return a / b
def square(a):
return a ** 2
def cube (a):
return a ** 3
def square_n_time (a,n)
return a ** n
print "I'm going use the calculator functions to multiply 5 and 6"
x = multiply(5,6)
print x
| true |
c645fe0b5568fa3dc0fe8e55cf8e7f72a7280fdf | gmdmgithub/pandas-playground | /validators_util.py | 2,235 | 4.34375 | 4 | import re
import pandas as pd
import validators
import util_func as ut
def valid_email(val):
"""
simple email validation - to consider using python validate_email - existence is possible
Arguments -- val: single cell
Return: 0 - not valied, 1 valied
"""
if ut.isnull(val):
return 0
#from validate_email import validate_email
# return validate_email(val,verify=True)
#for more than one we pick-up first
if len(val.split('|')) > 0 and len(val.split('|')[0]) > 0:
val = val.split('|')[0]
return 0 if not validators.email(val) else 1
def validate_birthday(val):
"""
For a belgium validate birthday and Registry number
In T24 R11 TAX.ID is unique and mandatory if the RESIDENCE is BE. A check is be made on the national register number in Belgium which is composed of 11 digits:
the first 6 positions form the date of birth in the opposite direction. For a person born on July 30, 1985, his first 6 numbers are 850730;
The following 3 positions constitute the daily birth counter. This figure is even for women and odd for men; • the last 2 positions constitute the check digit. This check digit is a sequence of 2 digits.
This number is the complement of 97 of the modulo 97 of the number formed:
- by the first 9 digits of the national number for persons born before 1 January 2000;
- by the number 2 followed by the first 9 digits of the national number for persons born after 31 December 1999.
Checks only Belgium customers
Arguments -- val: three piped cells - Country code | tax.id | birth_day
Return:
- True/False -
"""
if ut.isnull(val):
return False
val = str(val)
val = val.split('|')
if len(val) != 3:
return False
if val[0] != 'BE':
return True
if len(val) <3 :
return False
tax_id = val[1]
tax_id = re.sub(r"\D", "", tax_id)
if len(tax_id) != 11:
return False
if val[2][0] == '2':
tax_id = '2'+tax_id
check_num, val_num = int(tax_id[-2:]), int(tax_id[:-2])
belgium_modulo_number = 97
return (belgium_modulo_number - val_num % belgium_modulo_number) == check_num
| true |
cd84527fd7b49f9837dd3ca6b60a96c1c10e1d15 | sudhirmd005/PYTHON-excerise-files- | /cl_var.py | 1,482 | 4.15625 | 4 | # instance variable and class variable
""" DEFINE : INSTANCE variable can be accessable inside the each instances where as
class variable can be accessible through out the class
Instance variables are variables whose value is assigned inside
a constructor or method with 'self' whereas class variables are variables
whose value is assigned in the class."""
# defining a class
class pet:
family = 'animal'
def __init__(self, name, age, category):
self.name = name
self.age = age
self.category = category
def pet_details(self):
print(f" you pet's name is {self.name}, \n and it is {self.age} years old and it is a {self.family} .\n it belongs to a category of {self.category} ")
#p = pet ("motu", 6, "carnivours") for one time entry
# if user want to change the entry every time then we need to modify the code
try:
check = int(input(" Press 1 if your pet is an animal: "))
if check == 1:
print("your PET is an animal")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
mane = input("please enter your Pet's name: ")
ag = int(input("please enter your Pet's age: "))
cat = input("please enter your Pet's category: ")
p = pet (mane, ag, cat)
p.pet_details()
print(p.family)
else:
raise Exception
except Exception as e:
print(" your have a pet which is not a animal category")
| true |
99da173ebb0630569b348bb913912ff2ffd216da | ayushgnero/temporary | /Pyhton/Problem Solving/Very Big Number.py | 1,394 | 4.1875 | 4 | """
In this challenge, you are required to calculate and print the sum of the elements in an array, keeping in mind that some of those integers may be quite large.
Function Description
Complete the aVeryBigSum function in the editor below. It must return the sum of all array elements.
aVeryBigSum has the following parameter(s):
int ar[n]: an array of integers .
Return
long: the sum of all array elements
Input Format
The first line of the input consists of an integer
.
The next line contains
space-separated integers contained in the array.
Output Format
Return the integer sum of the elements in the array.
Constraints
Sample Input
5
1000000001 1000000002 1000000003 1000000004 1000000005
Output
5000000015
Note:
The range of the 32-bit integer is
.
When we add several integer values, the resulting sum might exceed the above range. You might need to use long int C/C++/Java to store such sums.
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the aVeryBigSum function below.
def aVeryBigSum(ar):
t=0
r = len(ar)
for x in range(r):
t = t + ar[x]
return t
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
ar_count = int(input())
ar = list(map(int, input().rstrip().split()))
result = aVeryBigSum(ar)
fptr.write(str(result) + '\n')
fptr.close()
| true |
77bfe14deea1964d1997f7ad8ee83f7cdffcc197 | EastonI/gpaCalculator | /Grade Percent Average.py | 1,197 | 4.21875 | 4 | print("GPA Calculator\n")
numOfClasses = int(input("Enter your number of classes: "))
if numOfClasses == 4:
grade = float(input("\nEnter the percentage of your first class: "))
grade1 = float(input("Enter the percentage of your second class: "))
grade2 = float(input("Enter the percentage of your third class: "))
grade3 = float(input("Enter the percentage of your fourth class: "))
totalGrade = float(grade) + float(grade1) + float(grade2) + float(grade3)
GPA = float(totalGrade) / 4
print("\nYour GPA is: " + str(GPA))
if numOfClasses == 6:
grade = float(input("\nEnter the percentage of your first class: "))
grade1 = float(input("Enter the percentage of your second class: "))
grade2 = float(input("Enter the percentage of your third class: "))
grade3 = float(input("Enter the percentage of your fourth class: "))
grade4 = float(input("Enter the percentage of your fifth class: "))
grade5 = float(input("Enter the percentage of your sixth class: "))
totalGrade = float(grade) + float(grade1) + float(grade2) + float(grade3) + float(grade4) + float(grade5)
GPA = float(totalGrade) / 6
print("\nYour GPA is: " + str(GPA))
| false |
0a9de29b3d031c4f64c74c248c1012c59697b590 | rajataneja101/Python-Lab | /alternates/classes/time.py | 1,819 | 4.125 | 4 | #16/2/2017
import copy
class time:
hours=0
minutes=0
seconds=0
def __init__(self,hours=0,minutes=0,seconds=0):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def input_values(self):
print("Enter time (hh:mm:ss) : ")
self.hours = int(input("Enter hours : "))
self.minutes = int(input("Enter Minutes : "))
self.seconds = int(input("Enter seconds : "))
def print_values(self):
print(self.hours, ':', self.minutes, ':', self.seconds)
def __add__(self, other):
self.hours = self.hours + other.hours
if(self.hours >= 24):
self.hours -= 24
self.minutes = self.minutes + other.minutes
if(self.minutes >= 60):
self.minutes -= 60
self.hours += 1
self.seconds = self.seconds + other.seconds
if(self.seconds >= 60):
self.seconds -= 60
self.minutes += 1
return time(self.hours, self.minutes, self.seconds)
def __sub__(self, other,t3):
t3.hours = t3.hours - other.hours
if(t3.hours < 24):
t3.hours += 24
t3.minutes = t3.minutes - other.minutes
if(t3.minutes < 0):
t3.minutes += 60
t3.hours -= 1
t3.seconds = t3.seconds - other.seconds
if(t3.seconds < 0):
t3.seconds += 60
t3.minutes -= 1
return time(t3.hours, t3.minutes, t3.seconds)
def __str__(self):
return "{0}:{1}:{2}".format(self.hours,self.minutes,self.seconds)
t1=time()
t2=time()
t1.input_values()
t1.print_values()
t2.input_values()
t2.print_values()
t3=copy.copy(t1)
print("t1+t2",time.__add__(t1,t2))
print("t1-t2=",time.__sub__(t1,t2,t3)) | false |
d56261addd33e68f1a5be1e10a5452c2021fe276 | Drakshayani86/MathBot | /trignometry.py | 897 | 4.1875 | 4 | #importing required modules and files
import math
#finds the trignometic values
def trignometric_val():
#takes user choice as input
value = int(input("Enter your value : "))
if(value>=1 and value<=6):
#takes the user input in degrees
deg = int(input("Enter value of degree: "))
#converting degrees into radians
radian = math.radians(deg)
if(value == 1):
print("Result : ",math.sin(radian))
elif(value == 2):
print("Result : ",math.cos(radian))
elif(value == 3):
print("Result : ",math.tan(radian))
elif(value == 4):
print("Result : ",(1/math.tan(radian)))
elif(value == 5):
print("Result : ",(1/math.cos(radian)))
else:
print("Result : ",(1/math.sin(radian)))
#invalid choice
else:
print("Enter a valid number") | true |
a91a8218ffb59dfe1f6ef6888d3021ad6aca1250 | SumanSunuwar/python-basic-advance | /advance_scopes.py | 1,652 | 4.21875 | 4 | #scopes = > global and local scope
# num = 10 # gloabal variable (Immutable obj)
# def some_func():
# global num
# num += 1 #local variable
# print(f"this is inside function: {num}")
# print(f"value of num before function exec: {num}")
# some_func()
# print(f"value of num after function exec: {num}")
# alist = [1,2,3,4] #global (immutable)
# def func():
# alist.append(10)
# print(f"inside function: {alist}")
# print(alist)
# func()
# print(alist)
# def outer_function():
# def inner_func():
# print("this is inner function")
# inner_func()
# print("this is outer function")
# outer_function()
# def main():
# num = 10
# def inner_func():
# nonlocal num
# num = num + 5
# print(num)
# inner_func()
# main()
# def outer_function(n):
# def first_func():
# print("this is first function")
# def second_func():
# print("this is second function")
# if n == 1:
# return first_func
# if n == 2:
# return second_func
# first = outer_function(1) = first_func
# second = outer_function(2) = second_func
# first()
# second()
# def main(n):
# def add(a,b):
# return a+b
# def sub(a,b):
# return a-b
# if n == 1:
# return add
# elif n == 2:
# return sub
# func_add = main(1) # referencing inner add function = add
# func_sub = main(2) #referencing inner sub function = sub
# print(func_add(12,3))
# print(func_sub(12,3))
#home => login()
#post => login()
#message => login()
# def greet(name):
# print(f"Welcome {name}")
# # greet("ram")
# def greet_shyam(func):
# func("shyam")
# def greet_ram(func): #func = greet
# func("Ram") #greet("Ram")
# greet_ram(greet)
# greet_shyam(greet)
| true |
8ea0e242d2f0027b357281d5ff2e95111711838c | mvkumar14/Data-Structures | /code_challenge_2.py | 2,279 | 4.40625 | 4 | # Print out all of the strings in the following array that represent a number divisible by 3:
# [
# "five",
# "twenty six",
# "nine hundred ninety nine,
# "twelve",
# "eighteen",
# "one hundred one",
# "fifty two",
# "forty one",
# "seventy seven",
# "six",
# "twelve",
# "four",
# "sixteen"
# ]
# The expected output for the above input is:
# nine hundred ninety nine
# twelve
# eighteen
# six
# twelve
# You may use whatever programming language you wish.
# Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process.
# start by defining a dictionary that changes string numbers to
# integers (string integers but still integers)
places = {'hundred': 100}
tens_places = {'twenty':20,"thirty":30,'forty':40,'fifty':50,'sixty':60,'seventy':70,'eighty':80,'ninety':90}
ones = {'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9}
tens = {'eleven':11,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16,'seventeen':17,'eighteen':18,'nineteen':19}
text_num_dict = {}
dicts = [places,tens_places,ones,tens]
for i in dicts:
text_num_dict.update(i)
input_list = [
"five",
"twenty six",
"nine hundred ninety nine",
"twelve",
"eighteen",
"one hundred one",
"fifty two",
"forty one",
"seventy seven",
"six",
"twelve",
"four",
"sixteen"
]
for item in input_list:
word_list = item.split()
output = []
for word in word_list:
number = text_num_dict[word]
if number == 100:
output[-1] = 100 * output[-1]
else:
output.append(number)
check_number = sum(output)
if check_number%3 == 0:
print(item)
# for every item in list
# word_list = string.split()
# for every word in word_list
# start appending values to an output list
# str.join outputlist
# if int(joined output_list) %3 == 0:
# print item
# else continue
# output list functionality
# whenever I see "hundred" multiply the previous number in the output list by
# 100 and then replace the previous value. so instead of appending
# output[-1] = 100 * output[-1]
# then sum up the output array to get my solution.
| true |
ed1438961951485f7787cb4a0fdb5f8e71924ad2 | chandan-stak/AI_1BM18CS026 | /prog3_IDDFS/IDDFS.py | 2,798 | 4.125 | 4 | # Python program to print DFS traversal from a given
# given graph
from collections import defaultdict
# This class represents a directed graph using adjacency
# list representation
class Graph:
def __init__(self, vertices):
# No. of vertices
self.V = vertices
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A function to perform a Depth-Limited search
# from given source 'src'
def DLS(self, src, target, maxDepth):
if src == target: return True
# If reached the maximum depth, stop recursing.
if maxDepth <= 0: return False
# Recur for all the vertices adjacent to this vertex
for i in self.graph[src]:
if (self.DLS(i, target, maxDepth - 1)):
return True
return False
# IDDFS to search if target is reachable from v.
# It uses recursive DLS()
def IDDFS(self, src, target, maxDepth):
# Repeatedly depth-limit search till the
# maximum depth
for i in range(maxDepth):
if (self.DLS(src, target, i)):
return True
return False
print("Iterative deepening depth first search")
n = int(input("Enter the number of vertices: "))
g = Graph(n);
e1 = 1
print("Enter the connecting vertices and -1 to stop")
while e1 != -1:
e1 = int(input("add edge between: "))
if e1 == -1:
break
e2 = int(input("and: "))
g.addEdge(e1, e2)
target = int(input("Enter the target to search: "))
maxDepth = int(input("Enter the maximum depth: "))
src = 0
if g.IDDFS(src, target, maxDepth) == True:
print("Target is reachable from source " +
"within max depth")
else:
print("Target is NOT reachable from source " +
"within max depth")
'''
Output
Iterative deepening depth first search
Enter the number of vertices: 7
Enter the connecting vertices and -1 to stop
add edge between: 0
and: 1
add edge between: 0
and: 2
add edge between: 1
and: 3
add edge between: 1
and: 4
add edge between: 2
and: 5
add edge between: 2
and: 6
add edge between: -1
Enter the target to search: 6
Enter the maximum depth: 3
Target is reachable from source within max depth
Process finished with exit code 0
Iterative deepening depth first search
Enter the number of vertices: 4
Enter the connecting vertices and -1 to stop
add edge between: 0
and: 1
add edge between: 1
and: 2
add edge between: 2
and: 3
add edge between: -1
Enter the target to search: 3
Enter the maximum depth: 1
Target is NOT reachable from source within max depth
''' | true |
7a6c640a591ba246c5e397d953042bed14c0067f | welgt/Exercicios_python_pi2_Dp | /Aula03/Ex03_interseccaoLista.py | 927 | 4.4375 | 4 | '''
3) Escreva um função que efetua a INTERSECÇÃO entre duas listas, ou seja, os
elementos em comum entre as duas listas. Considere que as listas não contêm
valores duplicados e não estão ordenadas. Como resultado deve ser gerado uma
nova lista e retornada, a nova lista conterá a INTERSECÇÃO das duas listas, exemplo:
A = [7, 2, 5, 8, 4] e B = [4, 2, 9, 5]
C = A ∩ B = [2, 5, 4]
'''
def interseccao(a,b):
c = ['*'] * (len(a) + len(b))
i = 0
for A in a:
for B in b:
if A == B:
c[i] = B
if c[i] != '*':
print(c[i], end=" ")
i += 1
a = [7, 2, 5, 8, 4]
b = [4, 2, 9, 5]
interseccao(a,b)
'''
a = [7, 2, 5, 8, 4]
b = [4, 2, 9, 5]
i = 0
j = 0
c= [0]*5
resp = ""
while i < len(a):
while j < len(b):
if a[i] == b[j]:
resp = resp + str(a[i])
#c[i] = a[i]
j+=1
i+=1
print(resp)
print(c)
''' | false |
7d90b4076944f7330a557b2a3dc625f4c039d83e | dp1608/python | /LeetCode/17/171021third_maximum_number.py | 2,077 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# @StartTime : 10/21/2017 14:34
# @EndTime : 10/21/2017 14:49
# @Author : Andy
# @Site :
# @File : 171021third_maximum_number.py
# @Software : PyCharm
"""
Given a non-empty array of integers, return the third maximum number in this
array. If it does not exist, return the maximum number.
The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum
(2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum
distinct number.
Both numbers with value 2 are both considered as second maximum.
"""
#初始化花费了大量的代码行数,不过一遍AC哦
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_number = nums[0]
for num in nums:
if num > max_number:
max_number = num
if len(nums) < 3:
return max_number
# 初始化第二大的元素
i = 0
max_number2 = nums[i]
while max_number2 == max_number:
i += 1
if i == len(nums):
return max_number
max_number2 = nums[i]
for num in nums:
if num > max_number2 and num < max_number:
max_number2 = num
# 初始化第三大的元素
i = 0
max_number3 = nums[i]
while max_number3 == max_number or max_number3 == max_number2:
i += 1
if i == len(nums):
return max_number
max_number3 = nums[i]
for num in nums:
if num > max_number3 and num < max_number2:
max_number3 = num
if max_number3 == max_number or max_number3 ==max_number2:
return max_number
return max_number3
So = Solution()
print So.thirdMax([3, 2, 1])
print So.thirdMax([1, 2]) | true |
bf75bd8eadff62ac94ad23de041ddf5bc5416086 | dp1608/python | /LeetCode/17/171009max_area_of_island.py | 2,305 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @StartTime : 10/9/2017 14:18
# @EndTime : 10/9/2017 15:15
# @Author : Andy
# @Site :
# @File : 171009max_area_of_island.py
# @Software : PyCharm
"""
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's
(representing land) connected 4-directionally (horizontal or vertical.)
You may assume all four edges of the grid are surrounded by water. Find the
maximum area of an island in the given 2D array. (If there is no island,
the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
"""
class Solution(object):
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
max_area = 0
row = len(grid)
col = len(grid[0])
for i in range(row):
for j in range(col):
temp_area = self.findArea(grid,i,j)
if temp_area > max_area:
max_area = temp_area
return max_area
def findArea(self,grid,row,col):
if row < 0 or col < 0:
return 0
if row > len(grid)-1:
return 0
if col > len(grid[0])-1:
return 0
if grid[row][col] == 0:
return 0
elif grid[row][col] == 1:
grid[row][col] = 0
result = self.findArea(grid, row-1, col) + self.findArea(grid, row + 1, col) + \
self.findArea(grid, row, col + 1) + self.findArea(grid, row, col-1)+1
return result
Max = Solution()
grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
result = Max.maxAreaOfIsland(grid)
print('finish')
print(result) | true |
8bb8bfe62a053c3c6dc005e90d69d21167b397e2 | dp1608/python | /LeetCode/1806/180608zigzag_conversion.py | 1,565 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @Start_Time : 2018/6/8 17:43
# @End_time:
# @Author : Andy
# @Site :
# @File : 180608zigzag_conversion.py
"""
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
"""
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
size = len(s)
if numRows < 1:
return
if numRows == 1:
return s
cvt_s = [[] for _ in range(numRows)]
ss = ''
traverse = 0
positive = 1
for i in range(size):
cvt_s[traverse].append(s[i])
if traverse == numRows - 1:
positive = -1
if traverse == 0:
positive = 1
traverse += positive
for i in range(numRows):
ss = ss + ''.join(cvt_s[i])
return ss
s = "PAYPALISHIRING"
print(Solution().convert(s, 3))
# ss = Solution().convert(s, 3)
# ss = ''.join(cvt_s[0])
# print(ss) | true |
1d38d807788b0e3ba2b9c896dcf5c656e7976357 | dp1608/python | /LeetCode/1807/116_populating_next_right_pointers_in_each_node_180702.py | 2,627 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Start_Time : 2018/7/2 15:30
# @End_time:
# @Author : Andy
# @Site :
# @File : 116_populating_next_right_pointers_in_each_node_180702.py
"""
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
Recursive approach is fine, implicit stack space does not count as extra space for this problem.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
Example:
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
"""
# Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
# 不是常数空间,很尴尬,审题
# class Solution(object):
# # @param root, a tree link node
# # @return nothing
# def connect(self, root):
# if not root:
# return
# # tree = [[root]]
# # tree.append(root)
#
# if not root:
# return []
#
# to_print = 1
# res = []
# trees = []
# trees.append(root)
# while trees:
# temp = []
# next_nums = 0
# while to_print:
# temp.append(trees[0])
# if trees[0].left:
# trees.append(trees[0].left)
# next_nums += 1
# if trees[0].right:
# trees.append(trees[0].right)
# next_nums += 1
# del[trees[0]]
# to_print -= 1
# res.append(temp)
# to_print = next_nums
#
# size = len(res)
# for i in range(size):
# for j in range(0, len(res[i]) - 1):
# res[i][j].next = res[i][j + 1]
class Solution(object):
# @param root, a tree link node
# @return nothing
def connect(self, root):
if not root:
return
if root.left:
root.left.next = root.right
else:
return
if root.next:
root.right.next = root.next.left
self.connect(root.left)
self.connect(root.right)
| true |
7da2a3869b97014c1638dc19f39e0676a67ad973 | dp1608/python | /LeetCode/17/171018best_time_to_buy_and_sell_stock.py | 1,851 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# @StartTime : 10/18/2017 15:13
# @EndTime : 10/18/2017 15:58
# @Author : Andy
# @Site :
# @File : 171018best_time_to_buy_and_sell_stock.py
# @Software : PyCharm
"""
Say you have an array for which the ith element is the price of a given stock
on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be
larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
"""
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
max_profit = 0
min_price = prices[0]
for num in prices:
min_price = min(min_price, num)
if num - min_price > max_profit:
max_profit = num - min_price
# max_profit = max(num - min_price, max_profit)
return max_profit
# Wrong answer of [7,2,4,1]
# class Solution(object):
# def maxProfit(self, prices):
# """
# :type prices: List[int]
# :rtype: int
# """
# if len(prices) == 0:
# return 0
# max_price = max(prices)
# min_price = min(prices)
# max_index = prices.index(max_price)
# min_index = prices.index(min_price)
# return max(max_price - min(prices[0:max_index + 1]),
# max(prices[min_index:]) - min_price)
So = Solution()
print So.maxProfit([7, 1, 5, 3, 6, 4])
print So.maxProfit([7, 6, 4, 3, 1])
print So.maxProfit([7, 2, 4, 1])
print So.maxProfit([])
| true |
a84eb297b6a54c8c3b69f375bc9622700111a2b0 | dp1608/python | /LeetCode/17/reshape_the_matrix.py | 2,287 | 4.6875 | 5 | # -*- coding: utf-8 -*-
# @StartTime : 9/28/2017 10:14
# @EndTime : 9/28/2017 10:36
# @Author : Andy
# @Site :
# @File : reshape_the_matrix.py
# @Software : PyCharm
"""
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into
a new one with different size but keep its original data. You're given a matrix represented
by a two-dimensional array, and two positive integers r and c
representing the row number and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements
of the original matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal, o
utput the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped
matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.
"""
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
nums_row = len(nums)
nums_col = len(nums[0])
if r*c > nums_row*nums_col:
return nums
reshape_nums = [[0 for col in range(c)] for row in range(r)]
original_row = 0
original_col = 0
for row in range(0,r):
for col in range(0,c):
reshape_nums[row][col] = nums[original_row][original_col]
if original_col+1 >= nums_col:
original_row += 1
original_col = 0
else:
original_col += 1
return reshape_nums
Solu = Solution()
nums = [[1, 2], [3, 4],[5,6]]
r = 2
c = 3
result = Solu.matrixReshape(nums,r,c)
print result
| true |
f81faa097ead6fc3d0812e0a288c5a4cb893e2a4 | dp1608/python | /LeetCode/1807/134_gas_station_180721.py | 2,544 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# @StartTime : 2018/7/21 21:26
# @EndTime : 2018/7/21 21:40
# @Author : Andy
# @Site :
# @File : 134_gas_station_180721.py
# @Software: PyCharm
"""
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station
(i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once in the clockwise direction,
otherwise return -1.
Note:
If there exists a solution, it is guaranteed to be unique.
Both input arrays are non-empty and have the same length.
Each element in the input arrays is a non-negative integer.
Example 1:
Input:
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
Output: 3
Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
Example 2:
Input:
gas = [2,3,4]
cost = [3,4,3]
Output: -1
Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
"""
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
if sum(gas) < sum(cost):
return -1
if not gas:
return -1
num = len(gas)
sub = []
for i in range(num):
sub.append(gas[i] - cost[i])
index = 0
sum_arr = 0
max_sum = 0
for i in range(num):
sum_arr += sub[i]
if sum_arr > max_sum:
max_sum = sum_arr
if sum_arr < 0:
sum_arr = 0
index = i + 1
return index
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
print(Solution().canCompleteCircuit(gas, cost)) | true |
35160d62a4a0e631598cf309500bf6d84e780527 | dp1608/python | /LeetCode/17/171018pascal's_triangle.py | 1,155 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @StartTime : 10/18/2017 14:20
# @EndTime : 10/18/2017 14:42
# @Author : Andy
# @Site :
# @File : 171018pascal's_triangle.py
# @Software : PyCharm
"""
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
"""
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
nums = []
def generate1(self, i, last_result):
row_result = []
if i == 0:
row_result = [1]
else:
for j in range(i+1):
if j ==0 or j == i:
row_result.append(1)
else:
row_result.append(last_result[j-1] + last_result[j])
return row_result
row_result = []
for i in range(numRows):
row_result = generate1(self,i, row_result)
nums.append(row_result)
return nums
So = Solution()
print So.generate(5)
print So.generate(0) | false |
57d42228e26afb65aef09f2edb2b5104103663cf | CP1404/Practicals | /prac_03/capitalist_conrad.py | 1,156 | 4.1875 | 4 | """
CP1404/CP5632 - Practical
Capitalist Conrad wants a stock price simulator for a volatile stock.
The price starts off at $10.00, and, at the end of every day there is
a 50% chance it increases by 0 to 10%, and
a 50% chance that it decreases by 0 to 5%.
If the price rises above $1000, or falls below $0.01, the program should end.
The price should be displayed to the nearest cent (e.g. $33.59, not $33.5918232901)
"""
import random
MAX_INCREASE = 0.1 # 10%
MAX_DECREASE = 0.05 # 5%
MIN_PRICE = 0.01
MAX_PRICE = 1000.0
INITIAL_PRICE = 10.0
price = INITIAL_PRICE
print(f"${price:,.2f}")
while MIN_PRICE <= price <= MAX_PRICE:
price_change = 0
# generate a random integer of 1 or 2
# if it's 1, the price increases, otherwise it decreases
if random.randint(1, 2) == 1:
# generate a random floating-point number
# between 0 and MAX_INCREASE
price_change = random.uniform(0, MAX_INCREASE)
else:
# generate a random floating-point number
# between negative MAX_DECREASE and 0
price_change = random.uniform(-MAX_DECREASE, 0)
price *= (1 + price_change)
print(f"${price:,.2f}")
| true |
fb364986fb5737f6f517f6d62928cdad5a5f8b06 | CP1404/Practicals | /prac_10/recursion.py | 700 | 4.28125 | 4 | """
CP1404/CP5632 Practical
Recursion
"""
def do_it(n):
"""Do... it."""
if n <= 0:
return 0
return n % 2 + do_it(n - 1)
# TODO: 1. write down what you think the output of this will be,
# TODO: 2. use the debugger to step through and see what's actually happening
print(do_it(5))
def do_something(n):
"""Print the squares of positive numbers from n down to 0."""
if n < 0:
print(n ** 2)
do_something(n - 1)
# TODO: 3. write down what you think the output of do_something(4) will be,
# TODO: 4. use the debugger to step through and see what's actually happening
# do_something(4)
# TODO: 5. fix do_something() so that it works according to the docstring
| true |
c9d2cee52a708856839e5c8659a63b58b67fa6c5 | gauravjoshi1998/joshi_gaurav1-hackerrank | /percentage.py | 627 | 4.125 | 4 | #You have a record of students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry.
#The marks can be floating values. The user enters some integer followed by the names and marks for students.
#The user then enters a student's name. Output the average percentage marks obtained by that student, correct to two decimal places.
#You are required to save the record in a dictionary data type.
N = int(input())
ans = {}
for i in range(N):
g = input().split(' ')
ans[g[0]] = [float(x) for x in g[1:]]
student = input()
print "%.2f" %(sum(ans[student])/len(ans[student]))
| true |
b7db1b591dc1c70e5664f3b6d96167c9f8af3cd0 | snallanc/Python-Projects | /quick-examples/lambdaFunc.py | 361 | 4.34375 | 4 | """
lambda keyword is used to define/return small anonymous functions.
lambda expressions are meant to have just one expression per definition.
"""
def power(x):
return lambda y: x ** y
p=power(10)
print("Powers of 10:\n")
for i in range(1,10):
print(p(i))
"""
Output:
Powers of 10:
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
""" | true |
39d8eb384876ef640b633c9c95097675d8ea670a | SACHSTech/livehack-1-python-basics-JackyW19 | /problem1.py | 556 | 4.1875 | 4 | """
Name: problem1.py
Purpose: compute the temperature in celsius to fahrenheit and output it to the user.
Author: Wang.J
Created: date in 07/12/2020
"""
print ("**** Welcome to the celsius to fahrenheit ****")
# get the temperature in celsius from the UserWarning
celsius_temperature = float(input("Enter the temperature in celsius: "))
# compute the temperature in celsius to fahrenheit
fahrenheit = float(celsius_temperature*(9/5) + 32)
# output the converted fahrenheit temperature
print ("The temperature in fahrenheit is: " + str(fahrenheit)) | true |
c22afee28f141c89f3021c6bf8c6c6caed098afc | bobbytoo2/SJ-Sharks | /TuitionIncrease.py | 1,102 | 4.1875 | 4 | # TuitionIncrease.py
'''
This program calculates tuition (per semester) on a
yearly basis with the percent increase and amount
of years.
'''
def main():
# Enter tuition fee
t = float(input("Enter the current tuition fee: "))
while t < 0:
print("ERROR: The tuition fee cannot be negative.")
t = float(input("Enter the current tuition fee: "))
# Enter tuition increase rate
x = int(input("Enter the percent increase: "))
while x < 0:
print("ERROR: The tuition increase rate cannot be negative.")
x = int(input("Enter the percent increase: "))
# Enter number of years
y = int(input("Enter the number of years: "))
while y < 0:
print("ERROR: The amount of years cannot be negative.")
y = int(input("Enter the number of years: "))
# Print header
print("%4s %16s" %("Year", " Projected Tuition (per Semester)"))
print("---------------------------------------")
# Calculate interest amount
for year in range(1, y+1):
tuitionInterest = t * x/100
# Update per semester tuition
t += tuitionInterest
print("%d %6s %7.2f" %(year, "$", t))
print()
main() | true |
889a9805a5758489e51c052a6e4fb4b8b44cc9d8 | IsadoraRochaB/lp2.4 | /a2b3/quest1.py | 223 | 4.125 | 4 | D = int(input('Insira a quilometragem alcançada pela partícula: '))
D -= 5
(D%8)
if (D%8 <= 3):
print (('Essa partícula atingiu o sensor'),(D%8))
else:
print ('Essa partícula não chegou a atingir algum sensor') | false |
cd98b77f7b44f64495f7221e320b8f7967830e9b | kanatnadyrbekov/Ch1Part2-Task-17 | /task17.py | 1,457 | 4.125 | 4 | # Write the code which will write excepted data to files below
# For example given offices of Google:
# 1) google_kazakstan.txt
# 2) google_paris.txt
# 3)google_uar.txt
# 4)google_kyrgystan.txt
# 5)google_san_francisco.txt
# 6)google_germany.txt
# 7)google_moscow.txt
# 8)google_sweden.txt
# When the user will say “Hello”
# Your code must communicate and give a choice from listed offices. After it
# has to receive a complain from user, and write it to file chosen by user.
# Hint: Use construction “with open”
def complains():
google_branches = {1: 'google_kazakhstan.txt',
2: 'google_paris.txt',
3: 'google_kyrgyzstan.txt',
4: 'google_san_francisco.txt',
5: 'google_germany.txt',
6: 'google_moscow.txt',
7: 'google_sweden.txt'
}
print("Enter a number: ")
for key, value in google_branches.items():
office = value.replace('_', ' ').title()
print(f"{key}:{office.replace('.Txt','')}")
user_choice = int(input("Enter branch num:"))
try:
office = google_branches[user_choice]
user_text = input("Enter your text:")
with open(office, 'w') as the_file:
the_file.write(user_text)
print("Thanks for feedback")
except KeyError:
print("Choose from the list above")
complains()
complains() | true |
850f118e89a82c763881e122bcb146796ce8c12a | mdfarazzakir/Pes_Python_Assignment-3 | /Program55.py | 1,776 | 4.21875 | 4 | """
Exception Handling Write a program for converting weight from Pound to Kilo grams.
a) Use assertion for the negative weight.
b) Use assertion to weight more than 100 KG
"""
"""Function to convert pounds to kg and to check that the weight should not be negative"""
def poundsTokgs(pound):
print("\na)Converting non negative weight as pounds to kgs")
try:
assert(pound>=0),"Cannot accept negative weight"
return("The weight in kg is: ",pound*0.453592)
except AssertionError as AErr:
return("Your weight is of negative value.")
return("Error is ",AErr)
"""Function to convert pounds to kg and to check that the weight should be greater than 100kgs"""
def weight100plus(pound):
print("\nb)Converting weight as pounds to kgs greater than 100kgs")
try:
weightInkg = pound*0.453592
assert(weightInkg>=100),"Cannot accept weight lesser than 100kgs"
return("The weight in kg is: ",weightInkg)
except AssertionError as AErr:
return("Your weight is less than 100kgs, please try again.")
return("Error is ",AErr)
print("\n",poundsTokgs(6))
print("\n",poundsTokgs(-45))
print("\n",weight100plus(5))
print("\n",weight100plus(400))
# Output:
# C:\Users\faraz\Desktop\Python\Pes_Python_Assignments-3>python Program55.py
# a)Converting non negative weight as pounds to kgs
# ('The weight in kg is: ', 2.721552)
# a)Converting non negative weight as pounds to kgs
# Your weight is of negative value.
# b)Converting weight as pounds to kgs greater than 100kgs
# Your weight is less than 100kgs, please try again.
# b)Converting weight as pounds to kgs greater than 100kgs
# ('The weight in kg is: ', 181.4368)
# C:\Users\faraz\Desktop\Python\Pes_Python_Assignments-3> | true |
d94858c4bddeb340f0a45af9a59aa707384ef2fa | mdfarazzakir/Pes_Python_Assignment-3 | /Program60/listPackage/list3.py | 2,146 | 4.28125 | 4 | """
Python List functions and Methods
Create a list of 5 names and check given name exist in the List.
a) Use membership operator (IN) to check the presence of an element.
b) Perform above task without using membership operator.
c) Print the elements of the list in reverse direction.
"""
l = ['Frank','Murray','Arthur','Fleck','Gotham']
"""a) Checking the presence of element in the list using IN operator"""
print("a) Using membership operator (IN) to check the presence of an element.")
ckName = input('\nEnter the name you want to check in the list: ')
if ckName in l:
# pos = [i for i in range(0,len(l))]
print("\nThe name ",ckName," is present in the list at position :",l.index(ckName))
else:
print("\nThe name is not present.")
"""b) Checking the presence of element in the list without IN operator"""
print("\nb) Performing above task a) without using membership operator.")
ckName = input('\nEnter the name you want to check in the list: ')
count=0
for i in range(0,len(l)):
if l[i]==ckName:
print("\nThe name",ckName,"is present in the list at position ",l.index(ckName))
# if count==1:
# print("\nThe name is not present.")
print("\nList before reversing: ",l)
print("\nPrinting the elements of the list in reverse direction.")
rl = [l[i] for i in range(len(l)-1,-1,-1)]
print("\n",rl)
# Output:
# C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-1>python Program15.py
# a) Using membership operator (IN) to check the presence of an element.
#
# Enter the name you want to check in the list: Frank
#
# The name Frank is present in the list at position : 0
#
# b) Performing above task a) without using membership operator.
#
# Enter the name you want to check in the list: Arthur
#
# The name Arthur is present in the list at position 2
#
# The name is not present.
#
# List before reversing: ['Frank', 'Murray', 'Arthur', 'Fleck', 'Gotham']
#
# Printing the elements of the list in reverse direction.
#
# ['Gotham', 'Fleck', 'Arthur', 'Murray', 'Frank']
#
# C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-1>
| true |
deab2c1a0cbc174c7feaa1c00c7dbb837ff09ed9 | mdfarazzakir/Pes_Python_Assignment-3 | /Program58/calc.py | 1,144 | 4.3125 | 4 | """Function to add two numbers"""
def add(num1,num2):
return(num1 + num2)
"""Function to subtract two numbers"""
def subtract(num1,num2):
return(num1 - num2)
"""Function to multiply two numbers"""
def multiply(num1,num2):
return(num1 * num2)
"""Function to find the suare root of a number"""
def squareRoot(num):
import math as m
return(m.sqrt(num))
"""Function to divide two numbers with quotient as output"""
def divide(num1,num2):
return(num1/num2)
"""Function to divide two numbers with remainder as output"""
def modulus(num1,num2):
return(num1%num2)
"""Function to do floor division on two numbers"""
def floorDiv(num1,num2):
return(num1//num2)
"""Function to find if the number is prime or not"""
def primeNumber(num):
count = 0
for i in range(2,num):
if num%i == 0:
count = 1
if count == 1:
print(num," is not a Prime number")
else:
print(num," is a prime number")
"""Function to generate fibonacci series"""
def fibo(num):
n1 = 0
n2 = 1
for _ in range(num):
print(n1)
nxt = n1+n2
n1 = n2
n2=nxt | true |
a87c5c45b59b01bf7934f3ef409e77ce066c6950 | mdfarazzakir/Pes_Python_Assignment-3 | /Program60/stringPackage/string12.py | 2,127 | 4.46875 | 4 | def strgOp():
strg = input("Enter the string: ")
print("\nYour enetered string is: ",strg)
print("\nString operation using startswith return True if S starts with the specified prefix, False otherwise: ")
stg1 = input("Enter the string for check: ")
print("\nAfter performing startswith:",strg.startswith(stg1))
print("\nString operation using endswith return True if S ends with the specified suffix, False otherwise: ")
stg2 = input("Enter the string for check: ")
print("\nAfter performing endswith: ",strg.endswith(stg2))
print("\nString operation using join Concatenate any number of strings: ")
print("\nJoining the strings from whitspace position: ",strg.join(" "))
print("\nString operation using rfind return the highest index in S where substring sub is found: ")
stg3 = input("Enter the string to find its position: ")
print("\nAfter performing rfind: ",strg.rfind(stg3))
print("\nString operation using strip return a copy of the string with leading and trailing whitespace remove: ")
print("\nAfter performing strip: ",strg.strip())
strgOp()
# Output:
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program29_6.py
# Enter the string: Anaconda
#
# Your enetered string is: Anaconda
#
# String operation using startswith return True if S starts with the specified prefix, False otherwise:
# Enter the string for check: A
#
# After performing startswith: True
#
# String operation using endswith return True if S ends with the specified suffix, False otherwise:
# Enter the string for check: a
#
# After performing endswith: True
#
# String operation using join Concatenate any number of strings:
#
# Joining the strings from whitspace position:
#
# String operation using rfind return the highest index in S where substring sub is found:
# Enter the string to find its position: a
#
# After performing rfind: 7
#
# String operation using strip return a copy of the string with leading and trailing whitespace remove:
#
# After performing strip: Anaconda
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>
| true |
f47d8e9d4fed9676d7e6b134f18818d93db21d44 | mdfarazzakir/Pes_Python_Assignment-3 | /Program41b.py | 846 | 4.15625 | 4 | """
Dictionary and Date & Time:
Using calendar module perform following operations.
a) Print the 2016 calendar with space between months as 10 characters.
b) How many leap days between the years 1980 to 2025.
c) Check given year is leap year or not.
d) print calendar of any specified month of the year 2016.
"""
"""Importing the calender module"""
import calendar as cl
"""Requirment is to calculate the number of leap days between the years 1980 to 2025, so stating the limit"""
yearFrom = 1980
yearTill = 2025
"""Using the leapDays() method to get the number of leap days"""
leapDays = cl.leapdays(yearFrom,yearTill)
print("Total number of leap days is %d between 1980 and 2025"%leapDays)
# Output:
# rgolem@golem:~/Desktop/Python/Pes_Python_Assignments-3$ python3 Program41b.py
# Total number of leap days is 12 between 1980 and 2025 | true |
ac44a72d80053e2484a03a77451db74accf387ae | mdfarazzakir/Pes_Python_Assignment-3 | /Program60/stringPackage/string5.py | 2,072 | 4.59375 | 5 | """
Strings:
Write a program to check given string is Palindrome or not.That is reverse the given string and check whether it is same as original string, if so
then it is palindrome.Example: String = "malayalam" reverse string = "malayalam" hence given string is palindrome. Use built functions to check
given string is palindrome or not.
"""
"""Taking sting input"""
strg = input("Enter the string: ")
"""Length of the string"""
sL = len(strg)
"""Intializing a variable as string"""
strg1 = str()
for i in range(sL-1,-1,-1):
strg1 = strg1 + strg[i]
if strg1 ==strg:
print("Palindrome")
else:
print("Not a palindrome")
# Output:
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program27.py
# Enter the string: Arora
# Not a palindrome
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program27.py
# Enter the string: malayalam
# Palindrome
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program27.py
# Enter the string: arora
# Palindrome
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program27.py
# Enter the string: aaaabbbaaa
# Not a palindrome
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program27.py
# Enter the string: aaabbbaaa
# Palindrome
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program27.py
# Enter the string: acacacaca
# Palindrome
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program27.py
# Enter the string: acacacacac
# Not a palindrome
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program27.py
# Enter the string: acacacaa
# Not a palindrome
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>ccaaccaacc
# 'ccaaccaacc' is not recognized as an internal or external command,
# operable program or batch file.
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program27.py
# Enter the string: ccaaccaaccaacc
# Palindrome
#
# (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>
| true |
a9d6b7af8185c2cca2dd3df0c0a9aace8b3e4942 | Amarthya03/Scripting-Languages-Lab | /Week_2/lab2.py | 635 | 4.25 | 4 | # Python has 5 data types: Number, String, List , Tuple, Dictionary
# Strings are immutable
# All the elements belonging to a list or tuple can be of different data type
# List elements and size can be changed
# Tuples are "read-only" lists. They are immutable. Once created, their size and elements cannot be changed
# We need tuples, because they are homogeneous, meaning they can store only one type of data
# Question: demo - 3
mydictionary = { "name": "Michael Corleone", "identity": "The Godfather", "age": 30 }
print(mydictionary)
key = mydictionary["name"]
value = mydictionary.get("name")
print("Key is", key)
print("Value is", value)
| true |
f500e62929cdeee175464927e2564d59eda1d8ac | vonbalzer/module | /db/people.py | 288 | 4.25 | 4 | def what():
answer = input("Do you know how much will be, 2 + 2 ? !!!yes or no!!!")
if answer == 'yes':
print('You are smart')
elif answer == 'no':
print('You need to learn the multiplication table, xD')
else:
print('Read the terms carefully)))') | true |
61bd084536f349759ea4ce6e26a81a507f30b56e | aliceshan/Practice-Questions | /recursion_dynamic_programming/robot_in_a_grid.py | 2,743 | 4.25 | 4 | """
Type: Dynamic programming, graphs
Source: Cracking the Coding Interview (8.2)
Prompt: Imagine a rovot sitting on the upper left corner of grid with r rows and c columns.
The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them.
Design an algorithm to find a path for the robot from the top left to the bottom right.
"""
import unittest
def get_path(grid):
''' Dynamic programming, going backwards from (r,c). Like backwards DFS.
Note: finds a path, not necessarily shortest path.
'''
if not grid:
return None
path = []
failed = set()
if _get_path(grid, len(grid) - 1, len(grid[0]) - 1, path, failed):
return path
return None
def _get_path(grid, row_idx, col_idx, path, failed):
if row_idx < 0 or col_idx < 0 or not grid[row_idx][col_idx]: #if we are out of bounds, or the step is "off limits"
return False
point = row_idx * len(grid[0]) + col_idx # points are counted to the right then down, starting at 0
if point in failed:
return False
if point == 0 or _get_path(grid, row_idx, col_idx - 1, path, failed) or _get_path(grid, row_idx - 1, col_idx, path, failed):
path.append(point)
return True
failed.add(point)
return False
def get_path_dfs(grid):
''' TODO: complete this implementation.
DFS going forwards from (0,0). Same as above but going in the opposite direction.
Note: finds a path, not necessarily shortest path.
'''
path = []
visited = set() # could also use a list of length r*c to keep track of indices, but avg lookup time is the same
if _get_path_dfs(grid, 0, 0, path, visited):
return reversed(path)
return None
def _get_path_dfs(grid, row_idx, col_idx, path, visited):
if row_idx >= len(grid) or col_idx >= len(grid[0]) or not grid[row_idx][col_idx]:
return False
point = row_idx * len(grid[0]) + col_idx
if point == (len(grid)-1)*(len(grid[0])-1) or _get_path_dfs(grid, row_idx + 1, col_idx, path, visited) or _get_path_dfs(grid, row_idx, col_idx + 1, path, visited):
return True
class GetPathTests(unittest.TestCase):
def setUp(self):
# empty grid
self.grid1 = [[]]
self.ev1 = None
# one element grid
self.grid2 = [[True]]
self.ev2 = [0]
# grid with no path
self.grid3 = [
[True, False, False],
[False, True, True]]
self.ev3 = None
#grid with one path
self.grid4 = [
[True, False, False],
[True, True, True],
[False, False, True],
]
self.ev4 = [0, 3, 4, 5, 8]
def test_get_path(self):
self.assertEqual(get_path(self.grid1), self.ev1)
self.assertEqual(get_path(self.grid2), self.ev2)
self.assertEqual(get_path(self.grid3), self.ev3)
self.assertEqual(get_path(self.grid4), self.ev4)
if __name__ == '__main__':
unittest.main()
| true |
560df3a1ab20c6a2e6f2966e6070e93a2682d537 | parisa7103/Python | /hw3q3.py | 400 | 4.125 | 4 | #Define a procedure, product_list,
#takes as input a list of numbers,
#and returns a number that is
#the result of multiplying all
#those numbers together.
#product_list([9]) => 9
#product_list([1,2,3,4]) => 24
def product_list(inputList):
result = 1
for a in inputList:
result *= a
print result
inputList1 = [9]
inputList2 = [1,2,3,4]
product_list(inputList1)
product_list(inputList2)
| true |
ab1c2281fd3c21a6768c9c4343c11146b95b29a6 | TanyaPaquet/sortrec | /sortrec/sorting.py | 2,490 | 4.46875 | 4 | def bubble_sort(items):
'''Return array of items, sorted in ascending order.
Args:
items (array): list or array-like object to sort.
Returns:
array: list or array-like object to sorted in acsending order.
Examples:
>>> bubble_sort([3, 6, 3, 5, 8, 1])
[1, 3, 3, 5, 6, 8]
>>> bubble_sort(['bee', 'fly', 'mozzi', 'bug'])
['bee', 'bug', 'fly', 'mozzi']
'''
end = len(items) - 1
while end != 0:
#Check and swap element by element.
for i in range(end):
if items[i] > items[i+1]:
items[i], items[i+1] = items[i+1], items[i]
end = end - 1
return items
def merge_sort(items):
'''Return array of items, sorted in ascending order.
Args:
items (array): list or array-like object to sort.
Returns:
array: list or array-like object to sorted in acsending order.
Examples:
>>> merge_sort([3, 6, 3, 5, 8, 1])
[1, 3, 3, 5, 6, 8]
>>> merge_sort(['bee', 'fly', 'mozzi', 'bug'])
['bee', 'bug', 'fly', 'mozzi']
'''
length = len(items)
if length == 1:
return items
mid = length // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
ordered = []
while len(left) > 0 and len(right) > 0:
if left[0] < right[0]:
ordered.append(left[0])
del left[0]
else:
ordered.append(right[0])
del right[0]
if len(left) == 0:
ordered = ordered + right
if len(right) == 0:
ordered = ordered + left
return ordered
def quick_sort(items):
'''Return array of items, sorted in ascending order.
Args:
items (array): list or array-like object to sort.
Returns:
array: list or array-like object to sorted in acsending order.
Examples:
>>> quick_sort([3, 6, 3, 5, 8, 1])
[1, 3, 3, 5, 6, 8]
>>> quick_sort(['bee', 'fly', 'mozzi', 'bug'])
['bee', 'bug', 'fly', 'mozzi']
'''
length = len(items)
if length <= 1:
return items
check = items[-1]
less = []
more = []
equal = []
#Compare to check and organise accordingly
for i in items:
if i < check:
less.append(i)
elif i > check:
more.append(i)
elif i == check:
equal.append(i)
less = quick_sort(less)
more = quick_sort(more)
return less + equal + more
| true |
6fa9fd0df0aa8c79b20d6844d9df464589a145a2 | PrithviRajMamidala/Leetcode_Solutions | /Problems/Arrays&Strings/climbingStairs.py | 424 | 4.125 | 4 | """bottom-top approach
Can use dictionary for storing other elements and easy lookup more optimized solution"""
def climbStairs(n):
stairs = []
stairs.extend([0, 1, 2])
# print(stairs)
if n <= 2:
return stairs[n]
i = 3
while i <= n:
stairs.append(stairs[i-1] + stairs[i-2])
i += 1
return stairs[n]
if __name__ == '__main__':
print(climbStairs(4)) | true |
abf3c8d71bd970d0b6f48040b70f1e9df32fba0f | rohan2jos/SideProjects | /BinaryTree/HeapNode.py | 2,092 | 4.21875 | 4 | '''
Class for the node that will be used in the heap
will be imported into the implementing program
'''
class HeapNode:
data = 0
left = ''
right = ''
'''
__init__() --> constructor
args: data, left node, right node
returns: the initialized node with the passed arguments
'''
def __init__(self, data, left, right):
print "[HeapNode.__init__()] initializing HeapNode with ", data
self.data = data
self.left = None
self.right = None
'''
get_data()
args: none
returns: the data that is contained in this node
'''
def get_data(self):
return self.data
'''
get_right()
args: none
returns: the right sub-node to this node. Will return nothing if it is the leaf node
'''
def get_right(self):
print "[HeapNode.get_right()] returning the right node of the current HeapNode"
return self.right
'''
get_left()
args: none
returns: the left sub-node to this node. Will return nothing if it is the leaf node
'''
def get_left(self):
print "[HeapNode.get_left()] returning the left node of the current HeapNode"
return self.left
'''
set_data()
args: Integer -> data
returns: nothing
Sets the data of this node to the data argument that was passed
'''
def set_data(self, data):
print "[HeapNode.set_data] setting data of the HeapNode to ", data
self.data = data
'''
set_right()
args: HeapNode
returns: nothing
Sets the right sub-node of this node to the node that was passed
'''
def set_right(self, node):
print "[HeapNode.set_right] setting the right node of " + str(self.data) + " to " + str(node.get_data())
self.right = node
'''
set_left()
args: HeapNode
returns: nothing
Sets the left sub-node of this node to the node that was passed
'''
def set_left(self, node):
print "[HeapNode.set_left] setting the left node of " + str(self.data) + " to " + str(node.get_data())
self.left = node
| true |
404285ea7804e88c002400b7f301f07933f2ea5b | jdpoccorie/ejercicios | /r5_10.py | 546 | 4.125 | 4 | # Nombre: Juan Diego Poccori Escalante
# Código: 144884
# 10. Escribir un algoritmo para calcular el promedio aritmético de N números
# Leer numero
numero = int(input("Ingresar número: "))
# Verificar si numero es positivo
if numero >= 0:
i = 1
suma = 0
promedio = 0
while numero >= i:
# Leer numeros
ingresaNum = int(input(f"Ingresar numero {i}: "))
suma+=ingresaNum
i+=1
# Calcuar promedio
promedio = suma / numero
# Mostrar promedio
print(f"El promedio es: {promedio}")
else:
print("Error: Debe ser un número positivo")
| false |
7fc0f940d23c137748ab18f91b1625b25d2c38f3 | sampita/Python-Showroom-Junkyard | /cars.py | 1,655 | 4.1875 | 4 | # Create an empty set named showroom.
showroom = set()
# Add four of your favorite car model names to the set.
showroom = {'Jeep Renegade', 'Kia Soul', 'Ford Thunderbird', 'Toyota Prius'}
# Print the length of your set.
print(len(showroom))
# Pick one of the items in your show room and add it to the set again.
showroom.add('Ford Thunderbird')
# Print your showroom. Notice how there's still only one instance of that model in there.
# print(showroom)
# Using update(), add two more car models to your showroom with another set.
showroom.update(['Tesla Truck', 'Honda CRV'])
# print(showroom)
# You've sold one of your cars. Remove it from the set with the discard() method.
showroom.discard('Tesla Truck')
print(showroom)
#Acquiring more cars
#Now create another set of cars in a variable junkyard. Someone who owns a junkyard full of old cars has approached you about buying the entire inventory. In the new set, add some different cars, but also add a few that are the same as in the showroom set.
junkyard = {'Jeep Renegade', 'Kia Soul', 'Ford Thunderbird', 'Toyota Corolla', 'Hyundai Sonata'}
# Use the intersection method to see which cars exist in both the showroom and that junkyard.
intersect_table = list(showroom & junkyard)
print("intersect_table:", intersect_table)
# Now you're ready to buy the cars in the junkyard. Use the union method to combine the junkyard into your showroom.
union_set = showroom.union(junkyard)
# print("union:", union_set)
# Use the discard() method to remove any cars that you acquired from the junkyard that you do not want in your showroom.
union_set.discard('Toyota Corolla')
print("union:", union_set) | true |
02640b8941b4e0ea239b980c9ea90123cd6c538b | jared-chapman/Projects | /Python/Python_Examples/Chapter 9 (Files)/Writing to files.py | 1,167 | 4.3125 | 4 | #open a file with the open function
#Takes two parameters, a string representing the path, and a string representing the mode to open the file in
#File paths shouldn't be typed manually as different OS's label them differently
#Instead, use the built-in os module. Takes each location in a file as a parameters
#Filepath parameter
import os
filepath = os.path.join("C",
"Users",
"jared",
"Desktop",
"Python Examples",
"Chapter 9 (Files)",
"Example.py")
print(filepath)
#Mode parameter
#R - read only
#W - for writing only. Overwrites file if it exists. Creates a new file if it doesn't
#W+ - for reading and writing. Overwrites file if it exists. Creates a new file if it doesn't
#open function returns an object, called a file object
#Which can be used to read or write to a file .
#If you open a file with the open function, you must cles it with the close function.
#Opens a file, writes text to it, then closes the file
st = open("st.txt", "w")
st.write("Hi from Python!")
st.close
| true |
9c8d0bf8df50fb169aec3657cdb7cb0c2ebd0faf | jared-chapman/Projects | /Python/Python_Examples/Chapter 4 (Functions)/Functions.py | 924 | 4.59375 | 5 | #Define a function with [def functionName(paramaters):]
def double(x):
return x*2
#Call a function with [functionName(paramaters)]
result = double(3)
print(result)
#A function doesn't have to have parameters
def sayMyName():
return "Jared"
name = sayMyName()
print(name)
#A function can have multiple parameters, and doesn't have to return
def multiply(a,b):
print(a*b)
multiply(3,4)
#A function can have optional parameters
#Optional parameters are defined with the function
def pow(q, w=2):
"""
:q: int to be squared
:w: to the power of
:return: int q to the power of w, or squared if blank
"""
return q**w
print(pow(4,4)) #4 to the power of 4
print(pow(5)) #5 to the power of 2
#Built-in Functions
print(len("Hello"))
print(str(100)) #int to string
print(int("4")) #string to int
print(float(100)) #int to float
| true |
a4c841c701a38f50417a4b3f1c91f630f17cd5f8 | Lackman-coder/python-tutorail | /while_loop/introduction.py | 690 | 4.53125 | 5 | i = 1
while i < 6:
print(i)
i += 1 # With the while loop we can execute a set of statements as long as a condition is true.
# Note: remember to increment i, or else the loop will continue forever.
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1 # With the break statement we can stop the loop even if the while condition is true.
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i) # With the continue statement we can stop the current iteration, and continue with the next.
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6") # With the else statement we can run a block of code once when the condition no longer is true.
| true |
ad064a81e1db44094af4f23eca4857085402a233 | Lackman-coder/python-tutorail | /list/add list items.py | 722 | 4.5625 | 5 | thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist) # To add an item to the end of the list, use the append() method.
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist) # Insert an item as the second position.
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist) # Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple) # The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).
print(thislist) # Add elements of a tuple to a list.
| true |
09fdff6a6ae012ea69be341a50b80954b2d7ab41 | Lackman-coder/python-tutorail | /list/remove list itmes.py | 699 | 4.4375 | 4 | thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist) # The remove() method removes the specified item.
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist) # The pop() method removes the specified index.
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist) # If you do not specify the index, the pop() method removes the last item.
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist) # The del keyword also removes the specified index.
thislist1 = ["apple", "banana", "cherry"]
del thislist1
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist) # The clear() method empties the list. | true |
67d39141c45d50ecf1b95ada231c6c603fcaba26 | kinderferraz/mc102 | /lab02/main.py | 1,015 | 4.25 | 4 | # MC102 O -- Alkindar Rodrigues
# lab 02 -- Calculadora simples
# para ler o primeiro operando
op1 = input()
if op1.isdigit():
op1 = int(op1)
else:
op1 = float(op1)
# para ler a operação a ser realizada
e = input()
# para ler o segundo operando
op2 = input()
if op2.isdigit():
op2 = int(op2)
else:
op2 = float(op2)
# variavel de controle para casos de divisão por zero
erro = False
# para realizar o cálculo
if e == "+":
calc = op1 + op2
elif e == "-":
calc = op1 - op2
elif e == "*":
calc = op1 * op2
elif e == "/":
if op2 != 0:
calc = op1 / op2
else:
erro = True
elif e == "//":
if op2 != 0:
calc = op1 // op2
else:
erro = True
elif e == "%":
if op2 != 0:
calc = op1 % op2
else:
erro = True
elif e == "**":
calc = op1**op2
# verifica o tipo do resultado e imprime de acordo
if erro is False:
if type(calc) == int:
print(calc)
else:
print(format(calc, ".2f"))
else:
print("Erro.")
| false |
6122065a8b5bf2e5c61c3a0a92464559a6c5281e | gdashua/codeWitAssignments | /codewit_July_Wk3/ageFinder.py | 1,187 | 4.28125 | 4 | #second assignment
import datetime
def ageFinder():
print('Please enter your last birthday to know you exact birthdate')
print()
try:
day = int(input('day: '))
month = int(input('month: '))
year = int(input('year: '))
day_position = '';
print('How old are you?')
current_age = int(input())
birth_year = year-current_age #gets the year you were born
x = datetime.datetime(birth_year, month, day ) #sets the dateObject for birthday
day = str(day)
day_arr=list(day)
if (day_arr[len(day)-1]) == '1':
day_position = 'st'
elif (day_arr[len(day)-1]) == '2':
day_position = 'nd'
elif (day_arr[len(day)-1]) == '3':
day_position = 'rd'
else:
day_position = 'th'
day +=day_position
print()
#gets the exact day, month and year from the birthday object
print('HURRAY!!! You birthdate is: ' + x.strftime("%A")+ ', '+day+' '+x.strftime("%B")+ ' ' +x.strftime("%Y"))
print()
print('You can check again or exit...')
ageFinder()
except:
print()
print('Wrong input! only positive integers are accepted,')
ageFinder()
ageFinder() | false |
7f3e78c527fb47cf594222462974dd04342819a8 | JoaquinRodriguez2006/CursoPythonSabados | /Ejercicios Clase 1 - Joaquín Rodríguez.py | 1,431 | 4.125 | 4 | #CLASE 1:
# Ejercicio 1
mensaje=("Hola")
print(mensaje)
mensaje=("Chau")
print(mensaje)
#Ejercicio 2
mensaje=("HolaFede")
print(mensaje)
#Ejercicio 3
print(5+3)
print(9-1)
print(80/10)
print(4*2)
#Ejercicio 4
mi_entero=14
print(type(mi_entero))
mi_booleano=True
print(type(mi_booleano))
mi_string= "AB12"
print(type(mi_string))
mi_real=(1.000)
print(type(mi_real))
#RESULTADOS:
'''
<class 'int'>
<class 'bool'>
<class 'str'>
<class 'float'>
'''
#Ejercicio 5
print(int(3.8))
print(int("4"))
#Ejercicio 6
print(1 != 2)
#Salida:True
print(True == 1)
#Salida:True
print(False != False)
#Salida:False
print(False > 0)
#Salida:False
var5= ()
print(1.0 < 1)
#Salida:False
print("test" == "test")
#Salida:True
print(1.0 >= 1)
#Salida: True
#Ejercicio 7
entrada = input("ingrese su nombre: ")
entrada = input("ingrese su edad: ")
variable100 = (100-input("ingrese su edad: "))
sumaaños = (2021+variable100)
#Ejercicio 8
Celsius = 30
Fahrenheit = (9.0/5.0) * Celsius + 32
print(Fahrenheit)
#TEMPERATURA: 86° FAHRENHEIT
#Ejercicio 9
entrada1 = input("ingrese un numero: ")
entrada2 = input("ingrese otro numero: ")
suma = (entrada1 + entrada2)
resta = (entrada1 - entrada2)
multiplicación = (entrada1*entrada2)
división = (entrada1/entrada2)
potencia = (entrada1**entrada2)
divisiónentera = (entrada1//entrada2) | false |
c7a8a4ab465127aad357db61f5a00cf496a27c4a | leobarros/zumbis | /lista_1/questao08.py | 265 | 4.21875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#Faça agora o contrário, de Fahrenheit para Celsius.
fahrenheit = float(input("Temperatura em Fº: "))
celsius = ((fahrenheit - 32) / 1.8000)
#ºC = ((ºF - 32)/1.8000)
print ("Temperatura em Celsius é: ", celsius)
| false |
acf5c8dc39ec562558978c1f25b7f5ca4d039edd | sayaliphatak9628/Python | /Data structure - Tuples.py | 374 | 4.34375 | 4 | '''
#Tuples are like list.
#tuples introduction
x = ('abc','def','ghi','jkl')
print(x)
print(x[2])
y=(1,3,9,12,7,4)
print(max(y))
y[2]=5
print(y)
for i in y:
print(i)
#tuples can be added on left-hand side also
#tuples and dictionaries
(x,y) = (1,'sayali')
print(x,y)
(a,b) = (44,65)
print(b)
dic = dict()
dic ['a']=65
dic['b']=66
tupp=dic.items()
print(tupp)
'''
| false |
ae5e01be8e3605a1c14866421730be6f299b1bc8 | greysou1/pycourse | /mod2/practice/challenge.py | 602 | 4.15625 | 4 | the_list = ['cat', 'dog', 'machine']
def list_o_matic(the_list, entry):
if entry == '':
popped = the_list.pop()
return popped + ' popped from list'
elif entry in the_list:
the_list.remove(entry)
return '1 instance of "' + entry + '" removed from the list'
else:
the_list.append(entry)
return '1 instance of "' + entry + '" appended to the list'
while the_list:
print(the_list)
entry = input('Enter: ')
if entry == 'quit':
break
else:
print(list_o_matic(the_list, entry))
print('Goodbye!') | true |
7ec2a68c19999add01fe0d807dc817fee175d94c | midhilajnisam1/dumbest-dictionary | /Firstprog/mishi.py | 489 | 4.3125 | 4 | dict1 = {"Burger":"Best fast food for timepass", "PS4":"A Gaming Console for Game Lovers", "Midhilaj":"Best in the world","Avengers":"Best multi super hero movie ever",2:"Lucky Number for Most peoples" }
print("""Enter any of the words below to know the dumbest definitions\n
1. Burger\n
2. PS4\n
3. Midhilaj\n
4. Avengers\n
5. 2\n
""")
user_input= input("Enter your selected word from the list:\n")
print(dict1[user_input])
print("Thank You for using Dumbest Dictionary Ever!!") | false |
f078f8206acd2bdeb1429404507975e17fb84c90 | bijp/pycharm | /actual_combat/top6.py | 523 | 4.21875 | 4 | """定义一个python类IOString,有两个成员方法get_String 和 print_String
get_String 获取用户输入
print_String 将获取的输入信息大写输出
请写出类的实现,并分别调用这两个方法"""
class IOString():
def __init__(self):
self.inpu=''
def get_String(self):
self.inpu=input('请输入信息:')
def print_String(self):
t=self.inpu
print(t.upper())
if __name__ == '__main__':
ios = IOString()
ios.get_String()
ios.print_String() | false |
e6e14e6d570ac3ea2d0d5622545d817323a23b18 | TheSahilGit/Recursive-Functions | /Recursion.py | 1,159 | 4.3125 | 4 | """Use of recursive function to draw beautiful fractal patterns."""
### Sahil Islam ###
### 09/06/2020 ###
import pygame
pygame.init()
width = 800
height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height))
"""This specific method draws the Sierpinski triangle. (Both circle and square) """
#
def circle(x, y, r):
pygame.draw.circle(screen, red, (int(x), int(y)), int(r), 1)
if r > 2:
circle(x + 0.5 * r, y, r * 0.5)
circle(x - 0.5 * r, y, r * 0.5)
circle(x, y + 0.5 * r, r * 0.5)
def square(x, y, w):
pygame.draw.rect(screen, red, [int(x - w / 2.), int(y - w / 2.), int(w), int(w)], 1)
if w > 2:
square(x + 0.5 * w, y, w * 0.5)
square(x - 0.5 * w, y, w * 0.5)
square(x, y - 0.5 * w, w * 0.5)
#
while True:
screen.fill(white)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
square(width / 2., height / 2., 300)
pygame.display.update()
clock.tick(100)
| false |
38998023327df8304e560fe098edcc07fb05cdec | adrianocerutti/fatorial_python | /fatorial.py | 354 | 4.15625 | 4 | '''
Programa que lê um número inteiro n >= 0 e imprime n!
'''
print("Cálculo do fatorial de um número\n")
# leia o valor de n
n = int(input("Digite um número inteiro não-negativo: "))
i = 1 # contador
n_fat = 1 # variável de cálculo fatorial
# calcule n!
while i <= n:
n_fat = n_fat * i
i = i + 1
print(i-1, "Fatorial =", n_fat)
| false |
d9f1229f680f3f33e15eb90522e36aca499f5c7f | hafij15/python-basic | /6/short_circuit_evalution.py | 261 | 4.28125 | 4 | # name = ''
# if name == "":
# default_name = "Guest"
# else:
# default_name = name
# print(default_name)
# name = 'Hafij'
# default_name = name or 'Guest'
# print(default_name)
name = "Hafij"
upper_name = name and name.upper()
print(upper_name)
| true |
82570514a9830884ba59d6acd247f0d9000d5a78 | tberhanu/elts-of-coding | /Arrays/primes.py | 1,202 | 4.40625 | 4 | import math
def is_prime(n):
if n == 2:
return True
if n < 2:
return False
i = 2
while i <= math.sqrt(n):
if n % i == 0:
return False
i += 1
return True
def list_all_primes_upto(n):
"""
Getting all the prime numbers upto number N.
Note: Rather than going through each number upto N and calling is_prime
function N times, it's much better to get prime numbers and assign
False for all the other numbers that are multiple of that prime number
as well as for all the even numbers.
"""
ddict = {2: True}
for i in range(3, n+1):
if i % 2 == 0:
ddict[i] = False # Assigning False for Even Numbers
else:
ddict[i] = True # Assigning True for Odd Numbers
curr = 3
while curr <= n:
if is_prime(curr):
i = 2
while i * curr <= n:
ddict[i * curr] = False
i += 1
curr += 2 # Incrementing by 2 since we consider only Odds to be prime.
return ddict
if __name__ == "__main__":
# for i in range(10):
# print(i, is_prime((i)))
print(list_all_primes_upto(19))
| true |
fc1a7e72faaff24a58411840f763eb732bbe91cf | tberhanu/elts-of-coding | /HashTables/test_collatz_conjecture.py | 1,878 | 4.46875 | 4 | def test_collatz_conjecture_driver(num):
s = {1: 1}
i = 2
return test_collatz_conjecture(i, num, s)
def test_collatz_conjecture(i, num, s):
"""
Coolatz conjecture is: Taking any natural number, and halve it if it's even, or multiply it by 3 and add 1 if it's
odd number. If doing this repeatedly will end up in number 1 (neither proved or disproved).
Question: Test the Collatz conjecture for the first N positive integers.
Challenge: How will you test for the first billion integers? How will you ACCELERATE the process?
Hints: 1. Reuse Computation via hashTable just like you did with fibonnaci sequences.
2. To save time, skip EVEN numbers, since they will be halved, and the resulting number
must have already been checked.
3. Using BIT SHIFTING for Mathematical Operation like multiplication and addition.
4. Partition the search set and use many computers in PARALLEL.
Note: Since the numbers in sequence may grow beyond 32-bits, you should use 64-bit integer and
keep testing for overflow; alternately, you can use arbitrary precision integers.
Time Complexity: We can not say much about time complexity beyond the obvious, namely that it is at least
proportional to N.
"""
if i > num:
return s
if i in s:
return s[i]
ii = i
while i != 1:
if i % 2 == 0:
i = i // 2
else:
i = 3 * i + 1
# print(i)
if i == 1:
s[ii] = 1
print("Number : ", ii, "reached ", 1)
return test_collatz_conjecture(ii + 1, num, s) # skipping the evens since evens will end up to 1
if __name__ == "__main__":
num = 7
result = test_collatz_conjecture_driver(num)
# print(result)
| true |
1a4dcdb5122d2540963d77450759faa7c10bd71a | tberhanu/elts-of-coding | /DynamicProgramming/min_triangle_path_weight.py | 1,576 | 4.15625 | 4 | def min_path_weight(triangle):
"""
Write a program that takes as input a triangle of numbers and returns the weight of a minimum weight path.
Tess Strategy:
Once we know the min at row 1, then we will know at row 2, and once we know the min at row 2, we will know the
min at row 3 without the need of row 1. This concept not only leads us to the Dynamic Programming solution but
also gives a hint to use a space of O(N) as it's enough to have an array of size N serve as our CACHE, instead
of the CACHE TABLE, O(N * N).
Time: 1 + 2 + 3 + ... + N = N (N + 1) / 2 which is O(N ** 2)
Space: O(N) as we are using an array of size N for our CACHE.
"""
last_row_size = len(triangle[len(triangle) - 1])
cache = [float("inf") for _ in range(last_row_size)]
cache[0] = triangle[0][0]
temp = cache[:]
for arr in triangle[1:]:
for i in range(len(arr)):
if i - 1 >= 0:
temp[i] = min(cache[i], cache[i - 1]) + arr[i]
else:
temp[i] = cache[i] + arr[i]
cache = temp[:]
print(cache)
return min(cache)
if __name__ == "__main__":
# [2]
# [4, 4]
# [8, 5, 6]
# [4, 2, 6, 2]
# [1, 5, 2, 3, 4]
triangle = [[2],
[4, 4],
[8, 5, 6],
[4, 2, 6, 2],
[1, 5, 2, 3, 4]]
result = min_path_weight(triangle)
print(result) # 15, and the path is 2 > 4 > 5 > 2 > 2 | true |
6f73e8b67c000778c1007c8a558fdfb591641a47 | tberhanu/elts-of-coding | /Searching/binary_search.py | 2,520 | 4.1875 | 4 | """
In built Binary Search Libraries:
1. bisect.bisect_left(arr, e): return the first index whose value is >= e, else return len(arr)
arr = [0, 1, 2, 4]
bisect.bisect_left(arr, 2): return 2
bisect.bisect_left(arr, 3): return 3
num = [0, 1, 2, 2, 2, 2, 4, 5]
bisect.bisect_left(num, 2): return 2
2. bisect.bisect_right(arr, e): return the first index whose value is > e, else return len(arr)
arr = [0, 1, 2, 3]
bisect.bisect_left(arr, 2): return 3
num = [0, 1, 1, 5]
bisect.bisect_left(num, 2): return 3
Question: Given a SORTED ARRAY, use BINARY SEARCH ALGORITHM to search for an element.
Time Complexity: T(n) = T(n/2) + C, so O(log N), but still Binary Search expect the array to be
already sorted which may take O(N log N) time.
"""
def binary_search_iterative(e, arr):
left = 0
right = len(arr) - 1
while left <= right:
mid = left + (right - left) // 2 # the trick to avoid potential overflow
# mid = (left + right) // 2
if e > arr[mid]:
left = mid + 1
elif e < arr[mid]:
right = mid - 1
else:
return mid
return -1
def binary_search_recursive_driver(e, arr):
left_array_size = 0
return binary_search_recursive(e, arr, left_array_size)
def binary_search_recursive(e, arr, left_array_size):
if len(arr) == 0:
return -1
mid = len(arr) // 2
if e == arr[mid]:
return mid + left_array_size
if e < arr[mid]:
return binary_search_recursive(e, arr[:mid], left_array_size)
else:
left_array_size = len(arr[:mid+1])
return binary_search_recursive(e, arr[mid + 1:], left_array_size)
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 9, 90, 99, 999]
e = 5
print(binary_search_iterative(e, arr)) # 4
arr = [1, 2, 3, 4, 5, 9, 90, 99, 999]
e = 55
print(binary_search_iterative(e, arr)) # -1
print("+++++++++++")
arr = [1, 2, 3, 4, 5, 9, 90, 99, 999] # 4
e = 5
print(binary_search_recursive_driver(e, arr))
arr = [1, 2, 3, 4, 5, 9, 90, 99, 999]
e = 55
print(binary_search_recursive_driver(e, arr)) # -1
print("___________")
arr = [1, 2, 3]
print(binary_search_recursive_driver(1, arr)) # 0
arr = [1, 2, 3]
print(binary_search_recursive_driver(2, arr)) # 1
arr = [1, 2, 3]
print(binary_search_recursive_driver(3, arr)) # 2
arr = [1, 2, 3]
print(binary_search_recursive_driver(4, arr)) # -1 | true |
72412b507958b248e4c579e8b8ab337d3e3c4a22 | tberhanu/elts-of-coding | /Arrays/46. permutations.py | 796 | 4.125 | 4 | """
Given a collection of distinct integers, return all possible permutations.
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
"""
def permute(nums):
nums2 = nums[:] # copying the nums to reserve
start = 0
result = []
return permutation(nums, nums2, start, result)
def permutation(nums, nums2, start, result):
if start == len(nums) - 1:
print(nums)
result.append(nums)
for i in range(start, len(nums)):
nums2 = nums[:]
nums[i], nums[start] = nums[start], nums[i]
permutation(nums, nums2, start + 1, result)
nums = nums2[:] # bringing nums back to the original value, [1, 2, 3]
return result
if __name__ == "__main__":
nums = [1, 2, 3, 4]
print(permute(nums))
| true |
f353962660242276ab460e96fd3b3ffdac2ba141 | tberhanu/elts-of-coding | /Graphs/search_maze.py | 2,761 | 4.25 | 4 | from collections import namedtuple
WHITE, BLACK = range(2)
Coordinate = namedtuple('Coordinate', ('x', 'y'))
def search_maze_driver(maze, start, end):
path = []
return search_maze(maze, start, end, path)
def search_maze(maze, start, end, path):
"""
Consider a black and white digitized image of a maze-white pizels represent open areas and black spaces are walls.
There are two special white pixels: one is designated the ENTRANCE and the other is the EXIT.
Given a 2D array of black and white entries representing a maze, Find a way of getting from ENTRANCE to the EXIT.
Strategy: DFS
Time: O(|V| + |E|) ????????? Of course, we touched almost all vertices and edges.????
Space: O(|V|) since we've an array, path, of maximum size of |V|
"""
if maze[start.x][start.y] == BLACK:
return False
path.append(start)
maze[start.x][start.y] = BLACK
if start == end:
return path
if start.y - 1 >= 0:
going_left = search_maze(maze, Coordinate(x=start.x, y=start.y - 1), end, path)
else:
going_left = False
if start.y + 1 < len(maze):
going_right = search_maze(maze, Coordinate(x=start.x, y=start.y + 1), end, path)
else:
going_right = False
if start.x - 1 >= 0:
going_down = search_maze(maze, Coordinate(x=start.x - 1, y=start.y), end, path)
else:
going_down = False
if start.x + 1 < len(maze):
going_up = search_maze(maze, Coordinate(x=start.x + 1, y=start.y), end, path)
else:
going_up = False
if not any([going_left, going_right, going_down, going_up]):
path.pop()
return False
return path
if __name__ == "__main__":
matrix = [[WHITE] * 10 for _ in range(10)]
matrix[0][0], matrix[0][6], matrix[0][7] = BLACK, BLACK, BLACK
matrix[1][2] = BLACK
matrix[2][0], matrix[2][2], matrix[2][5], matrix[2][6], matrix[2][8], matrix[2][9] = BLACK, BLACK, BLACK, BLACK, BLACK, BLACK
matrix[3][3], matrix[3][4], matrix[3][5], matrix[3][8] = BLACK, BLACK, BLACK, BLACK
matrix[4][1], matrix[4][2] = BLACK, BLACK
matrix[5][1], matrix[5][2], matrix[5][5], matrix[5][7], matrix[5][8] = BLACK, BLACK, BLACK, BLACK, BLACK
matrix[6][4] = BLACK
matrix[7][0], matrix[7][2], matrix[7][4], matrix[7][6] = BLACK, BLACK, BLACK, BLACK
matrix[8][0], matrix[8][2], matrix[8][3], matrix[8][7], matrix[8][8], matrix[8][9] = BLACK, BLACK, BLACK, BLACK, BLACK, BLACK
matrix[9][7], matrix[9][8] = BLACK, BLACK
for mat in matrix:
print(mat)
print("____________________________")
start = Coordinate(x=9, y=0)
end = Coordinate(x=0, y=9)
paths = search_maze_driver(matrix, start, end)
for path in paths:
print((path.x, path.y))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.