blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ce2e9a4fce24333c40aab5c06c2b83d16c5ae9c0 | booherbg/ken | /ppt/magic/functions_examples.py | 2,601 | 4.125 | 4 | '''
Working with functions
'''
# one parameter, required
def person1(name):
print "My name is %s" % name
#one parameter, optional w/ default argument
def person2(name='ken'):
print "My name is %s" % name
#three parameters, two optional
def person3(name, city='cincinnati', work='library'):
print "My name is %s from %s, I work at %s" % (name, city, work)
#one required parameter, the rest are variable
def person4(name, *params):
print "My name is %s, my parameter list is:" % name
for i in params:
print i
#one required param, variable keywords
def person5(name, **keywords):
print "My name is %s" % name
if keywords.has_key('city'):
print "I am from %s" % keywords['city']
for kw,val in keywords.items():
print "%s: %s" % (str(kw), str(val))
# one required param, then variable params, then variable keywords
def person6(*params, **keywords):
if keywords.has_key('name'):
name = keywords['name']
else:
name = 'anonymous'
print "My name is %s" % name
print "My params are:"
for i, p in enumerate(params):
print "%d. %s" % (i, str(p))
print "My keywords are:"
# Note the use of a tuple unpacking from enumerate...
for i, (key, val) in enumerate(keywords.items()):
print "%d. %s:%s" % (i, str(key), str(val))
print "Now I'm going to call the function contained in the keyword 'func':"
if keywords.has_key('func'):
print "==== result from calling: %s =====" % keywords['func']
keywords['func'](**keywords)
else:
print "no function found"
# simple usage
print 'person1'
person1('blaine')
print ''
print 'person2'
person2()
person2('ken')
print ''
print 'person3'
person3('blaine')
person3('blaine', 'dayton', 'airport')
person3('blaine', work='coffee shop')
person3('blaine', work='donut shop', city='san francisco')
print ''
print 'person4'
person4('blaine', 'random', 'parameters', 'for', 5, 19, person4)
# * means "take everything in range(10) and make them actual arguments. don't pass in a list of numbers,
# pass in parameters of integers
person4('blaine', *range(10))
# but you could do this too!
person4('blaine', range(10))
print ''
print 'person5'
person5('blaine', keyword='mykeyword', city='columbus, ohio')
person5(city='cleveland', name='blaine')
print ''
print 'person6'
person6(1,2,3,4,5, name='blaine', city='cincinnati', work='clifton labs')
# pay attention now, this gets interesting!
person6(1,2,3,4, name='blaine', city='cincinnati', work='cliftonlabs', func=person5)
| true |
9c73b01299eeb325f8035f6c3307aab051fd804d | ShehrozeEhsan086/ICT | /Python_Basics/replace_find.py | 689 | 4.28125 | 4 | # replace() method
string = "she is beautiful and she is a good dancer"
print(string.replace(" ","_")) # replaces space with underscore
print(string.replace("is","was")) # replaces is with was
print(string.replace("is","was",1)) #replaces the first is with was
print(string.replace("is","was",2)) #replaces both is in the sentence to was
# find() method
# find the location for a value
print(string.find("is"))
print(string.find("is", 5)) # will look for "is" after position 4
# if the location of the first "is" is unknown we can do;.
is_pos1 = string.find("is")
print(is_pos1)
is_pos2 = string.find("is",is_pos1 +1) # +1 so that it wont count the first "is"
print(is_pos2) | true |
508877d679b9c33911f6c9823045770931d7c0f0 | CallumRai/Radium-Tech | /radium/helpers/_truncate.py | 855 | 4.375 | 4 | import math
def _truncate(number, decimals=0):
"""
Truncates a number to a certain number of decimal places
Parameters
----------
number : numeric
Number to truncate
decimals : int
Decimal places to truncate to, must be non-negative
Returns
-------
ret : numeric
Number truncated to specified decimal places
Raises
------
TypeError
Decimals is not an integer
ValueError
Decimals is negative
"""
if not isinstance(decimals, int):
raise TypeError('Decimals must be an integer.')
elif decimals < 0:
raise ValueError('Decimals must be >= 0.')
elif decimals == 0:
# If decimals is zero can truncate as normal
return math.trunc(number)
factor = 10.0 ** decimals
return math.trunc(number * factor) / factor
| true |
541985ab340362d1e210695e949cea874923687e | Somu96/Basic_Python | /FileHandling/student_dict.py | 880 | 4.28125 | 4 | #student nested dictionary
student = {'Std_1': {'name': 'Som', 'math': 35, 'science': 35},
'Std_2': {'name': 'Vanitha', 'math': 99, 'science': 99}
'Std_3': {'name': 'Divya', 'math': 100, 'science': 100}
}
add_std = True
def get_stu_info():
stu_id = input('Enter the ID for student \n')
if stu_id in student.keys():
print('Duplicate Student ID. Re-run the program')
else:
student[stu_id]={'name': input(f'Enter name for {stu_id} : '), 'math':input('Enter Math score : '), 'science':input('Enter Science Score : ')}
print("Welcome to Student records")
while add_std :
add_std_check = input('Are you here add information of a student ? Yes/No \n')
if add_std_check == 'Yes':
get_stu_info()
else:
add_std = False
print(f'Thank you here are the student details we have {student}')
| false |
6bbaf096406780be38dceedcf04602b1d48210d0 | AliSalman86/Learning-The-Complete-Python-Course | /10Oct2019/list_comprehension.py | 1,678 | 4.75 | 5 | # list comprehension is a python feature that allows us to create lists very
# succinctly but being very powerful.
# doubling a list of numbers without list comprehension:
numbers = [0, 1, 2, 3, 4, 5]
doubled_numbers = list()
# use for loop to iterate the numbers in the list and multiply it by 2
for number in numbers:
doubled_numbers.append(number * 2)
print(doubled_numbers)
print("=========================================")
# same above with list comprehension
numbers_2 = [1, 2, 3, 4, 5]
doubled_numbers_2 = [number * 2 for number in numbers_2]
print(doubled_numbers_2)
print("=========================================")
# practice for comprehension
names = ["Alex", "Alice", "Jaafar", "Jenna"]
last_name = "Jordan"
full_names = [f"{name} full name is {name} {last_name}." for name in names]
print(full_names)
print("=========================================")
# multi lists comprehension
a_numbers = [3, 4, 5, 6]
b_numbers = [8, 5, 3, 1]
multiplied = [a * b for a in a_numbers for b in b_numbers]
print(multiplied)
print(f"multiply a_numbers list by b_numbers list give us {len(multiplied)} possibility")
print("=========================================")
# validating names to true is first letter is capital or small
# lower(), will make all letters in a string in a list lower case.
# title(), make every string in a list start with capital letter.
friend = input("Enter your name: ")
friends = ["Alex", "Alice", "Jaafar", "Jenna"]
friends_lower = [name.lower() for name in friends]
print(friend)
print(friends_lower)
if friend.lower() in friends_lower:
print(f"Hello {friend.title()}")
else:
print(f"Hi, nice to meet you {friend.title()}")
| true |
a6ff0a523770dff757aecf156646ae5ad1ef9687 | AliSalman86/Learning-The-Complete-Python-Course | /07Oct2019/basic_while_exercise.py | 738 | 4.40625 | 4 | # you can input any letter but it will actually do something only if p entered to
# print hello or entered q to quit the program
user_input = input("Please input your choice p to start the prgram or q to terminate: ")
# Then, begin a while loop that runs for as long as the user doesn't type 'q', if q
# entered then program terminate.
while user_input != "q":
# if user input p then hello printed
if user_input == "p":
print("Hello!")
# ask user again what to input p to print again or q to quit
# entering any other letters would led the program to input a letter again without
# printing or quiting
user_input = input("Please input your choice p to start the prgram or q to terminate: ")
print("program terminated")
| true |
2e21af9e8646ab019caf79da570e11bb0f2d7a44 | AliSalman86/Learning-The-Complete-Python-Course | /16Oct2019/lambda_func_python.py | 1,634 | 4.46875 | 4 | # lambda functions get inputs, do a small amount of processing then return outputs
# functions can do 2 things:
# 1- perform an action (not a lambda function):
print("I am a function that perform an action, showing people a print, without changing the data")
# 2- return an output(can be used as lambda function):
def divide(x, y):
return x / y
# to turn the above divide function to a lambda function, we can do below
# variable = lambda keyword list of params(inputs): the processing(outputs)
l_divide = lambda w, z: w/z
print(divide(6, 3))
# lambda functions can be self triggered or executed:
print((lambda x, y: x / y)(15, 3))
print("===============================================================")
# lambda usage:
# non-lambda:
students = [
{"name": "Rolf", "grades": (67, 90, 95, 100)},
{"name": "Bob", "grades": (56, 78, 80, 90)},
{"name": "Jen", "grades": (98, 90, 95, 99)},
{"name": "Anne", "grades": (100, 100, 95, 100)},
]
def average(sequence):
return sum(sequence) / len(sequence)
for student in students:
print(f"{student['name']} has an average grades of: {average(student['grades'])}")
print("===============================================================")
# lambda usage:
# lambda:
students = [
{"name": "Rolf", "grades": (67, 90, 95, 100)},
{"name": "Bob", "grades": (56, 78, 80, 90)},
{"name": "Jen", "grades": (98, 90, 95, 99)},
{"name": "Anne", "grades": (100, 100, 95, 100)},
]
average_1 = lambda sequence: sum(sequence) / len(sequence)
for student in students:
print(f"{student['name']} has an average grades of: {average(student['grades'])}")
| true |
e55dfe9f427f2175b7b376ebec07ebfece9a3413 | AliSalman86/Learning-The-Complete-Python-Course | /13Oct2019/list_comprehension_with_conditions.py | 1,744 | 4.5625 | 5 | # we can use conditions with list comprehension to make it more flexible.
# Info: we have 2 lists, a list of friend names and a list of event's guest names
# Problem: we want to find list of friends who attended the party.
# there is to solutions:
# Solution 1: using sets and intersection() without list comprehension,
# valid but longer solution:
friends = ["Rolf", "ruth", "charlie", "Jen"]
guests = ["jose", "Bob", "Rolf", "Charlie", "michael"]
# for accurate comparison we need to turn all names to all lower case letters,
# to avoid the issue of having a name in title case in one list and in lower case
# in the other list
# convert the new lists to sets:
friends_lower = set([friend.lower() for friend in friends])
guests_lower = set([guest.lower() for guest in guests])
# print unique values, guests who are friends, using sets and intersection() and
# convert the set to list so we can make the names title case using title()
present_friends = list(friends_lower.intersection(guests_lower))
present_friends_proper = list()
for name in present_friends:
present_friends_proper.append(name.title())
print(present_friends_proper)
# solution 2: using list comprehension with conditionals
friends = ["Rolf", "ruth", "charlie", "Jen"]
guests = ["jose", "Bob", "Rolf", "Charlie", "michael"]
# convert the two lists to all lower case for valid comarison
friends_lower2 = [friend.lower() for friend in friends]
guests_lower2 = [guest.lower() for guest in guests]
# print(friends_lower2)
# print(guests_lower2)
present_friends2 = [
# select a name from the friends list
name.title() for name in friends_lower2
# if the friend name is in the guests list as well
if name in guests_lower2
]
print(present_friends2)
| true |
c11ceb526f159f47b92a781ed5fd8fad6d372247 | skulshreshtha/Data-Structures-and-Algorithms | /DS/queue_implementation_using_two_lists.py | 1,189 | 4.28125 | 4 | class MyQueue(object):
def __init__(self):
""" Creates two empty stacks for implementing the queue (FIFO)."""
self._front_stack = []
self._back_stack = []
def peek(self):
""" Returns (without removing) the element at front of the queue."""
self._prepare_stacks()
return self._front_stack[-1]
def pop(self):
""" Returns and removes the element at front of the queue."""
self._prepare_stacks()
return self._front_stack.pop()
def put(self, value):
""" Adds element to the back of the queue."""
self._back_stack.append(value)
def _prepare_stacks(self):
""" Move all elements from back stack to front stack for peek and pop."""
if(len(self._front_stack) == 0):
while(len(self._back_stack) > 0):
self._front_stack.append(self._back_stack.pop())
queue = MyQueue()
t = int(input())
for line in range(t):
values = map(int, input().split())
values = list(values)
if values[0] == 1:
queue.put(values[1])
elif values[0] == 2:
queue.pop()
else:
print(queue.peek()) | true |
7218ec87313889d8b40deed9b8e620279a667d04 | Psyconne/python-examples | /ex39_init.py | 611 | 4.4375 | 4 | #you can only use numbers to index into lists
print 'this is a list'
things = ['a', 'b', 'c', 'd']
print 'things: ', things
print things[1]
things[1] = 'r'
print things[1]
print 'things: ', things
#a dict associates one thing to another, no matter what it is
print 'this is dicts'
stuff = {'name': 'El Idrissi', 'age': 22, 'height': 6*10 +8}
print stuff ['name']
print stuff ['age']
print stuff ['height']
stuff ['city'] = 'El jadida'
print stuff['city']
#what order ?
print (stuff)
stuff [3] = 'Nice'
stuff [4] = 'Wow'
#what order ?
print (stuff)
#to delete
del stuff['city'], stuff[3], stuff[4]
print (stuff)
| false |
07379dcf89e6ee2650643c049ff6a457c9089df0 | ingwplanchez/Python | /Program_48_FuncionesExternas/Modulos.py | 1,849 | 4.21875 | 4 |
def Bienvenidos(): # def se utiliza para definir una funcion
print("Bienvenido a la agenda telefonica.\n")
print("1.- Agregar un elemento a la agenda")
print("2.- Listar los elementos de la agenda")
print("3.- Buscar por nombres\n")
def Escribir():
print("Has elegido agregar un elemento a la agenda.\n")
## APERTURA DE UN ARCHIVO PARA AGREGAR ELEMENTOS
Agenda = open("AgendaTelefonica.csv",'a') # Se abre el archivo Para escribir y
# Y se agrega el contenido q se le escriba
# al archivo Sin Borrar lo anterior ('a')
Posicion = input("Introduce una posicion:")
Nombre = input("Introduce el nombre: ")
Telefono = input("Introduce el numero de telefono: ")
print("Se ha guardado en la agenda el contacto: %s.\nCon su numero de tlf: %s.\n"%(Nombre,Telefono))
## ESCRITURA DE ELEMENTOS EN UN ARCHIVO
Agenda.write(Posicion)
Agenda.write(";")
Agenda.write(Nombre)
Agenda.write(";")
Agenda.write(Telefono)
Agenda.write(";")
Agenda.write("\n")
print("Se han terminado de agregar los datos")
Agenda.close() # Cierra el archivo que se abrio
def Consulta(fin):
print("Has elegido listar los elementos de la agenda.\n")
## APERTURA DE UN ARCHIVO PARA LEER ELEMENTOS
Agenda = open("AgendaTelefonica.csv")
Numero = 0
while Numero<fin:
Formato = Agenda.readline()
print(Formato.replace(";","\t\t")) # Se reemplaza un valor por otro
Numero = Numero + 1
print("He terminado de leer el archivo")
Agenda.close() # Cierra el archivo que se abrio
def MiError():
print("La opcion no es valida.")
def Buscador():
print("Aqui se buscaran los contactos.")
| false |
a27c424b39d298263ab0d41bf10ad186a0dacec4 | kopchik/itasks | /round2/fb_k-nearest.py | 430 | 4.125 | 4 | #!/usr/bin/env python3
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
def nearest(loc, points, k):
def distance(point):
return (loc.x-point.x)**2 \
+ (loc.y-point.y)**2
points.sort(key=distance, reverse=True)
return points[-k:]
if __name__ == '__main__':
points = [
Point(1,1),
Point(2,1),
Point(4,10),
]
print(nearest(loc=Point(0,0), points=points, k=2))
| true |
2221d7ed1b60b7649e28e66ae9d30596ed3abc5c | kopchik/itasks | /round5/rot13.py | 983 | 4.21875 | 4 | #!/usr/bin/env python3
def rot13(s, base=13):
"""
Encodes and decodes strings with ROT-13 (https://en.wikipedia.org/wiki/ROT13).
Arguments:
s -- string to encode/decode.
base -- number of shifts to perform
Returns:
string representing encoded/decoded data.
"""
decoded = []
for c in s:
newcode = ord(c) - ord('a') + base
wrapped = newcode % 26 + ord('a')
decoded.append(wrapped)
# map integers to chars in ascii-table and form the string
return "".join(map(chr, decoded))
def rot13_clever(s, base=13):
""" Same as rot13, but in a short and obscure way. """
return "".join(chr((ord(c) - ord('a') + base) % 26 + ord('a')) for c in s)
if __name__ == '__main__':
encoded = "rkgerzr"
decoded = "extreme"
print(rot13_clever(encoded))
# some basic tests
assert rot13(encoded) == decoded, "ROT-13 decoding failed"
assert rot13(decoded) == encoded, "ROT-13 encoding failed"
| true |
68eedc593ebe156fa80d85279b3dab4b955d3e52 | jingxuanyang/BFS_Sequences | /halton.py | 2,008 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Write a computer code for the Halton sequence. The input should be the
# dimension s and n, and the output should be the nth Halton vector where
# the bases are the first s prime numbers.
# About Halton Sequence
#
# Reference https://en.wikipedia.org/wiki/Halton_sequence
# imports
import math
import random
# Write a computer code for the Halton sequence. The input should be
# the dimension s and n, and the output should be the nth Halton vector where
# the bases are the first s prime numbers.
def get_primes(N=1000):
''' get up to the first 1000 primes '''
primes = []
if N <= 1000:
lines = []
with open('1000.txt', 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
primes += line.split()
primes = [int(p) for p in primes[:N]]
return primes
primes = get_primes()
def halton(index, base):
''' return the nth number of a halton sequence with base
implementation taken from pseudocode at
https://en.wikipedia.org/wiki/Halton_sequence
'''
num = 0
f = 1.0
while (index > 0):
f = f / base
num = num + f * (index % base)
index = math.floor((index / base))
return num
def halton_vector(s, index, shift=False):
''' input: the dimension s (num of bases) and idx (Halton index)
output: nth Halton vector where the bases are the first s prime numbers
'''
return [halton(index=index, base=primes[i]) for i in range(s)]
def halton_seq(s, N, shift=True):
''' return a list of N halton vectors (tuples) of dimension s '''
hs = []
offset = [random.random() for i in range(s)]
for i in range(1, N+1):
hv = halton_vector(s, i)
if shift:
hv = [((hv[i] + offset[i]) % 1) for i in range(s)]
hs.append(tuple(hv))
return hs
#test
#hs = halton_seq(s=2, N=100, shift=False)
#print(hs[:10])
| true |
a92f00bdd7408a9bc210c991f0108448019bf0a2 | Sangavi-123/Data-Structures-and-Algorithms | /BubbleSort.py | 1,235 | 4.59375 | 5 | # Bubble sort implementation
# create a list
l = [6,8,1,4,10,7,8,9,3,2,5]
# Algorithm
"""
The algorithms has two loops
Inner for loop takes each element and compares it with neighboring elements
If the element is bigger than neighbor the element is swapped. This is done
for each element in the list. But one iteration through the entire list may
not sort it completely
Hence there is an outer while loop. Because using another for loop outside may
not be efficient. The number of iterations to sort the entire list may be less
than the total number of elements in the list
Hence while loop saves few iterations by quitting the process once all elements
are sorted
"""
plt.ion()
# Define a function that performs bubble sort
def bubbleSort(iterable):
swap = True
while swap:
swap = False
for item in range(len(iterable)-1): # Last element doesnt have next element
if iterable[item] > iterable[item + 1]:
swap = True
iterable[item], iterable[item+1] = iterable[item + 1], iterable[item] # * Dynamic assignment
print(iterable)
return iterable
sortedList = bubbleSort(l)
| true |
da0709770e89c51aa2636d04f580e41c7c102e56 | Sangavi-123/Data-Structures-and-Algorithms | /InsertionSort.py | 815 | 4.3125 | 4 | import numpy as np
l = [6,1,8,4,10]
l1 = [2,6,11,90,3,2,4]
l3 = [17,2,9,3,7]
# Algorithm
"""
the algorithm iterated from the first element and not the zeroth element.
it compare each element with previous elements and if the other element is large,
it is swappped. Now the element [identity - just a name] which is before the swapped index is checked and
it is repeated until there is no element at all.
this process is repeated for each element in the list
"""
def insertionSort(l):
for i in range(1,len(l)):
if l[i] < l[i-1]:
#swap
l[i],l[i-1] = l[i-1],l[i]
key = i-1
while(key!=0):
if l[key] < l[key-1]:
#swap
l[key], l[key-1] = l[key-1], l[key]
key -= 1
return l
print(insertionSort(l3))
| true |
3b2c1da384a2abf780f1ad906cfb6f13d12835be | groulet/checkio-code | /scientific-expedition/conversion-from-camelcase/solve.py | 1,542 | 4.5625 | 5 | '''
https://py.checkio.org/en/mission/conversion-from-camelcase/
Your mission is to convert the name of a function (a string) from CamelCase ("MyFunctionName") into the Python format ("my_function_name") where all chars are in lowercase and all words are concatenated with an intervening underscore symbol "_".
Input: A function name as a CamelCase string.
Output: The same string, but in under_score.
Example:
from_camel_case("MyFunctionName") == "my_function_name"
from_camel_case("IPhone") == "i_phone"
from_camel_case("ThisFunctionIsEmpty") == "this_function_is_empty"
from_camel_case("Name") == "name"
How it is used: To apply function names in the style in which they are adopted in a specific language (Python, JavaScript, etc.).
Precondition:
0 < len(string) <= 100
Input data won't contain any numbers.
'''
import re
def from_camel_case(name):
# using regex:
#name[0].lower() + re.sub(r'([A-Z])',lambda m: '_'+m.group(0).lower(),name[1:])
return ''.join([name[0].lower()] + ['_'+l.lower() if l.isupper() else l for l in name[1:]])
if __name__ == '__main__':
print("Example:")
print(from_camel_case("Name"))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert from_camel_case("MyFunctionName") == "my_function_name"
assert from_camel_case("IPhone") == "i_phone"
assert from_camel_case("ThisFunctionIsEmpty") == "this_function_is_empty"
assert from_camel_case("Name") == "name"
print("Coding complete? Click 'Check' to earn cool rewards!")
| true |
51b287c0ad340098350a847c3a489ae1814eb81f | groulet/checkio-code | /home/digits-multiplication/solve.py | 1,328 | 4.5625 | 5 | '''
https://py.checkio.org/en/mission/digits-multiplication/
You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes.
For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes).
Input: A positive integer.
Output: The product of the digits as an integer.
Example:
checkio(123405) == 120
checkio(999) == 729
checkio(1000) == 1
checkio(1111) == 1
How it is used: This task can teach you how to solve a problem with simple data type conversion.
Precondition: 0 < number < 106
'''
from functools import reduce
def checkio(number: int) -> int:
# learning "reduce" from functools
# create a list of int > 0 with list comprehension and converting number to string
# use reduce with a lambda function to multiply each digit in the created list
return reduce(lambda x,n: x*n,[int(i) for i in str(number) if int(i) > 0])
if __name__ == '__main__':
print('Example:')
print(checkio(123405))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(123405) == 120
assert checkio(999) == 729
assert checkio(1000) == 1
assert checkio(1111) == 1
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
| true |
a84806404994be5321900302c8c6f12a0e83d498 | tahmid-tanzim/problem-solving | /Arrays_and_Strings/__Waterfall-Streams.py | 2,850 | 4.1875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Waterfall%20Streams
"""
You're given a two-dimensional array that represents the structure of an
indoor waterfall and a positive integer that represents the column that the
waterfall's water source will start at. More specifically, the water source
will start directly above the structure and will flow downwards.
Each row in the array contains 0s and 1s, where a
0 represents a free space and a 1 represents a block
that water can't pass through. You can imagine that the last row of the array
contains buckets that the water will eventually flow into; thus, the last row
of the array will always contain only 0s. You can also imagine
that there are walls on both sides of the structure, meaning that water will
never leave the structure; it will either be trapped against a wall or flow
into one of the buckets in the last row.
As water flows downwards, if it hits a block, it splits evenly to the left and
right-hand side of that block. In other words, 50% of the water flows left and
50% of it flows right. If a water stream is unable to flow to the left or to
the right (because of a block or a wall), the water stream in question becomes
trapped and can no longer continue to flow in that direction; it effectively
gets stuck in the structure and can no longer flow downwards, meaning that 50%
of the previous water stream is forever lost.
Lastly, the input array will always contain at least two rows and one column,
and the space directly below the water source (in the first row of the array)
will always be empty, allowing the water to start flowing downwards.
Write a function that returns the percentage of water inside each of the
bottom buckets after the water has flowed through the entire structure.
You can refer to the first 4.5 minutes of this question's video explanation
for a visual example.
Sample Input
array = [
[0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0],
]
source = 3
Sample Output
[0, 0, 0, 25, 25, 0, 0]
// The water will flow as follows:
// [
// [0, 0, 0, ., 0, 0, 0],
// [1, ., ., ., ., ., 0],
// [0, ., 1, 1, 1, ., 0],
// [., ., ., ., ., ., .],
// [1, 1, 1, ., ., 1, 0],
// [0, 0, 0, ., ., 0, 1],
// [0, 0, 0, ., ., 0, 0],
// ]
"""
# O(w^2 * h) time | O(w) space
# where w and h are the width and height of the input array
def waterfallStreams(array, source):
pass
if __name__ == '__main__':
print(waterfallStreams([
[0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0],
], 3))
| true |
6fe09d0536e033edf229e0d7e9f3be559deeb540 | tahmid-tanzim/problem-solving | /Linked_Lists/__Zip-Linked-List.py | 1,189 | 4.5 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Zip%20Linked%20List
"""
You're given the head of a Singly Linked List of arbitrary length
k. Write a function that zips the Linked List in place (i.e.,
doesn't create a brand new list) and returns its head.
A Linked List is zipped if its nodes are in the following order, where
k is the length of the Linked List:
1st node -> kth node -> 2nd node -> (k - 1)th node -> 3rd node -> (k - 2)th node -> ...
Each LinkedList node has an integer value as well as
a next node pointing to the next node in the list or to
None / null if it's the tail of the list.
You can assume that the input Linked List will always have at least one node;
in other words, the head will never be None / null.
Sample Input
linkedList = 1 -> 2 -> 3 -> 4 -> 5 -> 6 // the head node with value 1
Sample Output
1 -> 6 -> 2 -> 5 -> 3 -> 4 // the head node with value 1
"""
# O(n) time | O(1) space
# where n is the length of the input Linked List
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def zipLinkedList(linkedList):
return None
if __name__ == '__main__':
pass
| true |
78346fb924bee1aedf9291633904599970d52a52 | tahmid-tanzim/problem-solving | /Arrays_and_Strings/Generate-Document.py | 1,524 | 4.46875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Generate%20Document
"""
You're given a string of available characters and a string representing a
document that you need to generate. Write a function that determines if you
can generate the document using the available characters. If you can generate
the document, your function should return true; otherwise, it
should return false.
You're only able to generate the document if the frequency of unique
characters in the characters string is greater than or equal to the frequency
of unique characters in the document string. For example, if you're given
characters = "abcabc" and document = "aabbccc" you
<b>cannot</b> generate the document because you're missing one c.
The document that you need to create may contain any characters, including
special characters, capital letters, numbers, and spaces.
"""
# O(n+m) time, O(c) space
# n is the number of characters,
# m is the length of the document
# c is number of unique letter in the characters string
def generateDocument(characters, document):
hashtable = dict()
for char in characters:
if char not in hashtable:
hashtable[char] = 0
hashtable[char] += 1
for char in document:
if char in hashtable and hashtable[char] > 0:
hashtable[char] -= 1
else:
return False
return True
if __name__ == '__main__':
print(generateDocument("Bste!hetsi ogEAxpelrt x ", "AlgoExpert is the Best!")) # True
| true |
391f27573f012bac2679959c171562cf27d68121 | tahmid-tanzim/problem-solving | /Sorting/Bubble-Sort.py | 603 | 4.28125 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Bubble%20Sort
# Best Time Complexity - O(n), Space Complexity - O(1)
# Avg. & Worst Time Complexity - O(n^2), Space Complexity - O(1)
def bubbleSort(array):
isSorted = False
n = len(array)
while not isSorted:
isSorted = True
i = 0
while i < n - 1:
if array[i] > array[i + 1]:
array[i], array[i + 1] = array[i + 1], array[i]
isSorted = False
i += 1
n -= 1
return array
if __name__ == "__main__":
print(bubbleSort([8, 5, 29, 5, 6, 3]))
| false |
caf12586797ad108848b25770645b7bb36dfd2c0 | tahmid-tanzim/problem-solving | /Heap/__Continuous-Median.py | 1,423 | 4.15625 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Continuous%20Median
"""
Write a ContinuousMedianHandler class that supports:
1. The continuous insertion of numbers with the insert method.
2. The instant (O(1) time) retrieval of the median of the numbers that have
been inserted thus far with the getMedian method.
The getMedian method has already been written for you. You simply
have to write the insert method.
The median of a set of numbers is the "middle" number when the numbers are
ordered from smallest to greatest. If there's an odd number of numbers in the
set, as in {1, 3, 7}, the median is the number in the middle
(3 in this case); if there's an even number of numbers in the
set, as in {1, 3, 7, 8}, the median is the average of the two
middle numbers ((3 + 7) / 2 == 5 in this case).
Sample Usage
// All operations below are performed sequentially.
ContinuousMedianHandler(): - // instantiate a ContinuousMedianHandler
insert(5): -
insert(10): -
getMedian(): 7.5
insert(100): -
getMedian(): 10
"""
# Insert: O(log(n)) time | O(n) space
# where n is the number of inserted numbers
class ContinuousMedianHandler:
def __init__(self):
# Write your code here.
self.median = None
def insert(self, number):
# Write your code here.
pass
def getMedian(self):
return self.median
if __name__ == '__main__':
pass
| true |
c4621e516b2b3c5f053085912110f31cde5a09d1 | tahmid-tanzim/problem-solving | /Trees_and_Graphs/Binary Search Trees/__Right-Smaller-Than.py | 1,137 | 4.15625 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Right%20Smaller%20Than
"""
Write a function that takes in an array of integers and returns an array of
the same length, where each element in the output array corresponds to the
number of integers in the input array that are to the right of the relevant
index and that are strictly smaller than the integer at that index.
In other words, the value at output[i] represents the number of
integers that are to the right of i and that are strictly smaller
than input[i].
Sample Input
array = [8, 5, 11, -1, 3, 4, 2]
Sample Output
[5, 4, 4, 0, 1, 1, 0]
// There are 5 integers smaller than 8 to the right of it.
// There are 4 integers smaller than 5 to the right of it.
// There are 4 integers smaller than 11 to the right of it.
// Etc..
"""
# Average case: when the created BST is balanced
# O(nlog(n)) time | O(n) space - where n is the length of the array
# Worst case: when the created BST is like a linked list
# O(n^2) time | O(n) space
def rightSmallerThan(array):
pass
if __name__ == "__main__":
print(rightSmallerThan([8, 5, 11, -1, 3, 4, 2]))
| true |
e1e70a36206e3958e422cf061a398739b185aad8 | tahmid-tanzim/problem-solving | /Trees_and_Graphs/Min-Height-BST.py | 2,514 | 4.28125 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Min%20Height%20BST
"""
Write a function that takes in a non-empty sorted array of distinct integers,
constructs a BST from the integers, and returns the root of the BST.
The function should minimize the height of the BST.
You've been provided with a BST class that you'll have to use to
construct the BST.
Each BST node has an integer value, a
left child node, and a right child node. A node is
said to be a valid BST node if and only if it satisfies the BST
property: its value is strictly greater than the values of every
node to its left; its value is less than or equal to the values
of every node to its right; and its children nodes are either valid
BST nodes themselves or None / null.
A BST is valid if and only if all of its nodes are valid
BST nodes.
Note that the BST class already has an insert method
which you can use if you want.
Sample Input
array = [1, 2, 5, 7, 10, 13, 14, 15, 22]
Sample Output
10
/ \
2 14
/ \ / \
1 5 13 15
\ \
7 22
// This is one example of a BST with min height
// that you could create from the input array.
// You could create other BSTs with min height
// from the same array; for example:
10
/ \
5 15
/ \ / \
2 7 13 22
/ \
1 14
"""
# O(n) time, O(n) space
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __str__(self):
return str(self.value)
def insert(self, value):
if value < self.value:
if self.left is None:
self.left = BST(value)
else:
self.left.insert(value)
else:
if self.right is None:
self.right = BST(value)
else:
self.right.insert(value)
def sortedDFS(array, min_height=[]):
n = len(array)
if n == 0:
return
middle_index = n // 2
min_height.append(array[middle_index])
sortedDFS(array[:middle_index], min_height)
sortedDFS(array[middle_index + 1:], min_height)
return min_height
def minHeightBst(array):
nodes = sortedDFS(array, [])
root = BST(nodes[0])
i = 1
while i < len(nodes):
root.insert(nodes[i])
i += 1
return root
if __name__ == "__main__":
print(minHeightBst([1, 2, 5, 7, 10, 13, 14, 15, 22]))
| true |
254ff9b1dc2888bfba0f9a72e3f9f1f37bcd0e90 | tahmid-tanzim/problem-solving | /Arrays_and_Strings/Smallest-Difference.py | 1,642 | 4.25 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Smallest%20Difference
"""
Write a function that takes in two non-empty arrays of integers, finds the
pair of numbers (one from each array) whose absolute difference is closest to
zero, and returns an array containing these two numbers, with the number from
the first array in the first position.
Note that the absolute difference of two integers is the distance between
them on the real number line. For example, the absolute difference of -5 and 5
is 10, and the absolute difference of -5 and -4 is 1.
You can assume that there will only be one pair of numbers with the smallest
difference.
Sample Input
arrayOne = [-1, 5, 10, 20, 28, 3]
arrayTwo = [26, 134, 135, 15, 17]
Sample Output
[28, 26]
"""
# Time Complexity - O(nlog(n) + mlog(m))
# Space Complexity - O(1)
def smallestDifference(arrayOne, arrayTwo):
minDiff = float("inf")
output = []
i = 0
j = 0
arrayOne.sort()
arrayTwo.sort()
while i < len(arrayOne) and j < len(arrayTwo):
first_val = arrayOne[i]
second_val = arrayTwo[j]
if first_val < second_val:
currentDiff = abs(second_val - first_val)
i += 1
elif second_val < first_val:
currentDiff = abs(first_val - second_val)
j += 1
else:
return [first_val, second_val]
if currentDiff < minDiff:
minDiff = currentDiff
output = [first_val, second_val]
return output
if __name__ == "__main__":
print(smallestDifference([- 1, 5, 10, 20, 28, 3], [26, 134, 135, 15, 17])) # [28, 26]
| true |
ca20a33dbf1d50c3c4b915e463c019906d05020a | tahmid-tanzim/problem-solving | /Searching/Search-In-Sorted-Matrix.py | 1,360 | 4.34375 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix
"""
You're given a two-dimensional array (a matrix) of distinct integers and a
target integer. Each row in the matrix is sorted, and each column is also sorted; the
matrix doesn't necessarily have the same height and width.
Write a function that returns an array of the row and column indices of the
target integer if it's contained in the matrix, otherwise
[-1, -1].
Sample Input
matrix = [
[1, 4, 7, 12, 15, 1000],
[2, 5, 19, 31, 32, 1001],
[3, 8, 24, 33, 35, 1002],
[40, 41, 42, 44, 45, 1003],
[99, 100, 103, 106, 128, 1004],
]
target = 44
Sample Output
[3, 3]
"""
# O(n + m) time | O(1) space
# where n is the length of the matrix's rows and m is the length of the matrix's columns
def searchInSortedMatrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < target:
row += 1
else:
return [row, col]
return [-1, -1]
if __name__ == '__main__':
print(searchInSortedMatrix([
[1, 4, 7, 12, 15, 1000],
[2, 5, 19, 31, 32, 1001],
[3, 8, 24, 33, 35, 1002],
[40, 41, 42, 44, 45, 1003],
[99, 100, 103, 106, 128, 1004],
], 44))
| true |
1afe66ec741a4890d9bb8f695d129957a81814e8 | tahmid-tanzim/problem-solving | /Dynamic_Programming/triple-step.py | 1,261 | 4.34375 | 4 | #!/usr/bin/python3
# Cracking the Coding Interview - 8.1
# Dynamic Programming
# Time complexity - O(3 ^ n)
def tripleStep(n):
if n < 0:
return 0
if n == 0:
return 1
return tripleStep(n - 1) + tripleStep(n - 2) + tripleStep(n - 3)
# Dynamic Programming with Tabulation
# BottomUp Approach
# Time complexity - O(n)
def countWaysTabulation(n):
table = [None] * (n + 1)
table[0] = 1
table[1] = 1
table[2] = 2
i = 3
while i <= n:
table[i] = table[i - 1] + table[i - 2] + table[i - 3]
i += 1
return table[-1]
# Dynamic Programming with Memoization
# TopDown Approach
# Time complexity - O(n)
def countWays(n):
return tripleStepWithMemoization(n, [None] * (n + 1))
def tripleStepWithMemoization(n, matrix):
if n < 0:
return 0
if n == 0:
return 1
if matrix[n] is not None:
return matrix[n]
matrix[n] = tripleStepWithMemoization(n - 1, matrix) + tripleStepWithMemoization(n - 2, matrix) + tripleStepWithMemoization(n - 3, matrix)
return matrix[n]
if __name__ == "__main__":
# print(f'Answer - {tripleStep(5)}')
print(f'Answer with Memoization - {countWays(45)}')
print(f'Answer with Tabulation - {countWaysTabulation(45)}')
| false |
a1bc7035f2da69f3b360a3596cdce78baae0bdf0 | tahmid-tanzim/problem-solving | /Searching/Shifted-Binary-Search.py | 2,977 | 4.375 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Shifted%20Binary%20Search
"""
Write a function that takes in a sorted array of distinct integers as well as a target
integer. The caveat is that the integers in the array have been shifted by
some amount; in other words, they've been moved to the left or to the right by
one or more positions. For example, [1, 2, 3, 4] might have
turned into [3, 4, 1, 2].
The function should use a variation of the Binary Search algorithm to
determine if the target integer is contained in the array and should return
its index if it is, otherwise -1.
If you're unfamiliar with Binary Search, we recommend watching the Conceptual
Overview section of the Binary Search question's video explanation before
starting to code.
Sample Input
array = [45, 61, 71, 72, 73, 0, 1, 21, 33, 37]
target = 33
Sample Output
8
"""
# O(log(n)) time | O(log(n)) space
class Solution1:
def shiftedBinarySearchHelper(self, array, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
if target == array[middle]:
return middle
if array[left] <= array[middle]:
# left sorted
if array[left] <= target < array[middle]:
return self.shiftedBinarySearchHelper(array, target, left, middle - 1)
else:
return self.shiftedBinarySearchHelper(array, target, middle + 1, right)
else:
# right sorted
if array[middle] <= target < array[right]:
return self.shiftedBinarySearchHelper(array, target, middle + 1, right)
else:
return self.shiftedBinarySearchHelper(array, target, left, middle - 1)
def shiftedBinarySearch(self, array, target):
return self.shiftedBinarySearchHelper(array, target, 0, len(array) - 1)
# O(log(n)) time | O(1) space
class Solution2:
@staticmethod
def shiftedBinarySearchHelper(array, target, left, right):
while left <= right:
middle = (left + right) // 2
if target == array[middle]:
return middle
if array[left] <= array[middle]:
# left sorted
if array[left] <= target < array[middle]:
right = middle - 1
else:
left = middle + 1
else:
# right sorted
if array[middle] <= target < array[right]:
left = middle + 1
else:
right = middle - 1
return -1
def shiftedBinarySearch(self, array, target):
return self.shiftedBinarySearchHelper(array, target, 0, len(array) - 1)
if __name__ == '__main__':
obj = Solution1()
print(obj.shiftedBinarySearch([45, 61, 71, 72, 73, 0, 1, 21, 33, 37], 33))
obj = Solution2()
print(obj.shiftedBinarySearch([45, 61, 71, 72, 73, 0, 1, 21, 33, 37], 33))
| true |
89f98bd8a53b8a5466b576f2eabba8dec0d76d2e | tahmid-tanzim/problem-solving | /Arrays_and_Strings/First-Duplicate-Value.py | 1,320 | 4.3125 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/First%20Duplicate%20Value
"""
Given an array of integers between 1 and n,
inclusive, where n is the length of the array, write a function
that returns the first integer that appears more than once (when the array is
read from left to right).
In other words, out of all the integers that might occur more than once in the
input array, your function should return the one whose first duplicate value
has the minimum index.
If no integer appears more than once, your function should return -1.
Note that you're allowed to mutate the input array.
Sample Input #1
array = [2, 1, 5, 2, 3, 3, 4]
Sample Output #1
2
// 2 is the first integer that appears more than once.
// 3 also appears more than once, but the second 3 appears after the second 2.
Sample Input #2
array = [2, 1, 5, 3, 3, 2, 4]
Sample Output #2
3
// 3 is the first integer that appears more than once.
// 2 also appears more than once, but the second 2 appears after the second 3.
"""
# O(n) time, O(1) space
def firstDuplicateValue(array):
for item in array:
index = abs(item) - 1
if array[index] < 0:
return abs(item)
array[index] *= -1
return -1
if __name__ == '__main__':
print(firstDuplicateValue([2, 1, 5, 2, 3, 3, 4]))
| true |
0457984ce7a77d93fcad90843c19ef4c219c91be | tahmid-tanzim/problem-solving | /Arrays_and_Strings/Longest-Peak.py | 1,675 | 4.46875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Longest%20Peak
"""
Write a function that takes in an array of integers and returns the length of
the longest peak in the array.
A peak is defined as adjacent integers in the array that are strictly
increasing until they reach a tip (the highest value in the peak), at which
point they become strictly decreasing. At least three integers are required to form a peak.
For example, the integers 1, 4, 10, 2 form a peak, but the
integers 4, 0, 10 don't and neither do the integers
1, 2, 2, 0. Similarly, the integers 1, 2, 3 don't
form a peak because there aren't any strictly decreasing integers after the 3.
Sample Input
array = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]
Sample Output
6 // 0, 10, 6, 5, -1, -3
"""
# O(n) time, O(1) space
def longestPeak(array):
all_peaks_index = []
long_peak = 0
# Find Peaks
i = 1
n = len(array)
while i < n - 1:
if array[i] > array[i + 1] and array[i] > array[i - 1]:
all_peaks_index.append(i)
i += 1
for peak_index in all_peaks_index:
# Traverse Left
left_index = peak_index - 2
while left_index >= 0 and array[left_index] < array[left_index + 1]:
left_index -= 1
# Traverse Right
right_index = peak_index + 2
while right_index < n and array[right_index] < array[right_index - 1]:
right_index += 1
if long_peak < (right_index - left_index - 1):
long_peak = (right_index - left_index - 1)
return long_peak
if __name__ == '__main__':
print(longestPeak([1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]))
| true |
9900be549d5d606590669361432c07b16bfed919 | tahmid-tanzim/problem-solving | /Stacks_and_Queues/__Sort-Stack.py | 1,584 | 4.125 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Sort%20Stack
"""
Write a function that takes in an array of integers representing a stack,
recursively sorts the stack in place (i.e., doesn't create a brand new array), and returns it.
The array must be treated as a stack, with the end of the array as the top of
the stack. Therefore, you're only allowed to
1. Pop elements from the top of the stack by removing elements from the end of
the array using the built-in .pop() method in your programming
language of choice.
2. Push elements to the top of the stack by appending elements to the end of
the array using the built-in .append() method in your
programming language of choice.
3. Peek at the element on top of the stack by accessing the last element in the
array.
You're not allowed to perform any other operations on the input array,
including accessing elements (except for the last element), moving elements,
etc.. You're also not allowed to use any other data structures, and your solution must be recursive.
Sample Input
stack = [-5, 2, -2, 4, 3, 1]
Sample Output
[-5, -2, 1, 2, 3, 4]
"""
# O(n^2) time | O(n) space
# where n is the length of the stack
def insertAtRightPosition(stack, val):
pass
def recursiveSorting(stack):
if len(stack) == 0:
return stack
topValue = stack.pop(-1)
recursiveSorting(stack)
insertAtRightPosition(stack, topValue)
def sortStack(stack):
return recursiveSorting(stack)
if __name__ == "__main__":
print(sortStack([-5, 2, -2, 4, 3, 1]))
| true |
454704723c91aaa38436e984d0a865a2c976bf16 | tahmid-tanzim/problem-solving | /Trees_and_Graphs/Binary Trees/__Right-Sibling-Tree.py | 1,842 | 4.1875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Right%20Sibling%20Tree
"""
Write a function that takes in a Binary Tree, transforms it into a Right Sibling Tree, and returns its root.
A Right Sibling Tree is obtained by making every node in a Binary Tree have
its right property point to its right sibling instead of its
right child. A node's right sibling is the node immediately to its right on
the same level or None / null if there is no node immediately to its right.
Note that once the transformation is complete, some nodes might no longer have
a node pointing to them. For example, in the sample output below, the node
with value 10 no longer has any inbound pointers and is effectively unreachable.
The transformation should be done in place, meaning that the original data
structure should be mutated (no new structure should be created).
Each BinaryTree node has an integer value, a
left child node, and a right child node. Children
nodes can either be BinaryTree nodes themselves or None / null.
Sample Input
tree = 1
/ \
2 3
/ \ / \
4 5 6 7
/ \ \ / / \
8 9 10 11 12 13
/
14
Sample Output
1 // the root node with value 1
/
2-----------3
/ /
4-----5-----6-----7
/ / /
8---9 10-11 12-13 // the node with value 10 no longer has a node pointing to it
/
14
"""
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# O(n) time | O(d) space
# where n is the number of nodes in the Binary Tree and d is the depth (height) of the Binary Tree
def rightSiblingTree(root):
pass
if __name__ == "__main__":
pass
| true |
b7f4391572eab18178ed397bc1b8ea51ea9ed7d7 | tahmid-tanzim/problem-solving | /Linked_Lists/__Node-Swap.py | 1,057 | 4.21875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Node%20Swap
"""
Write a function that takes in the head of a Singly Linked List, swaps every
pair of adjacent nodes in place (i.e., doesn't create a brand new list), and
returns its new head.
If the input Linked List has an odd number of nodes, its final node should remain the same.
Each LinkedList node has an integer value as well as
a next node pointing to the next node in the list or to
None / null if it's the tail of the list.
You can assume that the input Linked List will always have at least one node;
in other words, the head will never be None / null.
Sample Input
head = 0 -> 1 -> 2 -> 3 -> 4 -> 5 // the head node with value 0
Sample Output
1 -> 0 -> 3 -> 2 -> 5 -> 4 // the new head node with value 1
"""
# O(n) time | O(1) space
# where n is the number of nodes in the Linked List
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def nodeSwap(head):
return None
if __name__ == '__main__':
pass
| true |
a4962f58924124af332458eac342123774a77ba2 | tahmid-tanzim/problem-solving | /Trees_and_Graphs/Graphs/__Detect-Arbitrage.py | 1,826 | 4.53125 | 5 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Detect%20Arbitrage
"""
You're given a two-dimensional array (a matrix) of equal height and width that
represents the exchange rates of arbitrary currencies. The length of the array
is the number of currencies, and every currency can be converted to every
other currency. Each currency is represented by a row in the array, where
values in that row are the floating-point exchange rates between the row's
currency and all other currencies, as in the example below.
0:USD 1:CAD 2:GBP
0:USD [ 1.0, 1.27, 0.718]
1:CAD [ 0.74, 1.0, 0.56]
2:GBP [ 1.39, 1.77, 1.0]
In the matrix above, you can see that row 0 represents USD, which
means that row 0 contains the exchange rates for
1 USD to all other currencies. Since row
1 represents CAD, index 1 in the USD row contains
the exchange for 1 USD to CAD. The currency labels are listed
above to help you visualize the problem, but they won't actually be included
in any inputs and aren't relevant to solving this problem.
Write a function that returns a boolean representing whether an arbitrage
opportunity exists with the given exchange rates. An arbitrage occurs if you
can start with C units of one currency and execute a series of
exchanges that lead you to having more than C units of the same
currency you started with.
Note: currency exchange rates won't represent real-world exchange rates, and
there might be multiple ways to generate an arbitrage.
Sample Input
exchangeRates = [
[ 1.0, 0.8631, 0.5903],
[1.1586, 1.0, 0.6849],
[1.6939, 1.46, 1.0],
]
Sample Output
true
"""
# O(n^3) time | O(n^2) space
# where n is the number of currencies
def detectArbitrage(exchangeRates):
return False
if __name__ == "__main__":
print()
| true |
cd8f888f235ddf31bf6b8dcd869221dd07d72b4c | tahmid-tanzim/problem-solving | /Sorting/Merge-Sort.py | 2,132 | 4.4375 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Merge%20Sort
"""
Write a function that takes in an array of integers and returns a sorted
version of that array. Use the Merge Sort algorithm to sort the array.
If you're unfamiliar with Merge Sort, we recommend watching the Conceptual
Overview section of this question's video explanation before starting to code.
Sample Input
array = [8, 5, 2, 9, 5, 6, 3]
Sample Output
[2, 3, 5, 5, 6, 8, 9]
"""
def merge(leftSortedArray, rightSortedArray):
i = 0
j = 0
array = []
while i < len(leftSortedArray) and j < len(rightSortedArray):
if leftSortedArray[i] < rightSortedArray[j]:
array.append(leftSortedArray[i])
i += 1
elif leftSortedArray[i] > rightSortedArray[j]:
array.append(rightSortedArray[j])
j += 1
else:
array.append(leftSortedArray[i])
i += 1
array.append(rightSortedArray[j])
j += 1
while i < len(leftSortedArray):
array.append(leftSortedArray[i])
i += 1
while j < len(rightSortedArray):
array.append(rightSortedArray[j])
j += 1
return array
def mergeSortHelper(array, leftIdx, rightIdx):
if leftIdx > rightIdx:
return []
if leftIdx == rightIdx:
return [array[leftIdx]]
middleIdx = (leftIdx + rightIdx) // 2
leftSortedArray = mergeSortHelper(array, leftIdx, middleIdx)
rightSortedArray = mergeSortHelper(array, middleIdx + 1, rightIdx)
return merge(leftSortedArray, rightSortedArray)
# Best: O(nlog(n)) time | O(n) space - where n is the length of the input array
# Average: O(nlog(n)) time | O(n) space - where n is the length of the input array
# Worst: O(nlog(n)) time | O(n) space - where n is the length of the input array
def mergeSort(array):
return mergeSortHelper(array, 0, len(array) - 1)
if __name__ == '__main__':
# print(merge_sort([1, 5, 6, 3, 8, 4, 7, 2, 4]))
print(mergeSort([38, 27, 43, 3, 9, 82, 10]))
# print(merge_sort([1, 4, 5, 8, 2, 6, 7, 8, 9]))
# merge_sort([1, 5, 6, 3, 8, 4, 7])
| true |
125c1a7bd7101bab95075dd25ff88ede5b144faf | dgoon/ExercisesForProgrammers | /Chapter-2/2/count.py | 227 | 4.15625 | 4 | #! /usr/bin/env python3
import sys
print('What is the input string? ', end='')
sys.stdout.flush()
s = sys.stdin.readline().strip()
if len(s) == 0:
print('Empty string!')
else:
print('%s has %d characters.' % (s, len(s)))
| true |
18cf159378beeda3b07ae556acbaa45921672afd | ivan-ops/progAvanzada | /Ejercicio_85.py | 1,309 | 4.25 | 4 | #Ejercicio 85
#convertir un entero a un numero cardinal.
#las palabras como primero segundo tercero y cuarto, son llamados tambien como numeros cardinales
#en este ejercicio debe describir una funcion que tome un numero entero como su unico parametro y regrese una cadena de caracteres.
#con la palabra cardinal del numero entereo insertado.
#su funcion debe manejar los numeros entero entre el 1 y el 12
#y debe regresar su correspondiente en numero cardinal.
#Incluya un programa principal que demuestre su funcion desplegando cada entero del 1 al 12 y su numero cardinal
def cardinal (numero):
if numero == 1:
card = 'primero'
if numero == 2:
card = 'segundo'
if numero == 3:
card = 'tercero'
if numero == 4:
card = 'cuarto'
if numero == 5:
card = 'quinto'
if numero == 6:
card = 'sexto'
if numero == 7:
card = 'septimo'
if numero == 8:
card = 'octavo'
if numero == 9:
card = 'noveno'
if numero == 10:
card = 'decimo'
if numero == 11:
card = 'onceavo'
if numero == 12:
card = 'doceavo'
return card
entero = int(input('Inserte el numero entero: '))
num= cardinal(entero)
print('la numero entero en cardinal es: ',num) | false |
9c7728063cd8feefc5c9105f2f3826f5c3f19170 | im876/Python-Codes | /Codes/occurance_of_digit.py | 393 | 4.25 | 4 | #take user inputs
Number = int(input('Enter the Number :'))
Digit = (int(input('Enter the digit :')))
#initialize Strings
String1 = str()
String2 = str()
#typecast int to str
String1 = str(Number)
String2 = str(Digit)
#count and print the occurrence
#Count function will return int value
#so change it's type to string and concatenate it
print('Digit count is :',str(String1.count(String2)))
| true |
7b862c422c3649116c6aa3cf2d168661b2f47c57 | NurlybekOrynbekov/python-projects | /etc/tableView.py | 686 | 4.1875 | 4 | #! python3
# tableView.py - Форматирует переданный список, и выводит его в табличном виде
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(list):
widht = []
for row in list:
maxWidth = 0
for col in row:
maxWidth = max(maxWidth, len(col))
widht.append(maxWidth)
for y in range(len(list[0])):
text = ''
for x in range(len(list)):
text = text + list[x][y].rjust(widht[x]) + ' '
print(text)
printTable(tableData) | false |
817311e1832e80358d0055866cda4d9974a638c6 | shortdistance/workdir | /python 内置序列处理函数/testZip.py | 271 | 4.28125 | 4 | # -*-coding:utf-8-*-
'''
zip() in conjunction with the * operator can be used to unzip a list:
zip(x,y) 压缩, zip(*list) 带型号表示解压
'''
x = [1, 2, 3]
y = [4, 5, 6]
z = [5, 6, 7]
zipped = zip(x, y, z)
print zipped
x2, y2, z2 = zip(*zipped)
print x2, y2, z2
| false |
c012c84ecadc853a90bd9608d7e9eb2e12205ea8 | malladi2610/Python_programs | /Dictionaries/interchange_keys_elements.py | 1,118 | 4.25 | 4 | d = {} #The input Dictionary
d_ic = {} #Dictionary obtained after interchange
def dict_generate(x):
for i in range(x): #The loop used to create the input dictionary
d_keys = input("Enter the key value for the dictionary : ")
d_values = input("Enter the values for the dictionary : ")
d[d_keys] = d_values
return d
def dict_interchange():
d_keys = list(d.values()).copy() #The list of values of dictionary are assigned to the keys
d_values = list(d.keys()).copy() #The list of keys of dictionary are assigned to the values
for i in range(x):
d_keys_ic = d_keys[i] #The loop used to create the interchanged dictionary
d_values_ic = d_values[i]
d_ic[d_keys_ic] = d_values_ic
return d_ic
#Main Loop
x = int(input("Enter the no.of elements to be entered in the dictionary :"))
d_generated = dict_generate(x)
print("The input dictionary is :")
print(d_generated)
d_interchanged = dict_interchange()
print("The interchanged dictionary is :")
print(d_interchanged)
| true |
4bb3a680db9def453f45c2a2ae88b0b0adf5133a | malladi2610/Python_programs | /Assignment_programs/Assignment_1/Assignment2.4.py | 304 | 4.3125 | 4 | """
Write a program to print a pattern of numbers. The input should be the number of rows.
Example: Input:4
Output:
1
1 2
1 2 3
1 2 3 4
"""
input = int(input("Enter the number to generate the pattern : "))
for i in range(1,input+1):
for j in range(1,i+1):
print(j," ",end = "")
print() | true |
7804b927c81293aa67afcdfd9c49009994ff8f02 | malladi2610/Python_programs | /Strings/displayinglast10char.py | 236 | 4.3125 | 4 | """
Write the program to display the last 10 characters of the string
“Python Application Programming” on the console.
"""
x = input('Enter a string: ')
n = len(x)
y = x[-1:-10:-1]
print("The last 10 char of the string are : ",y) | true |
14203b17746f5858660083ed7924636ac0995591 | malladi2610/Python_programs | /Lists/frequency_of_elements.py | 423 | 4.4375 | 4 | """
Program to count the frequency of a given element in a list of numbers
"""
list = []
i = 0
count = 0
n = int(input("Enter the number of elements of the list"))
while i < n:
list.append(int(input("Enter the elements of the list :")))
i += 1
x = int(input("Enter the elements to get its frequency : "))
for i in list:
if(x == i):
count += 1
print("The frequency of the element ",x, " is ", count)
| true |
e36544d6aaa97846fb062aa4dd4dfa13e6e40e4a | fahimahammed/problem-solving-with-python | /32-reverse-string-function.py | 313 | 4.4375 | 4 | # 32. Write a function to reverse a string.
def rev_string(text):
rev_str = ""
if len(text) > 0:
for i in range(len(text)-1, -1, -1):
rev_str += text[i]
return rev_str
else:
return "This is empty string."
str1 = input("Enter a string: ")
print(rev_string(str1))
| true |
1ac888ad20e87c6e29c18ff9c25099b2e05f2120 | fahimahammed/problem-solving-with-python | /11-rectangle-area-perimeter.py | 414 | 4.625 | 5 | # 11. Write a python program that prints the perimeter of a rectangle to take its height and width as input.
width = float(input("Enter the width of the rectangle: "))
height = float(input("Enter the height of the rectangle: "))
area = width * height
perimeter = 2 * (width + height)
print("The area of the rectangle: {0: 0.2f}".format(area))
print("The perimeter of the rectangle: {0: 0.2f}".format(perimeter)) | true |
7c410cc1e0820b7b65c6b1726bbdef55a719a003 | fahimahammed/problem-solving-with-python | /9-triangle-area.py | 287 | 4.28125 | 4 | # 9. Write a python program that will accept the base and height of a triangle and compute the area.
base = float(input("Enter the base of the triangle:"))
height = float(input("Enter the height of the triangle:"))
area = 0.5 * base * height
print(f"The area of the triangle: {area}") | true |
1aa7edf4aec48c3ecc01543641c619b6ee4c19d9 | fahimahammed/problem-solving-with-python | /24-2D-array2.py | 490 | 4.3125 | 4 | # 24. Write a program which takes two digits m (row) and n (column) as input and generates a two-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. Note: i = 0, 1, ....., m-1 and j = 0, 1, ......, n-1
m = int(input("Input number of row: "))
n = int(input("Number of column: "))
multi_list = [ [0 for col in range(n)] for row in range(m)]
for row in range(m):
for col in range(n):
multi_list[row][col] = row*col
print(multi_list) | true |
9ac53ddb3db9ef9fe046fb833eb6807fa3518ce0 | fahimahammed/problem-solving-with-python | /15-string-reverse.py | 273 | 4.40625 | 4 | # 15. Write a program that accepts a word the user and reverse it.
word = input("Enter a string/word: ")
for i in range(len(word)-1, -1, -1):
print (word[i], end="")
# alternative
# word = input("Enter a string/word: ")
# rev_word = word[::-1]
# print (rev_word)
| true |
4276c42b834688b91429c1cbdbfa11507ccb56d1 | nirmalit/DATA-STRUCTURE-python | /SingleLinkedList.py | 1,552 | 4.15625 | 4 | class Node:
def __init__(self,val):
self.value = val
self.next = None
class Single:
def __init__(self,val):
self.head = val
def printlist(self):
self.l = self.head
while self.l is not None:
print(self.l.value)
self.l=self.l.next
def insert_at_begin(self,val):
e=Node(val)
e.next=self.head
self.head=e
def insert_at_end(self,val):
e=Node(val)
self.last=self.head
while self.last.next is not None:
self.last=self.last.next
self.last.next=e
def insert_at_index(self,val,index):
e=Node(val)
self.i=0
self.previous_node=self.head
while(self.i<index):
self.previous_node=self.previous_node.next
self.i+=1
e.next=self.previous_node.next
self.previous_node.next=e
def remove_element(self,val):
self.previous_node=self.head
if self.previous_node.value==val:
self.head=self.previous_node.next
return
while self.previous_node.next.value != val:
self.previous_node=self.previous_node.next
self.current=self.previous_node.next
self.previous_node.next=self.current.next
#creating node e1,e2,e3,e4
e1=Node("1")
e2=Node("2")
e3=Node("3")
e4=Node("4")
#linking nodes e1 -> e2 -> e3 -> e4
e1.next= e2
e2.next= e3
e3.next=e4
list1=Single(e1)
print("Before Insertion")
list1.printlist()
list1.remove_element("4")
print("After removing")
list1.printlist()
| false |
c7d26e9968dcb66683bb5d48617a34fd1f49fb34 | natalia-sitek/udemy-python-tutorial2 | /Methods_and_Functions/excersises.py | 1,162 | 4.21875 | 4 | def function():
print("Hello World")
function()
def myfunc(name):
print('Hello ' + name)
myfunc("Jose")
def is_greater(x, y):
return x > y
print(is_greater(2, 3))
def myfunction(a):
if a == True:
return "Hello"
elif a == False:
return "Goodbye"
print(myfunction(True))
def changing(x, y, z):
if z == True:
return x
else:
return y
def myfunct(a, b):
return a + b
def is_even(n):
if n % 2 == 0:
return True
else:
return False
# Define the function called myfunc that takes in arbitrary number of arguments and returns their sum
def myfunc(*args):
return sum(args)
# Define the function called argument that takes in arbitrary number of arguments and returns a list of arguments which are even
def argument(*args):
return ([x for x in args if x % 2 == 0])
def lesser_of_two_evens(a, b):
if a % 2 == 0 and b % 2 == 0:
if a < b:
result = a
else:
result = b
else:
if a > b:
result = a
else:
result = b
return (result)
print(lesser_of_two_evens(10, 2))
| true |
eb8394ddadc6edc22066ff17cce16489ac770b15 | guilhermepirani/think-python-2e | /exercises/cap04/mypolygon.py | 2,853 | 4.65625 | 5 | # Page 31: 4.3 Exercises
''' final code at 4.3.5
Make a more general version of circle called arc that takes an additional
parameter angle, which determines what fraction of a circle to draw.
The parameter angle is in units of degrees,
so when angle=360, arc should draw a complete circle.
'''
import math
import turtle
def square(t, lenght):
for _ in range(4):
t.fd(lenght)
t.lt(90)
def polygon(t, length, n):
for _ in range(n):
t.fd(length)
t.lt(360 / n)
def circle(t, r):
length = (2 * math.pi * r) / 120
polygon(t, length, 120)
def arc(t, r, angle):
length = 2 * math.pi * r * angle / 360
n = int(length / 3) + 1
n_length = length / n
n_angle = angle / n
for _ in range(n):
t.fd(n_length)
t.lt(n_angle)
if __name__ == '__main__':
bob = turtle.Turtle()
arc(bob, 50, 180)
turtle.mainloop()
# Step through to final code
''' code for 4.3.1
Write a function called square that takes a parameter named t,
which is a turtle.
It should use the turtle to draw a square.
Write a function call that passes bob as an argument to square,
and then run the program again.
def square(t):
for _ in range(4):
t.fd(100)
t.lt(90)
square(bob)
'''
''' code for 4.3.2
Add another parameter, named length, to square.
Modify the body so length of the sides is length,
and then modify the function call to provide a second argument.
Run the program again. Test your program with a range of values for length.
def square(t, lenght):
for _ in range(4):
t.fd(lenght)
t.lt(90)
square(bob, 100)
'''
''' code for 4.3.3
Make a copy of square and change the name to polygon.
Add another parameter named n and modify the body so it draws an n-sided
regular polygon.
Hint: The exterior angles of an n-sided regular polygon are 360/n degrees.
-- def polygon --
polygon(bob, 100, 10)
'''
''' code for 4.3.4
Write a function called circle that takes a turtle, t, and radius, r,
as parameters and that draws an approximate circle by calling polygon with an
appropriate length and number of sides.
Test your function with a range of values of r.
Hint: figure out the circumference of the circle
and make sure that length * n = circumference.
global --> PI = 3.14159265359
-- def circle --
circle(bob, 100)
'''
''' 4.12.1 Stack diagram
__main__ :
bob ---> turtle.Turtle()
radius ---> 100
polyline:
t ---> bob
n ---> 158
length ---> 3.9766995615060674
angle ---> 2.278481012658228
arc :
t ---> bob
r ---> 100
angle ---> 360
arc_length ---> 628.3185307179587
n ---> 158
step_length ---> 3.9766995615060674
step_angle ---> 2.278481012658228
circle :
t ---> bob
r ---> 100
''' | true |
63ae1c501ff338b576bc3ed70ee1b2b123e6f231 | guilhermepirani/think-python-2e | /exercises/cap05/ex-5-2.py | 1,458 | 4.46875 | 4 | '''Code for 5.14.2
Fermat’s Last Theorem says that there are no positive integers a, b,
and c such that:
a**n + b**n = c**n
for any values of n greater than 2.
Write a function named check_fermat that takes four parameters—a, b, c and n
—and checks to see if Fermat’s theorem holds.
If n is greater than 2 and a**n + b**n = c**n
the program should print, “Holy smokes, Fermat was wrong!”
Otherwise the program should print, “No, that doesn’t work.”
Write a function that prompts the user to input values for a, b, c and n,
converts them to integers, and uses check_fermat to check whether they
violate Fermat’s theorem.'''
def check_input(i):
if i.isalpha():
i = 0
return i
else:
return int(i)
def check_fermat():
'''Try inputs to check if they validate fermat's theorem'''
print("Calculate if: positives a**n + b**n = c**n when n > 2")
a = b = c = n = 0
while a <= 0:
a = input("Enter any number for a: ")
a = check_input(a)
while b <= 0:
b = input("Enter any number for b: ")
b = check_input(b)
while c <= 0:
c = input("Enter any number for c: ")
c = check_input(c)
while n <= 2:
n = input("Enter any number for n: ")
n = check_input(n)
abp_sum = a ** n + b ** n
if abp_sum == c ** n:
print(abp_sum, "and", c ** n, '!', "Holy smokes, Fermat was wrong!\n")
else:
print(abp_sum, "and", c ** n, '!', "No, that doesn’t work.\n")
check_fermat() | true |
5fb2d3114328cf17562d0cf581219c502318b4e4 | paige0701/algorithms-and-more | /projects/leetCode/easy/flipAndInvertImage.py | 664 | 4.125 | 4 | """
Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
"""
class Solution:
def flipAndInvertImage(self, A):
# for i in A:
# i.reverse()
# print(i)
# for index,val in enumerate(i):
# if i[index] == 0 :
# i[index] = 1
# else:
# i[index] =0
return [[i-1 for i in row[::-1]] for row in A]
if __name__ == '__main__':
solution = Solution()
print(solution.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]])) | false |
b094776c0a3d6bccb6a5f08896d3cd8d390f78b9 | muthoni12/python_dictionary | /dictionarytask.py | 1,791 | 4.21875 | 4 | '''
Given a list of dictionaries containing data such as productNmae, exclprice
passed to a function as a parameter, together with the tax rate.
Calculate the incl of each product.
Then print thier values.
incl = excl + vat
vat = excl * tax
e.g
product = [
{
"prodname" : "Milk",
"excl": 50
},
{
"prodname" : "Bread",
"excl": 40
}
]
output
milk 65
bread 55
'''
def calculateincl(products, rate):
incl = 0
for product in products:
vat = product["excl"] * rate
incl = product["excl"] + vat
print(product["prodname"] +" "+ str(incl))
calculateincl([
{
"prodname": "Milk",
"excl": 50
},
{
"prodname": "Milk",
"excl": 40
}
], 0.16)
'''
Given a list of dictionaries containing data such as productNmae, exclprice
passed to a function as a parameter, together with the tax rate.
Calculate the incl of each product.
Then return a list of dictionaries containing the product and their respective incl prices.
'''
def calculateincl(products, rate):
incl = {}
for product in products:
vat = product["excl"] * rate
incl = product["excl"] + vat
return {product["prodname"], incl}
calculateincl([
{
"prodname": "Milk",
"excl": 50
},
{
"prodname": "bread",
"excl": 40
}
], 0.16)
'''
def calculateincl(products, rate):
incl = {}
for product in products:
vat = product["excl"] * rate
incl = product["excl"] + vat
return {product["prodname"], incl}
P = [
{
"prodname": "Milk",
"excl": 50
},
{
"prodname": "bread",
"excl": 40
}
]
calculate(p, 0.16)
'''
| true |
1dc2d86b1240db1f91628d8d3acbe7a00c195a70 | MattSokol79/Python_Modules | /exception_handling.py | 843 | 4.4375 | 4 | # We will have a look at the practical use cases and implementation of try, except
# raise and finally
# we will create a variable to store file data using open()
# 1st Iteration
# try: # Use try block for a line of code where we know this will throw an error
# file = open("orders.text")
# except:
# print("Panic alert!")
try: # Use try block for a line of code where we know this will throw an error
file = open("orders.text")
except FileNotFoundError as errmsg: # Aliasing the erro
print("Alert something went wrong" + str(errmsg))
# if we still wanted the users to see the actual exception together with customised message
raise # raise will send back the actual exception i.e. FileNotFoundError
finally: # finally will execute regardles of the above conditions
print("Hope you had a good Customer experience") | true |
27fbb699b4d656f29113dbfa803aa1e7a8121b7c | manojnookala/20A95A0503_IICSE-A-python-lab-experiments | /Exp6.3.py | 785 | 4.125 | 4 | Sort the two lists
L1=[45,63,23,12,78]
L2=[12,90,72,-1]
Combine L1&L2 as single list and display the elements in the sorted order
#Dislay
L3=[-1,12,12,23,45,63,72,78,90]
Perform sorting on the list.....
Program
l1=[]
l2=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter element:"))
l1.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
d=int(input("Enter element:"))
l2.append(d)
new=l1+l2
new.sort()
print("Sorted list is:",new)
#output
Enter number of elements:5
Enter element:45
Enter element:63
Enter element:23
Enter element:12
Enter element:78
Enter number of elements:4
Enter element:12
Enter element:90
Enter element:72
Enter element:-1
Sorted list is: [-1, 12, 12, 23, 45, 63, 72, 78, 90]
>>>
| true |
6d88f10a97c6d25538438847a99efae1d0cb9380 | manojnookala/20A95A0503_IICSE-A-python-lab-experiments | /DictCreationSimple.py | 1,007 | 4.125 | 4 | #Dictionary to store branchcode->name
dict_ds={05:"CSE",12:"IT",03:"ECE",04:"MECH"}
print dict_ds
#type of data structure
print type(dict_ds)
#accessing elements from the dictionary
res=dict_ds[12] #dictionary_name[key]
print "At key 12 the value is {}" .format(res)
#New dictionary
#Key-Unique,value:Repeated
dict_ds1={05:"CSE",05:"CSE-A","Name":"manoj","Fname":"NVVSatyanarayana"}
print dict_ds1
#Modify the values from the dictionary
print "Old value is %s" %dict_ds1["Name"]#dictionary_name[key]
dict_ds1["Name"]="Devi"#dictionary_name[key]=NewValue
print "New value is %s" %dict_ds1["Name"]#manoj
#Add New Keys to dictionary?
#dict_ds1[key]=value
dict_ds1["Department"]="CSE"
print "New Dict After Adding Key"
print dict_ds1
...
OUTPUT:
{4: 'MECH', 3: 'ECE', 12: 'IT', 5: 'CSE'}
<type 'dict'>
At key 12 the value is IT
{5: 'CSE-A', 'Fname': 'manoj', 'Name': 'manoj'}
Old value is manoj
New value is manu
New Dict After Adding Key
{'Department': 'CSE', 5: 'CSE-A', 'Fname': 'manu', 'Name': 'manoj'}
'''
| false |
ea73d93111c62459ded64da672161f5252351988 | AdityaDale/Word-Phrase-Alignment | /parser-modification/list-processing1.py | 364 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
my_list = [[[["This"],["desire"]],[["dates"],[["back"]],[["to"],[[[[["at"],["least"]]],["the"],["time"]],[["of"],[["ancient"],["Greece"]]]]]],["."]]]
def print_list(l):
for i in l:
if type(i) is list:
if(len(i) > 1):
print(i)
print_list(i)
print_list(my_list)
| false |
6853a6e911ee6500595b74d9fe859527437c5687 | samuelkb/PythonPath | /range_enumerate.py | 1,551 | 4.28125 | 4 | # Coding question fizz_buzz
def fizz_buzz(numbers):
'''
:param numbers: The list of numbers
:type numbers: list
Given a list of integers:
1. Replace all integers that are evenly divisible by 3 with "fizz"
2. Replace all integers divisible by 5 with "buzz"
3. Replace all integers divisible by both 3 and 5 with "fizzbuzz"
>>> numbers = [45, 22, 14, 65, 97, 72]
>>> fizz_buzz(numbers)
>>> numbers
['fizzbuzz', 22, 14, 'buzz', 97, 'fizz']
'''
# Range way
#for i in range(len(numbers)):
# num = numbers[i]
# if num % 3 == 0:
# numbers[i] = "fizz"
# if num % 5 == 0:
# numbers[i] = "buzz"
# if num % 3 == 0 and num % 5 == 0:
# numbers[i] = "fizzbuzz"
# We will use the module doctest with the command `python3 -m doctest range_enumerate.py`
# That will be looking at your doc string took tests, and run them and compare the output
# enumerate() is a fuction that takes in iterable and iterates through that iterable
# and returns tuples where the first element of the tuple is the index and the second
# element is the value.
# [tup for tup in enumerate([1, 2, 3])] -> [(0, 1), (1, 2), (2, 3)]
# [tup for tup in enumerate([1, 2, 3], start=10)] -> [(10, 1), (11, 2), (12, 3)]
for i, num in enumerate(numbers):
if num % 3 == 0:
numbers[i] = "fizz"
if num % 5 == 0:
numbers[i] = "buzz"
if num % 3 == 0 and num % 5 == 0:
numbers[i] = "fizzbuzz" | true |
522dad05bfae5a45a23b0d720c99dc9bafda1d95 | cburleso/Cybersecurity_Login_System | /database_demo.py | 2,446 | 4.71875 | 5 | """
Example SQLite Python Database
==============================
Experiment with the functions below to understand how the
database is created, data is inserted, and data is retrieved
"""
import sqlite3
from datetime import datetime
def create_db():
""" Create table 'plants' in 'plant' database """
try:
conn = sqlite3.connect('plant.db')
c = conn.cursor()
c.execute('''CREATE TABLE plants
(
name text,
date_planted text,
last_watered text,
nutrients_used text
)''')
conn.commit()
return True
except BaseException:
return False
finally:
if c is not None:
c.close()
if conn is not None:
conn.close()
def get_date():
""" Generate timestamp for data inserts """
d = datetime.now()
return d.strftime("%m/%d/%Y, %H:%M:%S")
def add_plant():
""" Example data insert into plants table """
new_plant_name = str(input("Please enter the name of your plant: ")) # Need exception handling
new_plant_date = str(get_date())
last_watered = str(get_date())
nutrients_used = str(input("Did you use nutrients? y or n: ")) # Need to create valid input check
data_to_insert = [(new_plant_name, new_plant_date, last_watered, nutrients_used)]
try:
conn = sqlite3.connect('plant.db')
c = conn.cursor()
c.executemany("INSERT INTO plants VALUES (?, ?, ?, ?)", data_to_insert)
conn.commit()
except sqlite3.IntegrityError:
print("Error. Tried to add duplicate record!")
else:
print("Success")
finally:
if c is not None:
c.close()
if conn is not None:
conn.close()
def query_db():
""" Display all records in the plants table """
try:
conn = sqlite3.connect('plant.db')
c = conn.cursor()
for row in c.execute("SELECT * FROM plants"):
print(row)
except sqlite3.DatabaseError:
print("Error. Could not retrieve data.")
finally:
if c is not None:
c.close()
if conn is not None:
conn.close()
create_db() # Run create_db function first time to create the database
add_plant() # Add a plant to the database (calling multiple times will add additional plants)
query_db() # View all data stored in the
| true |
277c015c89a057a15b2b328394b7c112fbc04da8 | ameliawilson/March-Madness | /first_connection.py | 1,245 | 4.25 | 4 | ################################################
# March Madness
# Day 1 - Making a Connection
#
# Create a connection to a webpage
# Print out what the servers says back to you
################################################
import requests
import sys
def MakeConnection(URL):
'''URL: string that is a website URL
returns response object
Make request to spcified URL using python requests module'''
name = 'Amelia'
email = 'ameliawilson17@gmail.com'
user_agent = 'python-requests/2.18.4 (Compatible; {}; mailto:{})'.format(name, email)
# Your header should include your info
myHeader = {'User-Agent': user_agent}
# Submit a get request to the URL, return Response Object
r = requests.get(URL, headers=myHeader)
# If the status code is not 200 something went wrong
# print Rejected and exit the program
if r.status_code != 200:
print('Rejected')
sys.exit()
# return the response object
return r
# Website you want to make a request to
URL = 'https://www.google.com'
# Get the response object for your URL/robots.txt
response = MakeConnection(URL + '/robots.txt')
# Print out the text of the response object
#print(response.status_code)
print(response.text) | true |
d24e017ce0c4dc509e0d04abef2da1fc6495b9a5 | hima-cmd/hello | /src/Chap4/pizzas.py | 403 | 4.1875 | 4 | #using for loop
pizzas_names = ['veggie','chicken','spicy veggie']
for pizzas in pizzas_names:
print("I like "+pizzas+" pizza.")
#message = f"I like {pizzas}"
#print(message)
print("I really like pizzas.")
animal_names = ['dog','cat','fish','hamster']
for pets in animal_names:
print("A "+pets+" would make a good pet.")
print("Any of these animals would make a great pet!")
| true |
eaf1b3d1f50cbaa6f0f03452054c3046b456484b | hima-cmd/hello | /src/Chap6/looping.py | 303 | 4.34375 | 4 | #looping through dictionaries
rivers = {
'egypt' : 'nile',
'india': 'ganga',
'china': 'yantze',
}
for country, river in rivers.items():
print("\nCountry : "+country)
print("River : " +river)
print(" The "+
river + " flows through "+
country)
| false |
18b0fe0064ee558b5d28d3fb640441be010062c2 | hima-cmd/hello | /src/Chap7/modulus.py | 461 | 4.5 | 4 | '''
input() function takes one argument: the prompt, or instructions,
that we want to display to the user so they know what to do.
'''
# modulo operator (%),
# which divides one number by another number and returns the remainder:
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " is odd.") | true |
e39406fb8b066d24e00840b2cc460d8b38fff0d7 | taylerhughes/Euler | /Euler_Problem_1.py | 814 | 4.15625 | 4 | """
Multiples of 3 and 5
Problem 1
https://projecteuler.net/problem=1
Tue Jan 20 20:09:24 2015
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9. The sum
of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
container = []
highest_value = 1000
def get_multiples(multiple, highest_value):
for i in range(0, highest_value, multiple):
if i != 0:
print "Adding %s to the list." % (i)
container.append(i)
# Remove duplicates
def remove_duplicates(values):
output = []
seen = set()
for x in values:
if x not in seen:
output.append(x)
seen.add(x)
return output
get_multiples(3, highest_value)
get_multiples(5, highest_value)
result = remove_duplicates(container)
print container
print "Result %s" % sum(result) | true |
655c389034bfecdc84ccd2c5dfab22da4e1f323e | arshia-puri9/assignment-2and-3 | /assignment2/assign2.py | 538 | 4.28125 | 4 | #answer1: To print anything on screen:
print('Let\'s start Python')
#answer2: To Join two strings using +:
a='hello'
b='world'
print(a+b)
# Or you can simply:
print('hello'+'world')
#answer3:
x=input("enter value for x\n")
y=input("enter value for y\n")
z=input("enter value for z\n")
print("Value of x is",x)
print("Value of y is",y)
print("Value of z is",z)
#answer4:
print('"Let\'s get started"')
#answer5:
#answer6:
pi=3.14
radius=float(input("enter radius\n"))
area=pi*radius*radius
print("Area of the circle is",area)
| true |
db446e1ca49ac6fbf9158b5c07da6d0b0244c4b7 | Jhouteddy/python_learn | /datatype.py | 447 | 4.21875 | 4 | # 資料: 程式的基本單位
# 數字
3456
3.5
# 字串
"測試中文"
"hello world"
# 布林值
True
False
# 有順序、可動的列表 List
[3, 4, 5]
["hello", "world"]
# 有順序、不可動的列表 Tuple
(3, 4, 5)
("hello", "world")
# 集合 Set
{3, 4, 5}
{"hello", "world"}
# 字典 Dictionary
{"apple": "蘋果", "data": "資料"}
# 變數: 用來儲存資料的自訂名稱
# 變數名稱=資料
x = 3
# print(資料)
print(x)
| false |
7c6458d82de39bc9b029e003efc3d48fc46c8d6c | darkares23/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 368 | 4.15625 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
if matrix == [[]]:
print()
for row in range(len(matrix)):
for column in range(len(matrix[row])):
if column < len(matrix[row]) - 1:
print("{:d}".format(matrix[row][column]), end=' ')
else:
print("{:d}".format(matrix[row][column]))
| false |
a94b19b61e99f8d64a63d99d51bfaac8f0565b29 | pratik-practice-work/Code_Practice | /Python_Scripting/2.Dictionaries.py | 1,237 | 4.46875 | 4 | ###########################################################################################################################
#
# A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with
# curly brackets, and they have keys anvalues.
# Functions for Dictionary : dict(),del(),len()
#
###########################################################################################################################
#!/usr/bin/env python
print('\n')
Dictionary = {"apple": "green","banana": "yellow","cherry": "red"}
print ("1. Dictionary = ", Dictionary)
Dictionary["apple"] = "red"
print ("2. Dictionary = ", Dictionary)
## It is possible to update the dictionary by adding new index
Dictionary["guava"] = "green"
print ("3. Dictionary = ", Dictionary)
## As well as deleting is done using del() function
del(Dictionary["guava"])
print ("4. Dictionary = ", Dictionary)
## dict() is constructor for Dictionary can be invoked for instantiation
Dictionary_2 = dict(apple="green", banana="yellow", cherry="red")
print ("5. Dictionary_2 = ", Dictionary_2)
## To Print Length of the Dictionary len() function is used
print ("Length of Dictionart_2 is : ", len(Dictionary_2))
print('\n')
| true |
ad0248e7c4c153cd1a00e2eaab4cfa092a076898 | CarlosDaniel0/atividades_tds | /Lista1 Fábio/questao32.py | 321 | 4.125 | 4 | #Diferença entre o número e seu inverso
print('')
numero = int(input('Digite um valor de 3 digitos: '))
c = (numero // 100 % 10)
d = (numero // 10 % 10) * 10
u = (numero // 1 % 10) * 100
inverso = u + d + c
soma = numero - inverso
print('')
print('O valor digitado corresponde a diferença com o inverso de:', soma)
| false |
ca68177e1840f0f252d196fe635ee3a71400b807 | ibrahimBeladi/ICS490 | /HW3/count_word.py | 1,091 | 4.15625 | 4 | #************************File #2**************************#
# This file is used to find the number of reviews #
# containing a specific word. It reads the file #
# "all-words.csv" and count the number of one's in #
# The column contains_{word}. #
# #
#*********************************************************#
import pandas
def count_word(word):
print 'Reading Dataset...'
file_name = 'word-count/all-words.csv'
try:
data_frame = pandas.read_csv(file_name)
is_contain_col = data_frame['contains_'+word]
count = 0
print 'Counting the occurrence of the word "{}"...'.format(word)
for x in is_contain_col:
if x == 1:
count += 1
print 'The word "{}" has appeared in {} reviews.'.format(word,count)
except Exception:
print 'Unable to open CSV file. Check that the file "{}" is exist.'.format(file_name)
if __name__ == '__main__':
count_word('perfect')
| true |
72d5958b0b9f4b834d9acf7322c8d2e7aa685056 | NatalieP-J/python | /jplephem/__init__.py | 2,811 | 4.15625 | 4 | """Use a JPL planetary ephemeris to predict planet positions.
This package uses a Jet Propulsion Laboratory ephemeris to predict the
position and velocity of a planet, or the magnitude and rate-of-change
of the Earth's nutation or the Moon's libration. Its only dependency is
``NumPy``. To take the smallest and most convenient ephemeris as an
example, you can install this package alongside ephemeris DE421 with
these commands::
pip install jplephem
pip install de421
Loading DE421 and computing a position require one line of Python each,
given a barycentric dynamical time expressed as a Julian date::
import de421
from jplephem import Ephemeris
eph = Ephemeris(de421)
x, y, z = eph.position('mars', 2444391.5) # 1980.06.01
The result of calling ``position()`` is a 3-element NumPy array giving
the planet's position in the solar system in kilometers along the three
axes of the ICRF (a more precise reference frame than J2000 but oriented
in the same direction). If you also want to know the planet's velocity,
call ``compute()`` instead::
x, y, z, dx, dy, dz = eph.compute('mars', 2444391.5)
Velocities are returned as kilometers per day.
Both of these methods will also accept a NumPy array, which is the most
efficient way of computing a series of positions or velocities. For
example, the position of Mars at each midnight over an entire year can
be computed with::
import numpy as np
t0 = 2444391.5
t = np.arange(t0, t0 + 366.0, 1.0)
x, y, z = eph.position('mars', 2444391.5)
You will find that ``x``, ``y``, and ``z`` in this case are each a NumPy
array of the same length as your input ``t``.
The string that you provide to ``e.compute()``, like ``'mars'`` in the
example above, actually names the data file that you want loaded from
the ephemeris package. To see the list of data files that an ephemeris
provides, call its ``names()`` method. Most of the ephemerides provide
thirteen data sets::
earthmoon mercury pluto venus
jupiter moon saturn
librations neptune sun
mars nutations uranus
Each ephemeris covers a specific range of dates, beyond which it cannot
provide reliable predictions of each planet's position. These limits
are available as attributes of the ephemeris::
t0, t1 = eph.jalpha, eph.jomega
The ephemerides currently available as Python packages (the following
links explain the differences between them) are:
* `DE405 <http://pypi.python.org/pypi/de405>`_ (May 1997)
* `DE406 <http://pypi.python.org/pypi/de406>`_ (May 1997)
* `DE421 <http://pypi.python.org/pypi/de421>`_ (February 2008)
* `DE422 <http://pypi.python.org/pypi/de422>`_ (September 2009)
* `DE423 <http://pypi.python.org/pypi/de423>`_ (February 2010)
"""
from .ephem import Ephemeris, DateError
| true |
00f4a5c42d0a09e196b1be5f11b7dc7be24b7bfb | LourencoNeto/ces22 | /Aula 2/cap8/Exercicio_8_19_10.py | 1,598 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 6 17:52:27 2018
@author: Lourenço Neto
"""
import sys
def reverse(word):
"""Return the string word reversed"""
start = -2 #Since we will pick the last letter separatly, the start of pick the letter in the reverse direction at the penultimate letter
end = -1 #And it end in the letter before the penultimate. Setting this, we should carry the "window" that check the current letter until its found the first one
reversed_word = ""
reversed_word += word[-1:] #First of all, we pick the last letter of the string
for i in range(len(word) - 1): #Then, pass for each letter of the word from the right to the left, pick the letter and add to the reversed_word variable
reversed_word += word[start:end]
start -= 1
end -= 1
return reversed_word
def is_palindrome(word):
"""Return if the string word is a palindrome"""
reversed_word = reverse(word)
if(reversed_word == word):
return True
else:
return False
def test(did_pass):
""" Print the result of a test """
linenum = sys._getframe(1).f_lineno #Get the caller's line number
if did_pass:
msg = "Test at line {0} ok." .format(linenum)
else:
msg = ("Test at line {0} FAILED. ".format(linenum))
print(msg)
def test_suite(): #Few tests of "is_palindrome" function
test(is_palindrome("abba"))
test(not is_palindrome("abab"))
test(is_palindrome("tenet"))
test(not is_palindrome("banana"))
test(is_palindrome("straw warts"))
test(is_palindrome("a"))
test_suite()
| true |
1d5138ec6b9f356f024209cb579baef6d81d8caa | billjasi/My_GitHub_Project | /split3.py | 463 | 4.34375 | 4 | #The split() method can be called with no arguments.
#In this case, split() uses spaces as the delimiter.
#Please notice that one or more spaces are treated the same.
#This split form handles sequences of whitespace.
#Program that uses split, no arguments: Python
# Input string.
# ... Irregular number of spaces between words.
s = "One two three"
# Call split with no arguments.
words = s.split()
# Display results.
for word in words:
print(word) | true |
1c9d706b91fd4ff9babef66c0ffc7c832d2551a6 | Chrisvimu/CS50AssignmentsAndStudy | /pset6/mario/less/mario.py | 409 | 4.125 | 4 | from cs50 import get_int
# Declaring pyramid height with 0
pyramid = 0
# Loops asking for user input until an int betwen 1 and 8 is provided.
while(pyramid < 1 or pyramid > 8):
pyramid = get_int("Height: ")
# prints # and spaces depending of the height of the pyramid
for row in range(pyramid):
gatos = row + 1
spaces = pyramid - gatos
print(" " * spaces, end="")
print("#" * gatos)
| true |
f17f8dd9021198fb497b3d1874671440846fc555 | aditya8081/Project-Euler | /problem14.py | 1,134 | 4.25 | 4 | # There are too many iterations to test by brute force
# instead, we will create a set of iterations to hit 1 for every number
# we start like this
cache = {2:1} # because the sequence for 2 will converge after 1 step
def Collatz(number): # this defines the Collatz operation
if number not in cache: # if the number cache does not exist yet
if number%2:# if the number is odd,
cache[number] = 1 + Collatz(3*number + 1) # then the sequences it will take equals one plus the next number
else: # if it is even
cache[number] = 1 + Collatz(number/2) # then the sequance equals 1 + half of the number
return cache[number] # once we have defined it, this is the number of steps it will take
lChain = 0 # we start with the longest chain as 0
num = 0 # the number that is the answer is 0 as well
for x in range(3,1000000): # for 3 to one million
check = Collatz(x) # we make a check value for the Collatz length of x
if check > lChain: # if the length is greater
lChain = check # we create a new length
num = x # and x becomes the new answer
print num
| true |
efc2000a01cfc5a0f95b9d773e36eafad01674f4 | MarcoMen-Temp/CollatzSeq | /Week3 -Exercise.py | 630 | 4.28125 | 4 | #Marco Men's week 3-Collatz Sequence
raw_input = int(input('Enter a number, please:'))
number = raw_input
steps = 0 #<--- Loop begins here
while number > 1:
if number % 2 == 0:
number = number / 2
print(number) #<--- For even numbers,print
else: #<---Non-even=Odd
number = number * 3 + 1
print(number) #<--For odd numbers,print
steps += 1 #<---add 1 after the loop,otherwise it will continue running continuously
#{}.format (steps)) adapted from: 'https://docs.python.org/3/library/stdtypes.html#str.format'
print('%s' % (raw_input) ,'took {}'.format(steps)) , 'steps'
| true |
c6c425df00f1f72e89c6078f4206523f58565543 | AlfredoGuadalupe/Lab-EDA-1-Practica-9 | /Funciones2.py | 352 | 4.15625 | 4 | #Definiendo una función que regresa el cuadrado de un número
def cuadrado(x):
return x**2
x = 5
#La función format() sirve para convertir los parámetros que recibe,
#en cadenas; éstos valores son reemplazadas por las llaves de la cadena.
print("El cuadrado de {} es {}".format(x, cuadrado(x)))
#La función cuadrado() regresa un valor
| false |
8c25b4d2b65840e8411a61dac6a76a19bafe194d | MisterDecember/adder | /Adder/Arithmetic.py | 660 | 4.15625 | 4 | #!/usr/bin/env python3
x = 5
y = 3
print("Now let's get mathematical!")
print()
print('Here is your the x ({}) / y ({}) looks like since Python 3'.format(x, y))
z = x / y
print(f'result is {z}')
print('______________________________________')
print()
# *********************************
print('to get no remainder use double slash x ({}) // y ({}) '.format(x, y))
z = x // y
print(f'result is {z}')
print('______________________________________')
print()
# *********************************
print('to get ONLY remainder use percentile x ({}) % y ({}) '.format(x, y))
z = x % y
print(f'result is {z}')
print('______________________________________')
print() | true |
2758e4466cd4be6f78f98b9132f2ba0e9bddd4d5 | Bjcurty/PycharmProjects | /Python-Refresher/12_list_comprehension/code.py | 572 | 4.1875 | 4 | # List comprehension allows us to create new lists from old lists
# Pretty cool stuff
# numbers = [1, 3, 5]
# doubled = [x * 2 for x in numbers]
#
# # antiquated
# # for num in numbers:
# # doubled.append(num * 2)
#
# print(doubled)
friends = ["Rolf", "Sam", "Samantha", "Saurabh", "Jen"]
starts_s = [friend for friend in friends if friend.startswith("S")]
# for friend in friends:
# if friend.startswith("S"):
# starts_s.append(friend)
print(friends)
print(starts_s)
print(friends is starts_s)
print("friends:", id(friends), "starts_s", id(starts_s))
| true |
e200f41e2929c1689160c41c54241a319c153117 | Bjcurty/PycharmProjects | /Python-Refresher/27_class_composition/code.py | 921 | 4.625 | 5 | # Composition is a counterpart to inheritance that is used to build out classes that use others
# More used than inheritance
class BookShelf:
def __init__(self, *books):
# def __init__(self, quantity):
self.books = books
def __str__(self):
return f"BookShelf with {len(self.books)} books."
# shelf = BookShelf(300)
# print(shelf)
# Even though we can inherit from BookShelf, it's probably not best to do so as the quantity variable isn't
# needed. This is why inheritance is not so useful.
# Composition is for the thought: 'A BookShelf is composed of many books'
# class Book(BookShelf):
class Book:
# def __init__(self, name, quantity):
def __init__(self, name):
# super().__init__(quantity)
self.name = name
def __str__(self):
return f"Book {self.name}"
book = Book("Harry Potter")
book2 = Book("Python 101")
shelf = BookShelf(book, book2)
print(shelf) | true |
472f8f6dbba0f89c602fd1e11885c41db8a5fe54 | glaswasser/30DaysOfCode_Python | /Day_9_Recursion_3 | 1,346 | 4.125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(n):
if n == 1:
return(1)
else:
# create a list for the numbers to multiply
number = []
for i in reversed(range(1, n+1)):
number.append(i)
# now multiply all items of that list:
# number[1]*number[1+1]*number[1+2...]
result = 1
for j in range(0, len(number)):
try:
# what it should do:
print(number[j], "times", number[j+1])
except IndexError:
break
# I don't know why the following works, but it works
result = result * number[0+j]
return(result)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
# The open function opens a file and gives you a file object used to access the file's contents according to the specified modes.
#The "w" mode supplied in your example opens a file for reading, discarding any data previously in that file.
#The os.environ is used to get the environmental variables.
# https://www.reddit.com/r/learnpython/comments/99fktz/came_across_this_in_hackerrank/
n = int(input())
result = factorial(n)
fptr.write(str(result) + '\n')
fptr.close()
| true |
50b0974a7c8c0c97c2825390afd0eee024704c46 | nasumilu-owner/cop2002 | /Project 3/ml_homes.py | 1,736 | 4.3125 | 4 | #!/usr/bin/env python3
# Michael Lucas
# COP2002.054
# 2020-1-12
# Project 3 - Real Estate Values
def main():
print('\tReal Estate Values')
print('*' * 35)
home_values = get_values()
if len(home_values) != 0 :
print('*' * 35)
print('Prices of homes in your area:')
print(home_values)
print('*' * 35)
print(f'The median value is $ {median_value(home_values)}')
print(f'The average sale price is $ {average_value(home_values)}')
print(f'The minimum sale price is $ {min(home_values)}')
print(f'The maximum sale price is $ {max(home_values)}')
else :
print('No home values were inputed, thank you!')
def average_value(values):
'''Calculates the average value from an array of values.'''
return sum(values)/len(values)
def median_value(values):
'''Calculates the median value from an array of values.'''
length = len(values)
#median value for odd number of values inputted
if(length % 2 == 1):
return values[ int((length + 1)/2) - 1 ]
#median value for even number of values inputted
return (values[ int((length/2) - 1) ] + values[int((length/2))]) / 2
def get_values():
'''Gets an array of home prices from standard input.'''
values = []
value = get_value()
while value != -99 :
values.append(value)
value = get_value()
values.sort()
return values
def get_value():
'''Gets a valid home value'''
value = None
while value is None:
try:
value = float(input('Enter cost of one home or -99 to quit: '))
except ValueError:
print('Try again!', end=' ')
return value
if __name__ == "__main__":
main() | true |
4de875ac13c9eca13003061e104819cb0d27b1d0 | mikegoescoding/CodeWars-Kata | /python/8-kyu/returnNegative-8kyu.py | 1,009 | 4.59375 | 5 | # Return Negative
# 8kyu
'''
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Example:
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
Notes:
The number can be negative already, in which case no change is required.
Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense.
'''
# def make_negative(number):
# if number > 0:
# return -number
# elif number == 0:
# return number
# else:
# return number
# ANOTHER SOLUTION USING abs(number) / -abs(number)
def make_negative(number):
if number <= 0:
return number
else:
return -abs(number)
print(make_negative(42))
print(make_negative(0))
print(make_negative(-24))
print(make_negative(21))
print(make_negative(0))
print(make_negative(-33))
print(make_negative(-99))
print(make_negative(0))
print(make_negative(-1))
print(make_negative(8)) | true |
b4f70f022dcbecbd07394cad78a1015ea1921be5 | mikegoescoding/CodeWars-Kata | /python/7-kyu/shortestWord-7kyu.py | 804 | 4.3125 | 4 | # SHORTEST WORD
# 7KYU
"""
x Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
"""
# # 1
# def find_short(s):
# words = s.split(' ')
# words.sort(key=len)
# return len(words[0])
# # 2
# def find_short(s):
# lengths = []
# for word in s.split(" "):
# lengths.append(len(word))
# return min(lengths)
# # 3
# def find_short(s):
# return min(len(x) for x in s.split())
# 4
def find_short(s):
s = s.split() # splits the string into a list of individual words
l = min(s, key = len) # finds the shortest string in the list
return len(l) # returns shortest word length
print(find_short("bitcoin take over the world maybe who knows perhaps")) | true |
1dc19c1b2dd1f970caf9f6a47fe20b7e7febcd8e | salam1416/100DaysOfCode | /day64.py | 369 | 4.3125 | 4 | # Python Try-Except
try:
print('a')
except NameError: # if this specific exception occured
print('a name-error exception occured')
except: # another exception occured
print('another exception occured')
else: # will print when no error is catched
print('no exceptions! ')
finally: #will happend regardless if there's exception or not
print('anyway ') | true |
3df1082b6f8774ad647076daf854b8866ca41813 | salam1416/100DaysOfCode | /day15.py | 422 | 4.25 | 4 | # Python Lists 3
# list methods
a = [1,2,3,4,5,6]
print(len(a)) # length of list
a.append(7) # adding an item
print(a)
a.insert(2, 'the new item')
print(a)
a.remove(1) # removing an item
print(a)
a.pop() # remove the last item
print(a)
a.clear() # clear the whole list
print(a)
a = [1,2,4,5,6,7]
b = a.copy() # copying a list
b.append(8)
print(a, b)
newlist = [] # list constructor
newlist2 = list() # another constructor
| true |
f9cfc9f446a322b794823cac7423e6ae5da2bb0d | salam1416/100DaysOfCode | /day66.py | 367 | 4.25 | 4 | # Python string formatting 2
price = 49
itemno = 567
quanitity = 3
myorder = 'I want {0} pieces of item number {1} for {2:.2f} dollars'
print(myorder.format(quanitity, itemno, price))
# another example
age = 36
name = 'John'
txt = 'His name is {1}. {1} is {0} years old'
print(txt.format(age, name)) # interesting
print("my name is {name}".format(name = 'salam'))
| true |
34f887ad79ec5cc6ade82b36d674ccdb02ff2caa | salam1416/100DaysOfCode | /day34.py | 693 | 4.125 | 4 | # Python Function 2
def aFun(nums):
for i in nums:
print(i)
N = [3,5,2,5,29,21]
aFun(N)
# you could specify the input of a function
def aFun2(num1, num2, num3):
return num1+num2*num3
print(aFun2(num2 = 5, num3 = 9, num1 = 43))
# unlimited input
def aFun3(*kids):
print('The youngest child is '+ kids[2])
aFun3('ali', 'ahmed', 'moh', 'hadi') # it took the third item
# however, all items must be of the same type
# Recursion
# be careful not run into infinite loops
def tri_recursion(k):
if k>0:
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
print('\n Recursion Example Results ')
tri_recursion(6) | true |
721e042907e6bc18b39d1078e2d88d0c34f7f38c | halimahbukirwa/Python-Statements-Test | /number_six.py | 241 | 4.25 | 4 | # Use List Comprehension to create a list of the first letters of every word in the string below:
st = 'Create a list of the first letters of every word in this string'
lst = [word[0] for word in st.split() if len(word)%2 == 0]
print(lst) | true |
4b169422db4655c3cfa2bfddbccb0f088d51ba11 | frey-norden/p3-spec | /punc_strip.py | 922 | 4.1875 | 4 |
def punctuation_stripper(s):
''' takes a string s and strips the puncs
returns a new string of only letters '''
punctuation = '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
# punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
# alternative is list above: punctuation_chars --> both work based on preference
new_string = ''
for letter in s:
if letter not in punctuation:
new_string += letter
return new_string
def get_pos(s):
''' takes a string s and determines if positive connotation
returns a positive int for how many words are +
'''
s.lower()
wrds = s.split()
# list of positive words to use
positive_words = []
with open("positive_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
positive_words.append(lin.strip())
if s in pos_f:
| false |
694060764d8fdddb2dbe5531b751c7125586f140 | vanhung1234/vanhung1234.github.io | /page_203_project_03.py | 1,027 | 4.46875 | 4 | """
Author: Mai Văn Hùng
Date: 24/10/2021
Program: Elena complains that the recursive newton function in Project 2 includes an extra
argument for the estimate. The function’s users should not have to provide this
value, which is always the same, when they call this function. Modify the definition of the function so that it uses a keyword argument with the appropriate
default value, and call the function without a second argument to demonstrate
that it solves this problem
Solution:
....
"""
import math
tolerance = 0.000001
def newton(x, estimate=1):
difference = abs(x - estimate ** 2)
if difference <= tolerance:
return estimate
else:
return newton(x, (estimate + x / estimate /2))
def main():
while True:
x = input("Enter a positive number or enter/return to exit:")
if x == "":
break
x = float(x)
print("The program's estimate is: ", newton(x))
print("Python's estimate is ", math.sqrt(x))
main()
| true |
cd5b5e78ea29c95d36374f2c5655412aff051d99 | vanhung1234/vanhung1234.github.io | /page_199_exercise_01.py | 340 | 4.375 | 4 | """
Author: Mai Văn Hùng
Date: 24/10/2021
Program: Write the code for a mapping that generates a list of the absolute values of the numbers in a list named numbers.
Solution:
....
"""
number = [1, -2, 3, -4, -5]
print("The original list is : " + str(number))
res = list(map(abs, number))
print("Absolute value list : " + str(res)) | true |
94a690f032c7e4c4291545f458977e58d008c94e | gridscaleinc/Learning-Python | /domanthan/Less005/Less005.py | 927 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# What we learn here: How to print, for loop controls.
class Magnifier :
def observe(self, obj):
print("----------- Start Observing.......")
print("----------- type:", type(obj))
print("----------- id:", id(obj))
print("----------- is function?:", callable(obj))
print("----------- vars:", vars(type(obj)))
print("<<<<<<<<<<< End Observing")
print()
class Abc:
name = "Abc"
age = 12
country = "ジオン公国"
def say() :
print(country, name)
magnifier = Magnifier()
magnifier.observe("abc")
magnifier.observe(magnifier.observe)
obj = Abc()
magnifier.observe(obj)
## Listを観察
abc = ["a","b","c"]
magnifier.observe(abc)
## Mapを観察
codes = {"a":1, "b":2, "c":3}
magnifier.observe(codes)
## 集合を観察
codeset = {1,2,'A'}
magnifier.observe(codeset)
| true |
409bd89a1225c1fdcdbd61905fea94eb2397f3cf | slee8835/intro-to-python | /unit.py | 790 | 4.375 | 4 | """
This program contrains two functions: get_input and calc_temp.
These functions are used to take in a temperature input in C
from user, then convert that temperature to Fahrenheit.
"""
def get_input():
"""
this function gets temperature input from users in Celsius.
"""
cel_temp = float(input("Please enter a temperature in Celsius: "))
return cel_temp
def calc_temp(cel):
"""
this function takes in a paramter "cel" which is degree Celsius,
and it will calculate the equivalent temperature in Fahrenheit
"""
#to convert C to F: (°C × 9/5) + 32
Far_temp = (cel*9/5)+32
return Far_temp
def main():
c = get_input()
f = calc_temp(c)
print(str(c) + " degrees Celsius is equivalent to " + str(f) + " degrees Fahrenheit.")
if __name__== "__main__":
main() | true |
3761e07acce219aeb14d2f3f84f6b4cb3265b8f2 | riteshmsit/sampleprog | /cspp1-practice/m22/assignment2/clean_input.py | 476 | 4.34375 | 4 | '''
Write a function to clean up a given string by removing the special characters and retain
alphabets in both upper and lower case and numbers.
'''
import re
def clean_string(string):
#function to clean the string of special characters
updated_string = re.sub("[^a-z,^A-Z,0,1,2,3,4,5,6,7,8,9]","",string)
if '^' in updated_string:
return ''
return updated_string
def main():
string = input()
print(clean_string(string))
if __name__ == '__main__':
main()
| true |
ebdb0c6a80210e2eecc8ffff1f04488b8c2ef683 | asis-parajuli/Python-Basics | /tuples.py | 922 | 4.5625 | 5 | # tuples are emutable means we can't modify them
point = (1, 2)
# in tuple we can ignore parenthenisis like point = 1 , 2
# if we have only one item in tuple we should use tralying comma like point = 1,
# for defining an empty tuple we should use empty parenthesis like point = ()
# we can concatinate one tuple with another
point = (1, 2) + (3, 4)
print(point)
# we can use a repetation operator to repeat a tuple
point = (1, 2) * 3
print(point)
# we can convert a list into tuple
point = tuple([1, 2])
print(point)
# strings
point = tuple("hello world")
print(point)
# we can access individual item in a tuple by using an index
point = (1, 2, 3)
print(point[0])
print(point[0:2])
# we can unpack the tuple
x, y, z = point
if 10 in point:
print("exists")
else:
print("doesn't exists")
# tuple in real world is used to prevent accidental modification of a sequence or order
| true |
19ee68fdf253ea8b0d4bedd9141d902c67a44831 | Harry-003/Python_programs | /Q3.py | 210 | 4.25 | 4 | """
WPP to enter value in centimetre and convert it to meter and kilometre.
"""
cm = int(input("Enter value in centimeters : "))
print("Value in meters :",cm/100)
print("Value in kilometeres :",cm/1000) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.