blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
18f4f6cfcbb35d6a5ca499e16bafb7332de292cf | ZSL-1024/Python-Crash-Course | /chapter_04 Working with lists/my_pizzas_your_pizzas.py | 472 | 4.28125 | 4 | # Excercise 4-11
favorite_pizzas = ['pepperoni', 'hawaiian', 'veggie']
for pizza in favorite_pizzas:
print("I like " + pizza + " pizza.\n")
print("I really love pizza!")
# make a copy
friend_pizzas = favorite_pizzas[:]
favorite_pizzas.append('seafood')
friend_pizzas.append('pesto')
print("My favorite pizzas are:")
for pizza in favorite_pizzas:
print(pizza)
print("\nMy friend’s favorite pizzas are:")
for pizza in friend_pizzas:
print(pizza) | true |
2cc8646554831328d956d62cfc45bface9824c73 | sudhir-j-sapkal/python-basic-examples | /02Strings/indexing_slicing.py | 291 | 4.3125 | 4 | #Get the character at position 1 (remember that the first character has the position 0):
#Substring. Get the characters from position 2 to position 5 (not included)
my_name = "Sudhir Sapkal"
#Indexing can be done on String
print(my_name[1])
#Slicing can be done on string
print(my_name[2:5])
| true |
763807b01b1e8e97365a25285b593d256ca42609 | sudhir-j-sapkal/python-basic-examples | /10Statements/loops.py | 1,955 | 4.5625 | 5 | #Python has two primitive loop commands:
# 1.while loops
# 2.for loops
#While - With the while loop we can execute a set of statements as long as a condition is true.
i = 1
while i < 6:
print(i)
i += 1
print("===================================================");
#For - A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
#The range() Function - To loop through a set of code a specified number of times, we can use the range() function,
#The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
print("====================================================")
for i in range(6):
print(i)
#The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
print("====================================================")
for i in range(2, 6):
print(i)
#The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):
print("=====================================================")
for i in range(2, 30, 3):
print(i)
#Else in For Loop
#The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
print("=====================================================")
for i in range(10):
print(i)
else:
print("Finally finished!")
#Nested Loops
#A nested loop is a loop inside a loop.
#The "inner loop" will be executed one time for each iteration of the "outer loop":
print("======================================================");
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
| true |
f4f1aa98401a4e468040245b5a2f63c5287faa7b | vineethMM/DataStructuresAndAlgorithms | /recursion/odd_even.py | 874 | 4.125 | 4 | def push_odd_to_end(s):
def inner(s, start, end):
if start < end:
if s[start] % 2 == 1 and s[end] % 2 == 0:
temp = s[start]
s[start] = s[end]
s[end] = temp
inner(s, start + 1, end -1)
elif s[start] % 2 == 1 and s[end] % 2 == 1:
inner(s, start, end - 1)
else:
inner(s, start + 1, end)
inner(s, 0, len(s) - 1)
return s
if __name__ == "__main__":
input1 = [3, 5, 7, 2, 4, 6]
expected1 = [6, 4, 2, 7, 5, 3]
actual1 = push_odd_to_end(input1)
assert expected1 == actual1, f"Test failed for input {input1}"
input2 = [1, 2, 3, 4, 5, 6, 7, 8]
expected2 = []
actual2 = push_odd_to_end(input2)
assert expected2 == actual2, f"Test failed for input {input2}"
print("Test passed")
| false |
c0512e75a4fa293586beb6546520efff4e46ab09 | jcdickman/draconem_py_lab | /checkio/missions/ed_all_upper-1.py | 816 | 4.4375 | 4 | def is_all_upper(text: str) -> bool:
# 1) will recive arguments called "text" of datatype "str"
# 2) Check the String if there are any characters in it and also check for all upper case characters
# 3) return true if the string is empty or return false if the string has all upper case characters
if any(x.islower() for x in text):
return False
else:
return True
if __name__ == '__main__':
print("Example:")
print(is_all_upper('ALL UPPER'))
# These "asserts" are used for self-checking and not for an auto-testing
assert is_all_upper('ALL UPPER') == True
assert is_all_upper('all lower') == False
assert is_all_upper('mixed UPPER and lower') == False
assert is_all_upper('') == True
print("Coding complete? Click 'Check' to earn cool rewards!") | true |
d3637982e75b6683070a3b899c72af43370a1e90 | rpfarish/small_projects | /scratch_14.py | 788 | 4.21875 | 4 | # have person guess a number and if they are right than let them enter their
# name and tell them they are superman
num = 0
gender = input("Enter your gender: Man or Woman: \n")
gender.lower()
print("Enter a number between 0 and 30")
while num != 27:
try:
num = abs(int(input("Enter a Number: ")))
except ValueError:
print("Please Enter A Number.")
if gender == 'woman':
def name (super_hero):
result1 = "is Superwoman"
print(super_hero)
return result1
print("Enter your name:")
print(name(input("") + "\n"))
else:
def name (super_hero):
result1 = "is Superman"
print(super_hero)
return result1
print("Enter your name:")
print(name(input("") + "\n"))
| true |
9630d5c63400ba0a6bb8b1cc58dc97fb3dc9ef72 | drs021/Homebrew-Calculator | /Python Beer Bottling Calculator.py | 1,095 | 4.53125 | 5 | 3
print("Welcome to the Cap Counter Program :)")
print("This will calculate how many caps are required based on the number and size of bottles required.")
fermenter_volume = float(input("First: Enter gals in fermenter:"))
six_packs = int(input("Now, Enter how many 12 oz six packs you would like:"))
print("The remaining number of 22 oz bottles is calculated below.")
#six pack volume is fermenter volume converted to ounces
#and subtracting user input: six_packs converted to ounces
#6 bottles/pack times 12 ounce/bottle
print()
print()
six_pack_volume = six_packs * 6 *12
#floor division to get how many 22 oz bottles go into fermenter volume
#after subtracting six_pack_volume
#multiply fermenter volume in gallons by 128 oz/gal to get ounces
number_of_22oz = (fermenter_volume *128 - six_pack_volume)// 22
bottle_caps_needed = number_of_22oz + six_packs * 6
print("number of 22 ounce bottles: ", number_of_22oz)
print("number of six packs: ", six_packs,"but you already said that!!")
print("You will also need: ", bottle_caps_needed,"bottle caps!")
| true |
2619f79e50c8e6bc4b387f1f85d49f0f70f8b4f8 | gracemarod/codingChallenges | /Others/dynamic programming/climbingStairs.py | 1,064 | 4.125 | 4 | '''You are climbing a staircase that has n steps. You can take the steps either 1 or 2 at a time.
Calculate how many distinct ways you can climb to the top of the staircase.
Recovered from https://codefights.com/interview-practice/task/oJXTWuwEZiC6FTw3A'''
def climbingStairs(n):
count = 0
#Go through the bases cases first.
# if n = 0, there are no steps to climb
# for n = 1, there's only one step to climb
# for 2 steps, you can either climb 2 steps at once or 1 step two times
# so return 2
if n<=2:
return n
else:
#make array to store fib values
table = [0 for x in range(n+1)]
#save base cases values
table[0]=0
table[1]=1
table[2]=2
for i in range(2,n):
#calculate fibonnaci in each iteration
table[i] = table[i-1] + table[i-2]
count += table[i]
return count+2
| true |
9e5922f7883d0d1d6e9569f8ff8a60728fd3b82e | edmarcavalcante/projectpython | /13.2_excecoes.py | 1,953 | 4.3125 | 4 | # continuação de arquivos e exceções
#_____USO DO BLOCO TRY-EXCEPT_____#
# exemplo básico. Em python, assim como na matemática, não se pode dividir
# um número por zero, pois não há resultado. Veremos que o erro apresentado
# pelo python quando tentamos fazer essa operação
numero1 = int(input("Informe um número: "))
numero2 = int(input("Informe outro número: "))
print("Vamos dividí-los")
print('\n')
divisao = numero1/numero2
print(divisao)
print('\n')
# essa operação vai trazer erro se o segundo número for zero
#forma de tratar esse erro - excecão
numero1 = int(input("Informe um número: "))
numero2 = int(input("Informe outro número: "))
print('\n')
print("Vamos dividí-los")
print('\n')
try:
divisao = int(numero1)/int(numero2)
except ZeroDivisionError: #é preciso colocar o nome do erro após o comando except
# cada tipo de erro tem um nome diferente
print("Não se pode dividr um número por zero")
else:
print(divisao)
# programa para ler arquivos aplicado o conceito de errro-exceções
arquivos_lista = ["arquivo_novo.txt", "dados_pessoais.txt", "livros_lidos_2019.txt", "casa.txt"]
#vou criar uma função para fazer esse trabalho de leitura de arquivos
def ler_arquivo (nome_arquivo):
try:
with open (nome_arquivo) as ler:
leitura = ler.read()
except FileNotFoundError:
print("Desculpe, mas esse arquivo não está no diretório")
else:
print(leitura)
print(ler_arquivo("arquivo_novo.txt"))
print('\n')
print(ler_arquivo("dados_pessoais.txt"))
print('\n')
print(ler_arquivo("casa.txt")) # nesse caso, a função vai apresentar a mensagem de except
# pois o arquivo casa.txt não está no diretório.
# AGORA APLICAR A FUNÇÃO EM UM LOOP FOR
arquivos_lista = ["arquivo_novo.txt", "dados_pessoais.txt", "livros_lidos_2019.txt", "casa.txt"]
for arq in arquivos_lista:
print(ler_arquivo(arq))
print('\n') | false |
af3667e7976d696b2523cebfe31964d34f3324f0 | edmarcavalcante/projectpython | /13_arquivos_exceções.py | 1,482 | 4.125 | 4 | #ARQUIVOS E EXCEÇÕES
#lembre-se que o arquivo de leitura deve está guardado no mesmo diretório do programa,
# que nesse caso é o 12_arquivos_exceções.
with open("dados_pessoais.txt") as meu_dados:
edmar = meu_dados.read()
print (edmar)
#o programa poderia ser escrito sem o with, mas necessitaria do close para encerra-lo
# o with é mais seguro porque o arquivo é fechado automaticamente quando n for usado.
# o close pode não ser tão seguro, pode gerar bugs no programa e o arquivo não ser fechado por alguma razão
#se o arquivo a ser lido não estiver no mesmo diretório do programa, é preciso colocar todo o caminho (path)
# as barras não são invertidas,
with open ("C:/Users/enged/Desktop/dados_mae.txt") as lucia:
lucia_dados = lucia.read()
print(lucia_dados)
print("\n")
#usando um laço for para printar linha por linha de uma arquivo texto
lucia_mae = "C:/Users/enged/Desktop/dados_mae.txt"
with open(lucia_mae) as lc:
for line in lc:
print(line)
#criando uma lista de linhas de um arquivo
print("\n")
edmar = "dados_pessoais.txt"
with open (edmar) as ed:
ed_lista = ed.readlines() # esse método cria uma lista onde cada item da lista é um linha do arquivo ed
for line in ed_lista:
print(line)
#comando para provar que ed_lista é uma lista de fato
print(type(ed_lista))
print(ed_lista[1])
#print(help(ed_lista)) - esse comando traz todos os métodos diponíveis para as listas
| false |
ba6b6c8f66b0ae4534995af35bfb3439b9f3e23e | obDann/fundamentals | /sorts/insertion_sort.py | 2,200 | 4.375 | 4 | def insertion_sort(L):
'''
(List of comparable objs) -> List of comparable objs
O(n^2) sorting algorithm
Returns a list of sorted objects from the passed list
'''
# copy the passed list so that we can return the sorted list
ret = L[:]
# and set the number of elements as a variable
num_ele = len(ret)
# then go through the list
for i in range(num_ele):
# we assume that the list L[:i] is sorted
# so we get the current element
curr_ele = ret[i]
# we want to place the element in the list where
# L[j - 1] < curr_ele <= L[j]
# s.t. j < i
# so we want to traverse backwards in our sorted list
j = i - 1
# and we want to have a satisfiable condition
satisfied = False
# so we iterate backwards
while (j >= 0 and not satisfied):
# there are two cases that do arise, and it is when j = 0 and
# when j != 0
if (j == 0):
# if this is the case, then we check if there is a satisfying
# condition where
if (ret[0] > curr_ele):
# pop the current element
curr_ele = ret.pop(i)
# then re-order the list
ret = [curr_ele] + ret
else:
# otherwise, we can assume that there are at least two elements
# so, the satisfiable condition is when
satisfied = ret[j - 1] < curr_ele
satisfied = satisfied and (curr_ele <= ret[j])
if (satisfied):
# if this is the case, we want to split the list into three
# where we have a middle element to remove from the list
mid_ele = [ret.pop(i)]
# then elements from j and onward
right_end = ret[j:]
# and the elements before j
left_end = ret[:j]
# then we redefine the list
ret = left_end + mid_ele + right_end
# decrement
j -= 1
# then we can return our list
return ret
| true |
676f0a94c67d35baca4266ba8ffa77a3ef7786d9 | matheusmendes58/Python-Fundamentos-2- | /analisando triangulos V2.0.py | 638 | 4.125 | 4 | p1 = float(input('digite o primeiro segmento:'))
p2 = float(input('digite o segundo segmento:'))
p3 = float(input('digite o terceiro segmento:'))
if p1 < p2 + p3 and p2 < p1 + p3 and p3 < p1 + p2:
print('Os segmentos FORMAM TRIANGULO', end='')
if p1 == p2 and p2 == p3:
print(' EQUILATERO')
elif p1 == p2 and p2 == p3 or p1 != p2 or p2 != p3:
print(' ISÓCELES')
elif p1 != p2 and p2 != p3 and p3 != p1:
print(' ESCALENO')
else:
print('Os segmentos não formam triangulo')
'''
maneira mais correta primeiro elif por o codigo do escaleno
e por fim else print('isóceles').
'''
| false |
0138e5ed5ffe9558d6d058cc2c167d144c065ee2 | Rjt17/Python | /automate_the_boring_stuff-with_python/binary_search.py | 1,273 | 4.1875 | 4 | #!/usr/bin/env python
searchList = []
rangeList = int(input("enter the number of values of the list: "))
if (rangeList <= 0):
print("your entered length of list is less than or equal to zero")
else:
for values in range(rangeList):
searchList.append(values + 1)
print(searchList)
target = int(input("enter the value you want to search under or equal to {}: ".format(rangeList)))
if (target > rangeList):
print("you entered a value larger than {}".format(rangeList))
elif (target == 0):
print("you entered a number to search which is equal to 0")
elif (target < 0):
print("you entered a number to search which is less than 0")
else:
lastTemp = rangeList
first = 0
last = lastTemp
middle = int((first + last) / 2)
while (first <= last):
if (searchList[middle] < target):
first = middle + 1
elif (searchList[middle] == target):
print("search value found at location {}".format(searchList[middle]))
break
else:
lastTemp = last
last = middle - 1
middle = int((first + last) / 2)
if (first > last):
print("value not found") | true |
76c55671352af469f6c8ab0c57f2665b019bad37 | MohamedPicault/My_Projects | /Games/Rock_Paper_Scissor.py | 1,377 | 4.375 | 4 | from random import choice
def computer_choice():
selection_list = ['rock', 'paper', 'scissor']
computer_select = choice(selection_list)
print(computer_select)
return computer_select
# add a recursion if player input is not in the list
def player_choice():
selection_list = ['rock', 'paper', 'scissor']
player_select = input('Please choose from the selection: rock, paper, scissor\n')
if player_select not in selection_list:
print('Please enter correct selection!')
player_choice()
return player_select
def rock_paper_scissor():
player = player_choice()
pc = computer_choice()
if (player == 'rock' and pc == 'scissor') or (player == 'paper' and pc == 'rock') or (
player == 'scissor' and pc == 'paper'):
print('Player is winner!')
elif player == pc:
print('Outcome is a draw')
else:
print('Pc is winner!')
# create a main function for proper practice
if __name__ == '__main__':
start = input('Welcome to my rock, paper, and scissor game. When you are ready enter start, to begin.\n')
while True:
if start == 'start' or start == 'yes' or start == 'Yes':
rock_paper_scissor()
start = input('Do you wish to play again? Yes or No\n')
elif start == 'No' or start == 'no':
break
else:
break
| true |
855e1604ece40a90d84f174eb7420ebb2e830b6c | Bocharick/GeekBrains_AI_Algorithms | /Lesson_01/Task_03.py | 1,212 | 4.25 | 4 | #!/usr/bin/python3
"""
По введенным пользователем координатам двух точек вывести уравнение прямой, проходящей через эти точки.
"""
print("Введите координату #1:")
X_coord1 = float(input('\tВведите x: '))
Y_coord1 = float(input('\tВведите y: '))
print("Введите координату #2:")
X_coord2 = float(input('\tВведите x: '))
Y_coord2 = float(input('\tВведите y: '))
X_vec1 = X_coord2 - X_coord1
Y_vec1 = Y_coord2 - Y_coord1
X_vec2 = Y_vec1
Y_vec2 = -X_vec1
C = -(X_vec2 * X_coord1 + Y_vec2 * Y_coord1)
print("Уравнение прямой:")
print("\tОбщее уравнение прямой:")
print("\t\t%.3f*X + %.3f*Y + %.3f = 0" % (X_vec2, Y_vec2, C))
"""
Вид 'y = kx + b' невозможен для прямых параллельных оси ординат.
"""
if Y_vec2 != 0:
k = X_vec2 / Y_vec2
b = C / Y_vec2
print("\tВ виде 'y = kx + b':")
print("\t\tY = %.3f*X + %.3f" % (k, b))
else:
print("\tПрямая параллельна оси ординат, запись вида 'y = kx + b' невозможна")
| false |
fc6ee4f6a46c13a88a30c769b560de871c114613 | Duaard/ProgrammingProblems | /HackerRank/Medium/TheTimeInWords/solution.py | 1,784 | 4.125 | 4 | #!/bin/python3
import os
time_dict = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
40: 'forty',
50: 'fifty'
}
def timeInWords(h, m):
minutes = ''
adjective = ''
# Set the adjective to be used based on minutes
if m >= 1 and m <= 30:
# Use past
adjective = 'past'
elif m != 0:
# Use to
adjective = 'to'
# Use the next hour to reference time
h += 1
# If the time is more than 30, invert it
if m > 30:
m = 60 - m
# Get the minutes to be used
if m == 0:
# Return the hour with o' clock
return time_dict[h] + " o' clock"
elif m == 15 or m == 45:
# Use quarter
minutes = 'quarter'
elif m == 30:
# Use half
minutes = 'half'
else:
# Convert the minutes into words
if m < 20:
# Simply get the conversion
minutes = time_dict[m]
else:
# Build the words
tens = m // 10 * 10
ones = m % 10
minutes = time_dict[tens] + ' ' + time_dict[ones]
if m > 1:
minutes += ' minutes'
else:
minutes += ' minute'
# Combine everything and return
return minutes + ' ' + adjective + ' ' + time_dict[h]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
h = int(input())
m = int(input())
result = timeInWords(h, m)
fptr.write(result + '\n')
fptr.close()
| false |
31bb4543014dec99ac3a243aad7f866db1ef4790 | kapeed54/python-exercises | /Functions/14. sort_dict_list.py | 599 | 4.34375 | 4 | # python program to sort a list of dictionaries using lambda
student_description = [{'name':'avhi', 'age':23, 'education':'4. bachelor'},
{'name':'rahul', 'age':15, 'education':'2. slc'},
{'name':'sabin', 'age':17, 'education':'3. +2'},
{'name':'deepak', 'age':27, 'education':'5. masters'},
{'name':'rohit', 'age':9, 'education':'1.primary'}]
print('Decription of Students :',student_description )
sort = sorted(student_description, key=lambda x:x['education'])
print("Sorting based on education: ", sort)
| true |
aabd64667bae400b076cfb4153810d9cdcfd297b | kapeed54/python-exercises | /Data Types/9. exchangecharacter.py | 218 | 4.4375 | 4 | #python program to change a given string to a new where the first and last chars have been exchanged.
def exchange(str):
return str[-1:] + str[1:-1] + str[:1]
print (exchange('workshop'))
print (exchange('2021'))
| true |
e7b7a0e10b943c5ce11da837d3d82a6c1b8f3a8e | kapeed54/python-exercises | /Data Types/7. longest_from_list.py | 408 | 4.40625 | 4 | #python function that takes a list of words and returns the length of the longest one.
def longest_word(word_list):
len_word = []
for i in word_list:
len_word.append((len(i),i))
len_word.sort()
return len_word[-1][0], len_word[-1][1]
output = longest_word(["Insight","Workshop","Bootcamps"])
print("The longest word is: ", output[1])
print("The length of this word is: ", output[0])
| true |
a135bb38b46aff14feb147f6f4f74c683e1e73d6 | kapeed54/python-exercises | /Functions/10. onlyprinteven.py | 233 | 4.21875 | 4 | #python program to print the even numbers from the given list
def num_list(list):
numbers = []
for num in list:
if num % 2 == 0:
numbers.append(num)
return numbers
print(num_list([1,2,3,4,5,6,7,8,9]))
| true |
1ee67df8b4110fab7a225510288cea856600c345 | kapeed54/python-exercises | /Data Types/40. addintuple.py | 225 | 4.53125 | 5 | # python program to add an item in a tuple
tuple1 = (1,2,3,4,5)
print (tuple1)
#since tuple are immutable, new elements cannot be added
# adding element in tuple using different method
tuple1 = tuple1 + (6,7)
print(tuple1)
| true |
1afb2e4b5772a71ace603b6908b47876eb109cb5 | Matthew-P-Lee/Python | /verticalc.py | 1,139 | 4.28125 | 4 | import math
#speed, distance, time calculations
class Verticalc(object):
grade = 0.0
distance = 0.0
speed = 0.0
time = 0.0
def __init__(self, grade,distance,speed,time):
self.grade = grade
self.distance = distance
self.speed = speed
self.time = time
def getVerticalFeet(self):
vert = ((float(grade)/100) * float(distance))
vertFeet = float(vert) * 5280
return vertFeet
def getDistance(self):
return float(speed/60.0) * float(time)
# def __str__(self):
# return
#calculate vertical gain from an angle and average speed - treadmill calculator
grade = input("Enter the average angle of the climb (in degrees): ")
distance = input("Enter the distance of the climb (in miles): ")
speed = input ("Enter your average pace (in mph): ")
time = input ("Enter your total time at " + str(grade) + "% grade (in minutes): ")
vc = Verticalc(grade,distance,speed,time)
#vertical feet gained
print "%s vertical feet at %s%% grade" % (str(vc.getVerticalFeet()), vc.grade)
#distance given time / speed
print "%s miles travelled at %s mph for %s minutes" % (str(vc.getDistance()),str(vc.speed),str(vc.time))
| true |
46c247e4bbf1a8a058a33180442920145793e4b3 | vignesh0794/codekata | /vowel.py | 239 | 4.21875 | 4 | choice= input("kindly enter yourr character:")
if(choice=='a' or choice=='e' or choice=='i' or choice=='o' or choice=='u'):
print("entered characted",choice,"is a vowel")
else:
print("entered characted",choice,"is a consonant") | false |
0ece816799a9b778b1e4fbc194106d41ca6bb53b | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/Generic_Trees.py | 2,603 | 4.25 | 4 | # Making a Generic Tree (N-Array Trees) along with implementation.
# Printing tree with good visual representation.
class TreeNode:
def __init__(self, data1, data2):
self.data1 = data1
self.data2 = data2
self.children = []
self.parent = None
def add_child(self, child):
child.parent = self
self.children.append(child)
# function to print tree as per the hierarchies
def print_tree(self, arg="both", level=0):
if(arg=="name"):
spaces = " "*level + "!--" if level > 0 else ""
print(spaces, self.data1)
for c in self.children:
c.print_tree(arg, level+1)
elif(arg=="designation"):
spaces = " "*level + "!--" if level > 0 else ""
print(spaces, self.data2)
for c in self.children:
c.print_tree(arg, level+1)
elif(arg=="both"):
spaces = " "*level + "!--" if level > 0 else ""
print(spaces, self.data1 + " (" + self.data2 + ")")
for c in self.children:
c.print_tree(arg, level+1)
# function to print tree as per the levels
def print_tree_level(self, level1, level=0):
spaces = " "*level + "!--" if level > 0 else ""
print(spaces, self.data1 + " (" + self.data2 + ")")
for c in self.children:
if(level1<=level):break
c.print_tree_level(level1, level+1)
# Used for making the demo tree.
# Organizational Hierarchy has been used in this example.
def build_managing_tree():
root = TreeNode("Nilupul", "CEO")
chinmay = TreeNode("Chinmay", "CTO")
gels = TreeNode("Gels", "HR Head")
vishwa = TreeNode("Vishwa", "Infrastructure Head")
aamir = TreeNode("Aamir", "Application Head")
vishwa.add_child(TreeNode("Dhaval", "Cloud Manager"))
vishwa.add_child(TreeNode("Abhijit", "App Manager"))
gels.add_child(TreeNode("Peter", "Recruitment Head"))
gels.add_child(TreeNode("Waqas", "Policy Manager"))
chinmay.add_child(vishwa)
chinmay.add_child(aamir)
root.add_child(chinmay)
root.add_child(gels)
return root
# Main Code
if __name__ == '__main__':
root_node = build_managing_tree()
print("Printing only Name hierarchy:")
root_node.print_tree(arg="name") # prints only name hierarchy
print(" ")
print("Printing only Designation hierarchy")
root_node.print_tree(arg="designation") # prints only designation hierarchy
print(" ")
print("Prints both the hierarchies")
root_node.print_tree(arg="both") # prints both (name and designation) hierarchy
print(" ")
print("Level 1 :")
root_node.print_tree_level(1)
print(" ")
print("Level 2 :")
root_node.print_tree_level(2)
print(" ")
print("Level 3 :")
root_node.print_tree_level(3)
print(" ")
| true |
134e0c371d1033f122a1456b091b7ae754f2f68c | dboyliao/SmallTools | /Python/count_pattern | 1,136 | 4.21875 | 4 | #!/usr/bin/env -S python3 -u
# Simple counting program
from __future__ import print_function
import re
import argparse
def count_pattern(fname, pattern, verbose=False):
count = 0
pattern = re.compile(pattern)
with open(fname) as rf:
l = rf.readline()
while not l == "":
match = pattern.findall(l)
if verbose:
print(match)
count += len(match)
l = rf.readline()
return count
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="count the number of matched pattern in the file."
)
parser.add_argument("fname", metavar="FILE", help="file name")
parser.add_argument(
"-e",
"--pattern",
metavar="PATTERN",
default="[^\s]",
help="regular expression pattern",
dest="pattern",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="run in verbose mode",
dest="verbose",
)
args = parser.parse_args()
count = count_pattern(args.fname, args.pattern, args.verbose)
print(count)
| true |
fcf67cc3e2495f4fcf2b2eccbf05fff57231669a | SivaprakashAnand/python-basics | /comma_code.py | 1,457 | 4.28125 | 4 | # comma_code.py
def list_the_list(the_list=[]):
"""
Takes a list value as an argument and returns a string with all the items
seperated by a comma and a space, with 'and' inserted before the last item.
Parameters
----------
the_list : list, optional
A list of items, by default []
Returns
-------
list_string: str
A string listing the items found in 'the_list'.
"""
# CASE: List is nonempty
if (the_list != []):
list_string = ''
list_length = len(the_list)
for index, item in enumerate(the_list):
# Force to string
item = str(item)
# CASE) First item in the list.
if (index == 0):
list_string += item
# CASE) Last item in the list.
elif (index == list_length - 1):
list_string += ', and ' + item + '.'
# CASE) Between first and last item in the list.
else:
list_string += ', ' + item
# CASE: List is empty
else:
list_string = '(An empty list)'
return list_string
# COMMENTED SOME TESTS BELOW:
'''
test_list = [11, 'eleven', 'twelve', 'cat', 'dog', 'cow', 'pig', False]
empty_list = []
list_in_a_list = [['cookie', 'cooky', 'cook-E'], ['burger', 'french fries', 'milkshake']]
print(list_the_list(test_list))
print()
print(list_the_list(empty_list))
print()
print(list_the_list(list_in_a_list))
'''
| true |
9afd0e5e7d379d75efb71105f5e377009d2fc1c2 | irtiza7/String-Operations | /Find Distinct Characters in String/main.py | 1,299 | 4.1875 | 4 | # Program to find all distinct characters in a given string.
def findDistinctChars(string):
countDict = {} # dictionary to stores characters while iterating along with their occurrences.
distinctChars = [] # list to store characters which have only single occurence.
# storing characters in countDict along with their occurrence.
for char in string:
# IF: the character is not already in dictionary then it means it hasn't occured yet. So store it with its occurrence equal to 1.
# ELSE: the character is already in countDict then it must have occured before. So increment its previous occurrence with 1.
if char not in countDict:
countDict[char] = 1
else:
countDict[char] = countDict[char] + 1
# append the character to distinceChars if its occurrence is equal to 1 i.e. it has occurred only once in given array.
for item in countDict:
if countDict[item] == 1:
distinctChars.append(item)
return distinctChars
testString1 = "apples"
testString2 = "characters"
print(f"Distinct Characters in |{testString1}|: {findDistinctChars(testString1)}")
print()
print(f"Distinct Characters in |{testString2}|: {findDistinctChars(testString2)}") | true |
e2bcc78bcfd926e17b887057f08b88440345e08a | smith-megan/pythonintro | /temperature.py | 249 | 4.125 | 4 | temp=95
raining= True
if temp > 80:
print("it's too hot!")
print("stay inside")
elif temp <60:
print("it's too cold")
print("stay inside!")
else:
print("enjoy the outdoors!")
if not raining:
print("go outside")
else:
print("cozy up!") | true |
74f7aae7945822892bb0c75f6d30a6084ac8eedf | FeardaMeow/algo_struct_studyguide | /algorithms/sort/insertion_sort.py | 1,163 | 4.21875 | 4 | '''
Description:
Given an array of integers, sort it using insertion sort algorithm.
Insertion sort is stable, in-place sorting algorithm that builds final
sorted array one item at a time.
Performance:
Comparisons:
worst = O(n^2)
best = O(n)
average = O(n^2)
Swaps:
worst = O(n^2)
best = O(1)
Space Complexity:
worst = O(n)
aux space = O(1)
Pseudocode:
i ← 1
while i < length(A)
x ← A[i]
j ← i - 1
while j >= 0 and A[j] > x
A[j+1] ← A[j]
j ← j - 1
end while
A[j+1] ← x[4]
i ← i + 1
end while
'''
def insertion_sort(arr, compare_fn):
for i in range(len(arr)-1):
key = arr[i+1]
j = i
while j >= 0 and compare_fn(arr[j], key):
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
def main():
import numpy as np
test_arr = np.arange(0,100)
np.random.shuffle(test_arr)
test_arr = list(test_arr)
print(test_arr)
insertion_sort(test_arr, lambda x,y: x > y)
print(test_arr)
if __name__ == "__main__":
main() | true |
d7cae83cb063a4b47c23287ba6c39c368fb3b004 | bhuvaneshkumar1103/talentpy | /product_recursive.py | 367 | 4.3125 | 4 | '''
Write python recursive function to perform multiplication of all elements of list L.
'''
#the function multiply will call itself untill lenth of the list.
def multiply(L,n = 0):
prod = 1
if n < len(L):
prod = L[n]*multiply(L,n+1)
return prod
L = [1,2,3,4,5,6,7,8,9]
print("The product of the list: ",end = "")
print(multiply(L))
| true |
9cf57dba23244e5c62642c233f5082f4381c892d | bhuvaneshkumar1103/talentpy | /caller_func.py | 1,631 | 4.5625 | 5 | '''
Create three functions as follows -
1. def remove_vowels(string) - which will remove all vowels from the given
string. For example if the string given is “aeiru”, then the return value should
be ‘r’
2. def remove_consonants(string) - which will remove all consonants from
given string. For example, if the string given is “aeri”, then the return value
should be ‘aei’.
3. def caller -> This function should 2 parameters
1. Function to call
2. String argument
This caller function should call the function passed as a parameter, by
passing second parameter as the input for the function. Example: caller(remove_vowles,
“aeiru”) should call remove_vowels function and should return ‘r’ as the output.
'''
def remove_vowels(st) :
vowel = ['A','E','I','O','U','a','e','i','o','u']
for i in st:
if i in vowel:
# it will replace the vowels in the string
st = st.replace(i,'')
return st
def remove_consonants(st):
vowel = ['A','E','I','O','U','a','e','i','o','u']
for i in st:
if i not in vowel:
# it will replace all the consonants in the string
st = st.replace(i,'')
return st
'''It will call the function which was passed has the 1st parameter and
give the input for the function which was passed has the 2nd parameter.
'''
def caller(func,st):
return func(st)
st = str(input("Enter a string: "))
print("Which Operation should be done in this string !!!")
print("\n 1.remove_vowels \n 2.remove_consonants ")
func = eval(input("Enter the operation name: "))
result = caller(func,st)
print(result) | true |
b3cd87ebc924b1c10186f11b86115b827fc9caff | Andrey-Pivtorak/python-projects | /rock_paper_scissors.py | 1,825 | 4.125 | 4 | # a task: rock, paper, scissors game
import random
# global constants
ROCK = 1
PAPER = 2
SCISSORS = 3
MIN_VALUE = 1
MAX_VALUE = 3
COMPUTER_WINS = 1
USER_WINS = 2
EQUALLY = 0
# main function
def main():
answer = 'y'
while answer == 'y' or answer == 'Y':
result = EQUALLY
while result == EQUALLY:
computer = random.randint(MIN_VALUE, MAX_VALUE)
player = int(input("--> Please, enter your choice: '1'-rock, '2'-paper, '3'-scissors "))
print('\nResults:')
print('The computer choose', showChoise(computer))
print('You choose', showChoise(player))
result = checkChoise(computer, player)
if result == EQUALLY:
print('-->> The computer and you made the same choice. Please, try again!')
if result == COMPUTER_WINS:
print('The computer wins!')
elif result == USER_WINS:
print('You win!')
answer = input('Do you want to replay: Y/N? ')
# checkChoise function
def checkChoise(computer, player):
if computer == player:
return EQUALLY
elif computer == ROCK and player == PAPER:
return USER_WINS
elif computer == ROCK and player == SCISSORS:
return COMPUTER_WINS
elif computer == PAPER and player == ROCK:
return COMPUTER_WINS
elif computer == PAPER and player == SCISSORS:
return USER_WINS
elif computer == SCISSORS and player == ROCK:
return USER_WINS
elif computer == SCISSORS and player == PAPER:
return COMPUTER_WINS
# showChoise function
def showChoise(choice):
if choice == 1:
return 'rock'
elif choice == 2:
return 'paper'
elif choice == 3:
return 'scissors'
else:
return 'wrong value!'
# call main function
main()
| true |
efabc9d9bf780501d662b7978bb826431ee3e508 | Arpit-Pathak14/operations_python | /operations.py | 1,056 | 4.34375 | 4 | '''
You can remove # or comment by ctrl + / or simply remove br crusor
You can also edit these codes according to your will
You can also convert the input from into to any format such as float, etc.
'''
# Adding two numbers
#Defing a value or a variable
# a = int(input("Enter your value: "))
# b = int(input("Enter your another number"))
# c = a + b
# print("Your sum is : ", (c))
# Substracting the number
# Defing the another value
# e = int(input("Enter your value: "))
# f = int(input("Enter your another number: "))
# g = e-f or f-e
# print("Your subtract number: ", g)
# Divison in python
# dividend = int(input("Enter your dividend here: "))
# divisor = int(input("Enter your divisor here: "))
# reminder = dividend / divisor
# print("Your result or remainder is : " , reminder)
#Multiplication in python
# num1 = int(input("Enter your first number here: "))
# num2 = int(input("Enter your secound number here"))
# result = num1 * num2
# print("Your result is: ", result)
'''
Happy coding!
''' | true |
fa3fd38813468a1366972e0efe4055389bbf6881 | sayeed007/PythonProgramming | /Pandas/2_Series.py | 678 | 4.15625 | 4 | import pandas as pd
a = [1, 7, 2]
#Create a simple Pandas Series from a list
myvar = pd.Series(a)
print(myvar)
#Labels => This label can be used to access a specified value.
print(myvar[0])
#Create Labels
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar)
#Key/Value Objects as Series
calories = {"day1": 420, "day2": 380, "day3": 390}
myvar = pd.Series(calories)
print(myvar)
#To select only some of the items in the dictionary
myvar = pd.Series(calories, index = ["day1", "day2"])
print(myvar)
#DataFrames => usually multi-dimensional tables
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
myvar = pd.DataFrame(data)
print(myvar)
| true |
10c227e08c2e76121257204d373675624475908d | sayeed007/PythonProgramming | /Numpy/5_NumPy_Data_Types.py | 623 | 4.15625 | 4 | import numpy as np
#Checking the Data Type of an Array
arr = np.array([1, 2, 3, 4])
print(arr.dtype)
arr = np.array(['apple', 'banana', 'cherry'])
print(arr.dtype)
#Creating Arrays With a Defined Data Type
#String
arr = np.array([1, 2, 3, 4], dtype='S')
print("array =", arr)
print("Array Data Type : ", arr.dtype)
#4-Byte Integer
arr = np.array([1, 2, 3, 4], dtype='i4')
print("array =", arr)
print("Array Data Type : ", arr.dtype)
#Converting Data Type on Existing Arrays || astype()
arr = np.array([1.1, -4, 3.1])
newarr = arr.astype(bool) #Also use[int/float/str]
print(newarr)
print(newarr.dtype)
| true |
bc2953006829b16b0c4c01c8ca5942f5255bf6d1 | sayeed007/PythonProgramming | /Numpy/4_NumPy_Array_Slicing.py | 620 | 4.15625 | 4 | import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5]) #sHOWING 2ND TO 5TH ELEMENTS
print(arr[4:]) #5th to Last
print(arr[:4]) #1st to 3rd, not including 5th
#Negative Slicing
print(arr[-3:-1]) #3rd last index to 2nd last index || not including the last element
#STEP
print(arr[1:5:2]) #2nd to 5th position whis stem 2
print(arr[::2]) #all element with step 2
#Slicing 2-D Arrays
print('\nSlicing 2-D Arrays')
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4]) #from 1st array
print(arr[0:2, 2]) #from 2nd array
print(arr[0:2, 1:4]) #From both array
| true |
82c650f87e08305ea3013aa470845328e6a687a6 | Ashot-Sargsyan/lesson | /happybirthday.py | 1,448 | 4.21875 | 4 | # print('Hi everyone, thank you for coming today ^_^')
# day=input('You all know what day it is or not?') == 'yes'
# print('Very well...and so whats next...',day)
# name=input('Please write yourname :')
# print(name,'','oooo you Arnak?','\n','Today is an important day for you')
# year = 1994
# print(year,type(year))
# print('Your age.. ',2020-int(year),'..am I right?')
# print(type((int(year))))
# import calendar
# year=int(input('My year is :'))
# month=int(input('My month is:'))
# print(calendar.month(year,month))
name=input('Please enter the word you need:')
for i in name:
i=i.upper()
if(i=='*'):
print(" # # #### ###### ###### # # \n # # # # # # # # # # \n ###### ###### ###### ###### ## \n # # # # # # ## \n # # # # # # ## \n\n")
elif(i=='+'):
print(' ##### ###### ##### ###### # # ##### #### # # \n # # ## # # ## # # # # # # # # \n ##### ## # ## ## ###### # # ###### ## \n # # ## # # ## # # # # # # ## \n ##### ###### # # ## # # ##### # # ## \n\n')
| false |
829424237cfc90945668d3d308141d746c32af28 | shiba2046/shiba2046.github.io | /_notes/recursive.py | 1,498 | 4.1875 | 4 |
# https://medium.com/@ekapope.v/learning-recursive-algorithm-with-sudoku-solver-in-python-345623de98ae
# example grid
# the black cells are filled with 0
grid = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]]
def possible(y,x,n):
global grid
# n is the number we want to fill in
# 1st
# check if n already existed in vertical (y) axis
# if exists, return False (not possible)
for i in range(9):
if grid[y][i] == n:
return False
# 2nd
# check horizontal (x) axis
for i in range(9):
if grid[i][x] == n:
return False
# 3rd
# check the 3x3 local grid
x0 = (x//3)*3
y0 = (y//3)*3
for i in range(3):
for j in range(3):
if grid[y0+i][x0+j] == n:
return False
# return true if pass all 3 checks.
return True
def solve():
global grid
for y in range(9):
for x in range(9):
# Find blank positions in the grid (value = 0)
if grid[y][x] == 0:
# Loop n from 1-9
for n in range(1,10):
if possible(y,x,n):
grid[y][x] = n
solve()
# This is where backtracking happens
# Reset the latest position back to 0 and try with new n value
grid[y][x] = 0
return
print(np.matrix(grid))
input('More?')
| false |
1c40cbd38302ab6d0321d817e8799447692d209b | cb0n3y/python3 | /python_crash_course_2/chapter_04_working_with_lists/making_numerical_lists/squares.py | 359 | 4.25 | 4 | #!/usr/bin/python3.6
#squares = []
# First way with a variable named square.
#for value in range(1, 11):
# square = value ** 2
# squares.append(square)
#
#
# Second way without a variable
#for value in range(1, 11):
# squares.append(value**2)
#
#
# Third way: list comprehension
squares = [value ** 2 for value in range(1, 11)]
print(squares)
| true |
5ce864bbe85a1f2860e36ceb3ce79d37fd683d9c | Aadyaghumre/Aadya-python | /Task sheet 2 - Task 1.py | 209 | 4.1875 | 4 | """
Program to convert quantity entered by user in pounds into kg.
"""
weight= float(input("Enter weight in pounds: "))
kg = weight * 0.453592
print(str(weight)+" pound(s)"+ " is = "+str(kg)+" kg.") | true |
671c7ea6d2165fb02f673fea20e181335675035d | duarte28nm/SR1 | /aula02/fruits.py | 590 | 4.15625 | 4 | print("")
print ("fruits = 'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana' ")
print("")
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print("quantidade: ")
print(len(fruits))
print("")
print("repeti:")
x=fruits.count('cenoura')
print(x)
print("")
print("repeti:")
x=fruits.count('apple')
print(x)
print("")
print("repeti:")
x=fruits.count('pear')
print(x)
print("")
print("índice:")
print(fruits.index('banana'))
print("")
print("índice:")
print(fruits.index('pear'))
print("")
print("reverso:")
print('lista: ', fruits)
fruits.reverse()
| false |
310b4bcd9690435d31590b9170daccbfa5ea60e6 | shashwatc12/Python-Projects | /Python_Basic_Projects/GuessTheNumber.py | 1,038 | 4.28125 | 4 | # GuessTheNumber.py
# Purpose: Use random module, for loop or any loop
# Program: Generate randowm number, Ask user to guess the user input
#Pseudocode
""" Randomly assign the value to variable
Let user give the input
Check if the number is within a given range
Compare the input with the given variable and let user know how close he is
Keep the counter for the number of guesses
End the program after the Guess is right """
import random
var=random.randint(1,7)
print(var)
guesscount=1
print('I am thinking of a number between 1 & 20')
for i in range(1,20):
print('Take a guess')
userinput=int(input())
if userinput>20 or userinput<1:
print('Wrong input: You need to selct the number between 1 and 20')
elif userinput>var:
print('your guess is too high')
elif userinput<var:
print('your guess is too low')
elif userinput==var:
print('your guess us correct')
print('Good job! You guessed my number in '+ str(guesscount)+' guesses!')
break
guesscount+=1 | true |
c862513c8f18e5e0c9725c62b64db07fa4759128 | zefaradi/Coding-Challenges-from-codewars.com | /prime number.py | 1,135 | 4.125 | 4 | # Is a number prime?
# Define a function that takes an integer argument and returns logical value true
# or false depending on if the integer is a prime.
# Per Wikipedia, a prime number (or a prime) is a natural number greater than 1
# that has no positive divisors other than 1 and itself.
# Requirements
# You can assume you will be given an integer input.
# You can not assume that the integer will be only positive. You may be given
# negative numbers as well (or 0).
# NOTE on performance: There are no fancy optimizations required, but still the
# most trivial solutions might time out. Numbers go up to 2^31 (or similar, depends
# on language version). Looping all the way up to n, or n/2, will be too slow.
# Example
# is_prime(1) /* false */
# is_prime(2) /* true */
# is_prime(-1) /* false */
def is_prime(num):
if (num < 2):
return (False)
elif (num == 2):
return (True)
sq = int((num)**(0.5) + 1)
for n in range(2,sq):
if (num % n == 0):
return False
break
return True
test = is_prime(100**100)
print(test)
| true |
d340cdb80d4406caefc1b57af47c6ad2947cef0a | Titan-Prometheus/learning | /home.py | 615 | 4.15625 | 4 | import sys
if len(sys.argv) >= 2: # check the number of argument passed
data = open(sys.argv[1], "a") # create file to add data
while True: # create a loop
line = input() # get line to save from the user
if line != "SAVE": # check if line is the exit command before saving line to the file
data.write(line + "\n") # save line to the file
else:
break #break out of the loop if the line is exit command
data.close() #close file
print("The above content has been saved to "+ str(sys.argv[1]))
else:
print("Oops: file name argument is required")
| true |
ed31870969ca1144cb5cd4db117306cbf5c4ee9d | msalameh83/Algorithms | /DynamicProgramming/matrix_chain_multiplication.py | 2,271 | 4.125 | 4 | __author__ = 'Mohammad'
"""
Given a sequence of matrices, find the most efficient way to multiply these matrices together.
The problem is not actually to perform the multiplications, but merely to decide in which
order to perform the multiplications.
We have many options to multiply a chain of matrices because matrix multiplication is associative.
In other words, no matter how we parenthesize the product, the result will be the same.
For example, if we had four matrices A, B, C, and D, we would have:
(ABC)D = (AB)(CD) = A(BCD) = ....
However, the order in which we parenthesize the product affects the number of simple
arithmetic operations needed to compute the product, or the efficiency. For example,
suppose A is a 10 x 30 matrix, B is a 30 x 5 matrix, and C is a 5 x 60 matrix. Then,
(AB)C = (10x30x5) + (10x5x60) = 1500 + 3000 = 4500 operations
A(BC) = (30x5x60) + (10x30x60) = 9000 + 18000 = 27000 operations.
Time Complexity: O(n^3)
Auxiliary Space: O(n^2)
http://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/
https://www.youtube.com/watch?v=vgLJZMUfnsU&list=PLrmLmBdmIlpsHaNTPP_jHHDx_os9ItYXr&index=3
"""
import sys
def MatrixChainOrder(arr, sz):
# For simplicity of the program, one extra row and one
# extra column are allocated in m[][]. 0th row and 0th
# column of m[][] are not used
m = [[0 for x in range(sz)] for x in range(sz)]
# m[i,j] = Minimum number of scalar multiplications needed
# to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where
# dimension of A[i] is arr[i-1] x arr[i]
# cost is zero when multiplying one matrix.
for i in range(1, sz):
m[i][i] = 0
# L is chain length.
for L in range(2, sz):
for i in range(1, sz-L+1):
j = i+L-1
m[i][j] = sys.maxsize
for k in range(i, j):
# q = cost/scalar multiplications
q = m[i][k] + m[k+1][j] + arr[i-1]*arr[k]*arr[j]
if q < m[i][j]:
m[i][j] = q
return m[1][sz-1]
# Driver program to test above function
arr = [1, 2, 3 ,4]
arr = [2, 3, 6, 4, 5]
size = len(arr)
print("Minimum number of multiplications is " + str(MatrixChainOrder(arr, size)))
# This Code is contributed by Bhavya Jain | true |
6c2934e1387737c4039419fd13c5cb9d6e5905e1 | msalameh83/Algorithms | /DynamicProgramming/minimum_cost_path.py | 1,322 | 4.34375 | 4 | __author__ = 'Mohammad'
"""
Problem:
Given a Matrix, what is the minimum cost path fro top left to bottom right.
You can only move right or down.
Example:
1 3 5 8
4 2 1 7
4 3 2 3
Answer:
1 3 2 1 2 3 = 12
To Get the Answer: build comulative sums of first row and column
1 4 9 17
5
9
1 4 9 17
5 6 7 14
9 9 9 12
1) Optimal Substructure
The path to reach (m, n) must be through one of the 3 cells: (m-1, n-1) or (m-1, n) or (m, n-1).
So minimum cost to reach (m, n) can be written as "minimum of the 3 cells plus cost[m][n]".
minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n]
2) Overlapping Subproblems
Following is simple recursive implementation of the MCP (Minimum Cost Path) problem.
The implementation simply follows the recursive structure mentioned above.
"""
def mcp(matrix):
chart=[[0]*len(matrix[0]) for i in range(len(matrix))]
chart[0][0]=matrix[0][0]
for i in range(1,len(matrix)):
chart[i][0]=matrix[i][0]+chart[i-1][0]
for i in range(1,len(matrix[0])):
chart[0][i]=matrix[0][i]+chart[0][i-1]
for i in range(1,len(matrix)):
for j in range(1,len(matrix[0])):
chart[i][j]=min(chart[i-1][j],chart[i][j-1])+matrix[i][j]
print (chart)
matrix=[[1,3,5,8],
[4,2,1,7],
[4,3,2,3]]
mcp(matrix) | true |
358c80d9d2869ec46ea046620e0282f568446e47 | MuflahNasir/basic-concepts-of-python-in-codes | /Locate Point.py | 697 | 4.21875 | 4 | import turtle
center1, center2 = eval(input("Enter the center of a circle x, y: "))
radius = eval(input("Enter radius of a circle: "))
point1, point2 = eval(input("Enter points x1, y1: "))
turtle.penup()
turtle.goto(center1, center2 - radius)
turtle.pendown()
turtle.circle(radius)
turtle.penup()
turtle.goto(point1, point2)
turtle.pendown()
turtle.dot(6, "red")
turtle.penup()
turtle.goto(center1 - 70, center2 - radius - 20)
turtle.pendown()
d = ((point1 - center1) * (point1 - center1) + (point2 - center2) * (point2 - center2)) ** 0.5
if d <= radius:
turtle.write("Point is inside a circle")
else:
turtle.write("Point is outside a circle")
turtle.hideturtle()
turtle.done()
| false |
dcb91b2c7b7d6e0d5e574645df39d02701ca2693 | Eminem-ant/Leet-Code | /Merge.py | 1,752 | 4.53125 | 5 | # Python program to merge a linked list into another at
# alternate positions
class Node(object):
def __init__(self, data:int):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def push(self, new_data:int):
new_node = Node(new_data)
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# Function to print linked list from the Head
def printList(self):
temp = self.head
while temp != None:
print(temp.data)
temp = temp.next
# Main function that inserts nodes of linked list q into p at alternate positions.
# Since head of first list never changes
# but head of second list/ may change,
# we need single pointer for first list and double pointer for second list.
def merge(self, p, q):
p_curr = p.head
q_curr = q.head
# swap their positions until one finishes off
while p_curr != None and q_curr != None:
# Save next pointers
p_next = p_curr.next
q_next = q_curr.next
# make q_curr as next of p_curr
q_curr.next = p_next # change next pointer of q_curr
p_curr.next = q_curr # change next pointer of p_curr
# update current pointers for next iteration
p_curr = p_next
q_curr = q_next
q.head = q_curr
# Driver program to test above functions
llist1 = LinkedList()
llist2 = LinkedList()
# Creating LLs
# 1.
llist1.push(3)
llist1.push(2)
llist1.push(1)
llist1.push(0)
# 2.
for i in range(8, 3, -1):
llist2.push(i)
print("First Linked List:")
llist1.printList()
print("Second Linked List:")
llist2.printList()
# Merging the LLs
llist1.merge(p=llist1, q=llist2)
print("Modified first linked list:")
llist1.printList()
print("Modified second linked list:")
llist2.printList()
| true |
db543d7cd0f05dc5c02a3cee26bc6c5872881039 | LeakeyMokaya/Leakey_BootCamp_Day2 | /Data_Types/data_type.py | 1,077 | 4.3125 | 4 | #Define a function called data_type, to take one argument. Compare and return results, based on the argument supplied to the function.
# Complete the test to produce the perfect function that accounts for all expectations.
#For strings, return its length.
#For None return string 'no value'
#For booleans return the boolean
#For integers return a string showing how it compares to hundred e.g. For 67 return 'less than 100' for 4034 return 'more than 100' or equal to 100 as the case may be
#For lists return the 3rd item, or None if it doesn't exist
def data_type(param):
if type(param) == str:
return len(param)
elif param is None:
return 'no value'
elif type(param) == bool:
return param
elif type(param) == int:
if param < 100:
return 'less than 100'
elif param > 100:
return 'more than 100'
else:
return 'equal to 100'
else:
if type(param) == list:
if len(param) < 3:
return None
else:
return param[2] | true |
c75ab8121ad4662d5223bcc8d3b5ee12aeaef57b | mnpenchev/mini-projects | /fibonaci.py | 651 | 4.28125 | 4 | def fiboanacci(number): # 0,1,1,2,3,5,8,13,21,34.... the value of the next number is the sum of the last two numbers
a,b = 0,1 # we start with 0 and 1
for i in range(number): # for every number in range of numbers
yield a # repeat a
temp = a # create new variable to store the value of a
a = b # now we want a to get the value of b
b = temp + b # and b to get the value of the last tow numbers
for x in fiboanacci(10): # now call the fibonacci function and print every number forom the range
print(x) | true |
604076d9f2d832c24ad4076922bcfe1d8d98e357 | shage001/interview-cake | /src/inflight-entertainment/inflight_entertainment.py | 938 | 4.375 | 4 | def two_movies( flight_length, movie_lengths ):
"""
**********************************************************************************************************************
You've built an in-flight entertainment system with on-demand movie streaming.
Users on longer flights like to start a second movie right when their first one ends, but they
complain that the plane usually lands before they can see the ending. So you're building a feature
for choosing two movies whose total runtimes will equal the exact flight length.
Write a function that takes an integer flight_length (in minutes) and an array of integers movie_lengths
(in minutes) and returns a boolean indicating whether there are two numbers in movie_lengths whose
sum equals flight_length.
When building your function:
Assume your users will watch exactly two movies
Don't make your users watch the same movie twice
Optimize for runtime over memory
""" | true |
9deb5ddf35fb4f87e0b645daf31ad73c33c54a56 | DrewDaddio/Automate-Python | /FilePath.py | 2,505 | 4.625 | 5 | # Files & Folders
# Chapter 8 of the textbook
# Files concepts:
# File path and File Name
print("""For Python to do backslashes then we can do multiple options in order to write the backslash :
1. We can do a double backslash - C:\\home\\Desktop\\test.txt
2. We can do similar to a regular expression - (r'C:\\home\\Desktop\\test.txt')
""")
print("We can also use the OS Module")
import os
print("""import os
print(os.path.join('Folder', 'folder2', 'folder3', 'file.png'))""")
print(os.path.join('Folder', 'folder2', 'folder3', 'file.png'))
print("""
os.sep
os.getcwd()
os.chdir('C:\\')""")
print(os.sep)
print(os.getcwd())
print(os.chdir('C:\\'))
print(""""Relative Paths vs. Absolute Paths
Absolute Paths: The full written file path
Relative Paths: are paths that are concise and have just the last 2 (approximately) needed""")
print("""Example:
os.chdir('C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Python 3.5')
os.path.abspath('spam.png')
""")
print(os.path.abspath('spam.png'))
print("""Example to check if a path is an absolute path:
os.path.isabs('..\\..\\spam.png')
os.path.isabs('c:\\folder\\folder')
Example to check if a path is a relative path:
os.path.relpath('c:\\folder1\\folder2\\spam.png', 'c:\\folder')
Example to pull out the directory until the last part of the file path:
os.path.dirname('c:\\folder\\folder2\\spam.png
example to pull out the last part of the file path:
os.path.basename('c:\\folder1\\folder\\spam.png')
os.path.basename('c:\\folder1\\folder')
""")
print(os.path.isabs('..\\..\\spam.png'))
print(os.path.isabs('c:\\folder\\folder'))
print(os.path.relpath('c:\\folder1\\folder2\\spam.png', 'c:\\folder'))
print(os.path.dirname('c:\\folder\\folder2\\spam.png'))
print(os.path.basename('c:\\folder1\\folder\\spam.png'))
print(os.path.basename('c:\\folder1\\folder'))
print("""To check if a filepath exists, is a file, is a directory, and the file size:
os.path.exists('c:\\folder1\\folder2\\spam.png')
os.path.exists('c:\\')
os.path.isfile('c:\\folder1\\folder2\\spam.png')
os.path.isdir('c:\\')
os.path.getsize('c:\\windows\\system32\\calc.exe)
""")
print(os.path.exists('c:\\folder1\\folder2\\spam.png'))
print(os.path.exists('c:\\'))
print(os.path.isfile('c:\\folder1\\folder2\\spam.png'))
print(os.path.isdir('c:\\'))
print(os.path.getsize('c:\\windows\\system32\\calc.exe'))
print("""To create new folders:
os.makdirs('c:\\delicous\walnut\\coffee')""")
| true |
0009307bc8054563fb381633cb9b4059860346c7 | DrewDaddio/Automate-Python | /raiseAssertStatements.py | 2,337 | 4.34375 | 4 | # Raise and Assert Statements
# How to debug
# Python will raise an exception whenever there are issues in the code
print("You can raise your own exceptions in your code as a way to stop the code in this function and move to the accept statement")
print("Exceptions are raised with the 'Raise' statement")
print("raise Exception('This is the error message.')")
def boxPrint(symbol, width, height):
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width)) + symbol)
print(symbol * width)
boxPrint('*', 15, 5)
def refBoxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('"symbol" needs to be a string of length 1.')
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width)) + symbol)
print(symbol * width)
# Below will raise exception
# refBoxPrint('**', 15, 5)
def ref2BoxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('"symbol" needs to be a string of length 1.')
if (width < 2) or (height < 2):
raise Exception('"width" and "height" must be greater or equal to 2.')
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width)) + symbol)
print(symbol * width)
# Below will raise exception
#ref2BoxPrint('*', 1, 1)
# the traceback.format_exc() Function
import traceback
# Below will try an exception
try:
raise Exception('This is the error message.')
except:
errorFile = open('error_log.txt', 'a')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written error_log.txt')
# Assertions and the assert statement
# Assertions are sanity checks on the code
#assert False, 'This is the "Assert" error message.'
market_2nd = {'ns': 'green', 'ew': 'red'}
def switchLights(intersection):
for key in intersection.keys():
if intersection[key] == 'green':
intersection[key] = 'yellow'
elif intersection[key] == 'yellow':
intersection[key] = 'red'
elif intersection[key] == 'red':
intersection[key] = 'green'
assert 'red' in intersection.values(), 'Neither light is red!' + str(intersection)
switchLights(market_2nd)
| true |
316dc86b3eb8490587d36910faf370964dc48789 | DrewDaddio/Automate-Python | /RegularExpression.py | 1,475 | 4.75 | 5 | #Regular Expressions
#Allow you to specify a pattern of text to search for.
#expression to check for phone number
def isPhoneNumber(text):
if len(text) != 12:
return False # not phone number sized
if text[3] != '-':
return False # missing dash
for i in range(4,7):
if not text[i].isdecimal():
return False # no first 3 digits
if text[7] != '-':
return False # missing last 4 digits
return True
print(isPhoneNumber('415-555-1234'))
message = "Call me 415-555-1011 tomorrow, or at 415-555-9999 for office line"
#to detect where in the string the phone number is
foundNumber = False
for i in range(len(message)):
chunk = message[i:i+12]
if isPhoneNumber(chunk):
print('Phone number found: ' + chunk)
foundNumber = True
if not foundNumber:
print('Could not find any phone numbers.')
#i is the beginning of the index and then it will go to 12 characters
#Now we will do this in a regular expression to show how it can be condensed
print("This will be done using the Regular Expression method now")
import re
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
#regular expressions use a lot of back slashes
# \d = Looking for a digit
# above will look for a pattern of "3 digits - 3 digits - 4 digits"
mo = phoneNumRegex.search(message)
print(mo.group())
print("This got the first pattern of digits")
| true |
c2ad8abce91863108ac451df8124182330c37517 | meghana153/M-R-Jeevan | /coding_solutions/digital root.py | 742 | 4.15625 | 4 | """
A digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n.
If that value has more than one digit, continue reducing in this way until a
single-digit number is produced. This is only applicable to the natural numbers.
"""
def digitalroot(num):
""" Return Digital Root Of A Number """
if num < 0:
raise ValueError
if num < 10:
return num
else:
num1 = 0
while num > 0:
num1 = num1 + num%10
num = num//10
# print(f'debug num = {num} num1 = {num1}')
if num1 < 10 :
return num1
else:
return digitalroot(num1)
num = int(input('Enter Number : '))
print(digitalroot(num))
| true |
808a2555897c6a110b1f19210380893843f7bb40 | cid-aaron/testmachine | /testmachine/examples/nonuniquelists.py | 818 | 4.21875 | 4 | """
Find an example demonstrating that lists can contain the same element multiple
times.
Example output:
t1 = 1
t2 = [t1, t1]
assert unique(t2)
"""
from testmachine import TestMachine
from testmachine.common import ints, lists, check
machine = TestMachine()
machine.add(
# Populate the ints varstack with integer values
ints(),
# Populate the intlists varstack with lists whose elements are drawn from
# the ints varstack
lists(source="ints", target="intlists"),
# Check whether a list contains only unique elements. If it contains
# duplicates raise an error.
check(
lambda s: len(s) == len(set(s)), argspec=("intlists",), name="unique"
),
)
if __name__ == '__main__':
# Find a program that creates a list with non-unique elements.
machine.main()
| true |
e7a0ba348930d02d51df27ea4dc08d3096e4fbe9 | nena6/Udacity-Introduction-to-Python-Programming | /nearest_square.py | 755 | 4.375 | 4 | #Implement the nearest_square function. The function takes an integer argument limit, and returns the largest square number that is less than limit. A square number is the product of an integer multiplied by itself, for example 36 is a square number because it equals 6*6.
#There's more than one way to write this code, but I suggest you use a while loop!
#TODO: Implement the nearest_square function
def nearest_square(limit):
x=0
square=0
while ((x*x)<limit):
square=x*x
x+=1
return square
test1 = nearest_square(40)
print("expected result: 36, actual result: {}".format(test1))
#Udacity solution
def nearest_square(limit):
answer = 0
while (answer+1)**2 < limit:
answer += 1
return answer**2
| true |
29ddac09ce1c38cf4e46351fdbfe10a33fa8bcd8 | irinanicoleta/Google-Atelierul-Digital-Python | /Homework-2/gad-02.py | 659 | 4.3125 | 4 | # initial list
my_list = [7, 8, 9, 2, 3, 1, 4, 10, 5, 6]
# sort the list in ascending order
ordered_list = my_list.copy()
ordered_list.sort()
print(ordered_list)
# sort the list in descending order
ordered_list = my_list.copy()
ordered_list.sort()
ordered_list.reverse()
print(ordered_list)
# show even numbers from list
ordered_list.reverse()
length = len(ordered_list)
print(ordered_list[0:length:2])
# show odd numbers from list
length = len(ordered_list)
print(ordered_list[1:length:2])
# show multiples of 3 from list
multiples = []
for i in range(length):
if ordered_list[i] % 3 == 0:
multiples.append(ordered_list[i])
print(multiples)
| true |
9b1969823fe0155b927a282b6cd18dba17a3d422 | gautamtarika/Programming_Basics | /Tkinter_Basic_Programs/multiplication_table.py | 504 | 4.125 | 4 | from tkinter import *
window=Tk()
window.title("Multiplication Table")
EnterTable=IntVar()
l=Label(window,text="Input Any number to find Its Multiplication Table").pack(anchor=W)
e=Entry(window,text=EnterTable)
e.pack(anchor=W)
def MT():
print("\n")
for i in range (1,11):
num=EnterTable.get()
print(num,'X',i,'=',(i*num))
B=Button(window,text="Calculate",command=MT).pack(anchor=W)
b2=Button(window,text="Quit",command=quit).pack(anchor=W)
window.mainloop() | true |
5bcb3cdd76247699b3e6221c389faf2219322ff9 | AlekseyB86/BasicsPython | /lesson_1/les1_task6.py | 1,094 | 4.53125 | 5 | """Lesson 1 task 6"""
# Спортсмен занимается ежедневными пробежками. В первый день его результат составил 'a' километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который общий результат спортсмена составит не менее 'b' километров.
# Программа должна принимать значения параметров 'a' и 'b' и выводить одно натуральное число — номер дня.
a = float(input('Сколько "a" км пробежал спортсмен в 1й день?: '))
b = float(input('Сколько "b" км он должен пробегать в день: '))
days = 1
while a < b:
a *= 1.1
days += 1
print(f'Общий результат спортсмена составит не менее {b} км на {days}й день')
| false |
7e354a92470a040765559552cd2457c54f11f87b | 121910313014/pythonprograms | /L-3 ASSIGNMENT-3-OPERATIONS-IN-ARRAY.py | 2,698 | 4.34375 | 4 | # OperationS in Array
# J. Raghuramjee - 121910313004
# Function to copy elements form array
def copy_array(arr):
# Creating another array to store elements
arr2 = []
# Logic to copy array elements using for loop
for i in arr:
arr2.append(i) # Appending each element from arr1 to arr2
print("Elements of the copied array are : ")
for i in arr2:
print(i)
# Function to remove duplicates
def remove_duplicates(arr):
# Creating another array to store elements
arr2 = []
# Logic to remove duplicates elements from an array
for i in arr:
if i not in arr2: # Checks if the element we want to add to arr2 is not in arr1
arr2.append(i)
print("The array without duplicate elements is :")
for i in arr2:
print(i)
# Function display elements
def display(arr):
print("The elements in the array are :")
# Loop to go through all the elements
for i in arr:
print(i)
# Function to delete element at index k
def del_at_k(arr,k):
# Check if the index is valid
if k>=len(arr):
print("Enter a valid index!")
else:
del arr[k] # Del keyword to remove element in array
print("The elements after deleting the array are :")
for i in arr:
print(i)
# Function to search an element in array
def search(arr,k):
found = False
# Loop to check if the element exists in array
for index in range(len(arr)):
if arr[index]==k:
found = True
print("The element", k, "is at index", index)
# prints this statment if element doesnt exit
if not found :print("The element does not exist")
# Taking the array as input
arr = []
n = int(input("Enter the size of the array: "))
print("Enter the elements of the array :")
for i in range(n):
k = input()
arr.append(k)
print("The elements of the array are : ", arr)
# Giving option to user
print("Select from the options below :")
print("Option 1 - Copy elements from this array to another array")
print("Option 2 - Remove duplicates from the array")
print("Option 3 - Delete element at k-th index")
print("Option 4 - Search for an element in the array")
print("Option 5 - Display all the elements in the array")
opt = int(input("Enter an option : "))
if opt==1:
copy_array(arr)
elif opt==2:
remove_duplicates(arr)
elif opt==3:
ind = int(input("Enter the index to remove the element : "))
del_at_k(arr,ind)
elif opt==4:
ele = input("Enter the element to search : ")
search(arr,ele)
elif opt==5:
display(arr)
else:
print("Enter a vaild input!")
| true |
c4006dc5b4a5a613416b1b4cc4effd13ae7fe3e2 | 121910313014/pythonprograms | /L-4 Represent a Sparse Martix.py | 602 | 4.25 | 4 | # Program to Represent a Sparse Matrix
# J. Raghuramjee - 121910313004
# Declare the 2-D matrix
arr = [[0,0,0,3],[0,1,3,0],[9,0,0,0],[0,0,0,4]]
r = len(arr) # Number of Rows
c = len(arr[0]) # Number of columns
# Printing the original array
print("The Original Matrix")
for i in arr:
print(*i)
print()
# Declaring an array to store sparse matrix
sp = []
# Finding the non zero elements
for i in range(r):
for j in range(c):
if arr[i][j]!=0:
sp.append([i,j,arr[i][j]])
# Printing the sparse matrix
print("The Sparse Matrix")
for i in sp:
print(*i)
| false |
8825a234094c4f497cf78979c83538e596e1c409 | 121910313014/pythonprograms | /L-5 Assignment Binary Search with Testcases.py | 1,221 | 4.125 | 4 | # Program to perform binary search with Testcases
# J. Raghuramjee - 121910313004
def binary(arr,key,low,high):
if high >= low:
mid = (high+low)//2
if arr[mid]==key:
return mid
elif arr[mid]>key:
return binary(arr, key, low, mid-1)
else:
return binary(arr, key, mid+1, high)
else:
return -1
def test(arr,key):
if arr!=sorted(arr):
print("Array is not sorted, cannot implement binary search")
return
ans = binary(arr,key,0,len(arr)-1)
if ans!=-1: print("The element", key, "is found at index", ans)
else: print("The element", key, "is not found")
# Binary Search with test cases
# Test case 1 , sorted array with element present
print("TEST CASE 1")
arr1 = [1,2,3,4,5,6,7,8,9,10] # sorted array
key1 = 5 # present key
test(arr1,key1)
# Test case 2 , sorted array with element not present
print("TEST CASE 2")
arr2 = [1,2,3,4,5,6,7,8,9,10] # sorted array
key2 = 78 # not present key
test(arr2,key2)
# Test case 3 , unsorted array with element present
print("TEST CASE 3")
arr3 = [3,2,13,4,5,61,7,80,45,7] # sorted array
key3 = 5 # present key
test(arr3,key3)
| true |
7f87603238a6319d6fb269850b78273151b4105e | kaanozbudak/codeSignal | /arcade/adjacentElementsProduct.py | 370 | 4.125 | 4 | # Created by kaanozbudak at 2019-07-18
# Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
inputArray = [3, 6, -2, -5, 7, 3]
def adjacentElementsProduct(inputArray):
return max([inputArray[i] * inputArray[i + 1] for i in range(len(inputArray) - 1)])
print(adjacentElementsProduct(inputArray))
| true |
2d85a19fc32d49083a6d3e929b4909bb6bef5be6 | rohit00001/Assignment-2-letsupgrade-DATA-STRUCTURE | /Assignment 2 DATA STRUCTURE letsupgrade/DataStructureQ1A2.py | 291 | 4.21875 | 4 | #Write a Python program to print even numbers in a list.
#Sample:
#Input: list1 = [12, 3, 55, 6, 144]
#Output: [12, 6, 144]
#Input: list2 = [2, 10, 9, 37]
#Output: [2, 10]
#PROGRAM
list1 = [12, 3, 55, 6, 144]
for num in list1:
if num % 2 == 0:
print(num, end=" ")
| true |
26b3fb33f5ef6d0c29ceaafef6e8a7aa2ace2fa7 | porala/python | /practice/41.py | 573 | 4.28125 | 4 | #FromScratch - Create a script that generates a file where all letters of English alphabet are listed one in each line
#TO BE USED AS FIRST LECTURE EXAMPLE
#SOLUTION WOULD BE LIKE: Think of the program as a machine that gets some input and produces some output.
#In this case the input would be alphabet letters and the output a file with the alphabet letters. And between we need to use every tool that we can to make that happen.
import string
with open("letters.txt", "w") as file:
for letter in string.ascii_lowercase:
file.write(letter + "\n")
| true |
f00a0f3977b3fa6f9191d3c8c3cd29543070023e | razzlestorm/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 680 | 4.3125 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
list_of_ints = []
left_edge = 0
right_edge = k
# use slicing to view elements:
while right_edge <= len(nums):
max_val = max(nums[left_edge:right_edge])
list_of_ints.append(max_val)
left_edge += 1
right_edge += 1
return list_of_ints
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
| true |
addfbc5d79a7af27d702ab7f44bff52cc515b542 | Legedith/Misc. | /tribonnachi.py | 395 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 20 23:54:25 2018
@author: DSC
"""
def tribonacci(signature, n):
"""Gives n elements of tribonacchi give the signature i.e. first 3 elements
and number of elements"""
if n >3:
for i in range(3,n):
signature.append(signature[i-1]+signature[i-2]+signature[i-3])
return signature[:n]
l = tribonacci([1,1,1], 8) | true |
3f050cbc37bd7fe043b68c5c9f8408dad5fa16e7 | zirin12/Leetcode-InterviewBit-Solutions | /InterviewBit/modular_expression.py | 1,088 | 4.125 | 4 | '''
Implement pow(A, B) % C.
In other words, given A, B and C,
find (AB)%C.
Input : A = 2, B = 3, C = 3
Return : 2
2^3 % 3 = 8 % 3 = 2
'''
class Solution:
# @param A : integer
# @param B : integer
# @param C : integer
# @return an integer
# O(logn) time complexity as the problem space is halved each time
# when calculating power the computation can take a lot time in the normal way even for moderately large numbers
# Sometimes or many a times the result is so large we can't even fit it in 31 bits ( 1 bit for sign )
# so calculating the power first and then doing the modulo is bad
# so we try to get the result through associative and commutative property of modulo
# we reduce the size of the problem by half using exponent properties by representing a^n as a^(n/2) x a^(n/2) for even n
# for odd n a^1 x a^(n-1)
def Mod(self, A, B, C):
if B == 0 :
return 1 if A else 0
elif B%2 == 0:
return (self.Mod(A,B//2,C)**2) % C
else:
return (A%C * self.Mod(A,B-1,C)) % C
| true |
549c0e91916004bbea8e7e3050885710a0e2190c | zirin12/Leetcode-InterviewBit-Solutions | /InterviewBit/intersection_sorted_arrays.py | 1,593 | 4.25 | 4 | '''
Find the intersection of two sorted arrays.
OR in other words,
Given 2 sorted arrays, find all the elements which occur in both the arrays.
Example :
Input :
A : [1 2 3 3 4 5 6]
B : [3 3 5]
Output : [3 3 5]
Input :
A : [1 2 3 3 4 5 6]
B : [3 5]
Output : [3 5]
'''
class Solution:
# @param A : tuple of integers
# @param B : tuple of integers
# @return a list of integers
# This could be a binary search function to reduce the time complexity from O(n) to O(logn)
def find_ele(self,L,ele):
for i in range(len(L)):
if ele >= L[i]:
return i
# Since both the arrays are sorted , find out the intersection in range of both the arrays .
# Find the max of the first elements of both the arrays , the array with the max element will be part of the
# inner range of the other array , find out the starting point of that inner range using another function
# run a while loop getting all the elements which are equal, increment the pointer of the array contaning min element
# in each iteration.
def intersect(self, A, B):
l_A = 0
l_B = 0
m = max(A[0],B[0])
res= []
if A[0]==m:
l_B = self.find_ele(B,m)
else :
l_A = self.find_ele(A,m)
while l_A < len(A) and l_B < len(B):
if A[l_A] == B[l_B]:
res.append(A[l_A])
l_A += 1
l_B += 1
elif A[l_A] > B[l_B]:
l_B += 1
else :
l_A += 1
return res
| true |
05ed1b1af8b0653733bc044789258ff003676725 | taoyan/python | /Python学习/day05/列表,元组,集合互相转换.py | 417 | 4.25 | 4 | my_list = [1,4,5,4]
my_tuple = (5,7,7)
my_set = {4,9,9}
print(my_set)
#把列表转成集合(集合不允许重复数据,转换会去重)
result = set(my_list)
print(result,id(my_list),id(result))
#元组转集合
result = set(my_tuple)
print(result,id(my_tuple),id(result))
#列表和集合转元组
print(tuple(my_list))
print(tuple(my_set))
#集合和元组转列表
print(list(my_tuple))
print(list(my_set)) | false |
54257cac631eba53a2b9b363dc9db13714481efd | afoukal/Python | /PractiseDay2.py | 1,516 | 4.40625 | 4 | # 1. Ask the user to enter their name and then display their name three times.
#name = input('What is your name? ')
# index = 0
# while index < 3:
# print(name)
# index += 1
# 2. Alter program 1 so that it will ask the user to enter their name and a number and then display their name that number of times.
# name_2 = input('What is your name? ')
# number_2 = int(input("Tell me any number"))
# 3. Ask the user to enter their name and display each letter in their name on a separate line.
# name_3 = input('What is your name? ')
# index_3 = 0
# while index_3 < len(name_3):
# print(name_3[index_3])
# index_3 += 1
# 4. Change program 3 to also ask for a number. Display their name (one letter at a time on each line) and repeat this for the number of times they entered.
#
# name_4 = input('What is your name? ')
# number_4 = int(input("Tell me any number"))
#
# repeat = 0
# while repeat < number_4:
# index_4 = 0
# while index_4 < len(name_4):
# print(name_4[index_4])
# index_4 += 1
# repeat += 1
# 14. Write a Python program to sum all the items in a list.
# list_14 = list(range(50))
# result = 0
# for item in list_14:
# result += item
# print(result)
# 16. Write a Python program to get the largest number from a list.
# list_16 = [1, 5, 99, 0, -1, -100]
# #print(max(list_16))
#
# max_value = list_16[0]
# for number in list_16:
# if max_value < number:
# max_value = number
# print(max_value)
nums = [1, 2, 3]
print(nums[1: 3] + nums[0:1])
| true |
81e0bee0f90dc8f9775128f10c78df4bae1efa61 | llpk79/Algorithms | /eating_cookies/eating_cookies.py | 1,196 | 4.15625 | 4 | #!/usr/bin/python
import sys
# The cache parameter is here for if you want to implement
# a solution that is more efficient than the naive
# recursive solution
def eating_cookies(n, cache=None):
"""I like this one better."""
cache = {0: 1, 1: 1, 2: 2} if cache is None else cache
if n in cache:
return cache[n]
cache[n] = eating_cookies(n - 1, cache) + eating_cookies(n - 2, cache) + eating_cookies(n - 3, cache)
return cache[n]
def eating_cookies(n, cache=None):
"""But since the tests give cache as a list..."""
if not cache:
cache = [0 for _ in range(11)]
cache[0], cache[1], cache[2] = 1, 1, 2
if cache[n]:
return cache[n]
cache[n] = eating_cookies(n - 1, cache) + eating_cookies(n - 2, cache) + eating_cookies(n - 3, cache)
return cache[n]
if __name__ == "__main__":
if len(sys.argv) > 1:
num_cookies = int(sys.argv[1])
print("There are {ways} ways for Cookie Monster to eat {n} cookies.".format(ways=eating_cookies(num_cookies),
n=num_cookies))
else:
print('Usage: eating_cookies.py [num_cookies]') | true |
c48a457d670e0a484dbad3c728929108df9ec65c | gopal2109/Data | /Python-programs/data_structures/tuples/tuple.py | 382 | 4.28125 | 4 | """
Group of characters which are enclosed by two parenthesis
Tuples are immutable objects.so we cannot alter elements which are inside the tuple.
"""
# count
"""
used to find repeating or occurrences of particular element in the tuple
takes one parameter
"""
a = (10, 0, 3, 0)
print a.count(0)
# index
"""
used to get index position of particular element
"""
print a.index(0, 2)
| true |
ab17ef65fad19fee2261333940731c550276e2c2 | gopal2109/Data | /Python-programs/data_structures/strings/string_reverse.py | 218 | 4.125 | 4 |
def reverse_string(string):
a = string[::-1]
return a
print reverse_string("string")
def reverse_words(string):
return ''.join(string[::-1])
string = "python developer"
print reverse_words(string)
| true |
ff9d61190c6fb1bef1d418a763acbd42be66bfeb | maj3r1819/LPTHW | /Exercises/exp30.py | 438 | 4.15625 | 4 | people=30
cars=40
buses=15
if(cars>people):
print("we should take the cars")
elif(cars<people):
print("we should not take the cars")
else:
print("we cant decide")
if(buses>cars):
print("thats too many buses")
elif(buses<cars):
print("maybe we could take the buses")
else:
print("we still cant decide")
if(people>buses):
print("Alright,lets just take the buses")
else:
print("Fine , lets stay home then")
| true |
426cc6d88f3cb63bd962a894b0d63c62f47f79bd | kevin115533/newtonSquareRoot | /newtonRecursion.py | 677 | 4.1875 | 4 | import math
def main():
while True:
x = input("Enter a positive number or hit Enter to quit: ")
if x == "":
exit()
newton(x, 1)
def newton(x, y):
number = float(x)
estimate = 1
tolerance = 0.000001
if number == 0:
return 0
elif number == 1:
return 1
elif number > 1:
while True:
estimate = (y + number / y) / 2
difference = abs(number - y ** 2)
if difference <= tolerance:
break
return newton(number, estimate)
print("The program's estimate: ", estimate)
print("Python's estimate: ", math.sqrt(number))
main() | true |
bd2f64767f1b94b323f8da35c4662c3e2ab4d668 | Drag49487Jr/Control-Flow-in-Python | /exercise-5.py | 709 | 4.125 | 4 | # exercise-05 Fibonacci sequence for first 50 terms
# Write the code that:
# 1. Calculates and prints the first 50 terms of the fibonacci sequence.
# 2. Print each term and number as follows:
# term: 0 / number: 0
# term: 1 / number: 1
# term: 2 / number: 1
# term: 3 / number: 2
# term: 4 / number: 3
# term: 5 / number: 5
# etc.
# Hint: The next number is found by adding the two numbers before it
total = 0
num1 = 0
num2 = 1
while total < 50:
if total < 2:
print(f'term = {total} | number = {total}')
else:
next_num = num1 + num2
print(f'term = {total} | number = {next_num}')
num1 = num2
num2 = next_num
total += 1
| true |
2a2013155322a04f4cdc496ad0f75186081acbf2 | Librason/learn_python | /35tryout.py | 468 | 4.4375 | 4 | def f():
choice = input("Please input a value: \n> ")
if choice == "1" or choice == "2":
# cannot simplify into choice == "1" or "2"
print(f"The input is {choice}.")
elif "3" in choice or "4" in choice:
print(f"{choice} is not a good option.")
elif choice == "5" or choice == "6":
print("That's a good choice.")
else:
print('Hello World')
f()
# the function must be initiated at the end.
| true |
b79db88261ba83427b2921ea9f3d098173f17257 | Librason/learn_python | /11input_ex11.py | 415 | 4.21875 | 4 | print("How old are you?", end = ' ')
# end = ' ' joins print and input into one line.
age = input()
print("How tall are you?", end = ' ')
height = input()
print("How much do you weight", end = ' ')
weight = input()
print(f"So, you're {age} years old, {height} tall and {weight} heavy.")
# input() is a string by default
# if math is needed, use int(input())
# or float(input()) to make it a number. | true |
b4ab751c49e2ac171c26c83c23ca2a35f0ba0e12 | rudrasingh21/Python-For-Beginners---1 | /24. Set and Frozen Set.py | 920 | 4.53125 | 5 | #SET is unordered collection of Unique records.
basket={"orange","apple","mango","apple","orange"}
print(type(basket))
print(basket)
#Output:
#{'mango', 'orange', 'apple'}
#you can see it gives you Unique record as output.
#OTHER Way
a=set()
a.add(1)
a.add(2)
a.add(3)
print(a)
b = {}
print(type(b))
#NOTE:- if you are giving blank {} , then it will be a directory
# if you are giving some value in {} , then it will be a SET.
#LIST allows Index operation , but SET don't allow Index operation.
#*******LIST to set**********
numbers=[1,2,3,4,1,2,3]
unique_number=set(numbers)
print(unique_number)
print(type(unique_number))
unique_number.add(5)
print(unique_number)
#*******FROZEN SET***************
fs=frozenset(numbers)
print(fs)
#NOTE:- Frozen set is same as Set , but it doesn't allow to add,
#So you can not change content of the set.
| true |
9f3b1d2981255dba0d89181b7d7c016288262841 | kuchunbk/PythonBasic | /3_list/Sample/list_ex23.py | 305 | 4.25 | 4 | '''Question:
Write a Python program to flatten a shallow list.
'''
# Python code:
import itertools
original_list = [[2,4,3],[1,5,6], [9], [7,9,0]]
new_merged_list = list(itertools.chain(*original_list))
print(new_merged_list)
'''Output sample:
[2, 4, 3, 1, 5, 6, 9, 7, 9, 0]
''' | false |
75e704e3f765f3e54df628be453f588f0d07e7e1 | kuchunbk/PythonBasic | /1_Basic_I/Basic/31.py | 610 | 4.1875 | 4 | def get_max_divisor_of_two_number(number1, number2):
min_number = min(number1, number2)
max_number = max(number1, number2)
if max_number % min_number:
for number in range(min_number // 2 + 1, 0, -1):
if min_number % number == 0 and max_number % number == 0:
return number
else:
return min_number
if __name__ == "__main__":
input_number1 = int(input('number1'))
input_number2 = int(input('number2'))
print("max divisor of two number: ", input_number1, input_number2)
print(get_max_divisor_of_two_number(input_number1, input_number2)) | true |
6387b84d13fb0611e7dfa400938d0004184a4ab3 | kuchunbk/PythonBasic | /1_Basic_I/Basic/32.py | 640 | 4.1875 | 4 | def get_lowest_common_multiple(number1, number2):
min_number = min(number1, number2)
max_number = max(number1, number2)
if max_number % min_number:
count = 1
while count <= min_number:
if max_number * count % min_number == 0:
return max_number * count
count += 1
else:
return max_number
if __name__ == "__main__":
input_number1 = int(input('number1'))
input_number2 = int(input('number2'))
print("Lowest common multiple of two number: ",
input_number1, input_number2)
print(get_lowest_common_multiple(input_number1, input_number2))
| true |
ce9548966068bc85335a277e98d94fabad51a6b5 | kuchunbk/PythonBasic | /1_Basic_I/Sample/basic_ex115.py | 353 | 4.375 | 4 | '''Question:
Write a Python program to compute the product of a list of integers (without using for loop).
'''
# Python code:
from functools import reduce
nums = [10, 20, 30,]
nums_product = reduce( (lambda x, y: x * y), nums)
print("Product of the numbers : ",nums_product)
'''Output sample:
Product of the numbers : 6000
''' | true |
a2b9ad9e21529360ea3b1af86feec54ac129c2ac | kuchunbk/PythonBasic | /9_date_time/Sample/date-time_ex28.py | 791 | 4.1875 | 4 | '''Question:
Write a Python program to get the dates 30 days before and after from the current date.
'''
# Python code:
from datetime import date, timedelta
current_date = date.today().isoformat()
days_before = (date.today()-timedelta(days=30)).isoformat()
days_after = (date.today()+timedelta(days=30)).isoformat()
print("\nCurrent Date: ",current_date)
print("30 days before current date: ",days_before)
print("30 days after current date : ",days_after)
'''Output sample:
Current Date: 2017-05-06
30 days before current date: 2017-04-06
30 days after current date : 2017-06-05
''' | true |
a53d92307519a5a1f7b03606b68814538ad4dc11 | kuchunbk/PythonBasic | /3_list/Sample/list_ex19.py | 226 | 4.125 | 4 | '''Question:
Write a Python program to get the difference between the two lists.
'''
# Python code:
list1 = [1, 2, 3, 4]
list2 = [1, 2]
print(list(set(list1) - set(list2)))
'''Output sample:
[3, 4]
''' | true |
e5e3f39155e70c24dd1a9b3144dfca29d02acc89 | kuchunbk/PythonBasic | /6_Set/Sample/sets_ex9.py | 277 | 4.375 | 4 | '''Question:
Write a Python program to create a symmetric difference.
'''
# Python code:
setx = set(["apple", "mango"])
sety = set(["mango", "orange"])
#Symmetric difference
setc = setx ^ sety
print(setc)
'''Output sample:
{'apple', 'orange'}
''' | true |
67d988ee85f7e937339edd0145f07a2c130c1b16 | kuchunbk/PythonBasic | /5_tuple/Sample/tuple_ex13.py | 2,127 | 4.34375 | 4 | '''Question:
Write a Python program to slice a tuple.
'''
# Python code:
>>> #create a tuple
>>> tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
>>> #used tuple[start:stop] the start index is inclusive and the stop index
>>> _slice = tuplex[3:5]
>>> #is exclusive
>>> print(_slice)
>>> #if the start index isn't defined, is taken from the beg inning of the tuple
>>> _slice = tuplex[:6]
>>> print(_slice)
>>> #if the end index isn't defined, is taken until the end of the tuple
>>> _slice = tuplex[5:]
>>> print(_slice)
>>> #if neither is defined, returns the full tuple
>>> _slice = tuplex[:]
>>> print(_slice)
>>> #The indexes can be defined with negative values
>>> _slice = tuplex[-8:-4]
>>> print(_slice)
>>> #create another tuple
>>> tuplex = tuple("HELLO WORLD")
>>> print(tuplex)
>>> #step specify an increment between the elements to cut of the tuple
>>> #tuple[start:stop:step]
>>> _slice = tuplex[2:9:2]
>>> print(_slice)
>>> #returns a tuple with a jump every 3 items
>>> _slice = tuplex[::4]
>>> print(_slice)
>>> #when step is negative the jump is made back
>>> _slice = tuplex[9:2:-4]
>>> print(_slice)
'''Output sample:
(5, 4)
(2, 4, 3, 5, 4, 6)
(6, 7, 8, 6, 1)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
(3, 5, 4, 6)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
('L', 'O', 'W', 'R')
('H', 'O', 'R')
('L', ' ')
''' | true |
6e8553f5000940402bbf108598d910d48cbecbe0 | kuchunbk/PythonBasic | /3_list/Sample/list_ex30.py | 545 | 4.4375 | 4 | '''Question:
Write a Python program to get the frequency of the elements in a list.
'''
# Python code:
import collections
my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30]
print("Original List : ",my_list)
ctr = collections.Counter(my_list)
print("Frequency of the elements in the List : ",ctr)
'''Output sample:
Original List : [10, 10, 10, 10, 20, 20, 20, 20, 40, 40, 50, 50, 30]
Frequency of the elements in the List : Counter({10: 4, 20: 4, 40: 2, 50: 2, 30: 1})
''' | true |
3d9907428f8325ec22389e2ef1f40bdf27866e1a | kuchunbk/PythonBasic | /2_String/Sample/string_ex18.py | 634 | 4.125 | 4 | '''Question:
Write a Python function to get a string made of its first three characters of a specified string. If the length of the string is less than 3 then return the original string.
'''
# Python code:
def first_three(str):
return str[:3] if len(str) > 3 else str
print(first_three('ipy'))
print(first_three('python'))
print(first_three('py'))
'''Output sample:
ipy
pyt
py
''' | true |
6e07078a63a5dd3d3e60aa9649b810d7c45c7fbb | kuchunbk/PythonBasic | /3_list/Sample/list_ex56.py | 234 | 4.15625 | 4 | '''Question:
Write a Python program to convert a string to a list.
'''
# Python code:
import ast
color ="['Red', 'Green', 'White']"
print(ast.literal_eval(color))
'''Output sample:
['Red', 'Green', 'White']
''' | true |
aaad43e98679a758419607a069de848aac84be14 | kumail-anis/PalindromeChecker | /Palindrome.py | 1,035 | 4.28125 | 4 | import re
def get_input(text):
return input(text)
#replace 'get_input("enter text here: ")' with '' to hardcode input for testfile
val = get_input("enter text here: ")
def reverse(val):
# this is returning a string using ::-1 that returns word backwards
return val[::-1]
def format(val):
# enter all formatting information here
val = re.sub('[^A-Za-z0-9]+', '', val) # regex to remove all special characters
val = val.lower() # change to lower casing
val = val.replace(" ", "") # remove spacing
return val
def isPalindrome(val):
# this is calling a reversed function
originalval = val
val = format(val)
rev = reverse(val)
# Checking if both string are equal or not
if (val == ''):
print("No value entered")
elif (val == rev):
print("'" + originalval + "'" + " is Palindrome")
return True
else:
print("'" + originalval + "'"" is not Palindrome as it becomes ""'" + rev + "'"" backwards" )
return False
isPalindrome(val)
| true |
8eb1cd33c7d19b559e20cdade82b82ec6571f4d8 | Rmahesh7/Python-Beginner-practice | /Python-Chapter 3-molecular.py | 779 | 4.375 | 4 | # molecular.py
# A program that computes the molecular weight of a carbohydrate (in grams per mole)
# based on the number of hydrogen, carbon, and oxygen atoms in the molecule.
# llustrates use of the math library.
import math # Makes the math library available.
def molecular():
print ("This program computes the molecular weight of a carbohydrate (in grams per mole).")
print()
print ("The formular of carbohydrate = C(H2O)")
print()
H = float(input("Enter the number of hydrogen atmos H: "))
C = float(input("Enter the number of carbon atmos C: "))
O = float(input("Enter the number of oxygen atmos O: "))
total = C + H * 2 + O
print()
print("The total combined molecular weight of all the atmos is:", total)
molecular()
| true |
47a56436ff19e10fd88a9a4db3cbbdb41f8d4459 | Rmahesh7/Python-Beginner-practice | /Python-Chapter 7-maxn.py | 463 | 4.21875 | 4 | # maxn.py
# Finds the maximum of a series of numbers
import math # Makes the math library available.
def maxn():
n = int(input("How many numbers are there? "))
# Set max to be the first value
maxval = float(input("Enter a number >> "))
# Now compare the n-1 successive values
for i in range(n-1):
x = float(input("Enter a number >> "))
if x > maxval:
maxval = x
print("The largest value is", maxval)
maxn()
| true |
95d3ea6b04c1a23243b278264cf9a56d2c421579 | Rmahesh7/Python-Beginner-practice | /Python-Chapter 1-chaos.py | 391 | 4.21875 | 4 | # File: chaos. py
# A simple program illustrating chaotic behavior.
def main():
print("This program illustrates a chaotic function")
n=eval(input("How many numbers should I print?"))
x=eval(input("Enter a number between 0 and 1:"))
y=eval(input("Enter a number between 0 and 1:"))
for i in range(n):
x=3.9*x*(1-x)
y=3.9*y*(1-y)
print(x,y)
main()
| true |
17e80c834fccf844e22a42b0618ae62bd6121b52 | Rmahesh7/Python-Beginner-practice | /Python-Chapter 13 - exponentiation.py | 316 | 4.375 | 4 | # chapter 13: Fast exponentiation
def recPower(a, n):
# raises a to the int power n
if n == 0:
return 1
else:
factor = recPower(a, n//2)
if n%2 == 0: # n is even
return factor * factor
else: # n is odd
return factor * factor * a
| false |
7f6af84bfa098b35b16e4c766ee646ea0cdc811f | nlns3444/python-dl | /labs/lab1/code/longestword.py | 1,087 | 4.28125 | 4 | # Taking input from the user
list1 = input("Enter any Sentence: ").split(" ")
# Function for evaluating the sentence
def give_sentence(list1):
# Declaring empty list
list2 = []
#Print middle words in a sentence
l=len(list1)
print (l)
# If the number of elements in the list are even print the middle, and the element next to it
if(l%2 == 0):
print("Middle Words of the Sentence are: " + list1[len(list1) // 2], list1[(len(list1) // 2) + 1])
else:
# If the length is an odd number print the middle element
print("Middle Words of the Sentence are: " + list1[len(list1) // 2])
# Printing Longest Word in the sentence
for item in list1:
list2.append(len(item))
print("Longest Word in the Sentence: "+list1[list2.index(max(list2))] +" "+"("+str(max(list2)) + " letters"+ ")")
# Printing Sentence in Reverse
# item[::-1] to reverse the string
# end = " " is to print side by side
print("Reversed Sentence: ", end= " ")
for item in list1:
print(item[::-1],end = " ")
give_sentence(list1) | true |
038a2c7b68730704b708aca7c9d353469dffe492 | gopukrish100/gopz | /PycharmProjects/gn/venv/marks.py | 445 | 4.125 | 4 | mark1=int(input("enter the mark of subject 1"))
mark2=int(input("enter the mark of subject 2"))
mark3=int(input("enter the mark of subject 3"))
total=mark1+mark2+mark3
if(total>140):
print("A+")
elif(total>130) & (total<=140):
print("A")
elif(total>120) & (total<=130):
print("B+")
else:
print("failed")
if(mark1>=mark2)&(mark1>=mark3):
print(mark1)
elif(mark2>=mark1)&(mark2>=mark3):
print(mark2)
else:
print(mark3)
| true |
fc3799340dfd0d4a293bf314d8c314e2e9c96009 | beingnishas/projecteuler | /001_Multiples_of_3_and_5.py | 496 | 4.375 | 4 | #!/usr/bin/env python
'''If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.'''
myarg = input("enter max limit: ")
def multiple_3_or_5(maxlimit):
counter=0
for i in range(1, int(maxlimit), 1):
if i%3==0 and i%15!=0:
counter+=i
if i%5==0 and i%15!=0:
counter+=i
return(counter)
print(multiple_3_or_5(myarg))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.