blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
15ea8695f41f7a946ad704915e69947be30a0c89 | gicici/python | /lists.py | 853 | 4.1875 | 4 | my_list=[1,2,3]
print(my_list)
#Lists can hold different types of numbers, strings or even floating point numbers
my_list= ['string',1,0.3,67, 'o']
print(my_list)
#len stands foor length
print(len(my_list))
my_list = ['one','two', 'three', 4,5]
#grabs elements on the index and that is 1
print(my_list[0])
l = [1,4,5]
l.append('append')
#append method above is used to add items permanetly to a list
print(l)
#nesting lists
lst_1 = [4,5,9]
lst_2 = [2,7.0]
lst_3 = [1,3,6]
matrix = [lst_1,lst_2,lst_3]
print(matrix)
my_list[4] = (4,5,8)
print(my_list )
l = []
for letter in l:
l.append(letter)
print(l)
l = [letter for letter in 'word']
lst = [number for number in range(11) if number%2==0]
print(lst)
celsius = [ 0,10,20.1,34.5]
fahrenheit = [ temp for temp in celsius]
print(fahrenheit)
lst = [x**2 for x in[x**2 for x in range(11)]]
print(lst) | true |
40c8dfe529c86ddbcdb60cf52e31600c9e64b669 | gicici/python | /ex2.py | 2,697 | 4.21875 | 4 | print("I could have code like this") #and the comment after
#You can also use a comment to "disable" or comment out
#print("This wont run")
l = [1,2,3]
print(l.append(4))
#objects are things on the real world
print(l.count(3))#this is used to check the type while count()is used to 'count ' the number of times something appears.
#class is a blueprint that defines the nature of an object.blueprint means an operational plan for.
#instance is a specific object created from particular class
#attribute is a characteristic of an object
#insatnce of a class is as follows
# x = Sample()
#method is the operation we perform on an object
class Dog(object):
#class object attribute this means no matter what object you make the species variable ill never change
species = 'mammal'
legs = 4
def __init__(self, breed, name, color):
self.breed = breed
self.name = name
self.color = color
sam = Dog(breed = 'Lab',name = 'Lance', color= 'brown')
print(sam.legs)# doesn't use () because it is not a method but it is an attribute
#methods are used in the encapsulation that is dividing responsilility
class Circle(object):
pi = 3.14
def __init__(self,radius):
self.radius = radius
def area(self):
return self.radius**2 * Circle.pi# we are taking it from the main class hence do not need to use self and uses self. radius to refer to the previous radius declared
#setting a new radius
def set_radius(self,new_radius):
#this method takes in the current radius and resets the current radius of the Circle
self.radius = new_radius
def get_radius(self):
return self.radius
def perimeter(self):
return self.radius * 2 * Circle.pi
c = Circle(radius = 3.4)
c.set_radius(20)
print(c.perimeter())
#inheritance is a way to form new classes from classes that have already been defined.
#derived classes are formeed from base classes.
class Animal(object):
def __init__(self):
print('Animal Created')
def whoAmI(self):
print('Animal')
def eat(self):
print('Eating')
class Dog(Animal):
def __init__(self):
Animal.__init__(self) # this is calling from the base class
print('Dog Created')
def whoAmI(self):
print('Dog')
def bark(self):
print('Woof!')
d = Dog()
print(d)# going to display both the dog and animal created since it has called the __init__ method on it
class Book(object):
def __init__(self, title, author, pages):
print('A book has been created')
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title %s, Author %s, Pages %s" %(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print('The book is gone')
b = Book('Python' , 'Jose' , 300)
del(b)
| true |
0747db47499bee241d6c2685bb29641204bd3576 | joydip10/Python-Helping-Codes | /errorsandexceptions2.py | 633 | 4.125 | 4 | class Animal:
def __init__(self,name):
self.name=name
def sound(self):
raise NotImplementedError("You haven't implemented this method in this particular subclass") #abstract method
class Dog(Animal):
def __init__(self,name,breed):
super().__init__(name)
self.breed=breed
def sound(self):
return "barkings"
class Cat(Animal):
def __init__(self,name,breed):
super().__init__(name)
self.breed=breed
def sound(self):
return "meaws"
tommy=Dog("Tommy","Dolmesian")
print(tommy.sound())
| true |
04005a5d88f72a3afa481f52fbd5478a3fb87316 | joydip10/Python-Helping-Codes | /args.py | 1,253 | 4.125 | 4 | def total(*nums):
total=0
print("Type of *nums: "+str(type(nums)))
print("Packed as tuple: ")
print(nums) #packed
print("Unpacked: ")
print(*nums) #unpacked
for i in nums:
total+=i
return total
print(total(1,2,3,4,5,6,7,8,9,10))
print("\n\n\n\n\n")
l=[i for i in range(1,11)]
t=(i for i in range(1,11))
s={i for i in range(1,11)}
print("\n\n\n\n\n")
print("When the input is as list: ")
print(total(*l))
print("\n\n\n\n\n")
print("When the input is as tuple: ")
print(total(*t))
print("\n\n\n\n\n")
print("When the input is as set: ")
print(total(*s))
#Exercise
l=[i for i in range(1,4)]
def func(num,*args):
if args:
l=[i**num for i in args]
return l
else:
return "You didn't put anything inside!!"
print(func(3,*l))
print(func(3,*[2,3,4]))
print(func(3))
print("\n\n\n\n\n\nExercise:")
def func(*args):
print(*args)
print(args)
summ=0;
for i in args:
summ=summ+i
return summ
def func1(*args):
print(*args)
print(args)
summ=0;
for i in args:
p=0;
for j in i:
p=p+j
summ=summ+p
return summ
print(func(1,2,3,4,5))
print('\n\n\n')
print(func1([1,2,3],[4,5,6],[7,8,9,10]))
| true |
258a1180264a716ab49e134082c6e03c1e191ff8 | pkopy/python_tests | /csv/csv_reader.py | 336 | 4.125 | 4 | import csv
def csv_reader(file_object):
'''
Read a CSV file using csv.DictReader
'''
reader = csv.DictReader(file_object, delimiter=',')
for line in reader:
print(line["first_name"]),
print(line["last_name"])
if __name__ == "__main__":
with open("data.csv") as f_obj:
csv_reader(f_obj) | true |
96127e3f4f8472101b61feea8c732ff990fe709b | oliveirajonathas/python_estudos | /pacote-download/pythonProject/exercicios_python_guanabara/ex103.py | 636 | 4.1875 | 4 | """
Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: o nome de um jogador e
quantos gols ele marcou.
O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente.
"""
def ficha(nome='', gols=0):
if nome == '':
nome = '<desconhecido>'
print(f'O jogador {nome} marcou {gols} gols.')
def lergols():
valor = input('Número de Gols: ')
if valor == '':
valor = 0
else:
int(valor)
return valor
jogador = str(input('Nome do jogador: ')).strip()
gol = lergols()
ficha(jogador, gol)
| false |
9274f65c1ce2cd7c5c7f286b0c6cb5cfe88a3c7a | oliveirajonathas/python_estudos | /pacote-download/pythonProject/exercicios_python_guanabara/ex026.py | 477 | 4.15625 | 4 | #Faça um programa que leia uma frase pelo teclado e mostre:
#Quantas vezes aparece a letra "A"
#Em que posição ela aparece a primeira vez
#Em que posição ela aparece a última vez
frase = str(input('Digite uma frase qualquer: '))
frase = frase.upper().strip()
print('Sua frase tem {} letras "A"'.format(frase.count('A')))
print('A primeira ocorrência é na posição {}'.format(frase.find('A')))
print('A última ocorrência é na posição {}'.format(frase.rfind('A')))
| false |
85a08b66a1d2b7b3dcee108a204733fa8faf9005 | oliveirajonathas/python_estudos | /pacote-download/python_e_django/cap09-funções_personalizadas/valor_referencia.py | 907 | 4.15625 | 4 | def quadrado_por_valor(x):
"""
Eleva x ao quadra, usando passagem por valor
:param x:
:return:
"""
print(f'Recebido o valor {x}')
x = x * x
print(f'Devolvido o valor {x}')
return x
def quadrado_por_ref(lista, x):
"""
Recebe uma lista e um valor x. Eleva x ao quadrado, e armazena-o na lista, usando passagem por referência.
:param lista:
:param x:
:return:
"""
print(f'Rcebido o valor {x}')
x = x * x
lista.append(x)
print(f'Devolvido o valor {x}')
return x
dummy = 4
print(f'dummy vale {dummy}')
print('Elevando dummy ao quadrado:')
print('por valor:')
print(quadrado_por_valor(dummy))
print(f'Após a execução de quadrado_por_valor(dummy), dummy agora vale {dummy}')
print('por referência:')
l = []
print(quadrado_por_ref(l, dummy))
print(f'Após a execução de quadrado_por_ref(l, dummy), dummy agora vale {l[0]}')
| false |
3400dfcfb0474d3cf2a0934d3891a52f90ffb277 | oliveirajonathas/python_estudos | /pacote-download/pythonProject/exercicios_python_guanabara/ex075-professor.py | 918 | 4.125 | 4 | """
Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
A) Quantas vezes apareceu o valor 9
B) Em que posição foi digitado o primeiro valor 3
C) Quais foram os números pares
"""
num = (int(input('Digite um número: ')), int(input('Digite outro número: ')),int(input('Digite mais um número: ')),
int(input('Digite o último número: ')))
if 9 in num:
print(f'O número 9 apareceu {num.count(9)} vezes!')
else:
print('O número 9 não foi digitado!')
if 3 in num:
print(f'O número três apareceu na {num.index(3) + 1} posição')
else:
print('O número 3 não foi digitado!')
pares = 0
for n in num:
if n % 2 == 0:
pares += 1
if pares > 0:
print('Os número PARES digitados foram: ', end='')
for n in num:
if n % 2 == 0:
print(n, end=' ')
else:
print('Não foram digitados valores pares!')
| false |
d5011d5d4c99dbbc004dcb866f29119bc9ceb356 | oliveirajonathas/python_estudos | /pacote-download/pythonProject/exercicios_python_guanabara/ex068.py | 1,545 | 4.21875 | 4 | """
Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador PERDER, mostrando
o total de vitórias consecutivas que ele conquistou no final do jogo
"""
from random import randint
print('*'*20)
print('Jogo do par ou ímpar')
print('*'*20)
vitoria = 0
while True:
# Computador e Jogador escolhem um número
computador = randint(1, 11)
numero = int(input('Digite um número: '))
# Jogador escolhe se quer PAR ou IMPAR
jogador = 'nada'
while jogador not in 'PI':
jogador = str(input('Qual sua escolha: [P] PAR ou [I] ÍMPAR')).strip().upper()[0]
# É feita a verificação se o resultado é PAR ou IMPAR
calculo = (computador + numero) % 2
if calculo == 0:
resultado = 'P'
else:
resultado = 'I'
# Definindo o vencedor
if jogador == resultado:
if resultado == 'P':
resultado = 'PAR'
else:
resultado = 'IMPAR'
vitoria += 1
print('-=-'*20)
print(f'Você jogou {numero} e o computador jogou {computador}... Deu {resultado}')
print('Você ganhou! Vamos jogar NOVAMENTE...')
print('-=-' * 20)
else:
if resultado == 'P':
resultado = 'PAR'
else:
resultado = 'IMPAR'
print('-=-' * 20)
print(f'Você jogou {numero} e o computador jogou {computador}... Deu {resultado}')
print(f'Você PERDEU! Você venceu {vitoria} vez(es).')
print('-=-' * 20)
break
print('FIM DE JOGO')
| false |
afd4a657a274651e77a674001aae5fe5b448dc72 | oliveirajonathas/python_estudos | /pacote-download/pythonProject/exercicios_python_guanabara/ex076.py | 948 | 4.25 | 4 | """
Crie um programa que tenha uma tupla única com os nomes de produtos e seus respectivos preços, na sequência.
No final, mostre uma listagem de preços, organizando os dados de forma tabular.
"""
print(60*'-')
print('{:^60}'.format('MERCADINHO J&R'))
print(60*'-')
produtos = ('Manteiga', 2.50, 'Pasta de Dente', 3.00, 'Filé Mignon Kg', 40.00, 'Cebola Kg', 2, 'Alho Poró', 12,
'Aquarius Fresh', 3.5, 'Sandália Havaiana', 38, 'Filtro São João', 120)
produto = produtos[::2]
preco = produtos[1::2]
for i in range(0, len(produto)):
print(f'{produto[i]:-<50}R${preco[i]:7.2f}')
print(60*'-')
'''
Solução do professor, considerando a lógica de que os produtos estão em index par e os preços em index ímpar
print(60*'-')
print('{:^60}'.format('MERCADINHO J&R'))
print(60*'-')
for pos in range(0, len(produtos)):
if pos % 2 == 0:
print(f'{produtos[pos]:.<30}', end='')
else:
print(f'R${produtos[pos]:>7.2f}')
print(60*'-')
''' | false |
5b266103eec47df939bfc388de3d8470f78b26bf | oliveirajonathas/python_estudos | /pacote-download/pythonProject/exercicios_python_guanabara/ex105.py | 1,125 | 4.125 | 4 | """
Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar um dicionário com
as seguintes informações:
- Quantidade de notas
- A maior nota
- A menor nota
- A média
- A situação (opcional)
Adicione também as docstrings da função
"""
def notas(*notas, sit=False):
"""
Função para analisar as notas e situações de vários alunos.
:param notas: uma ou mais notas dos alunos (aceita várias)
:param sit: valor opcional, indicando se deve ou não adicionar a situação
:return: dicionário com várias informações sobre a situação da turma
"""
total = len(notas)
maior = max(notas)
menor = min(notas)
media = sum(notas)/total
balanco = {
'total': total,
'maior': maior,
'menor': menor,
'media': media,
}
if sit:
if media < 7:
balanco['situacao'] = 'RUIM'
elif 7 <= media <= 9:
balanco['situacao'] = 'BOA'
elif media > 9:
balanco['situacao'] = 'EXCELENTE'
return balanco
print(notas(2.5, 2, 4, 5, 3, sit=True))
| false |
e6eec83a6b8c5cc929fc6d02d274ea88d2ff5553 | whoissahil/python_tutorials | /advancedListProject.py | 948 | 4.40625 | 4 | # We're back at it again with the shoes list. I have provided you with the shoes list from the last exercise.
# In this exercise, I want you to make a function called addtofront, which will take in two parameters, a list and a value to add to the beginning of that list.
# Once you have made your function, add this line of code to your exercise:
# addtofront(shoes, "White Vans")
# shoes = ["Spizikes", "Air Force 1", "Curry 2", "Melo 5"]
def addtofront(_xList, _xValue):
_xList.insert(0, _xValue)
return(_xList)
shoes = ["Spizikes", "Air Force 1", "Curry 2", "Melo 5"]
while True:
try:
_inp = input("Please enter what you want to add: ")
if "." in _inp:
float(_inp)
print ("Please enter a string value")
else:
int(_inp)
print ("Please enter a string value")
except Exception:
print("New list is: ", addtofront(shoes, _inp))
break
| true |
29be997f377f217335d050d19795fe8c889b4dde | srikanth8951/AssignmentWeek1 | /ReverseList.py | 367 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 26 15:36:21 2020
@author: hvsri
"""
def reverselist(list1):
list2 = []
print("After Reversing list")
for i in range(len(list1)-1, -1,-1):
list2.append(list1[i])
print(list2)
list1 = [10, 20, 30, 40, 50]
print("List Before reversing", list1)
reverselist(list1)
| false |
5824b0576b6bd3977296ab653a51cdc1f483c839 | Wall-Lai/COMP9021 | /final sample/10_27_gai_gai_not_one_line/sample_3.py | 2,908 | 4.125 | 4 | '''
Given a word w, a good subsequence of w is defined as a word w' such that
- all letters in w' are different;
- w' is obtained from w by deleting some letters in w.
Returns the list of all good subsequences, without duplicates, in lexicographic order
(recall that the sorted() function sorts strings in lexicographic order).
The number of good sequences grows exponentially in the number of distinct letters in w,
so the function will be tested only for cases where the latter is not too large.
'''
def get_combo(string, current):
if string == '':
return [current]
if string[0] in current:
return get_combo(string[1:], current)
return get_combo(string[1:], current + string[0]) + get_combo(string[1:], current)
# a = list(set(get_combo('aba','')))
# a.sort()
# print(a)
# def get_combination(string, current):
# if len(string) == 0:
# return [current]
# if string[0] in current:
# return get_combination(string[1:], current)
# return get_combination(string[1:], current + string[0]) + get_combination(string[1:] ,current)
# # a = list(set(get_combination('abcabcab','')))
# # a.sort()
# # print(a)
# # if len(string) == 0:
# # return [current]
# # if string[0] in current:
# # return get_combination(string[1:], current)
# # return get_combination(string[1:] , current + string[0]) + get_combination(string[1:], current)
# def good_subsequences(word):
# '''
# >>> good_subsequences('')
# ['']
# >>> good_subsequences('aaa')
# ['', 'a']
# >>> good_subsequences('aaabbb')
# ['', 'a', 'ab', 'b']
# >>> good_subsequences('aaabbc')
# ['', 'a', 'ab', 'abc', 'ac', 'b', 'bc', 'c']
# >>> good_subsequences('aaabbaaa')
# ['', 'a', 'ab', 'b', 'ba']
# >>> good_subsequences('abbbcaaabccc')
# ['', 'a', 'ab', 'abc', 'ac', 'acb', 'b', 'ba', 'bac',\
# 'bc', 'bca', 'c', 'ca', 'cab', 'cb']
# >>> good_subsequences('abbbcaaabcccaaa')
# ['', 'a', 'ab', 'abc', 'ac', 'acb', 'b', 'ba', 'bac',\
# 'bc', 'bca', 'c', 'ca', 'cab', 'cb', 'cba']
# >>> good_subsequences('abbbcaaabcccaaabbbbbccab')
# ['', 'a', 'ab', 'abc', 'ac', 'acb', 'b', 'ba', 'bac',\
# 'bc', 'bca', 'c', 'ca', 'cab', 'cb', 'cba']
# '''
# # Insert your code here
string = get_string(word)
result = list(set(get_combo(string,'')))
result.sort()
print(result)
# Insert your code here
def get_string(word):
if word == '':
return word
string = word[0]
for i in word[1:]:
if i != string[-1]:
string +=i
return string
def get_combo(string,current):
if string == '':
return [current]
if string[0] in current:
return get_combo(string[1:],current)
return get_combo(string[1:],current) + get_combo(string[1:],current+string[0])
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
1f6b22d7f7903e1c207096966e2bdfcd1a1ba55d | Timothy-Myers/Automate-The-Boring-Stuff-Projects | /Projects/collatz.py | 919 | 4.5625 | 5 | #this program shows how the Collatz sequence works by having a user enter a number and using the sequence to get the number down to 1
#definition where the number is analyzed
def collatz(number):
#continues until number is 1
while number != 1:
#examines if number is even
if number % 2 == 0:
number = number //2
#examines if number is odd
elif number % 2 == 1:
number = (number * 3) + 1
print (number)
#asks user to enter number
print ('Please enter a number')
while True:
number = input()
try:
#if a valid number is entered it's passed into the defnition
number = int(number)
collatz(number)
except ValueError:
#if an invalid integer is entered a message is shown until a valid integer is entered
print ('Please enter a valid number')
continue
| true |
189da249379adfb2f49a05d8dc55df795958ef4e | takuhartley/Python_Practice | /Dictionaries/dictionaries.py | 717 | 4.15625 | 4 | cars = {
"brand": "Tesla",
"model": "Model X",
"year": 2019
}
people = {
"name": "Robert",
"age": 22,
"gender": "Male"
}
print(cars)
x = cars["model"]
print(x)
x = cars.get("model")
print(x)
people["age"] = 1995
print(people)
for x in people:
print(x)
for x in people:
print(people[x])
for x in people.values():
print(x)
for x, y in people.items():
print(x, y)
if "model" in cars:
print("Yes, 'model' is one of the keys in the people dictionary")
print(len(people))
people["name"] = "Alex"
print(people)
cars.pop("model")
print(cars)
cars.popitem()
print(cars)
x = cars.setdefault("model", "Bronco")
print(x)
cars.update({"color": "White"})
print(cars)
x = cars.values()
print(x) | true |
8c68f853d4619feb42df22d15058ae25a383fde0 | vitorAmorims/python | /lista_remover.py | 734 | 4.34375 | 4 | # Python - Remover itens da lista
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
# Remover Índice Especificado
# O pop()método remove o índice especificado.
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
# Se você não especificar o índice, o pop()método remove o último item.
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
# A del palavra-chave também remove o índice especificado:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
# Limpe a lista
# O clear()método esvazia a lista.
# A lista ainda permanece, mas não tem conteúdo
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
| false |
8a1c165897fcb5222f6513d69810a7e0e3fcbb87 | TaynaValle/CursoEmVideo | /ex005.py | 239 | 4.125 | 4 | ''' Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e seu antecessor '''
n = int(input('Digite um número:'))
print('Analisando o valor {}, seu sucessor é {} e o seu antecessor é {}'.format(n, n+1, n-1)) | false |
a5381669b79f9d6dab81037a9a02070097328348 | NickCampbell91/CSE212FinalProject | /Final/Python/stack_2.py | 1,152 | 4.21875 | 4 | """
Python3 code to delete middle of a stack without using additional data structure.
Write the deleteMid function where st is the call to the Stack class,
n is the size of the stack, and curr is the current item number.
"""
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def deleteMid(st, n, curr) :
pass
# Driver function to test above functions
st = Stack()
# push elements into the stack
st.push('1')
st.push('2')
st.push('3')
st.push('4')
st.push('5')
st.push('6')
st.push('7')
deleteMid(st, st.size(), 0)
# Printing stack after deletion
# of middle.
while (st.isEmpty() == False) :
p = st.peek()
st.pop()
print (str(p) + " ", end="")
#Expected output is: 7 6 5 4 3 2 1
# This code is contributed by
# Manish Shaw (manishshaw1) | true |
fcd000e9f9879c7ef9455eb7c7d94db2f343c398 | terranigmark/code-wars-python | /6th-kyu/replace_with_alphabet_position.py | 643 | 4.40625 | 4 | """
Welcome.
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
"""
import string
def alphabet_position(text):
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
new_text = ""
for char in text:
if char.lower() in alphabet:
new_text += f"{alphabet.index(char.lower()) + 1} "
return new_text[:-1] | true |
3aaa7165b3aa1f34332771efee0612b25c2f494d | fwchj/cursoABMPythonPublic | /EjemplosCodigo/03_Input.py | 310 | 4.15625 | 4 | # Example on how to read input from the console (e.g. ask the user for an input)
print("Favor de ingresar un primer número")
a = float(input()) #usamos float() para convertir todo a float
print("Gracias, favor de ingresar un segundo número")
b = float(input())
print("La suma de %s y %s es %s" % (a,b,a+b)) | false |
48d0be95e3516bb22190dc11fcf34233a624da02 | fwchj/cursoABMPythonPublic | /EjemplosClase/list.py | 754 | 4.125 | 4 | # Ejemplos de list
mi_lista = [1,2,3,4]
print(mi_lista)
print(type(mi_lista))
# Imprimir un elemento en particular (tercero)
print(mi_lista[2])
print(type(mi_lista[2]))
# Agregar un 2.5 entre el 2 y el 3
mi_lista.insert(2,2.5)
print(mi_lista)
print(mi_lista[2])
print("El tamanio es: %s" % len(mi_lista))
# Eliminamos todos los elementos
mi_lista.clear()
print(mi_lista)
print("Ilustracion de pointers-------")
a = [1,3,5,7,9]
b = a
c = a.copy()
a[4]=-4
print(a)
print(b)
print(c)
m = [[1,2],[3,[4,"Hola"]]]
print(m)
print(m[1][1][1])
print("______________________________")
v = [2,4,5,3,6,7,9]
suma = 0
for u in v:
suma +=u
print(u,suma)
print("la suma es ",suma, "y el promedio es", suma/len(v))
| false |
56da0d684688b9093e915e5559b1c431981b921c | fwchj/cursoABMPythonPublic | /EjemplosCodigo/04_OperacionesMatematicas.py | 1,413 | 4.28125 | 4 | # Ejemplos de operaciones matemáticas básicas y avanzadas
# 1) Operaciones matemáticas básicas
# 2) Operaciones de asignacion compuesta
# 3) Operaciones matematicas mas avanzadas
# 1) Operaciones matemáticas básicas
a = 5 # Definimos una variable 'a' y ponemos el valor de 5
b = 10 # idem
c = 8 # idem
d = a + b; # suma: d = 15
e = b - a; # resta: e = 5
f = a * c; # producción: f = 40
g = b / a; # división g = 2
h = c % a; # modulus h = 3
print(a,b,c,d,e,f,g,h,sep="\n")
# 2) Operaciones de asignacion compuesta
print("Compound assignment operators")
print("c=",c,", d=",d)
d **= c
print(d)
x = 2; # x=2
x *= 2; # x = x*2 = 4
x *= 2; # x=8
x *= 2; # x=16
x *= 2; # x=32
print("x =",x)
# 3) Operaciones matematicas mas avanzadas
import math # Aqui importamos el paquete 'math'
print("\n\nOperaciones matematicas mas avanzadas:")
print("abs(-6.5)",abs(-6.5),sep=" = ")
print("math.ceil(-6.5)",math.ceil(-6.5),sep=" = ")
print("math.cos(5)",math.cos(5),sep=" = ")
print("math.exp(4)",math.exp(4),sep=" = ")
print("math.floor(6.5)",math.floor(6.5),sep=" = ")
print("math.log(55)",math.log(55),sep=" = ")
print("math.log10(55)",math.log10(55),sep=" = ")
print("max(4,44,9)",max(4,44,9),sep=" = ")
print("min(4,44,9)",min(4,44,9),sep=" = ")
print("math.sqrt(5.5)",math.sqrt(5.5),sep=" = ")
print("math.pow(4,5)",math.pow(4,5),sep=" = ")
| false |
2d8292045564876ab2c3caa27664982daf0c2965 | fwchj/cursoABMPythonPublic | /EjemplosCodigo/20_Hierarchy2_herencia.py | 1,100 | 4.1875 | 4 | # OOP with inheritance
# Defining the class
class Individual:
# Constructor
def __init__(self,salary,name,age,tenure,female):
self.salary = salary
self.name = name
self.age = age
self.tenure = tenure
self.female = female
# Method printing some basic information
def describe(self):
print("%s is %s years old, works since %s years in the company and earns a salary of %s\n" % (self.name,self.age,self.tenure,self.salary))
# Defining the sub-class (inherited from Individual)
class Owner(Individual):
def __init__(self,salary,name,age,tenure,female,shares):
self.shares = shares
Individual.__init__(self,salary, name, age, tenure, female)
def describe(self):
print("%s is %s years old, owns the company since %s years and earns a salary of %s. She has %s shares of the company\n" % (self.name,self.age,self.tenure,self.salary,self.shares))
vanessa = Owner(8729,"Vanessa",42,8,True,100)
pedro = Individual(5650,"Pedro",35,5,False)
vanessa.describe()
pedro.describe()
| true |
5dbbf8d13447181eb29b7730c7881e3a28de0bbb | AntonyRajeev/Python-codes | /positivelist.py | 299 | 4.25 | 4 | #to find and print all positive numbers in a range
list=[]
n=int(input("enter the no of elements and the respective elements in the list "))
for i in range(0,n):
i=int(input())
list.append(i)
print("The positive integers are -")
for k in list:
if k>=0:
print(k)
| true |
9ace8eb7b294e485f61ef6184f33773428071cd2 | JaredVC672/PrimerRepo | /prog3.py | 1,232 | 4.15625 | 4 | print("Operaciones")
print("S. Suma")
print("R. Resta")
print("M. Multiplicacion")
print("D. Division")
print("A. Salir")
opcion = input("¿Qué opción elige?: ")
while opcion.upper()=="S":
num1 = float(input("Dame un numero: "))
num2 = float(input("Dame otro numero: "))
res = (num1 + num2)
print("El resultado de la suma es: ", res)
opcion=input("¿Desea continuar [S/N]?")
while opcion.upper()=="R":
num1 = float(input("Dame un numero: "))
num2 = float(input("Dame otro numero: "))
res = (num1 - num2)
print("El resultado de la resta es: ", res)
opcion=input("¿Desea continuar [S/N]?")
while opcion.upper()=="M":
num1 = float(input("Dame un numero: "))
num2 = float(input("Dame otro numero: "))
res = (num1 * num2)
print("El resultado de la multiplicacion es: ", res)
opcion=input("¿Desea continuar [S/N]?")
while opcion.upper()=="D":
num1 = float(input("Dame un numero: "))
num2 = float(input("Dame otro numero: "))
res = (num1 / num2)
print("El resultado de la division es: ", res)
opcion=input("¿Desea continuar [S/N]?")
while opcion.upper()=="A":
res = "Saliendo"
for res in range(1,1):
print("El programa está ", res) | false |
bd33a8347b98dbd6d6ef23b3404284fe4594168d | arrenfaroreuchiha/condicionales | /condicional2.py | 228 | 4.15625 | 4 | # -*- coding: utf-8 -*-
print "menor de dos numeros"
a = int(raw_input("numero 1:"))
b = int(raw_input("numero 1:"))
if a == b:
print "son iguales"
elif a < b:
print "el menor es: %s" % a
else:
print "el menor es: %s" % b
| false |
dabd439f38d4e1ffbff4e5f40c4b2f72240e932c | roytalyan/Python_self_learning | /Leetcode/String/Valid Palindrome.py | 746 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
"""
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
temp = []
for i in range(len(s)):
if s[i].isalnum():
temp.append(s[i].lower())
temp_rever = temp[::-1]
return temp == temp_rever
x = ''
s = Solution()
print s.isPalindrome(x) | true |
a85bb8418f65b352eb78a56db24be3a9b3f28212 | clarkkarenl/codingdojoonline | /python_track/filter-by-type.py | 1,876 | 4.25 | 4 | # Assignment: Filter by Type
# Karen Clark
# 2018-06-02
# Assignment: Filter by Type
# Write a program that, given some value, tests that value for its type. Here's what you should do for each type:
# Integer
# If the integer is greater than or equal to 100, print "That's a big number!" If the integer is less than 100, print "That's a small number"
# String
# If the string is greater than or equal to 50 characters print "Long sentence." If the string is shorter than 50 characters print "Short sentence."
# List
# If the length of the list is greater than or equal to 10 print "Big list!" If the list has fewer than 10 values print "Short list."
def filter_by_type(x):
if isinstance(x, int):
if x >= 100:
print "That's a big number!"
elif x < 100:
print "That's a small number"
elif isinstance(x, str):
if len(x) >= 50:
print "Long sentence"
elif len(x) < 50:
print "Short sentence"
elif isinstance(x, list):
if len(x) >= 10:
print "Big list!"
elif len(x) < 10:
print "Short list"
else:
print "Type cannot be determined. Please try again."
# example vars to test
sI = 45
mI = 100
bI = 455
eI = 0
spI = -23
sS = "Rubber baby buggy bumpers"
mS = "Experience is simply the name we give our mistakes"
bS = "Tell me and I forget. Teach me and I remember. Involve me and I learn."
eS = ""
aL = [1,7,4,21]
mL = [3,5,7,34,3,2,113,65,8,89]
lL = [4,34,22,68,9,13,3,5,7,9,2,12,45,923]
eL = []
spL = ['name','address','phone number','social security number']
# invocations
filter_by_type(sI)
filter_by_type(mI)
filter_by_type(bI)
filter_by_type(eI)
filter_by_type(spI)
filter_by_type(sS)
filter_by_type(mS)
filter_by_type(bS)
filter_by_type(eS)
filter_by_type(aL)
filter_by_type(mL)
filter_by_type(lL)
filter_by_type(eL)
filter_by_type(spL)
| true |
b2219014425c2fd302f4cbf370390c6fadf60301 | RapheaSiddiqui/AI-Assignment-1 | /q11(checking vowel).py | 328 | 4.25 | 4 | print ("\t\t\t***CHECKING FOR A VOWEL***")
letter = input ("Enter a letter: ")
if letter == 'a' or letter == 'A' or letter == 'e' or letter == 'E' or letter == 'i' or letter == 'I' or letter == 'o' or letter == 'O' or letter == 'u' or letter == 'U' :
print (letter, "is a vowel!")
else:
print (letter, "is a consonant!") | false |
a999e0ce0226ee0082a3228d9df34f98fac04d5c | RapheaSiddiqui/AI-Assignment-1 | /q2(checking sign of a given number).py | 233 | 4.1875 | 4 | print ("\t\t\t***CHECKING NATURE OF A NUMBER***")
num = float(input("Enter any number: "))
if (num == 0):
print("It's a Zero!")
if (num < 0):
print("It's a Negative number!")
if (num > 0):
print("It's a Positive number!") | true |
bf847e692c05e126f0a3fe34ce54dccf46e6b501 | RapheaSiddiqui/AI-Assignment-1 | /q20(converting time into seconds).py | 277 | 4.1875 | 4 | print ("\t\t\t***TIME IN SECONDS***")
hrs = float (input("Enter hours: "))
mins = float (input("Enter minutes: "))
sec1 = hrs * 3600
sec2 = mins * 60
sec = sec1 + sec2
print (hrs,"hours =",sec1,"seconds")
print (mins,"minutes =",sec2,"seconds")
print ("Total =",sec,"seconds!") | false |
f019103d9d581f8f77b246cb553d964410d5300c | tnmas/python-exercises | /unit-6-assignment.py | 839 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# first we need to define the function and ask for to arguments
def compare(a,b):
#case 1 when the first number is greater than the second number
if a > b :
return 1
# case 0 when the twon numbers are equals
elif a == b:
return 0
# case -1 when the the second number is greater than the first one
else :
return -1
# now testing the 3 cases by static values
print (compare(5,2))
print (compare(2,5))
print (compare(3,3))
# prompting and storing the first number
user_input_A = input("Please enter the first number to compare\n")
#prompting and storing the second number
user_input_B = input("Please enter the first number to compare\n")
# compare and print the return value
print(compare(user_input_A,user_input_B))
| true |
98cdd8dadc1c159f49ee1a880d3326640e1a25e2 | Success2014/Leetcode | /stringtoInteger.py | 2,225 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 02 09:46:34 2015
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge,
please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given
input specs). You are responsible to gather all the input requirements up front.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until
the first non-whitespace character is found. Then, starting from this character,
takes an optional initial plus or minus sign followed by as many numerical
digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral
number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid
integral number, or if no such sequence exists because either str is empty or
it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values,
INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
Caveats:
1. white space
2. sign
3. overflow
@author: Neo
"""
def myAtoi(string):
if string == "":
return 0
INT_MAX = 2147483647
INT_MIN = -2147483648
n = len(string)
i = 0
while string[i].isspace() and i < n:
i += 1
sign = 1
if i < n and string[i] == "+":
i += 1
elif i < n and string[i] == "-":
sign = -1
i += 1
result = 0
while i < n and string[i].isdigit():
digit = int(string[i])
if result > INT_MAX / 10 or (result == INT_MAX / 10 and digit>=8):
if sign == 1:
return INT_MAX
else:
return INT_MIN
else:
result = result * 10 + digit
i += 1
return sign*result
a = " +-123"
print myAtoi(a) | true |
d357165d011143acf66bcdc431c0e0f144ac2230 | Success2014/Leetcode | /reverseLinkedListII.py | 2,256 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 09 12:08:25 2015
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Tags Linked List
Similar Problems (E) Reverse Linked List
idea:
题目主要考察链表的“就地逆置”操作(不改变链表的值,只操作指针)。
链表的就地逆置代码片段如下:
def reverse(head):
p = head
start = None
while p
next = p.next
p.next = start
start = p
p = next
return start
在上述代码的基础上,先用两个指针,一个走到第m个节点,一个走到第m-1个节点。
将原链表经过逆置部分及其前后的链表片段拼接即可。
使用“哑节点”(dummy node),可以使代码简化。
@author: Neo
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} m
# @param {integer} n
# @return {ListNode}
def reverseBetween(self, head, m, n):
"""最重要的三个指针:prev, start,end"""
if m == n:
return head
dummy = ListNode(0)
prev = dummy
node = head
for i in xrange(m-1):
prev.next = node
prev = prev.next
node = node.next
start = node#开始反转的位置,反转后在末尾
tmp = None
for j in xrange(m, n+1):
nxt = node.next
node.next = tmp
tmp = node
node = nxt
end = tmp#结束反转的位置,反转后在开头
prev.next = end
start.next = nxt
return dummy.next
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
sol = Solution()
print sol.reverseBetween(node1,2,4).val
| false |
ef4941567063ba507df1933c92f2ada872766ceb | Success2014/Leetcode | /spiralMatrix.py | 1,863 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 02 13:32:07 2015
Given a matrix of m x n elements (m rows, n columns), return all
elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
@author: Neo
"""
class Solution:
# @param {integer[][]} matrix
# @return {integer[]}
def spiralOrder(self, matrix):
"""沿着矩阵向右n步,向下m-1步,向左n-1步,向上m-2步...
直到m或者n为0停止"""
res = []
m = len(matrix) # rows of matrix
if m == 0:
return res
n = len(matrix[0]) # columns of matrix
row = 0 # current row index
column = -1 # current column index
while True:
for i in xrange(n): # walk right
column += 1
res.append(matrix[row][column])
m = m - 1
if m == 0:
return res
for j in xrange(m): # walk down
row += 1
res.append(matrix[row][column])
n = n - 1
if n == 0:
return res
for i in xrange(n): # walk left
column -= 1
res.append(matrix[row][column])
m = m - 1
if m == 0:
return res
for j in xrange(m): # walk up
row -= 1
res.append(matrix[row][column])
n = n - 1
if n == 0:
return res
sol = Solution()
matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
matrix2 = [[3],[2]]
matrix3 = []
print sol.spiralOrder(matrix3) | true |
e2851deac5f5546d0c421f4edfa8b1251820531c | rahulsrivastava30/python | /Calculator.py | 615 | 4.125 | 4 | def calculator(first_num,second_num,operation):
if(operation=='add'):
return first_num+second_num
elif(operation=='subtract'):
return first_num-second_num
else:
return "error"
first=(int)(input("Enter first num: "))
second=(int)(input("Enter second num: "))
symbol=input("Enter the operation-add or subtract: ")
answer=calculator(first,second,symbol)
if(answer=="error"):
print("Please check the operation entered, as there seems to be invalid input, the symbol you entered is "+symbol+" ,it should be add or subtract")
else:
print("Answer is "+str(answer)) | true |
d18ce7428e4636d54f94e94b3384374a1c8f8d74 | anigautama/PythonProgramming | /DataStructures/Stack/infix2postfix.py | 692 | 4.125 | 4 | #anil
def prior(i):
if i=='*' or i=='/' or i=='%':
return 1
elif i=='+' or i=='-':
return 2
elif i=='(':
return 3
from stacks import Stack
exp = input("Enter an infix expression: ") + ')'
op = Stack()
postfix = []
op.push('(')
for i in exp:
if i.isalpha():
postfix.append(i)
elif i=='(':
op.push(i)
elif i=='*' or i=='/' or i=='%' or i=='+' or i=='-':
if prior(op.peek()) < prior(i):
postfix.append(op.pop())
op.push(i)
elif i==')':
while(op.peek() != '('):
postfix.append(op.pop())
temp = op.pop()
print("The postfix expression is: {}".format("".join(postfix)))
| false |
ea2b8dd0a42bbbc763c14b8510031d2eb5df1530 | iri02000/rau-webappprogramming1 | /seminar5/intro_612.py | 404 | 4.1875 | 4 | n = input("Please enter a number: ")
print(type(n), n)
n = int(n)
print(type(n), n)
n = float(n)
print(type(n), n)
s = "This is a string"
parts = s.split(" ")
print(parts)
parts = s.split("is")
print(parts)
a = 13 % 2 # find out modul
print(a)
# line comment
# other line comment
"""
This is a block of comments.
I usually use this when I have a longer text to explain
what the code does.
"""
| true |
9daed156e8c67658b9d83de8c43676b705d9c054 | lzdyd/Python | /Lab1/7.py | 1,072 | 4.28125 | 4 | # Правильная дата (7)
# Написать функцию date, принимающую 3 аргумента — день, месяц и год. Вернуть True,
# если такая дата есть в нашем календаре, и False иначе.
def date(d, m, y):
if(d <= 0 or d >= 32 or m <= 0 or m >= 13 or y <= 0):
return False
if (is_year_leap(y) and m == 2):
if (d <= 29):
return True
else:
return False
if(m == 2):
if(d <= 28):
return True
else:
return False
if(m % 2 == 0):
return evenMonths(d)
if (m % 2 != 0):
return oddMonths(d)
def is_year_leap(year):
if (not year % 4 and year % 100) or not year % 400:
return True
else:
return False
def evenMonths(d):
if(d > 0 and d <= 30):
return True
else:
return False
def oddMonths(d):
if(d > 0 and d <= 31):
return True
else:
return False
print(date(29, 2, 2012))
print(date(29, 2, 2013)) | false |
febf94ee44cc42fe235e73fd460d14436e8534ec | Haroldov/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 240 | 4.1875 | 4 | #!/usr/bin/python3
def uppercase(str):
for ind, char in enumerate(str):
ascii = ord(char)
if ascii >= 97 and ascii <= 122:
ascii -= 32
print("{}".format(chr(ascii)), end="")
else:
print()
| false |
6b8812204a60737efe13a509304f24f92a695919 | sprakaha/Python-CyberSecurity101 | /Modules/Ciphers/DataConversions/convtask1.py | 548 | 4.15625 | 4 | ## TODO: Get the user to input a number
## Return the number in binary, WITHOUT using the bin() function
## Only has to work for positive numbers
## Conver the number to binary, return as an int
# DO NOT CHANGE FUNCTION NAME OR RETURN TYPE
def toBinary(digit):
## Your Code Here
pass
## Print out the Digit in Binary
def main():
# Get User Input
num = input("Enter a number to convert to binary: ")
# Uncomment the following line to test your code
# print(toBinary(user_num))
if __name__ == "main":
main() | true |
9e5669f5534a0b67417f3fcfebad14ece9791935 | sprakaha/Python-CyberSecurity101 | /Modules/Ciphers/CipherReviews/cipherintro.py | 2,323 | 4.3125 | 4 | ## Strings Review
# strings are a list of characters
# "hello" -> 'h', 'e', 'l', 'l', 'o'
greeting = "Hello! How are you?"
# Get first character of a string
# print(greeting[0])
# Get last character of a string
# print(greeting[len(greeting) - 1])
# print(greeting[len(greeting)]) # this will give an error - IndexError
# Get the middle character of a string
mid = int((len(greeting) - 1) / 2)
# print(greeting[mid])
# print(len(greeting))
# Pig latin
# e.g. hello -> ellohay
test1 = "book"
output = ""
output2 = ""
# for loop way
for i in range(1, len(test1)):
output += test1[i]
output += test1[0] + "ay" # concatenation
# print(output)
# Pythonic - special to Python!
output2 += test1[1:] + test1[0] + "ay"
# print(output2)
## Password Validation Review
# Get user input
password = input("Enter the password you want: ")
uppercase_letters = 0
lowercase_letters = 0
# Loop over EACH character in the string
for i in range(len(password)):
current = password[i]
# Count numbers, special characters, if in the words, etc...
# UPPER CASE is between - 65 to 90
# LOWER CASE is between - 97 to 122
if ord(current) >= 65 and ord(current) <= 90: # check if the character is uppercase ord()
uppercase_letters += 1
if ord(current) >= 97 and ord(current) <= 122:
lowercase_letters += 1
print("upper case count: ",uppercase_letters)
print("lower case count: ", lowercase_letters)
# Conditional to check if our rules are broken
if uppercase_letters < 1:
print("Not enough Upper case letters!")
if lowercase_letters < 1:
print("Not enough lower case letters!")
## Ciphers
# an algorithm for performing encryption or decryption
# algorithm is a series of well-defined steps that can be followed as a procedure
# deterministic! - following the same procedure always gets the same results
# What are some ideas for encrypting data you have?
# numeric cipher (alpha -> ASCII)
message = "the battle will start at eight"
print("Encrypted")
for i in range(len(message)):
print(str(ord(message[i])) + " ", end = "")
print("")
print("Decrypted: ")
encrypted = "116 104 101 32 98 97 116 116 108 101 32 119 105 108 108 32 115 116 97 114 116 32 97 116 32 101 105 103 104 116"
words = encrypted.split(" ")
for w in words:
print(chr(int(w)), end="")
print("")
| true |
b453b5d57be9bbdc53d67e3cd6b9b72cc1a3ae5b | octopus84/w3spython | /lambdas.py | 1,111 | 4.5625 | 5 |
#Lambda
# A lambda function is a small anonymous function.
# A lambda function can take any number of arguments,
# but can only have one expression.
# Syntax
# lambda arguments : expression
x = lambda a : a + 10
print(x(4))
x = lambda a, b : a * b
print(x(5,5))
x = 5#int(input("Ingresa 3 números: "))
y = 3#int(input("Ingresa 2 números: "))
z = 4#int(input("Ingresa 1 números: "))
xxx = lambda a, b, c, : a * b + c
print(xxx(x,y,z))
# Why Use Lambda Functions?
# The power of lambda is better shown when you use them as
# an anonymous function inside another function.
# Say you have a function definition that takes one argument,
# and that argument will be multiplied with an unknown number:
# Use that function definition to make a function that always
# doubles the number you send in:
# Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(8)
print(mydoubler(int(input("Ingresa número: "))))
# Or, use the same function definition to make both functions,
# in the same program:
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11)) | true |
f020dd09c72558fcd5361e11b888357320142c5a | Lance117/Etudes | /leetcode/greedy/435_non_overlapping_intervals.py | 775 | 4.1875 | 4 | """
Given a collection of intervals, find the minimum number of intervals you need to remove to
make the rest of the intervals non-overlapping.
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Greedy algorithm:
1. Select interval with the earliest finishing time
2. Count following intervals that overlap with that interval
3. Once you encounter an interval that doesn't overlap, select the interval with the next earliest
finishing time.
"""
def erase_overlap_intervals(intervals):
res, visited = 0, float('-inf')
for interval in sorted(intervals, key=lambda x: x[1]):
if interval[0] >= visited:
visited = interval[1]
else:
res += 1
return res | true |
d4837b1ae7b35db2030dc2b7606a6d550b382483 | Lance117/Etudes | /leetcode/tree/144_binary_tree_preorder_traversal.py | 942 | 4.125 | 4 | """
Given a binary tree, return the preorder traversal of its nodes' values.
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def preorder_traversal_rec(root):
"""
Time complexity: O(n)
Space complexity: O(h) since size of call stack depends on tree's height
"""
def pre_helper(root, res):
if not root:
return
res.append(root.val)
pre_helper(root.left, res)
pre_helper(root.right, res)
res = []
pre_helper(root, res)
return res
def preorder_traversal_iter(root):
"""
Use stack to keep track of current node, and add children right then left
so that the left nodes enter the results list first after popped.
"""
res, s = [], [root]
while s:
curr = s.pop()
if curr:
res.append(curr.val)
s += [curr.right, curr.left]
return res | true |
e860fe06a18873f6a7581828e49082bad6eeacb4 | nawjanimri/uned_fund_programacion | /libro/125_perimetro.py | 1,859 | 4.1875 | 4 | # Programa: Perimetro
# Descripción:
# Programa para calcular el perimetro de un triángulo dado por sus tres vértices
from math import sqrt
(xA, yA, xB, yB, xC, yC) = (0, 0, 0, 0, 0, 0) # Coordenadas de los puntos
perimetro = 0 # Valor del perimetro
'''
Procedimiento para leer las coordenadas X e Y de un punto.
Para facilitar la identificación del punto, se tiene que
pasar la letra que lo identifica como argumento.'''
def LeerCoordenadas(punto):
print( "Punto {}".format(punto))
x = float(input("¿Coordenada X ? "))
y = float(input("¿Coordenada Y ? "))
return (x, y)
# Procedimiento para leer las coordenadas de los 3 vértices
def LeerVertices():
global xA, yA, xB, yB, xC, yC
xA, yA = LeerCoordenadas('A')
xB, yB = LeerCoordenadas('B')
xC, yC = LeerCoordenadas('C')
# Función para calcular la distancia que hay entre dos puntos (xl,y1) y (x2,y2)
def Distancia(x1, y1, x2, y2 ):
deltaX = x2 - x1
deltaY = y2 - y1
return sqrt( deltaX*deltaX + deltaY*deltaY)
'''Procedimiento para calcular el perimetro de un triágulo
NOTA : Se utilizan variables globales dado el excesivo
número de argumentos necesarios: Total 7 argumentos:
3 puntos x 2 coordenada: 6 argumentos por valor
Resultado en perimetro = 1 argumento por referencia'''
def CalcularPerimetro():
global perimetro
global xA, yA, xB, yB, xC, yC
ladoAB = Distancia(xA, yA, xB, yB)
ladoAC = Distancia(xA, yA, xC, yC)
ladoBC = Distancia(xB, yB, xC, yC)
perimetro = ladoAB + ladoAC + ladoBC
# Procedimiento para imprimir la variable global perimetro
def ImprimirPerimetro():
print("El perímetro es igual a {0:5.2f}".format(perimetro))
if __name__ == "__main__":
LeerVertices()
CalcularPerimetro()
ImprimirPerimetro() | false |
dda83eb38db783203e4b9d73b21f8de326f857b6 | Arthanadftz/Codeacademy_ex | /BankAccount.py | 1,703 | 4.15625 | 4 | class BankAccount(object):
balance = 0
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s\'s acoount has balance: $%.2f' %(self.name, self.balance)
def show_balance(self):
print('Balance: $%.2f' %(self.balance))
def deposit(self, amount):
if amount <= 0:
print('You have tried to deposit $%.2f. Deposit amount should be more then 0$.' %(amount))
return
else:
print('$%.2f has been added to your account!' %(amount))
self.balance += amount
self.show_balance()
def withdraw(self, amount):
if amount > self.balance:
print('You can\'t withdrow $%.2f! This is less then your balance: $%.2f' %(amount, self.balance))
return
else:
print('$%.2f has been removed from your account!' %(amount))
self.balance -= amount
self.show_balance()
def menu():
print('Hello stranger! Please enter your name to get access to your account info.')
name = raw_input('Enter your name: ')
my_account = BankAccount(name)
print(my_account)
start = True
while start:
action = raw_input('Type B to see your balance. D for deposit and W for withdraw. E to exit: ')
action = action.upper()
if action == 'B':
my_account.show_balance()
elif action == 'D':
amount = float(raw_input('How much do you want to deposit? Enter value: '))
my_account.deposit(amount)
elif action == 'W':
amount = float(raw_input('How much do you want to withdraw? Enter value: '))
my_account.withdraw(amount)
elif action == 'E':
print('Good bye %s.' %(name))
start = False
else:
print('You have chosen invalid value. Try again')
continue
menu() | true |
58080d48d94741434048c39bd74cbd3f7b2a9b23 | Arthanadftz/Codeacademy_ex | /sorting_algs.py | 1,190 | 4.15625 | 4 | #Array sorting algorythms
def insert_sort(A):
""" Sortring A list by inserting """
N = len(A)
for top in range(1, N):
k = top
while k > 0 and A[k-1] > A[k]:
A[k], A[k-1] = A[k-1], A[k]
k -= 1
def choise_sort(A):
""" Sortring A list by choise """
N = len(A)
for pos in range(N-1):
for k in range(pos+1, N):
if A[k] < A[pos]:
A[k], A[pos] = A[pos], A[k]
def bubble_sort(A):
""" Sortring A list by buble method """
N = len(A)
for bypass in range(1, N):
for k in range(0, N-bypass):
if A[k] > A[k+1]:
A[k], A[k+1] = A[k+1], A[k]
def test_sort(sort_argotyrhm):
print("Testing: ", sort_argotyrhm.__doc__)
print("Testcase #1: ", end='')
A = [4, 2, 5, 1, 3]
A_sorted = [1, 2, 3, 4, 5]
sort_argotyrhm(A)
print('OK' if A == A_sorted else 'Fail')
print("Testcase #2: ", end='')
A = list(range(10, 20)) + list(range(10))
A_sorted = list(range(20))
sort_argotyrhm(A)
print('OK' if A == A_sorted else 'Fail')
print("Testcase #1: ", end='')
A = [4, 2, 4, 2, 3]
A_sorted = [2, 2, 3, 4, 4]
sort_argotyrhm(A)
print('OK' if A == A_sorted else 'Fail')
if __name__ == '__main__':
test_sort(insert_sort)
test_sort(choise_sort)
test_sort(bubble_sort) | false |
8463ec73798d9ed61757ff21d49f7da15f6068c9 | Maimit/python3_basic | /exercise_2.py | 265 | 4.25 | 4 | num1, num2, num3 = input("Enter number1, number2, number3 by comma separated: ").split(",")
average = (int(num1) + int(num2) + int(num3)) / 3
print(f"Average of {num1},{num2},{num3} is: {average}")
name = input("Enter name: ")
print("Reverse name: ", name[-1::-1]) | false |
675c46c9b05e7fa7f74a9113a2b15f50d6bbdf21 | mastermind2001/Problem-Solving-Python- | /snail's_journey.py | 1,349 | 4.3125 | 4 | # Date : 23-06-2018
# A Snail's Journey
# Each day snail climbs up A meters on a tree with H meters in height.
# At night it goes down B meters.
# Program which takes 3 inputs: H, A, B, and calculates how many days it will take
# for the snail to get to the top of the tree.
# Input format :
# 15 # For H
# 1 # For A
# 0.5 # For B
#
# where H > A > B
import math
def snail_journey(height_of_tree, climbs_up, climbs_down):
"""
:param height_of_tree: Height of tree
:param climbs_up: snail climbs up A meters each day on a tree
:param climbs_down: snail climbs down B meters each night from a tree
:return: number of days it takes to climb tree
"""
days = (height_of_tree - climbs_down) / (climbs_up - climbs_down)
return 'Snail will take ' + str(math.ceil(days)) + ' days to climb the tree.'
# input positive integer values
H = input()
A = input()
B = input()
# error handling for wrong input
try:
if float(H) and float(A) and float(B):
H = float(H)
A = float(A)
B = float(B)
if H > A > B:
# calling function snail_journey
print(snail_journey(H, A, B))
else:
raise ValueError
except ValueError:
print("""Invalid input. You can enter only positive numbers.\n
Input format :\n
15 # For H
1 # For A
0.5 # For B
where H > A > B.""")
| true |
9003b3a8093b7aeb22e8bbb03fe54c294f50082f | mastermind2001/Problem-Solving-Python- | /tower_of_hanoi.py | 1,993 | 4.15625 | 4 | # Date : 7-05-2018
# Write a program to find solution for
# Tower of Hanoi Problem
"""
This code uses the recursion to find the solution for tower of Hanoi Problem.
"""
# Handle the user input
try:
# No. of disks (a positive integer
# value greater than zero)
disk = int(input(""))
# Error handling for negative values
# and zero.
if disk <= 0:
raise Exception()
# calculating minimum number of
# moves required to solve the
# problem with n disks.
minimum_moves = 2**disk - 1
# mathematical formula to calculate
# minimum number of moves with n
# disks is : (2^n - 1)
print("The minimum number of moves required to solve the problem with", disk, "disks are : ", minimum_moves, "\n")
print("------------------------------------", "\n")
# a list of positive integers
# counting number of moves.
count = []
# a function to add number of moves
# to the list.
def count_moves(counts):
while counts in count:
counts += 1
count.append(counts)
return str(counts)
# Printing the solution
def prnt_move(fr, to):
print(count_moves(1)+".", "Move disk from", fr, "to", to)
# Main function to calculate the
# solution
def disks(n, fr, to, spare):
"""
n: positive integer value
greater than zero.
"""
# base case
if n == 1:
return prnt_move(fr, to)
# recursive case
else:
disks(n-1, fr, spare, to)
disks(1, fr, to, spare)
disks(n-1, spare, to, fr)
pole_1 = "Pole 1"
pole_2 = "Pole 2"
pole_3 = "Pole 3"
# calling function
disks(disk, pole_1, pole_3, pole_2)
# Error handling when user gives a wrong
# input
except:
print("Invalid Input. You can enter only positive integers greater than zero.")
| true |
132764e4ca174a49d6f2d24fa51334f72bec0771 | running-on-sunshine/python-exercises | /Python Exercises-102/hello.py | 688 | 4.25 | 4 | # ======================================================================= #
# Exercises - Python 102 #
# ======================================================================= #
# Begin here:
# ======================================================================= #
# Hello, you! #
# ======================================================================= #
# Prompt the user for their name using the raw_input function.
# Upon receiving their name, you will say hello to them.
name = raw_input('What is your name? ')
message = 'Hello, ' + name + '!'
print message | true |
65a3483498b5b0cedc45e141c9f57a8c2e3db83a | gophers-latam/pytago | /examples/contains.py | 867 | 4.125 | 4 | def main():
# Iterables should compare the index of the element to -1
a = [1, 2, 3]
print(1 in a)
print(4 in a)
print(5 not in a)
# Strings should either use strings.Compare or use strings.Index with a comparison to -1
# While the former is more straight forward, I think the latter will be nicer for consistency
b = "hello world"
print("hello" in b)
print("Hello" not in b)
# Checking for membership in a dictionary means we need to check if the key is in it
# ... Eventually this should behave well with mixed types
c = {"hello": 1, "world": 2}
print("hello" in c)
print("Hello" not in c)
# Bytes
d = b'hello world'
print(b'hello' in d)
print(b'Hello' not in d)
# Sets
e = {1, 2, 3, "hello"}
print("hello" in e)
print(4 not in e)
if __name__ == '__main__':
main()
| true |
e989dd43715b32a55bcdea03163bb8f9ebf10826 | kpoznyakov/py_lvl2_hw | /lesson_01/hw_task_02.py | 532 | 4.1875 | 4 | # 2. Каждое из слов «class», «function», «method» записать в байтовом типе без преобразования
# в последовательность кодов (не используя методы encode и decode)
# и определить тип, содержимое и длину соответствующих переменных.
words = (b"class", b"function", b"method")
for word in words:
print(type(word), "длиной", len(word))
print(word)
print("*" * 10)
| false |
e85d2015fd1c22f8479bcb5e68487fa6b6e0696a | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/learn-python/src/control_flow/test_try.py | 2,117 | 4.53125 | 5 | """TRY statement
@see: https://www.w3schools.com/python/python_try_except.asp
"try" statement is used for exception handling.
When an error occurs, or exception as we call it, Python will normally stop and generate an error
message. These exceptions can be handled using the try statement.
The "try" block lets you test a block of code for errors.
The "except" block lets you handle the error.
The "else" block lets you execute the code if no errors were raised.
The "finally" block lets you execute code, regardless of the result of the try- and except blocks.
"""
def test_try():
"""TRY statement"""
# The try block will generate an error, because x is not defined:
exception_has_been_caught = False
try:
# pylint: disable=undefined-variable
print(not_existing_variable)
except NameError:
exception_has_been_caught = True
assert exception_has_been_caught
# You can define as many exception blocks as you want, e.g. if you want to execute a special
# block of code for a special kind of error:
exception_message = ""
try:
# pylint: disable=undefined-variable
print(not_existing_variable)
except NameError:
exception_message = "Variable is not defined"
assert exception_message == "Variable is not defined"
# You can use the else keyword to define a block of code to be executed
# if no errors were raised.
message = ""
# pylint: disable=broad-except
try:
message += "Success."
except NameError:
message += "Something went wrong."
else:
message += "Nothing went wrong."
assert message == "Success.Nothing went wrong."
# The finally block, if specified, will be executed regardless if the try block raises an
# error or not.
message = ""
try:
# pylint: undefined-variable
print(not_existing_variable) # noqa: F821
except NameError:
message += "Something went wrong."
finally:
message += 'The "try except" is finished.'
assert message == 'Something went wrong.The "try except" is finished.'
| true |
b28ca804bf8a7ddd093b5aac170a3f3a8b7596c9 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/02-pyth/python-ds-master/data_structures/graphs/check_if_graph_is_tree.py | 1,245 | 4.125 | 4 | """
A graph is a tree if -
1. It does not contain cycles
2. The graph is connected
Do DFS and see if every vertex can be visited from a source vertex and check for cycle
"""
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def is_tree(self, s):
visited = [False] * self.vertices
parent = [-1] * self.vertices
stack = []
visited[s] = True
no_of_visited = 1
stack.append(s)
while stack:
s = stack.pop()
for i in self.graph[s]:
if visited[i] == False:
parent[i] = s
visited[i] = True
stack.append(i)
no_of_visited += 1
elif parent[s] != i:
return "Not a tree"
if no_of_visited == self.vertices:
return "Graph is Tree"
else:
return "Not a tree"
g = Graph(7)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
g.add_edge(4, 5)
g.add_edge(1, 6)
print(g.is_tree(0))
| true |
4a2d64f6ae9f0e76d0278e807c0669dd8ce6ff5d | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/course-work/cs-guided-project-binary-search-trees/src/demonstration_2.py | 1,131 | 4.34375 | 4 | """
You are given a binary tree. You need to write a function that can determin if
it is a valid binary search tree.
The rules for a valid binary search tree are:
- The node's left subtree only contains nodes with values less than the node's
value.
- The node's right subtree only contains nodes with values greater than the
node's value.
- Both the left and right subtrees must also be valid binary search trees.
Example 1:
Input:
5
/ \
3 7
Output: True
Example 2:
Input:
10
/ \
2 8
/ \
6 12
Output: False
Explanation: The root node's value is 10 but its right child's value is 8.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_valid_BST(root):
# Your code here
if root is None:
return False
if root.left is None and root.right is None:
return False
if root.left.value < root.value:
is_valid_BST(root.left)
if root.right.value > root.value:
is_valid_BST(root.right)
return True
| true |
d640ce7c735a28d7a21522a4ba324a81ea7f400d | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/leetcode/Sort_an_Array.py | 1,079 | 4.25 | 4 | # Given an array of integers nums, sort the array in ascending order.
#
# Example 1:
#
# Input: nums = [5,2,3,1]
# Output: [1,2,3,5]
# Example 2:
#
# Input: nums = [5,1,1,2,0,0]
# Output: [0,0,1,1,2,5]
def sortArray(nums):
def helper(nums, start, end):
if start >= end:
return
pivot = start
left = start + 1
right = end
while left <= right:
if nums[left] > nums[pivot] and nums[right] < nums[pivot]:
nums[left], nums[right] = nums[right], nums[left]
if nums[left] < nums[pivot]:
left += 1
if nums[right] > nums[pivot]:
right -= 1
nums[pivot], nums[right] = nums[right], nums[pivot]
leftSubArrayisSmaller = right - 1 - start < end - (right + 1)
if leftSubArrayisSmaller:
helper(nums, start, right - 1)
helper(nums, right + 1, end)
else:
helper(nums, right + 1, end)
helper(nums, start, right - 1)
helper(nums, 0, len(nums) - 1)
return nums
| true |
6f3983b4248adcadbd968a9cd95fdc01bfb3789f | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/course-work/cs-guided-project-hash-tables-i/src/guided.py | 2,080 | 4.25 | 4 | # d = {
# 'banana': 'is a fruit',
# 'apple' : 'is also a fruit',
# 'pickle': 'vegetable',
# }
# a hash fucntion
# -must take a string
# -return a number
# -must always return the same output for the same input
# -should be fast
storage = [None] * 8 # has a size of 8/ static array
def hash_func(string, capacity):
# turn into a number representation
# turn str into a byte representation encode()
byte_str = (
string.encode()
) # an array of numbers the ascii representation of all the characters
print(byte_str)
print(type(byte_str))
num = 0
for byte in byte_str:
num += byte
return num % capacity
print(hash_func("apple", 8))
print(hash_func("banana", 8))
index = hash_func("apple", 8)
print(f"Apple hashed to {index}, store it there in storage")
# hash() is slower main purpose is for security less luckly to be decoded
class Dict:
def __init__(self, capacity):
self.storage = [None] * capacity
self.capacity = capacity
def hash_func(self, key):
byte_str = key.encode()
num = 0
for byte in byte_str:
num += byte
return num % self.capacity
def insert(self, key, value):
# hash the key
index = self.hash_func(key)
self.storage[index] = (key, value)
def __setitem__(self, key, value):
self.insert(key, value)
def get(self, key):
index = self.hash_func(key)
return self.storage[index][1] # 1 to access the second value of the tuple
def __getitem__(self, key):
return self.get(key)
def delete(self, key):
index = self.hash_func(key)
self.storage[index] = None
d = Dict(8)
# print(d.storage)
# d.insert("apple", "is a fruit")
# d['apple'] = 'is a fruit' TypeError: 'Dict' object does not support item assignment cause of the set item fucntion that uses the insert value
d["apple"] = "is a fruit"
d["banana"] = "also is a fruit"
d["grapes"] = "still a fruit"
d["mango"] = "is a fruit"
print(d.storage)
print(d["apple"])
print(d["banana"])
| true |
10e97a74c79d2a0710d60765fd974f9e01866c46 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/learn-python/src/control_flow/test_break.py | 798 | 4.21875 | 4 | """BREAK statement
@see: https://docs.python.org/3/tutorial/controlflow.html
The break statement, like in C, breaks out of the innermost enclosing "for" or "while" loop.
"""
def test_break_statement():
"""BREAK statement"""
# Let's terminate the loop in case if we've found the number we need in a range from 0 to 100.
number_to_be_found = 42
# This variable will record how many time we've entered the "for" loop.
number_of_iterations = 0
for number in range(100):
if number == number_to_be_found:
# Break here and don't continue the loop.
break
else:
number_of_iterations += 1
# We need to make sure that break statement has terminated the loop once it found the number.
assert number_of_iterations == 42
| true |
fbb262b3510cc4bce1df1e37005b59c96c6ad556 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/leetcode/Symmetric_Tree.py | 1,352 | 4.25 | 4 | # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
#
# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
#
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root):
if not root:
return True
def helper(node1, node2):
if not node1 and not node2:
return True
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
return helper(node1.left, node2.right) and helper(node1.right, node2.left)
return helper(root.left, root.right)
def isSymmetricIterative(self, root):
if not root:
return True
stack = []
stack.append([root.left, root.right])
while len(stack):
node1, node2 = stack.pop()
if not node1 and not node2:
continue
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
stack.append([node1.left, node2.right])
stack.append([node1.right, node2.left])
return True
| true |
7decaf49edca172e937bb29d316a9da7cb00348c | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/WEEKS/wk17/CodeSignal-Solutions/52_-_longestWord.py | 381 | 4.15625 | 4 | def longestWord(text):
longest = []
word = []
for char in text:
if ord("A") <= ord(char) <= ord("Z") or ord("a") <= ord(char) <= ord("z"):
word.append(char)
else:
if len(word) > len(longest):
longest = word
word = []
if len(word) > len(longest):
longest = word
return "".join(longest)
| false |
8c3570abe515e660d278df1a404825b3d8a6f9fd | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/TOM-Lambda/CS35_DataStructures_GP/problems/smallest.py | 2,205 | 4.25 | 4 | def smallest_missing(arr, left, right):
"""
run a binary search on our sorted list
because we know that the input should already be sorted
and this would give us a O(log n) time complexity
over doing a linear search that would yield a time complexity of O(n)
"""
# check if left is greater than right
if left > right:
# if so return left
return left
<<<<<<< HEAD
=======
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
# work out where we want to split the array (mid_point)
mid_point = left + (right - left) // 2
# check if the mid_point value is the same as teh mid_point index
if arr[mid_point] == mid_point:
# do a recursive call to the right hand side of the array
return smallest_missing(arr, mid_point + 1, right)
# otherwise
else:
# do a recursive call to the left hand side of the array
return smallest_missing(arr, left, mid_point - 1)
"""
# here is a working solution from Vince Williams
def smallest(arr):
for ind, num in enumerate(arr):
if num != ind:
return ind
return (arr[-1] + 1)
print(smallest([0, 1, 2, 6, 9, 11, 15]))
print(smallest([1, 2, 3, 4, 6, 9, 11, 15]))
print(smallest([0, 1, 2, 3, 4, 5, 6]))
"""
<<<<<<< HEAD
if __name__ == '__main__':
A = [0, 1, 2, 6, 9, 11, 15]
print(f"The smallest Missing Element is {smallest_missing(A, 0, len(A) - 1)}") # => 3
A = [1, 2, 3, 4, 6, 9, 11, 15]
print(f"The smallest Missing Element is {smallest_missing(A, 0, len(A) - 1)}") # => 0
A = [0, 1, 2, 3, 4, 5, 6]
print(f"The smallest Missing Element is {smallest_missing(A, 0, len(A) - 1)}") # => 7
=======
if __name__ == "__main__":
A = [0, 1, 2, 6, 9, 11, 15]
print(
f"The smallest Missing Element is {smallest_missing(A, 0, len(A) - 1)}"
) # => 3
A = [1, 2, 3, 4, 6, 9, 11, 15]
print(
f"The smallest Missing Element is {smallest_missing(A, 0, len(A) - 1)}"
) # => 0
A = [0, 1, 2, 3, 4, 5, 6]
print(
f"The smallest Missing Element is {smallest_missing(A, 0, len(A) - 1)}"
) # => 7
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
| true |
5e867b0d715586f32ea76ce11d893c5979852f68 | bgoonz/UsefulResourceRepo2.0 | /_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/sort/bogo_sort.py | 740 | 4.15625 | 4 | import random
def bogo_sort(arr, simulation=False):
"""Bogo Sort
Best Case Complexity: O(n)
Worst Case Complexity: O(∞)
Average Case Complexity: O(n(n-1)!)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
def is_sorted(arr):
#check the array is inorder
i = 0
arr_len = len(arr)
while i+1 < arr_len:
if arr[i] > arr[i+1]:
return False
i += 1
return True
while not is_sorted(arr):
random.shuffle(arr)
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
| true |
444a0336a3282012b8c9e2c627097b7f0d926c3f | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/TOM-Lambda/CSEU4_DataStructures_GP/interview_questions/problem3.py | 962 | 4.125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
def add(self, value):
self.next = Node(value)
def reverse(self):
cur = self
new = cur.next
<<<<<<< HEAD
cur.next = None # new tail?
=======
cur.next = None # new tail?
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
while new is not None:
prev = cur
cur = new
new = cur.next
cur.next = prev
<<<<<<< HEAD
return cur
=======
return cur
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
root = Node(3)
cur = root
cur.add(4)
cur = cur.next
cur.add(5)
cur = cur.next
cur.add(6)
cur = cur.next
cur = root
while cur:
print(cur.value)
cur = cur.next
print("-----")
cur = root.reverse()
while cur:
print(cur.value)
<<<<<<< HEAD
cur = cur.next
=======
cur = cur.next
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
| false |
9e8a845992e85e0c5c4b3b0d7b64232969850061 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/learn-python/src/functions/test_function_default_arguments.py | 925 | 4.71875 | 5 | """Default Argument Values
@see: https://docs.python.org/3/tutorial/controlflow.html#default-argument-values
The most useful form is to specify a default value for one or more arguments. This creates a
function that can be called with fewer arguments than it is defined to allow.
"""
def power_of(number, power=2):
""" Raises number to specific power.
You may notice that by default the function raises number to the power of two.
"""
return number ** power
def test_default_function_arguments():
"""Test default function arguments"""
# This function power_of can be called in several ways because it has default value for
# the second argument. First we may call it omitting the second argument at all.
assert power_of(3) == 9
# We may also want to override the second argument by using the following function calls.
assert power_of(3, 2) == 9
assert power_of(3, 3) == 27
| true |
f456218d7e16eec46de4f5f1259fe046207246a3 | bgoonz/UsefulResourceRepo2.0 | /_REPO/MICROSOFT/c9-python-getting-started/python-for-beginners/10_-_Complex_conditon_checks/code_challenge_solution.py | 1,347 | 4.34375 | 4 | # When you join a hockey team you get your name on the back of the jersey
# but the jersey may not be big enough to hold all the letters
# Ask the user for their first name
first_name = input("Please enter your first name: ")
# Ask the user for their last name
last_name = input("Please enter your last name: ")
# if first name is < 10 characters and last name is < 10 characters
# print first and last name on the jersey
# if first name >= 10 characters long and last name is < 10 characters
# print first initial of first name and the entire last name
# if first name < 10 characters long and last name is >= 10 characters
# print entire first name and first initial of last name
# if first name >= 10 characters long and last name is >= 10 characters
# print last name only
# Check length of first name
if len(first_name) >= 10:
long_first_name = True
else:
long_first_name = False
# Check length of last name
if len(last_name) >= 10:
long_last_name = True
else:
long_last_name = False
# Evaluate possible jersey print combinations for different lengths
if long_first_name and long_last_name:
print(last_name)
elif long_first_name:
print(first_name[0:1] + ". " + last_name)
elif long_last_name:
print(first_name + " " + last_name[0:1] + ".")
else:
print(first_name + " " + last_name)
| true |
bdfb941afe94f555350eef11bdd5549dde16bad1 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/web-dev-notes-resource-site/2-content/Python/pcc_2e-master/chapter_09/dog.py | 714 | 4.1875 | 4 | class Dog:
"""A simple attempt to model a dog."""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command."""
print(f"{self.name} rolled over!")
my_dog = Dog("Willie", 6)
your_dog = Dog("Lucy", 3)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
my_dog.sit()
print(f"\nYour dog's name is {your_dog.name}.")
print(f"Your dog is {your_dog.age} years old.")
your_dog.sit()
| true |
8fb3d4d97fc3decf83bf2953b66dd4311fa580ff | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/02-pyth/algorithms-master/algorithms/maths/pythagoras.py | 674 | 4.4375 | 4 | """
input two of the three side in right angled triangle and return the third. use "?" to indicate the unknown side.
"""
def pythagoras(opposite, adjacent, hypotenuse):
try:
if opposite == str("?"):
return "Opposite = " + str(((hypotenuse ** 2) - (adjacent ** 2)) ** 0.5)
elif adjacent == str("?"):
return "Adjacent = " + str(((hypotenuse ** 2) - (opposite ** 2)) ** 0.5)
elif hypotenuse == str("?"):
return "Hypotenuse = " + str(((opposite ** 2) + (adjacent ** 2)) ** 0.5)
else:
return "You already know the answer!"
except:
raise ValueError("invalid argument were given.")
| true |
02ed1b0abb9e3d1d05e95fdf17eec352182ba901 | bgoonz/UsefulResourceRepo2.0 | /_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/arrays/longest_non_repeat.py | 2,614 | 4.375 | 4 | """
Given a string, find the length of the longest substring
without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3.
Note that the answer must be a substring,
"pwke" is a subsequence and not a substring.
"""
def longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
"""
if string is None:
return 0
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
dict[string[i]] = i + 1
max_length = max(max_length, i - j + 1)
return max_length
def longest_non_repeat_v2(string):
"""
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
"""
if string is None:
return 0
start, max_len = 0, 0
used_char = {}
for index, char in enumerate(string):
if char in used_char and start <= used_char[char]:
start = used_char[char] + 1
else:
max_len = max(max_len, index - start + 1)
used_char[char] = index
return max_len
# get functions of above, returning the max_len and substring
def get_longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
dict[string[i]] = i + 1
if i - j + 1 > max_length:
max_length = i - j + 1
sub_string = string[j: i + 1]
return max_length, sub_string
def get_longest_non_repeat_v2(string):
"""
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
start, max_len = 0, 0
used_char = {}
for index, char in enumerate(string):
if char in used_char and start <= used_char[char]:
start = used_char[char] + 1
else:
if index - start + 1 > max_len:
max_len = index - start + 1
sub_string = string[start: index + 1]
used_char[char] = index
return max_len, sub_string | true |
fb292ced4358a81ef561965389cda19bcb7ff34d | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/PYTHON_PRAC/leetcode/Maximize_Distance_to_Closest_Person.py | 1,219 | 4.15625 | 4 | # In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.
#
# There is at least one empty seat, and at least one person sitting.
#
# Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
#
# Return that maximum distance to closest person.
#
# Example 1:
#
# Input: [1,0,0,0,1,0,1]
# Output: 2
# Explanation:
# If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
# If Alex sits in any other open seat, the closest person has distance 1.
# Thus, the maximum distance to the closest person is 2.
# Example 2:
#
# Input: [1,0,0,0]
# Output: 3
# Explanation:
# If Alex sits in the last seat, the closest person is 3 seats away.
# This is the maximum distance possible, so the answer is 3.
class Solution:
def maxDistToClosest(self, seats):
dist = 0
while dist < len(seats) and seats[dist] == 0:
dist += 1
zero = 0
for i in range(dist + 1, len(seats)):
if seats[i] == 0:
zero += 1
else:
dist = max(dist, (zero + 1) // 2)
zero = 0
return max(dist, zero)
| true |
2cb7a4362a8cf521043affd8e6918a425f4b320e | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Recursion/First Index/first_index_of_array.py | 601 | 4.125 | 4 | # To find first index of an element in an array.
def firstIndex(arr, si, x):
l = len(arr) # length of array.
if l == 0: # base case
return -1
if (
arr[si] == x
): # if element is found at start index of an array then return that index.
return si
return firstIndex(arr, si + 1, x) # recursive call.
arr = [] # initialised array.
n = int(input("Enter size of array : "))
for i in range(n): # input array.
ele = int(input())
arr.append(ele)
x = int(input("Enter element to be searched ")) # element to be searched
print(firstIndex(arr, 0, x))
| true |
f253ed9ff0e143d23edaf116b2f0a76878bdeccb | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/Data-Structures/1-Python/arrays/top_1.py | 947 | 4.28125 | 4 | """
This algorithm receives an array and returns most_frequent_value
Also, sometimes it is possible to have multiple 'most_frequent_value's,
so this function returns a list. This result can be used to find a
representative value in an array.
This algorithm gets an array, makes a dictionary of it,
finds the most frequent count, and makes the result list.
For example: top_1([1, 1, 2, 2, 3, 4]) will return [1, 2]
(TL:DR) Get mathematical Mode
Complexity: O(n)
"""
def top_1(arr):
values = {}
# reserve each value which first appears on keys
# reserve how many time each value appears by index number on values
result = []
f_val = 0
for i in arr:
if i in values:
values[i] += 1
else:
values[i] = 1
f_val = max(values.values())
for i in values.keys():
if values[i] == f_val:
result.append(i)
else:
continue
return result
| true |
8b8eb1e64a7760cc3eb480d2f2ec608fb8728951 | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/TOM-Lambda/CSEUFLEX_Data_Structures_GP/stack.py | 1,626 | 4.3125 | 4 | """
A stack is a data structure whose primary purpose is to store and
return elements in Last In First Out order.
1. Implement the Stack class using an array as the underlying storage structure.
Make sure the Stack tests pass.
2. Re-implement the Stack class, this time using the linked list implementation
as the underlying storage structure.
Make sure the Stack tests pass.
3. What is the difference between using an array vs. a linked list when
implementing a Stack?
"""
# class Stack:
# def __init__(self):
# self.size = 0
# self.storage = []
# def __len__(self):
# return self.size
# def push(self, value):
# self.size += 1
# self.storage.append(value)
# def pop(self):
# if self.size == 0:
# return None
# self.size -= 1
# return self.storage.pop()
from singly_linked_list import LinkedList
<<<<<<< HEAD
=======
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
class Stack:
def __init__(self):
self.size = 0
self.storage = LinkedList()
<<<<<<< HEAD
=======
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
def __len__(self):
return self.size
# other option return len(self.storage)
def push(self, value):
self.storage.add_to_tail(value)
self.size += 1
<<<<<<< HEAD
=======
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
def pop(self):
if self.size == 0:
return None
self.size -= 1
<<<<<<< HEAD
return self.storage.remove_tail()
=======
return self.storage.remove_tail()
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
| true |
53c4afdf08f7e0ec27d981d51a6db6c7b280da3d | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/web-dev-notes-resource-site/2-content/Data-Structures/1-Python/dfs/maze_search.py | 1,105 | 4.3125 | 4 | """
Find shortest path from top left column to the right lowest column using DFS.
only step on the columns whose value is 1
if there is no path, it returns -1
(The first column(top left column) is not included in the answer.)
Ex 1)
If maze is
[[1,0,1,1,1,1],
[1,0,1,0,1,0],
[1,0,1,0,1,1],
[1,1,1,0,1,1]],
the answer is: 14
Ex 2)
If maze is
[[1,0,0],
[0,1,1],
[0,1,1]],
the answer is: -1
"""
def find_path(maze):
cnt = dfs(maze, 0, 0, 0, -1)
return cnt
def dfs(maze, i, j, depth, cnt):
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
row = len(maze)
col = len(maze[0])
if i == row - 1 and j == col - 1:
if cnt == -1:
cnt = depth
else:
if cnt > depth:
cnt = depth
return cnt
maze[i][j] = 0
for k in range(len(directions)):
nx_i = i + directions[k][0]
nx_j = j + directions[k][1]
if nx_i >= 0 and nx_i < row and nx_j >= 0 and nx_j < col:
if maze[nx_i][nx_j] == 1:
cnt = dfs(maze, nx_i, nx_j, depth + 1, cnt)
maze[i][j] = 1
return cnt
| true |
f611a878a16540a8544d96b179da3dbe91d2edf7 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_Another-One/Project Euler/Problem 04/sol1.py | 872 | 4.1875 | 4 | """
Problem:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers which is less than N.
"""
from __future__ import print_function
limit = int(input("limit? "))
# fetchs the next number
for number in range(limit - 1, 10000, -1):
# converts number into string.
strNumber = str(number)
# checks whether 'strNumber' is a palindrome.
if strNumber == strNumber[::-1]:
divisor = 999
# if 'number' is a product of two 3-digit numbers
# then number is the answer otherwise fetch next number.
while divisor != 99:
if (number % divisor == 0) and (len(str(number / divisor)) == 3):
print(number)
exit(0)
divisor -= 1
| true |
43815ab10b7af65236aff86fec476d95b2231dc7 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/web-dev-notes-resource-site/2-content/ciriculumn/week-17/python/Introduction-Programming-Python/Solutions/Module7TaxesChallengeSolution.py | 1,675 | 4.3125 | 4 | # Declare and initialize your variables
country = ""
province = ""
orderTotal = 0
totalWithTax = 0
# I am declaring variables to hold the tax values used in the calculations
# That way if a tax rate changes, I only have to change it in one place instead
# of searching through my code to see where I had a specific numeric value and updating it
GST = 0.05
HST = 0.13
PST = 0.06
# Ask the user what country they are from
country = input("What country are you from? ")
# if they are from Canada ask which province...don't forget they may enter Canada as CANADA, Canada, canada, CAnada
# so convert the string to lowercase before you do the comparison
if country.lower() == "canada":
province = input("Which province are you from? ")
# ask for the order total
orderTotal = float(input("What is your order total? "))
# Now add the taxes
# first check if they are from canada
if country.lower() == "canada":
# if they are from canada, we have to change the calculation based on the province they specified
if province.lower() == "alberta":
orderTotal = orderTotal + orderTotal * GST
elif (
province.lower() == "ontario"
or province.lower() == "new brunswick"
or province.lower() == "nova scotia"
):
orderTotal = orderTotal + orderTotal * HST
else:
orderTotal = orderTotal + orderTotal * PST + orderTotal * GST
# if they are not from Canada there is no tax, so the amount they entered is the total with tax
# and no modification to orderTotal is required
# Now display the total with taxes to the user, don't forget to format the number
print("Your total including taxes comes to $%.2f " % orderTotal)
| true |
31f32bc2b4e184cccc98e3a1e08f707a7d3b4138 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/PYTHON_PRAC/python-mega-algo/bit_manipulation/count_number_of_one_bits.py | 755 | 4.1875 | 4 | def get_set_bits_count(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer
>>> get_set_bits_count(25)
3
>>> get_set_bits_count(37)
3
>>> get_set_bits_count(21)
3
>>> get_set_bits_count(58)
4
>>> get_set_bits_count(0)
0
>>> get_set_bits_count(256)
1
>>> get_set_bits_count(-1)
Traceback (most recent call last):
...
ValueError: the value of input must be positive
"""
if number < 0:
raise ValueError("the value of input must be positive")
result = 0
while number:
if number % 2 == 1:
result += 1
number = number >> 1
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
a3845d1c4997ab5729ac3d57d09b96bc3636a5be | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/Overflow/Beginners-Python-Examples-master/algorithms/analysis/count.py | 877 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Simple algorithm to count
# number of occurrences of (n) in (ar)
# Sudo: Algorithm
# each time (n) is found in (ar)
# (count) varible in incremented (by 1)
# I've put spaces to separate different
# stages of algorithms for easy understanding
# however isn't a good practise
def count(ar, n):
count = 0
for element in ar:
# More complex condition could be
# => (not element != n)
if element == n:
count += 1
return count
# Testing
# add your test cases in list below
test_cases = [([1, 1, 2, 3, 5, 8, 13, 21, 1], 1), ("Captain America", "a")]
for test_case in test_cases:
print("TestCase: {}, {}".format(test_case[0], test_case[1]))
print("Results: {}\n".format(count(test_case[0], test_case[1])))
# You can add condition to check weather output is correct
# or not
| true |
acdb65d6e812f3f98073ac68414d41fec6da9136 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/WEEKS/wk17/d2/code-signal/return-index-of-string-in-list.py | 894 | 4.375 | 4 | # Write a function that searches a list of names(unsorted) for the name "Bob" and returns the location in the list. If Bob is not in the array, return -1.
#
# Examples:
#
# csWhereIsBob(["Jimmy", "Layla", "Bob"]) ➞ 2
# csWhereIsBob(["Bob", "Layla", "Kaitlyn", "Patricia"]) ➞ 0
# csWhereIsBob(["Jimmy", "Layla", "James"]) ➞ - 1
# Notes:
#
# Assume all names start with a capital letter and are lowercase thereafter(i.e. don't worry about finding "BOB" or "bob").
# [execution time limit] 4 seconds(py3)
#
# [input] array.string names
#
# [output] integer
#
# [Python 3] Syntax Tips
#
# # Prints help message to the console
# # Returns a string
#
#
# def helloWorld(name):
# print("This prints to the console when you Run Tests")
# return "Hello, " + name
def csWhereIsBob(names):
bob = "Bob"
if bob in names:
return names.index("Bob")
else:
return -1
| true |
9016bf310d2a3796cf746f8dce4bdf3eca7ff56f | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Sorting/Quick Sort/quick_sort.py | 2,006 | 4.21875 | 4 | # Program to implement QuickSort Algorithm in Python
"""
This function takes last element as pivot, places the pivot element at
its correct position in sorted array, and places all smaller(smaller than
pivot) to left of pivot and all greater elements to right of pivot
"""
def partition(arr, low, high):
"""
The value of i is initialized to (low-1) since initially first element
is swapped by itself
Reason: no greater element has been encountered apart from itself
"""
pivotElement = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] < pivotElement:
i += 1
# swap elements arr[i] and arr[j]
arr[i], arr[j] = arr[j], arr[i]
# swap pivot element with element at index=(i + 1) since loop ended,
# to obtain LHS of pivot
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
"""
This is the calling function that implements QuickSort algorithm, where:
arr = input array given by user
low = starting index
high = ending index
"""
def quickSort(arr, low, high):
if low < high:
# pi is partitioning index, arr[p] is now at right place
pi = partition(arr, low, high)
# Separately sort elements before partition and after partition
quickSort(arr, low, pi - 1)
quickSort(arr, pi + 1, high)
# main function
if __name__ == "__main__":
print("Enter the number of elements: ")
n = int(input())
print("Enter the elements of the array: ")
arr = list(map(int, input().split()))
quickSort(arr, 0, n - 1)
# print the final sorted array in ASCending order
print("The sorted array is: ")
for i in range(n):
print(arr[i], end=" ")
print()
"""
Input :
Enter the number of elements: 5
Enter the elements of the array: 22 11 44 55 33
Output :
The sorted array is: 11 22 33 44 55
Time & Space Complexity
Best or average case Time Complexity: O(nlogn)
Worst case Time Complexity: O(n^2)
Space Complexity: O(logn)
"""
| true |
d4c4ae8d85acbc6ee1e558adf68f81ee46e5e50f | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/leetcode/Queue_Using_Stack.py | 1,397 | 4.4375 | 4 | # Implement the following operations of a queue using stacks.
#
# push(x) -- Push element x to the back of queue.
# pop() -- Removes the element from in front of queue.
# peek() -- Get the front element.
# empty() -- Return whether the queue is empty.
# Example:
#
# MyQueue queue = new MyQueue();
#
# queue.push(1);
# queue.push(2);
# queue.peek(); // returns 1
# queue.pop(); // returns 1
# queue.empty(); // returns false
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.s1 = []
self.s2 = []
def push(self, x):
"""
Push element x to the back of queue.
"""
self.s1.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
"""
if self.s2:
return self.s2.pop()
while self.s1:
self.s2.append(self.s1.pop())
return self.s2.pop()
def peek(self):
"""
Get the front element.
"""
if self.s2:
return self.s2[len(self.s2) - 1]
while self.s1:
self.s2.append(self.s1.pop())
return self.s2[len(self.s2) - 1]
def empty(self):
"""
Returns whether the queue is empty.
"""
if self.s2 == [] and self.s1 == []:
return True
return False
| true |
5bbce313a69a231f379074df30877d764b26835f | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/TOM-Lambda/CSEUFLX_Algorithms_GP/00_demo.py | 239 | 4.1875 | 4 | import math
radius = 3
area = math.pi * radius * radius
<<<<<<< HEAD
print(f'The area of the circle is {area:.3f} ft\u00b2')
=======
print(f"The area of the circle is {area:.3f} ft\u00b2")
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
| true |
f920a8d5c1a3bbcb5fb2de8de1f6fc16268a2966 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/course-work/cs-guided-project-python-i/src/demonstration_01.py | 348 | 4.21875 | 4 | """
Challenge #1:
Create a function that takes two numbers as arguments and return their sum.
Examples:
- addition(3, 2) ➞ 5
- addition(-3, -6) ➞ -9
- addition(7, 3) ➞ 10
"""
def addition(a, b):
# Your code here
print("i am inside the function")
return a + b
print("this lives outside the function")
print(addition(-3, -1))
| true |
737a88c7ed53a9bcc2ce17afb8abf4ab5a1c8ba4 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/_PyAlgo-Tree/Sorting/Shell Sort/shell_sort.py | 1,601 | 4.15625 | 4 | # Python program for implementation of Shell Sort
"""
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm.
Shell sort is the generalization of insertion sort which overcomes the drawbacks of insertion sort by comparing elements separated by a gap of several positions.
Shell sort divides the array in the form of N/2 , N/4 , …, 1 (where N is the length of array)
and then sorting is done. This breaking of sequence and sorting takes place until the entire array is sorted.
"""
def shellSort(arr):
# Start with a big gap, then reduce the gap
size = len(arr)
gap = size // 2
# Do a gapped insertion sort for this gap size.
while gap > 0:
for i in range(gap, size):
# add a[i] to the elements that have been gap sorted
# save a[i] in temp and make a hole at position i
temp = arr[i]
# shift earlier gap-sorted elements up until the correct
# location for a[i] is found
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
# put temp (the original a[i]) in its correct location
arr[j] = temp
gap //= 2
arr = []
size = int(input("Enter size: "))
print("Enter elements:")
for i in range(0, size):
item = int(input())
arr.append(item)
shellSort(arr)
print("\nSorted Array:")
for i in range(size):
print(arr[i])
"""
INPUT
Enter size: 5
Enter elements:
5
4
3
2
1
Sorted Array:
1
2
3
4
5
Time Complexity: O(n^2)
Space Complexity: O(1)
"""
| true |
5b8e3a233922c9dfe86b8d43004bdd9debfbbfb5 | bgoonz/UsefulResourceRepo2.0 | /_MY_ORGS/Web-Dev-Collaborative/blog-research/ciriculumn/week.16-/python-lecture/15a-input-validation1.py | 350 | 4.15625 | 4 | # Input Validation
# - prompt
# - handle empty string
# - make it a number
# - handle exceptions
# - require valid input
age = 1
while age:
age = input("What's your age? ")
if age:
try:
age = int(float(age))
print(f'Cool! You had {age} birthdays.')
except:
print('Please enter a number')
| true |
c378476b8691a23f63afab909e338f8f400c2f29 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/INTERVIEW-PREP-COMPLETE/Practice/QueueWithTwoStacks/model_solution.py | 1,123 | 4.15625 | 4 | class Queue:
def __init__(self):
# Stack to hold elements that get added
self.inStack = []
# Stack to hold elements that are getting removed
self.outStack = []
def enqueue(self, item):
self.inStack.append(item)
def dequeue(self):
# if the outStack is empty
# we need to populate it with inStack elements
if len(self.outStack) == 0:
# empty out the inStack into the outStack
while len(self.inStack) > 0:
self.outStack.append(self.inStack.pop())
return self.outStack.pop()
def peek(self):
# same logic as `dequeue`
if len(self.inStack) == 0:
return None
else:
while len(self.inStack) > 0:
self.outStack.append(self.inStack.pop())
return self.outStack[0]
# Some console.log tests
q = Queue()
print(q.peek()) # should print None
q.enqueue(10)
print(q.peek()) # should print 10
q.enqueue(9)
q.enqueue(8)
print(q.dequeue()) # should print 10
print(q.dequeue()) # should print 9
print(q.dequeue()) # should print 8
| false |
34ace4f7e6af7e263ba09ea7c1547a54b1dbd804 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/1-projects/lambda/LambdaSQL/LambdaSQL-master/LambdaSQL.py | 998 | 4.125 | 4 | import sqlite3 as sql
connection = sql.connect("rpg_db.sqlite3")
print(
*connection.execute(
"""
SELECT cc.name, ai.name
FROM charactercreator_character AS cc, armory_item AS ai,
charactercreator_character_inventory AS cci
WHERE cc.character_id = cci.character_id
AND ai.item_id = cci.item_id
LIMIT 10;
"""
),
sep="\n",
end="\n\n"
)
# Creates a database
conn = sql.connect("toy_db.sqlite3")
# Adds a cursor
curs = conn.cursor()
# Creates a Table - don't do this more than once!!!
query = """
CREATE TABLE toy (name varchar(30), size int);
"""
curs.execute(query)
# Creates 2 Columns inside the Table and populates the first row.
query = """
INSERT INTO toy (name, size)
VALUES ("Awesome", 27);
"""
curs.execute(query)
# Commits Changes and closes the cursor
curs.close()
conn.commit()
# Gets new cursor
curs = conn.cursor()
# Makes selection and prints the results
# Should be `("Awesome", 27)`
query = """
SELECT * FROM toy;
"""
print(*curs.execute(query), sep="\n")
| true |
04556c7505ff2a77185611cf43a9796df0fd2293 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/_PYTHON/Python-master/factorial.py | 643 | 4.28125 | 4 | import math
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
n = int(input("Input a number to compute the factiorial : "))
print(factorial(n))
"""
Method 2:
Here we are going to use in-built fuction for factorial which is provided by Python for
user conveniance.
Steps:
-For this you should import math module first
-and use factorial() method from math module
Note:
Appear error when pass a negative or fraction value in factorial() method, so plz refrain from this.
Let's code it:
"""
if n >= 0:
print(math.factorial(n))
else:
print("Value of n is inValid!")
| true |
f2d4fc82f7fda06b56265a8369998c0318b65c47 | bgoonz/UsefulResourceRepo2.0 | /_OVERFLOW/Resource-Store/01_Questions/_Python/enum.py | 507 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Enum function
# yields a tuple of element and it's index
def enum(ar):
for index in range(len(ar)):
yield ((index, ar[index]))
# Test
case_1 = [19, 17, 20, 23, 27, 15]
for tup in list(enum(case_1)):
print(tup)
# Enum function is a generator does not
# return any value, instead generates
# tuple as it encounters element of array
# Tuples can be appended to list
# and can be returned after iteration
# However,
# Generator is a good option
| true |
e1707172df8425f34b1ff548061e6459fb73ae08 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/web-dev-notes-resource-site/2-content/Python/intro_programming-master/notebooks/rocket.py | 991 | 4.25 | 4 | from math import sqrt
class Rocket:
# Rocket simulates a rocket ship for a game,
# or a physics simulation.
def __init__(self, x=0, y=0):
# Each rocket has an (x,y) position.
self.x = x
self.y = y
def move_rocket(self, x_increment=0, y_increment=1):
# Move the rocket according to the paremeters given.
# Default behavior is to move the rocket up one unit.
self.x += x_increment
self.y += y_increment
def get_distance(self, other_rocket):
# Calculates the distance from this rocket to another rocket,
# and returns that value.
distance = sqrt((self.x - other_rocket.x) ** 2 + (self.y - other_rocket.y) ** 2)
return distance
class Shuttle(Rocket):
# Shuttle simulates a space shuttle, which is really
# just a reusable rocket.
def __init__(self, x=0, y=0, flights_completed=0):
super().__init__(x, y)
self.flights_completed = flights_completed
| true |
e648a1d072498fa610f6de94960414ff7105d28e | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/Data-Structures/1-Python/strings/validate_coordinates.py | 1,689 | 4.28125 | 4 | """"
Create a function that will validate if given parameters are valid geographical coordinates.
Valid coordinates look like the following: "23.32353342, -32.543534534". The return value should be either true or false.
Latitude (which is first float) can be between 0 and 90, positive or negative. Longitude (which is second float) can be between 0 and 180, positive or negative.
Coordinates can only contain digits, or one of the following symbols (including space after comma) -, .
There should be no space between the minus "-" sign and the digit after it.
Here are some valid coordinates:
-23, 25
43.91343345, 143
4, -3
And some invalid ones:
23.234, - 23.4234
N23.43345, E32.6457
6.325624, 43.34345.345
0, 1,2
"""
# I'll be adding my attempt as well as my friend's solution (took us ~ 1 hour)
# my attempt
import re
def is_valid_coordinates_0(coordinates):
for char in coordinates:
if not (char.isdigit() or char in ["-", ".", ",", " "]):
return False
l = coordinates.split(", ")
if len(l) != 2:
return False
try:
latitude = float(l[0])
longitude = float(l[1])
except:
return False
return -90 <= latitude <= 90 and -180 <= longitude <= 180
# friends solutions
def is_valid_coordinates_1(coordinates):
try:
lat, lng = [abs(float(c)) for c in coordinates.split(",") if "e" not in c]
except ValueError:
return False
return lat <= 90 and lng <= 180
# using regular expression
def is_valid_coordinates_regular_expression(coordinates):
return bool(
re.match(
"-?(\d|[1-8]\d|90)\.?\d*, -?(\d|[1-9]\d|1[0-7]\d|180)\.?\d*$", coordinates
)
)
| true |
11e1edbecab930d3e1e4d95fe9fb83602849a167 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/course-work/cs-guided-project-python-i/src/demonstration_09.py | 736 | 4.5 | 4 | """
Challenge #9:
Write a function that creates a dictionary with each (key, value) pair being
the (lower case, upper case) versions of a letter, respectively.
Examples:
- mapping(["p", "s"]) ➞ { "p": "P", "s": "S" }
- mapping(["a", "b", "c"]) ➞ { "a": "A", "b": "B", "c": "C" }
- mapping(["a", "v", "y", "z"]) ➞ { "a": "A", "v": "V", "y": "Y", "z": "Z" }
Notes:
- All of the letters in the input list will always be lowercase.
"""
def mapping(letters):
# Your code here
new_dictionary = {}
for value in letters:
new_value = value.upper()
new_dictionary[value] = new_value
return new_dictionary
print(mapping(["p", "s"]))
print(mapping(["a", "b", "c"]))
print(mapping(["a", "v", "y", "z"]))
| true |
755287b03fd2fc73be13ad660015e28a119e87ca | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/Data-Structures/1-Python/maths/find_primitive_root_simple.py | 2,240 | 4.25 | 4 | import math
"""
For positive integer n and given integer a that satisfies gcd(a, n) = 1,
the order of a modulo n is the smallest positive integer k that satisfies
pow (a, k) % n = 1. In other words, (a^k) ≡ 1 (mod n).
Order of certain number may or may not be exist. If so, return -1.
"""
def find_order(a, n):
if (a == 1) & (n == 1):
return 1
""" Exception Handeling :
1 is the order of of 1 """
else:
if math.gcd(a, n) != 1:
print("a and n should be relative prime!")
return -1
else:
for i in range(1, n):
if pow(a, i) % n == 1:
return i
return -1
"""
Euler's totient function, also known as phi-function ϕ(n),
counts the number of integers between 1 and n inclusive,
which are coprime to n.
(Two numbers are coprime if their greatest common divisor (GCD) equals 1).
Code from /algorithms/maths/euler_totient.py, written by 'goswami-rahul'
"""
def euler_totient(n):
"""Euler's totient function or Phi function.
Time Complexity: O(sqrt(n))."""
result = n
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
while n % i == 0:
n //= i
result -= result // i
if n > 1:
result -= result // n
return result
"""
For positive integer n and given integer a that satisfies gcd(a, n) = 1,
a is the primitive root of n, if a's order k for n satisfies k = ϕ(n).
Primitive roots of certain number may or may not be exist.
If so, return empty list.
"""
def find_primitive_root(n):
if n == 1:
return [0]
""" Exception Handeling :
0 is the only primitive root of 1 """
else:
phi = euler_totient(n)
p_root_list = []
""" It will return every primitive roots of n. """
for i in range(1, n):
if math.gcd(i, n) != 1:
continue
""" To have order, a and n must be
relative prime with each other. """
else:
order = find_order(i, n)
if order == phi:
p_root_list.append(i)
else:
continue
return p_root_list
| true |
4b29471c64eb3d3005ba1b7484d0fb9bf72ee325 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/course-work/Python-Brain-Teasers/hamming_weight.py | 1,004 | 4.28125 | 4 | """
Given an unsigned integer, write a function that returns the number of '1' bits
that the integer contains (the
[Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight))
Examples:
- `hamming_weight(n = 00000000000000000000001000000011) -> 3`
- `hamming_weight(n = 00000000000000000000000000001000) -> 1`
- `hamming_weight(n = 11111111111111111111111111111011) -> 31`
Notes:
- "Unsigned Integers (often called "uints") are just like integers (whole
numbers) but have the property that they don't have a + or - sign associated
with them. Thus they are always non-negative (zero or positive). We use uint's
when we know the value we are counting will always be non-negative."
"""
def hamming_weight(n):
# Your code here
count = 0
while n:
n &= n - 1
count += 1
return count
print(hamming_weight(n=0o00000000000000000000001000000011))
print(hamming_weight(n=0o00000000000000000000000000001000))
print(hamming_weight(n=0o11111111111111111111111111111011))
| true |
99d4b3a3a7bd6e1455cd7fed0e538cca41a634b1 | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/_External-learning-resources/_PYTHON/Python-master/Guessing_Game.py | 1,523 | 4.15625 | 4 | from random import randint
from time import sleep
print("Hello Welcome To The Guess Game!")
sleep(1)
print("I'm Geek! What's Your Name?")
name = input()
sleep(1)
print(f"Okay {name} Let's Begin The Guessing Game!")
a = comGuess = randint(
0, 100
) # a and comGuess is initialised with a random number between 0 and 100
count = 0
while (
True
): # loop will run until encountered with the break statement(user enters the right answer)
userGuess = int(
input("Enter your guessed no. b/w 0-100:")
) # user input for guessing the number
if (
userGuess < comGuess
): # if number guessed by user is lesser than the random number than the user is told to guess higher and the random number comGuess is changed to a new random number between a and 100
print("Guess Higher")
comGuess = randint(a, 100)
a += 1
count = 1
elif (
userGuess > comGuess
): # if number guessed by user is greater than the random number than the user is told to guess lower and the random number comGuess is changed to a new random number between 0 and a
print("Guess Lower")
comGuess = randint(0, a)
a += 1
count = 1
elif (
userGuess == comGuess and count == 0
): # the player needs a special reward for perfect guess in the first try ;-)
print("Bravo! Legendary Guess!")
else: # Well, A Congratulations Message For Guessing Correctly!
print("Congratulations, You Guessed It Correctly!")
| true |
1fcc988f266d75b8a780b95ffa2bd64f6883aa8f | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/ciriculumn/week-17/python/Introduction-Programming-Python/Solutions/Module4MortgageCalculatorChallengeSolution.py | 1,140 | 4.3125 | 4 | # Declare and initialize the variables
monthlyPayment = 0
loanAmount = 0
interestRate = 0
numberOfPayments = 0
loanDurationInYears = 0
# Ask the user for the values needed to calculate the monthly payments
strLoanAmount = input("How much money will you borrow? ")
strInterestRate = input("What is the interest rate on the loan? ")
strLoanDurationInYears = input("How many years will it take you to pay off the loan? ")
# Convert the strings into floating numbers so we can use them in teh formula
loanDurationInYears = float(strLoanDurationInYears)
loanAmount = float(strLoanAmount)
interestRate = float(strInterestRate)
# Since payments are once per month, number of payments is number of years for the loan * 12
numberOfPayments = loanDurationInYears * 12
# Calculate the monthly payment based on the formula
monthlyPayment = (
loanAmount
* interestRate
* (1 + interestRate)
* numberOfPayments
/ ((1 + interestRate) * numberOfPayments - 1)
)
# provide the result to the user
print("Your monthly payment will be " + str(monthlyPayment))
# Extra credit
print("Your monthly payment will be $%.2f" % monthlyPayment)
| true |
610a0d008ceef29a052a5cbac5629c90cb572906 | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/leetcode/Binary_tree Paths.py | 813 | 4.125 | 4 | # Given a binary tree, return all root-to-leaf paths.
#
# Note: A leaf is a node with no children.
#
# Example:
#
# Input:
#
# 1
# / \
# 2 3
# \
# 5
#
# Output: ["1->2->5", "1->3"]
#
# Explanation: All root-to-leaf paths are: 1->2->5, 1->3
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def binaryTreePaths(self, root):
res = []
path = ""
def helper(node, path):
if not node:
return
path += str(node.val) + "->"
if not node.left and not node.right:
res.append(path[:-2])
return
helper(node.left, path)
helper(node.right, path)
helper(root, path)
return res
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.