blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a957213cad27ef8e8fcb5fcad84e18a9ff3ffa33 | Arun-9399/Simple-Program | /binarySearch.py | 550 | 4.15625 | 4 | #Binary Search Algorithm
def binarySearch(alist, item):
first=0
last= len(alist)-1
found= False
while first<= last and not found:
midpoint= (first+last)//2
if alist[midpoint]== item:
found= True
else:
if item<alist[midpoint]:
last= midpoint-1
else:
first= midpoint+1
return found
if __name__ == "__main__":
testlist=[0, 1,2, 8,13,17,19,32,42]
print (binarySearch(testlist,3))
print (binarySearch(testlist, 32))
| true |
342ddc75e963daefe5348880baeaee70eb1d58f1 | nikita-sh/CSC148 | /Lab 3/queue_client.py | 1,219 | 4.375 | 4 | """
Queue lab function.
"""
from csc148_queue import Queue
def list_queue(lst: list, q: Queue):
"""
Takes all elements of a given list and adds them to the queue. Then, checks
the queue for items that are not lists and prints them. If the item being
checked is a list, it is added to the queue. This process repeats until it
is empty.
>>> q = Queue()
>>> l1 = [1, 3, 5]
>>> l2 = [1, [3, 5], 7]
>>> l3 = [1, [3, [5, 7], 9], 11]
>>> list_queue(l1, q)
1
3
5
>>> list_queue(l2, q)
1
7
3
5
>>> list_queue(l3, q)
1
11
3
9
5
7
"""
for i in lst:
q.add(i)
while not q.is_empty():
nxt = q.remove()
if type(nxt) != list:
print(nxt)
else:
for i in nxt:
q.add(i)
if __name__ == "__main__":
q = Queue()
val = int(input("Enter an integer:"))
if val == 148:
pass
else:
q.add(val)
while val != 148:
val = int(input("Enter an integer:"))
if val == 148:
break
else:
q.add(val)
total = 0
while not q.is_empty():
total += q.remove()
print(total)
| true |
1ec3e20f2743feadef75547e7c94d15bebe47939 | RuanNunes/Logica-de-Programa-o-com-Python | /WebProject1/listaEtuple.py | 962 | 4.25 | 4 | class listaEtuple(object):
#Tuple é um conjunto de dados na mes variavel definido com "()" e separado cada valor por virgula, as tuples não podem ser modificadas depois de instanciasdas
meses = ('janeiro','fevereiro','março','abril')
#listas também é um conjunto de dados porem separados por "[]", as listas podem ser atualizadas depois de atualizadas
alunos = ['marcos','ruan']
#printa na tela o primeiro indice
print(alunos[0])
#atualizando elementos da lista
alunos [1] = 'jair'
#adicionando novos elementos
alunos.append('ricardo')
#adicionando novos elementos em determinados indices
alunos.insert(1,'paula')
#ordenando a lista por ordem alfabetica
alunos.sort()
#retirando indices dizendo qual indice quer
alunos.pop(1)
#retirando elemntos pelo nome
alunos.remov('paula')
#concatenação com listas
alunos2 = ['joana','jorge']
totalDeAlunos = alunos + alunos2
pass | false |
f86a9c4575fc01964b15d16df211d5881daf9a25 | educa2ucv/Material-Apoyo-Python-Intermedio | /Codigo/1-ProfundizandoEnFunciones/Ejercicio-1.py | 876 | 4.1875 | 4 | """
Ejercicio #01:
Desarrolle una función que reciba una lista
de asignaturas (Matemáticas, Fisica, Quimica, Historia y Lenguaje)
pregunta al usuario la nota que ha sacado en cada una y elimine de la lista
las asignaturas aprobadas. Al final, el programa debe mostrar
por pantalla las asignaturas que el usuario tiene que repetir.
"""
asignaturas = [ 'Matematicas', 'Fisica', 'Quimica', 'Historia', 'Lenguaje']
def foo(asignaturas:list) -> None:
copia = asignaturas[:]
for asig_actual in asignaturas:
nota = int(input(f'Por favor, ingrese la nota de asignatura {asig_actual}: '))
if nota >= 10:
copia.remove(asig_actual)
print(f'Las asignaturas a repetir son: {copia}')
#foo(asignaturas)
def foo2(n):
n = n + 1000
return n
numero = 1000
numero = foo2(numero)
print(numero) | false |
b4f9216dde63230dad5f5c85948151dbdd3119db | hicaro/practice-python | /sorting/mergesort.py | 1,417 | 4.28125 | 4 | class MergeSort(object):
'''
__merge Sort sorting algorithm implementation
- Best case: O(n log(n))
- Average case: O(n log(n))
- Worst case: O(n log(n))
'''
@staticmethod
def __merge(array, aux, lo, mid, hi):
for k in range(lo, hi + 1):
aux[k] = array[k]
i = lo
j = mid + 1
for k in range(lo, hi + 1):
# all the first half was already copied
if i > mid:
array[k] = aux[j]
j = j + 1
# all the second half was already copied
elif j > hi:
array[k] = aux[i]
i = i + 1
# item from second half is smaller than item from first half one
elif aux[j] < aux[i]:
array[k] = aux[j]
j = j + 1
else:
array[k] = aux[i]
i = i + 1
@staticmethod
def __sort(array, aux, lo, hi):
if lo >= hi:
return
mid = (lo + hi) // 2
MergeSort.__sort(array, aux, lo, mid)
MergeSort.__sort(array, aux, mid + 1, hi)
if array[mid + 1] > array[mid]:
return
MergeSort.__merge(array, aux, lo, mid, hi)
@staticmethod
def sort(numbers=None):
_len = len(numbers)
aux = [0 for _ in range(_len)]
MergeSort.__sort(numbers, aux, 0, _len -1)
| false |
677822cf2d9796a31de51f13477c5f31d097da76 | hicaro/practice-python | /sorting/insertionsort.py | 502 | 4.125 | 4 | class InsertionSort(object):
'''
Insertion Sort sorting algorithm implementation
- Best case: O(n)
- Average case: O(n^2)
- Worst case: O(n^2)
'''
@staticmethod
def sort(numbers=None):
_len = len(numbers)
for i in range(1, _len):
to_insert = numbers[i]
j = i-1
while j >= 0 and numbers[j] > to_insert:
numbers[j+1] = numbers[j]
j=j-1
numbers[j+1] = to_insert
| true |
7df9e746b8e11f1e8d3dee1f840275f5e9763d68 | ruchitiwari20012/PythonTraining- | /operators.py | 693 | 4.53125 | 5 | # Arithmetic Operators
print(" 5+ 6 is ", 5+6)
print(" 5- 6 is ", 5-6)
print(" 5* 6 is ", 5*6)
print(" 5/6 is ", 5/6)
print(" 5//6 is ", 5//6)
# Assignment Operator
x=5
print(x)
x+=7
print(x)
x-=7
print(x)
x/=7
print(x)
#Comparison Operator
i=8
print(i==5)
print(i!=5)# i not equal to 5
print(i>=5)
print(i<=5)
# Logical Operator
a = True
b = False
print(a and b)
print(a or b)
# Identical Operator
# is , is not
print(a is b) # No
print(a is not b) # yes
# Membership Operators
#in , not in
print("Membership Operators")
list = [3,32,2,39,33,35]
print(32 in list)
print(324 not in list)
print("Bitwise Operator")
print(0 & 2)
print( 0| 3) | true |
f2121f4abcd95f8f5a98aaee6103f703cd5aa357 | danismgomes/Beginning_Algorithms | /isPalindromeInt.py | 603 | 4.15625 | 4 | # isPalindrome
# It verifies if a integer number is Palindrome or not
answer = int(input("Type a integer number: "))
answer_list = []
while answer != 0: # putting every digit of the number in a list
answer_list.append(answer % 10) # get the first digit
answer = answer // 10 # remove the first digit
def is_palindrome(a_list):
for i in range(0, len(a_list)//2):
if a_list[i] != a_list[len(a_list)-i-1]: # verifying if some element of the list is not palindrome
return "It is not Palindrome."
return "It is Palindrome."
print(is_palindrome(answer_list))
| true |
a55db03c2d0ccfe6c86920ea4c26131ec980d539 | fahimnis/CS303_Computer_Programming_Projects | /Reverse.py | 505 | 4.21875 | 4 | # File: Reverse.py
# Description: Homework_4
# Student's Name: Fahim N Islam
# Student's UT EID: fni66
# Course Name: CS 303E
# Unique Number: 50180
#
# Date Created: 2/6/20
# Date Last Modified: 2/10/20
def Reverse():
x = int(input("Enter an integer: "))
a = int(x/100)
b = int(x- a*100)
c = int(a/10)
d = int(b/10)
e = a - c*10
f = b - d*10
g = f*1000 + d*100 + e*10 + c
print("The reversed number is",g,end=".")
Reverse()
| false |
f542b03e60b159f12efa105551ea0bce8d205aea | Emerson-O/PythonBasicoE_Gerber | /HT3.py | 806 | 4.15625 | 4 | #Ejercicio1
print("EJERCICIO 1")
con1 = input("Ingrese la contraseña a almacenar por favor: ")
print("")
contraseña = input("Introduce tu contraseña para ingresar: ")
print("")
if con1.lower() == contraseña.lower():
print("Contraseña correcta, Bienvenido")
else:
print("La contraseña incorrecta")
print("")
## EJERCICIO No. 2
print("")
print("EJERCICIO NO. 2")
print("=================")
nombre = input ("¿ Cuál es su nombre?")
genero = input("¿Cuál es tu genero?")
if generon == "M":
if nombre.lower() < "m":
group = "A"
else:
group = "B"
else:
if nombre.lower () > "n":
group = "A"
else:
group = "B"
print("Tu grupo es"+group)
print("Gracias por usar el programa")
| false |
d257b52336940b64bc32956911164029f56c5f22 | maxz1996/mpcs50101-2021-summer-assignment-2-maxz1996 | /problem3.py | 1,587 | 4.40625 | 4 | # Problem 3
# Max Zinski
def is_strong(user_input):
if len(user_input) < 12:
return False
else:
# iterate through once and verify all criteria are met
number = False
letter = False
contains_special = False
uppercase_letter = False
lowercase_letter = False
special = {'!', '@', '#', '$', '%'}
numbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}
# using ascii codes to establish upper and lower bounds is a common pattern I've observed in algorithm problems involving strings
# https://www.programiz.com/python-programming/examples/ascii-character
lower_bound = ord('a')
upper_bound = ord('z')
for c in user_input:
if c in special:
contains_special = True
elif c in numbers:
number = True
elif lower_bound <= ord(c.lower()) <= upper_bound:
letter = True
if c.lower() == c:
lowercase_letter = True
else:
uppercase_letter = True
return number and letter and contains_special and uppercase_letter and lowercase_letter
print("Enter a password: ")
user_input = input()
if is_strong(user_input):
print("This is a strong password.")
else:
print("This is not a strong password!")
print("""Strong passwords contain:
-at least 12 characters
-both numbers and letters
-at least one of these special characters: !, @, #, $, %
-at least one capital and one lower case letter""") | true |
7e52333c372dac152d046fb6d2f6ff763b9cf019 | rajila/courserapython | /enfoqueoopI.py | 1,132 | 4.125 | 4 | class SupA:
varA = 1
def __init__(self):
pass
def funA(self):
return 'A'
def funC(self):
return 'CA'
class SupB:
varB = 2
def __init__(self):
pass
def funB(self):
return 'B'
def funC(self):
return 'CB'
def do(self):
'''
Nota: la situación en la cual la subclase puede modificar el comportamiento de su superclase
(como en el ejemplo) se llama polimorfismo.
La palabra proviene del griego (polys: "muchos, mucho" y morphe, "forma, forma"),
lo que significa que una misma clase puede tomar varias formas dependiendo de las
redefiniciones realizadas por cualquiera de sus subclases.
'''
self.doIt()
def doIt(self):
print('call from Superclass SupB')
'''
La herencia múltiple ocurre cuando una clase tiene más de una superclase.
'''
class Sub(SupA, SupB): # herencia multiple
def doIt(self):
print('call from Subclass Sub')
data = Sub()
print(data.varA, data.funA())
print(data.varB, data.funB())
print(data.funC())
data.do()
| false |
56c94622c6852985b723bf52b0c2f20d2617f6c8 | kaozdl/property-based-testing | /vector_field.py | 2,082 | 4.125 | 4 | from __future__ import annotations
from typing import Optional
import math
class Vector:
"""
representation of a vector in the cartesian plane
"""
def __init__(self, start: Optional[tuple]=(0,0), end: Optional[tuple]=(0,0)):
self.start = start
self.end = end
def __str__(self) -> str:
return f'Vector:{self.start}, {self.end} - {self.length}'
def __add__(self, v2: Vector) -> Vector:
if not isinstance(v2, Vector):
raise ValueError('Addition is only implemented for two vectors')
return Vector(
start=(
self.start[0] + v2.start[0],
self.start[1] + v2.start[1]),
end=(
self.end[0] + v2.end[0],
self.end[1] + v2.end[1])
)
def __eq__(self, v2: Vector) -> bool:
if not isinstance(v2, Vector):
raise ValueError('Equality is only implemented for two vectors')
return self.start == v2.start and self.end == v2.end
@property
def length(self) -> float:
"""
returns the length of the vector
"""
return math.sqrt((self.start[0] - self.end[0])**2 + (self.start[1] - self.end[1])**2)
def center(self: Vector) -> Vector:
"""
returns an equivalent vector but with start in (0,0)
"""
new_end = (self.end[0] - self.start[0], self.end[1] - self.start[1])
return Vector(end=new_end)
def project_x(self) -> Vector:
"""
Returns the projection over X of the vector
"""
return Vector(
start=(self.start[0],0),
end=(self.end[0],0)
)
def project_y(self) -> Vector:
"""
returns the projection over Y of the vector
"""
return Vector(
start=(0,self.start[1]),
end=(0,self.end[1]),
)
IDENTITY = Vector()
CANONIC_X = Vector(start=(0,0), end=(1,0))
CANONIC_Y = Vector(start=(0,0), end=(0,1))
| true |
033813da0698f0fbfee6e4925b9117b8faee476f | Jose-Humberto-07/pythonFaculdade | /funcoes/exe01.py | 376 | 4.21875 | 4 | def inverter(texto):
return texto[::-1]
pessoas = []
for p in range(3):
perguntas = {"Qual o seu nome?":"",
"Em que cidade você mora?":"",}
print((p+1),"° entrevistado")
for pe in perguntas:
print(pe)
perguntas[pe] = input()
print()
pessoas.append(perguntas)
for p in pessoas:
print(p)
| false |
d629fb9d9ce965a27267cbc7db6a33662e0ff1d1 | vusalhasanli/python-tutorial | /problem_solving/up_runner.py | 403 | 4.21875 | 4 | #finding runner-up score ---> second place
if __name__ == '__main__':
n = int(input("Please enter number of runners: "))
arr = map(int, input("Please enter runners' scores separated by space: ").split())
arr = list(arr)
first_runner = max(arr)
s = first_runner
while s == max(arr):
arr.remove(s)
print("The second runner's score was : {}".format(max(arr)))
| true |
4a50cdce034f5fc9fe4367c141aa77af9379f2e2 | lariodiniz/Udemy-Python-Kivy | /app-comerciais-kivy/aulas/operacao_matematica.py | 719 | 4.21875 | 4 | #print(10+10)
#print(10(50.50))
'''
print(10-10)
print(1000-80)
print(10/5)
print(10/6)
print(10//6) # devolve a divisão sem os pontos flutuantes
print(10*800)
print(55*5)
#Módulo de Divisão
6 % 2 #Resultado da divisão entre dois numeros
print(3 % 2)
print(4 % 2)
print(5 % 2)
print(7 % 3.1)
num1 = float(input("Digite um numero: "))
num2 = float(input ("Digite outro numero: "))
divisao = num1 / num2
resto = num1 % num2
print()
print(num1, " dividido por ", num2, " é igual a: ", divisao)
print("o resto da divisão entre ", num1, " e ", num2, " é igual a: ", resto)
'''
#Potenciação e Radiação
5**2 # 5 ao quadrado
9**8000 # nove elevado a oito mil
#raiz quadrada
81**(1/2) #raiz quadrada de 81 | false |
d4ed2875ee9e98891d885e415d31ad470c268195 | lariodiniz/Udemy-Python-Kivy | /app-comerciais-kivy/aulas/interacao.py | 1,211 | 4.125 | 4 | # -*- coding: utf-8
#Enquanto
"""
x = 0
while( x <= 10):
print(x)
x += 1
#Enquanto com Else
x = 0
print("while")
while(x<10):
print(x)
x+= 1
else:
print("else")
print("fim")
#Laço For
#For em python sempre trabalha com lista
for c in "python":
print(c)
#range
range(0,10,2) # devolve um objeto do tipo range, para ter o objeto em tipo list precisa-se converter
#Você pode passar somente o ultimo elemento do intervalo na função range
range(10)
#o range pode retornar uma lista descendo ou negativa
range(100,0,-3)
range(-100,0-3)
#for com range
for i in range(10):
print(i)
#for com range negativo
for i in range(-10,0,1):
print(i)
#Instrução break. Pode ser usado com for e com while
print("Antes de entrar no laço")
for item in range(10):
print(item)
if(item==6):
print("A condição estabelecida retornou true")
break
print("depois de entrado no laço")
"""
#instrução continue. pode ser usado com for e com while. ela finaliza um unico ciclo
print()
print("inicio")
i = 0
while(i<10):
i+=1
if (i%2==0):
continue
if(i>5):
break #break não executa o else.
print(i)
else:
print("else")
print("fim") | false |
0844afed653ec7311aa6e269867e2723f131deca | atg-abhijay/Fujitsu_2019_Challenge | /EReport.py | 1,374 | 4.34375 | 4 | import pandas as pd
def main():
"""
main function that deals with the file input and
running the program.
"""
df = pd.DataFrame()
with open('employees.dat') as infile:
"""
1. only reading the non-commented lines.
2. separating the record by ',' or ' ' into 3
columns - employee number, first name and last name
"""
df = pd.read_csv(infile, comment='#', header=None, names=['emp_number', 'emp_first_name', 'emp_last_name'], sep=" |,", engine='python')
process_dataframe(df, 'emp_number', 'Processing by employee number...')
print()
process_dataframe(df, 'emp_last_name', 'Processing by last (family) Name...')
def process_dataframe(dataframe, sort_column, message):
"""
Sort the given dataframe according to the column
specified and print the records from the resulting
dataframe along with the supplied message.
:param pandas.DataFrame dataframe: Dataframe to process
:param str sort_column: column by which to sort the dataframe
:param str message: a message to show before printing the sorted data
"""
sorted_df = dataframe.sort_values(by=[sort_column])
print(message)
for record in sorted_df.itertuples(index=False, name=None):
print(str(record[0]) + ',' + record[1] + ' ' + record[2])
if __name__ == '__main__':
main()
| true |
02d453b80c142ad4b130fd5c3f9748a588e4c49d | hansen487/CS-UY1114 | /Fall 2016/CS-UY 1114/HW/HW6/hc1941_hw6_q4.py | 460 | 4.25 | 4 | """
Name: Hansen Chen
Section: EXB3
netID: hc1941
Description: Read and evaluate a mathematical expression.
"""
expression=input("Enter a mathematical expression: ")
array=expression.split()
operand1=int(array[0])
op=array[1]
operand2=int(array[2])
output=0
if (op=='+'):
output=operand1+operand2
elif (op=='-'):
output=operand1-operand2
elif (op=='*'):
output=operand1*operand2
elif (op=='/'):
output=operand1/operand2
print(expression,"=",output) | false |
c3e6a8a88cce32769e8fe867b8e0c166255a8105 | hansen487/CS-UY1114 | /Fall 2016/CS-UY 1114/HW/HW6/hofai/q6.py | 488 | 4.25 | 4 | password=input("Enter a password: ")
upper=0
lower=0
digit=0
special=0
for letter in password:
if (letter.isdigit()==True):
digit+=1
elif (letter.islower()==True):
lower+=1
elif (letter.isupper()==True):
upper+=1
elif (letter=='!' or letter=='@' or letter=='#' or letter=='$'):
special+=1
if (upper>=2 and lower>=1 and digit>=2 and special>=1):
print(password,"is a valid password.")
else:
print(password,"is not a valid password.") | true |
d82eafc8998a0a3930ee2d868158da93fca0329b | hansen487/CS-UY1114 | /Fall 2016/CS-UY 1114/HW/HW2/hc1941_hw2_q5.py | 844 | 4.15625 | 4 | """
Name: Hansen Chen
Section: EXB3
netID: hc1941
Description: Calculates how long John and Bill have worked.
"""
john_days=int(input("Please enter the number of days John has worked: "))
john_hours=int(input("Please enter the number of hours John has worked: "))
john_minutes=int(input("Please enter the number of minutes John has worked: "))
bill_days=int(input("Please enter the number of days Bill has worked: "))
bill_hours=int(input("Please enter the number of hours Bill has worked: "))
bill_minutes=int(input("Please enter the number of minutes Bill has worked: "))
minutes=(john_minutes+bill_minutes)%60
hours=john_hours+bill_hours+(john_minutes+bill_minutes)//60
hours=hours%24
days=john_days+bill_days+(john_hours+bill_hours)//24
print("The total time both of them worked together is:",days,"days,",hours,"hours, and",minutes,"minutes.") | true |
252e629263ab4295b2bb5cfaf34efd5998df2274 | syasky/python | /day03/03_python元组-tuple.py | 998 | 4.25 | 4 | #tuple 不可更改的数据类型
#语法 xxx=(1,2,3)
tuple1=(1,2,3)
print(tuple1)
#而且可以省略括号
tuple2=4,5,6
print(tuple2)
#注意: 单元素的元组创建时要注意,加一个逗号
tuple3=('aa',)
print(type(tuple3))
tuple4='bb',
print(type(tuple4))
#元组可以放多种数据
tuple5=('a',1,True,None,[1,2,3],tuple4)
print(tuple5)
#元组可以多变量一次赋值
a,b,c=100,200,300
print(a)
print(b)
print(c)
d,e=[400,500]
print(d)
print(e)
f,g=([5,6],[7,8])
print(f)
#题目:将两个变量互换值
num1=1000
num2=2000
print(num1,num2)
num2,num1=num1,num2
print(num1,num2)
#tuple() 可以将一些变量转为元组
print(tuple('abc'))
print(tuple([2,3,4]))
#------更新数据-----
#因为元组不能修改,所以,不能增加,不能修改,不能删除 某个值
#-----------只能查询元组----------
# 与 列表 一模一样
#元组的操作符 与 list 一样一样的的。 + * in
| false |
a7e9f749651d491f1c84f088ea128cbeaf18d9a5 | lindsaymarkward/cp1404_2018_2 | /week_05/dictionaries.py | 505 | 4.125 | 4 | """CP1404 2018-2 Week 05 Dictionaries demos."""
def main():
"""Opening walk-through example."""
names = ["Bill", "Jane", "Sven"]
ages = [21, 34, 56]
print(find_oldest(names, ages))
def find_oldest(names, ages):
"""Find oldest in names/ages parallel lists."""
highest_age = -1
highest_age_index = -1
for i, age in enumerate(ages):
if age > highest_age:
highest_age = age
highest_age_index = i
return names[highest_age_index]
main()
| true |
96df163a93ed47fc84ed50b65857d9efa23d69ab | lhmisho/Data-Structure---Python-3 | /insertionSort.py | 341 | 4.15625 | 4 | def insertion_sort(L):
n = len(L)
for i in range(1, n):
item = L[i]
j = i - 1
while j >= 0 and L[j] > item:
L[j+1] = L[j]
j = j-1
L[j+1] = item
if __name__=="__main__":
L = [6,1,4,9,2]
print("Before sort: ", L)
insertion_sort(L)
print("After sort: ", L) | false |
d0b18dd59833733b72f5ef43a9b3d53ea0d1d429 | Abarna13/Floxus-Python-Bootcamp | /ASSIGNMENT 1/Inverted Pattern.py | 278 | 4.21875 | 4 | '''
Write a python program to print the inverted pyramid?
* * * * *
* * * *
* * *
* *
*
'''
#Program
rows = 5
for i in range(rows,0,-1):
for j in range(0,rows-1):
print(end="")
for j in range(0,i):
print("*",end= " ")
print()
| true |
d9918e166dc1f669bed7f96b01cce30470f0a85a | nealsabin/CIT228 | /Chapter5/hello_admin.py | 599 | 4.21875 | 4 | usernames = ["admin","nsabin","jbrown","arodgers","haaron"]
print("------------Exercise 5-8------------")
for name in usernames:
if name == "admin":
print("Hello, admin. Would you like to change any settings?")
else:
print(f"Hello, {name}. Hope you're well.")
print("------------Exercise 5-9------------")
usernames = []
if usernames:
for name in usernames:
if name == "admin":
print("Hello, admin. Would you like to change any settings?")
else:
print(f"Hello, {name}. Hope you're well.")
else:
print("The list is empty!") | true |
31d8a9230ed12e4d4cb35b2802a9c721c1d23d15 | nealsabin/CIT228 | /Chapter9/restaurant_inheritance.py | 1,049 | 4.21875 | 4 | #Hands on 2
#Exercise 9-2
print("\n----------------------------------------------------------")
print("-----Exercise 9-6-----\n")
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(f"{self.restaurant_name} serves {self.cuisine_type} food.")
print(f"Occupent Limit: {self.number_served}")
def set_number_served(self,served):
self.number_served = served
def increment_served(self, served):
self.number_served += served
class IceCreamStand(Restaurant):
def __init__(self,restaurant_name,cuisine_type):
super().__init__(restaurant_name,cuisine_type)
self.flavors=["vanilla","chocolate","strawberry"]
def display_flavors(self):
print(f"{self.restaurant_name} serves: ")
for flavor in self.flavors:
print(flavor)
stand=IceCreamStand("DQ","Ice Cream")
stand.display_flavors() | true |
5e2463436e602ab6a8764adee0e48605f50a7241 | Jay07/CP2404 | /billCalc.py | 252 | 4.125 | 4 | print("Electricity Bill Estimator")
Cost = float(input("Enter cents per kWh: "))
Usage = float(input("Enter daily use in kWh: "))
Period = float(input("Enter number of billing days: "))
Bill = (Cost*Usage*Period)/100
print("Estimated Bill: $", Bill) | true |
c7dfa455c559c0e9c0379f03bd985908c6a3342f | Plain-ST/python_practice_55knock | /29.py | 668 | 4.3125 | 4 | """
29. 辞書(キーの存在確認)
今,以下のように辞書が作成済みです.
d = {'apple':10, 'grape':20, 'orange':30}
この辞書に対して,'apple'というキーが存在するかを確認し,存在しなければ,'apple'というキーに対して-1という値を追加してください.
また,同様のことを'pineapple'でも行なってください.その後,最終的な辞書を出力してください.
期待する出力:{'apple': 10, 'grape': 20, 'orange': 30, 'pineapple': -1}
"""
d = {'apple':10, 'grape':20, 'orange':30}
if 'apple' not in d:d['apple']=-1
if 'pineapple' not in d:d['pineapple']=-1
print(d) | false |
42c4caab27c4cdd3afc59c6270f372c6e388edb3 | mvanneutigem/cs_theory_practice | /algorithms/quick_sort.py | 1,936 | 4.40625 | 4 |
def quick_sort(arr, start=None, end=None):
"""Sort a list of integers in ascending order.
This algorithm makes use of "partitioning", it recursively divides the
array in groups based on a value selected from the array. Values
below the selected value are on one side of it, the ones above it on the
other. then the process is repeated for each of these sides and so on.
Args:
arr (list): list to sort.
start (int): start index to sort list from
end (int): end index to sort to list to.
"""
if start is None:
start = 0
if end is None:
end = len(arr) -1
pivot = partition(arr, start, end)
if pivot == start:
if start + 1 != end:
quick_sort(arr, start+1, end)
elif pivot == end:
if start != end - 1:
quick_sort(arr, start, end-1)
else:
if start != pivot -1:
quick_sort(arr, start, pivot - 1)
if pivot + 1 != end:
quick_sort(arr, pivot + 1, end)
def partition(arr, start, end):
""""Separate the given array in two chuncks, by selecting a "pivot"value and
moving all values smaller than the pivot to one side of it, and the values
bigger than it to the other side of it.
Args:
arr (list): list to partition.
start (int): start index to partition.
end (int): end index to partition.
Returns:
int: index of the pivot value after partitioning the list.
"""
j = start+1
pivot = arr[start]
for i in range(start+1, end+1):
if arr[i] < pivot:
arr[i], arr[j] = arr[j], arr[i]
j += 1
# swap pivot to correct position
arr[j - 1], arr[start] = arr[start], arr[j - 1]
return j - 1
def main():
"""Example usage."""
arr = [8, 4, 76, 23, 5, 78, 9, 5, 2]
result = [2, 4, 5, 5, 8, 9, 23, 76, 78]
quick_sort(arr)
assert(result == arr)
| true |
1c7605d505ea2a2176883eaba72cfc04ff2fb582 | knowledgewarrior/adventofcode | /2021/day1/day1-p1.py | 1,590 | 4.40625 | 4 | '''
As the submarine drops below the surface of the ocean, it automatically performs a sonar sweep of the nearby sea floor. On a small screen, the sonar sweep report (your puzzle input) appears: each line is a measurement of the sea floor depth as the sweep looks further and further away from the submarine.
For example, suppose you had the following report:
199
200
208
210
200
207
240
269
260
263
This report indicates that, scanning outward from the submarine, the sonar sweep found depths of 199, 200, 208, 210, and so on.
The first order of business is to figure out how quickly the depth increases, just so you know what you're dealing with - you never know if the keys will get carried into deeper water by an ocean current or a fish or something.
To do this, count the number of times a depth measurement increases from the previous measurement. (There is no measurement before the first measurement.) In the example above, the changes are as follows:
199 (N/A - no previous measurement)
200 (increased)
208 (increased)
210 (increased)
200 (decreased)
207 (increased)
240 (increased)
269 (increased)
260 (decreased)
263 (increased)
In this example, there are 7 measurements that are larger than the previous measurement.
How many measurements are larger than the previous measurement?
'''
import sys
import os
def main():
counter = 1
with open('input.txt') as my_file:
num_list = my_file.readlines()
for i in range(0,len(num_list)-1):
if num_list[i+1] > num_list[i]:
counter +=1
print(str(counter))
if __name__ == '__main__':
main() | true |
2c05503575eccf27161b3217d13da4027c91affb | dharunsri/Python_Journey | /Inheritance.py | 738 | 4.3125 | 4 | # Inheritance
# Accessing another classes is calles inheritance
class Songs: # Parent class / super class
def name(self):
print("People you know")
def name2(self):
print("Safe and sound")
class selena(Songs): # Child class/ sub class - can access everything from parent class
def info(self):
print("American singer")
def info2(self):
print("Selena Gomez")
class swift(selena): # It can access both classes. Or if selena is not a child class then swift(selena,songs) - this will access both
def info3(self):
print("Taylor Swift")
s = Songs()
s2 = selena()
s3 = swift()
s.name()
s2.info2()
s3.info3() | true |
aabb79dc9eb7d394bf9a87cd51d9dacde5eabf3e | dharunsri/Python_Journey | /Python - Swapping of 2 nums.py | 1,286 | 4.3125 | 4 | # Swapping of two numbers
a = 10 # 1010
b = 20 # 10100
# Method 1
temp = a
a = b
b = temp
print(" Swapping using a temporary variable is : " ,'\n',a, '\n',b)
# Method 2
a = a+b # 10 + 20 = 30
b = a-b # 30 - 20 = 10
a = a-b # 30 - 10 = 20
print(" Swapping without using a temporary variable is : ",'\n', a ,'\n', b)
"""Sometimes the bits can be lost
for example,
5 = 101
6 =110
while swapping = 5 + 6 = 11 -> 1010 [ got 4 bits of 3 bits value. Losing a bit]
"""
# Method 3
# XOR method - here the losing of bits can be avoided
a = a^b
b = a^b
a = a^b
print("Swapping without using a temporary variable and without losing a bit: ", '\n',a ,"\n", b)
"""
xor works as - if the bit is, 0 in the second variable first will be the ans or if the bit is 1 in the second variable complement of 1st is ans
for example,
10 - 01010
20 - 10100
11110 - 30
so the swapping will perform like this
"""
# Method 4
# Simple way - Rot2 method (rotation 2 | 2 rotation method)
a,b =b,a
print("Swapping in a simple way without using temporary variable : ", '\n',a ,"\n", b)
| true |
2dd468406342dc6e8f767ba6d469613b19eed0ad | samanthamirae/Journey | /Python/OrderCostTracking.py | 2,862 | 4.25 | 4 | import sys
totalOrders = 0 #tracks number of orders in the batch
batchCost = 0 #tracks the total cost across all orders in this batch
# our functions
def orderprice(wA,wB,wC):
#calculates the cost total of the order
cTotal = 2.67 * wA + 1.49 * wB + 0.67 * wC
if cTotal > 100:
cTotal = cTotal * .95
return cTotal
def shippingcharge(oW):
#Finds the shipping charge for the order based on total weight
if oW <= 5:
sCost = 3.5
elif oW <= 20:
sCost = 10
else:
sCost = 9.5 + .1 * oW
return sCost
def submitorder():
#Lets the user submit a new order
global totalOrders
global batchCost
try: #checks for a float
weightA = float(input("How many pounds of Artichokes would you like to order?\n"))
weightB = float(input("How many pounds of Beets would you like to order?\n"))
weightC = float(input("How many pounds of Carrots would you like to order?\n"))
costTotal = orderprice(weightA,weightB,weightC)
orderWeight = weightA + weightB + weightC
shippingCost = shippingcharge(orderWeight)
orderTotal = shippingCost + costTotal
#update totals
totalOrders += 1
batchCost = batchCost + orderTotal
#Tell the user the cost, shipping charge, and final charge for their order
print("Total Cost is: " '${:,.2f}'.format(costTotal))
print("Shipping Charge for this order is: " '${:,.2f}'.format(shippingCost))
print("Order Cost and Shipping: " '${:,.2f}'.format(orderTotal))
except ValueError:
print("Invalid weight. Please choose again.")
def summary():
#Shows statistics of the batch including number of orders, total cost of all orders,
#and average cost for an order
avg = 0
if totalOrders > 0:
avg = batchCost / totalOrders
print("Number of Orders:",totalOrders)
print("Total Cost of All Orders: " '${:,.2f}'.format(batchCost))
print("Average Order Cost: " '${:,.2f}'.format(avg))
def reset():
#Resets the batch statistics to prepare for a new batch
global totalOrders
totalOrders = 0
global batchCost
batchCost = 0
#execute the program as long as "exit" isn't entered:
while True:
print("Type submit to enter a new order, ")
print("type summary to see batch statistics, ")
print("type reset to reset statistics, or type exit to exit")
line = sys.stdin.readline()
if line.strip() == 'submit':
submitorder()
elif line.strip() == 'summary':
summary()
elif line.strip() == 'reset':
reset()
elif line.strip() == 'exit':
break
else:
print("Invalid choice. Try again.")
| true |
788e78bede5679bcb0f93f4642602520baead921 | shirisha24/function | /global scope.py | 372 | 4.1875 | 4 | # global scope:-if we use global keyword,variable belongs to global scope(local)
x="siri"
def fun():
global x
x="is a sensitive girl"
fun()
print("chinni",x)
# works on(everyone) outside and inside(global)
x=2
def fun():
global x
x=x+x
print(x)
fun()
print(x)
# another example
x=9
def fun() :
global x
x=4
x=x+x
print(x)
fun() | true |
9332d185e61447e08fc1209f52ae41cecdc90132 | mchoimis/Python-Practice | /classroom3.py | 701 | 4.3125 | 4 | print "This is the grade calculator."
last = raw_input("Student's last name: ")
first = raw_input("Student's first name: ")
tests = []
test = 0 #Why test = 0 ?
while True:
test = input("Test grade: ")
if test < 0:
break
tests.append(test)
total = 0 #Why total = 0 ?
for test in tests:
total = total + test
average = total / len(tests) #Note the number of tests varies.
print "*" * 20
print "Student's name: ", first, last
num = 1
for test in tests:
print "Test {num}: {grade}".format(num=num, grade=test)
num = num + 1
print "Average: {average}".format(average=average) #Dont' know format...
| true |
7fb16ee09b9eb2c283b6e6cd2b2cabab06396a58 | mchoimis/Python-Practice | /20130813_2322_len-int_NOTWORKING.py | 1,302 | 4.1875 | 4 | """ input() takes values
raw_input() takes strings
"""
# Asking names with 4-8 letters
name = raw_input("Choose your username.: ")
if len(name) < 4:
print "Can you think of something longer?"
if len(name) > 8:
print "Uhh... our system doesn't like such a long name."
else:
print 'How are you, ', name, '.\n'
# Asking age in numbers
# int() turns objects into integers. It always rounds down.
# e.g., 3.0, 23.5 is a float, not an integer. int(3.5) == 3 TRUE
age = raw_input("What is your age?\n")
if type(age) is str:
print 'Please enter in number.'
if int(age) >= 24:
print 'Congratulations! You are qualified.\n'
else:
print 'Sorry, you are not qualified.\n'
# Asking tel in 10 digits
# len() returns the number of digits or letters of an object as integer
# len() doesn't take numbers as arguments?
tel = raw_input("What is your phone number?\n")
while len(tel) != 10:
print 'Please enter with 10 digits.'
tel = raw_input("Again, what is your phone number?\n")
if len(tel) == 10:
print 'Your number is', tel, '.\n'
ask = raw_input("Can I call you at this number? (Y or N)\n")
if ask == 'y':
print "Thanks for your input.\n"
elif ask == 'Y':
print "Thanks for your input.\n"
else:
print "Thanks, come again.\n"
| true |
85009ecac2bcdaeaf0b4ccf8cc715151574d28bd | rom4ikrom/Practical-session-5 | /last4.py | 417 | 4.25 | 4 | import math
print ("x^1 \t x^2 \t x^3")
print ("----------------------")
for num in range(1,6):
for power1 in range(1,2):
for power2 in range(2,3):
for power3 in range(3,4):
result1 = math.pow(num, power1)
result2 = math.pow(num, power2)
result3 = math.pow(num, power3)
print(result1, "\t", result2, "\t", result3)
| false |
f91a713fff27f167f0c6e9924a2f8b39b5d99cd3 | Manuferu/pands-problems | /collatz.py | 919 | 4.40625 | 4 | # Manuel Fernandez
#program that asks the user to input any positive integer and outputs the successive values of the following calculation.
# At each step calculate the next value by taking the current value and, if it is even, divide it by two, but if it is odd,
# multiply it by three and add one. Have the program end if the current value is one.
#ask user to insert an integer number
num = int(input("Please enter a positive integer:"))
div = 2
while num >1: # Keep in the loop in the case that always you have a value greater than 1
if (num % div)==0 : # If the value is even, the reminder will be 0, then enter here
num= int(num / 2) #update the value of num dividing by 2
else: # if the reminder is not 0, then is odd, enter here
num = (num * 3) + 1#update the value of num multiplying by three and add one
print(num)#print num each case it pass through the conditional
| true |
5a388d39dbab1a59a8bf51df96b26eb51192e70e | manojkumarpaladugu/LearningPython | /Practice Programs/largest_num.py | 358 | 4.53125 | 5 | #Python Program to Find the Largest Number in a List
num_list = []
n = input("Enter no. of elements:")
print("Enter elements")
for i in range(n):
num = input()
num_list.append(num)
print("Input list is: {}".format(num_list))
big = 0
for i in num_list:
if i > big:
big = i
print("Largest number in the list is: {}".format(big))
| true |
0e1dfa0c61334091f7f6bbc09e8e72d3c1e7365b | manojkumarpaladugu/LearningPython | /Practice Programs/GeeksforGeeks Archive/vowel_string.py | 720 | 4.5 | 4 | # Program to accept the strings which contains all vowels
'''
#method1
def is_string_vowel(string):
vowels = {'a','e','i','o','u','A','E','I','O','U'}
for char in string:
if not (char=='a' or char=='e' or char=='i' or char=='o' or char=='u'):
if not (char=='A' or char=='E' or char=='I' or char=='O' or char=='U'):
return 0
return 1
'''
#method2
def is_string_vowel(string):
vowels = {'a','e','i','o','u','A','E','I','O','U'}
for char in string:
if char not in vowels:
return 0
return 1
string = input("Enter a string:")
if is_string_vowel(string):
print("{} is accepted:".format(string))
else:
print("{} is not accepted:".format(string))
| false |
4655d4a9c07fdc83d990068507bb7a614bee7321 | manojkumarpaladugu/LearningPython | /Practice Programs/print_numbers.py | 310 | 4.34375 | 4 | #Python Program to Print all Numbers in a Range Divisible by a Given Number
print("Please input minimum and maximum ranges")
mini = input("Enter minimum:")
maxi = input("Enter maximum:")
divisor = input("Enter divisor:")
for i in range(mini,maxi+1,1):
if i % divisor == 0:
print("%d" %(i))
| true |
35b61f8813afb1b2f2fcbed2f6f0e9cb97097503 | manojkumarpaladugu/LearningPython | /Practice Programs/second_largest.py | 377 | 4.4375 | 4 | #Python Program to Find the Second Largest Number in a List
num_list = []
n = input("Enter no. of elements:")
print("Enter elements:")
for i in range(n):
num_list.append(input())
print("Input list is: {}".format(num_list))
num_list.sort(reverse=True)
print("The reversed list is: {}".format(num_list))
print("The second largest number is: {}", num_list[1])
| true |
2a4a24cc323bc98d2cc0d4f007daec09b8a762ec | manojkumarpaladugu/LearningPython | /Practice Programs/GeeksforGeeks Archive/large_prime_factor.py | 440 | 4.40625 | 4 | # Python Program for to Find largest prime factor of a number
def is_prime(num):
for i in range(2, (num / 2) + 1, 1):
if num % i == 0:
return 0
return 1
def find_largest_prime_factor(num):
maxi = 0
for i in range(1, (num / 2) + 1, 1):
if num % i == 0:
if is_prime(i):
if maxi < i:
maxi = i
return maxi
num = input("Enter a number:")
print find_largest_prime_factor(num)
| false |
6fb77fed8433ef037ebbd70be628f2d0d462d480 | manojkumarpaladugu/LearningPython | /Practice Programs/GeeksforGeeks Archive/binary_palindrome.py | 460 | 4.15625 | 4 | # Python | Check if binary representation is palindrome
def check_binary_palindrome(binary):
reverse_binary = ""
i = len(binary) - 1
while i >= 0:
reverse_binary += binary[i]
i -= 1
if reverse_binary == binary:
return 1
else:
return 0
binary = str(input("Enter a binary umber:"))
if check_binary_palindrome(binary):
print("{} is palindrome".format(binary))
else:
print("{} is not palindrome".format(binary))
| false |
56b022638dff063eefcda1b732613b1441b0bde3 | vinromarin/practice | /python/coursera-programming-for-everbd/Exercise_6-3.py | 402 | 4.125 | 4 | # Exercise 6.3 Encapsulate this code in a function named count, and generalize it
# so that it accepts the string and the letter as arguments.
def count(str, symbol):
count = 0
for letter in str:
if letter == symbol:
count = count + 1
return count
str_inp = raw_input("Enter string:")
smb_inp = raw_input("Enter symbol to count:")
cnt = count(str_inp, smb_inp)
print cnt | true |
e70a3ca8aeb66c993ba550fa3261f51f5c4ea845 | PurneswarPrasad/Good-python-code-samples | /collections.py | 2,017 | 4.125 | 4 | #Collections is a module that gives container functionality. We'll discuss their libraries below.
#Counter
from collections import Counter
#Counter is a container that stores the elemnts as dictionary keys and their counts as dictionary values
a="aaaaaabbbbcc"
my_counter=Counter(a) #makes a dictionary of a
print(my_counter.keys()) #prints the keys
print(my_counter.values()) #prints the values
print(my_counter.most_common(1)) #prints the most common key-value pair. Putting 2 will print the 2 most common key-value pairs, etc.
# most_common() returns a list with tuples in it.
print(my_counter.most_common(1)[0][0]) #this prints the element with the highest occurence.
print(list(my_counter.elements())) #iterates over the whole Counter and returns a list of elements
#NamedTuple
from collections import namedtuple
Point=namedtuple('Point', 'x,y')
pt=Point(1,-4) #returns point with x and y values
print(pt)
#OrderedDict library is used to create dictionaries whose order can be maintained. Python 3.7 and higher already has this built-in function while creating dictionaries.
#defaultDict
from collections import defaultdict
d=defaultdict(int)
d['a']=1
d['b']=2
d['c']=1
print(d['d']) #Giving a key-value that is not there in the dictionary will give a default value of the kind of datatype mentioned in the defaultdict() function.
#Deque (Double ended queue)-(Insert and remove from both ends)
from collections import deque
dq=deque()
dq.append(1)
print(dq)
dq.append(2) #appends 2 to the right of 1
print(dq)
dq.appendleft(3) #append 3 to the left of 1
print(dq)
dq.pop() #removoes an element from the right side
print(dq)
dq.popleft() #removes an element from the left
print(dq)
dq.clear() #Clears the entire deque
dq.extend(3,1,2,4,5,6) #appends multiple elements to the right
print(dq)
dq.extendleft(3,1,2,4,5,6) #appends multiple elements to the left
print(dq)
dq.rotate(1) #Shifts elements to the right side by 1 place
print(dq)
dq.rotate(-1) #Shifts elements to theleft by 1 place
print(dq) | true |
3798ed579d458994394902e490bd4afb781c843d | petr-jilek/neurons | /models/separationFunctions.py | 1,055 | 4.25 | 4 | import math
"""
Separation and boundary function for dataGenerator and separators.
Separation function (x, y): Return either 1 or 0 in which region output is.
Boundary function (x): Return value of f(x) which describing decision boundary for learning neural network.
"""
# Circle separation and boundary functions.
# Circle with center in x = 0.5 and y = 0.5 and radius 0.3
# (x - 0.5)^2 + (y - 0.5)^2 = 0.3^2
def circleSeparationFunc(x, y):
if (((x - 0.5) ** 2) + ((y - 0.5) ** 2)) < (0.3 ** 2):
return 1
else:
return 0
def circleBoundaryFunction(x):
a = (0.3 ** 2) - ((x - 0.5) ** 2)
if a > 0:
return math.sqrt(a) + 0.5
else:
return 0
def circleBoundaryFunction2(x):
a = (0.3 ** 2) - ((x - 0.5) ** 2)
if a > 0:
return -math.sqrt(a) + 0.5
else:
return 0
# Linear separation and boundary functions.
# Linear function y = f(x) = x
def linearSeparationFunc(x, y):
if y > x:
return 1
else:
return 0
def linearBoundaryFunction(x):
return x
| true |
dc11626d5790450752c98f192d4ddee383b21aae | teebee09/holbertonschool-higher_level_programming | /0x03-python-data_structures/3-print_reversed_list_integer.py | 227 | 4.59375 | 5 | #!/usr/bin/python3
def print_reversed_list_integer(my_list=[]):
"prints all integers of a list, in reverse order"
if my_list:
for n in range(0, len(my_list)):
print("{:d}".format(my_list[(-n) - 1]))
| true |
5fdf358cac32bc7fea9d0d862a9613d742675043 | sanjay-chahar/100days | /pizza-order.py | 668 | 4.21875 | 4 | pizza = input("What size pizza you want to order? S,M and L = ")
pepperoni = input("Do you want to add pepperoni ? Y or N = ")
cheese = input("Do you want add extra cheese? Y or N = ")
price = 0
if pizza == "S":
price += 15
if pepperoni == "Y":
price += 2
# print(f"Pizza price is £{price}")
elif pizza == "M":
price += 20
if pepperoni == "Y":
price += 3
else:
price += 0
elif pizza == "L":
price += 25
if pepperoni == "Y":
price += 3
else:
price += 0
if cheese == "Y":
price = price + 1
print(f"Final pizz Price is £{price}")
else:
print(f"Pizza price is £{price}")
| false |
4a4c9eb5d19396aa917b6ea5e9e74ab168b7287d | jramos2153/pythonsprint1 | /main.py | 2,176 | 4.40625 | 4 | """My Sweet Integration Program"""
__author__ = "Jesus Ramos"
#Jesus Ramos
# In this program, users will be able to solve elementary mathematical equations and graph.
name = input("Please enter your name: ")
print("Welcome", name, "!")
gender = input("Before we start, tell us a bit about your self. Are you male or female? ")
print("It's nice to know that you are a", gender)
age = input("What is your age? ")
print("Wow", age, "is so old!")
number = input("Thanks for sharing all of this information! What's your favorite number?")
print(number, "is a lame number, definitely not my favorite!")
operation = input("Since we're talking about numbers, what is your favorite math operation?")
print("Nice to know that", operation, "is your favorite, why don't we practice a few problems to get warmed up! ")
input("Let's start off with addition, what is 2 + 2?") # using first numeric operator (addition)
a = 2
b = 2
print("Let's check, smarty pants. Answer:", a + b)
input("How about 2 - 2?") # using second numeric operator (subtraction)
print("Hmmm, let's see if you got it! Answer:", a - b)
input("Let's kick it up a notch, what's 2 x 2?") # using third numeric operator (multiplication)
print("Will you get this one right? Answer:", a * b)
input("We're almost done with warm up, what's 2 divided by 2?")
print("Let's see if you got it. Answer:", a / b)
#line above shows fourth numeric operator (division)
input("That was a good warm up, let's step up our game. What is the remainder when you divide 85 by 15?")
c = 85
d = 15
print("Annnnddd the answer is: ", c % d)
#the line above shows the modular operator being used
input("Let's test how good your math skills really are. What is 85 raised to the power of 15?")
print("Let's see if you got it. Answer:", c ** d)
input("How about this, what is 85 divided by 15, to the nearest whole number when rounded down?")
print("The correct answer is:", c // d)
#line above shows the floor division numeric operator being used
input("That was still easy, what about x + 5 if x = 10?")
x = 10
x += 5
print("Let's see, the correct answer is: ", x)
#line above shows assignment and shortcut operator being used
| true |
614dcefde41a4b7d064f8248fceb4a7d3204e60e | fernandosergio/Documentacoes | /Python/Praticando/Utilização da linguagem/while encaixado desafio.py | 675 | 4.3125 | 4 | #usuario vai digita uma sequencia de numeros
#imprimi o fatorial do numero digitado
#while sem função
#entrada = 1
#while entrada => 0:
# entrada = int(input("Digite um número natural ou 0 para parar: "))
# i = 1
# anterior = 1
# while i <= entrada:
# mult = anterior * i
# anterior = mult
# i = i + 1
# print(mult)
# while com função
def fatorial (n):
i = 1
anterior = 1
while i <= n :
mult = anterior * i
anterior = mult
i = i + 1
print(mult)
def main():
entrada = 1
while entrada >= 0:
entrada = int(input("Digite um valor natural: "))
fatorial(entrada)
main()
| false |
06f51bde337c4f60bae678ada677654c4bab7afd | ramjilal/python-List-Key-concept | /shallow_and_deep_copy_list.py | 1,400 | 4.53125 | 5 | #use python 2
#first simple copy of a list, List is mutable so it can be change by its copy.
x = [1,2,3]
y = x # here list 'y' and list 'x' point to same content [1,2,3].
y[0]=5 # so whenever we will change list 'y' than list 'x' would be change.
print x #print -> [5,2,3]
print y #print -> [5,2,3]
#/**************************************************************\
#so to overcome this error we use SHALLOW copy.
#/**************************************************************\
#SHALLOW COPY of a LIST
from copy import *
x = [1,2,3]
y = copy(x)
y[0]=5
print x #print -> [1,2,3]
print y #print -> [5,2,3]
#/**************************************************************\
#but shallow copy also fail in deep copy of a list .let an example
#/**************************************************************\
from copy import *
x = [1,2,[3,4]]
y = copy(x)
y[0] = 12
y[2][0] = 5 # change value of first element of List [3,4].
print x #print -> [1,2,[5,4]]
print y #print -> [12,2,[5,4]]
#/**************************************************************\
#so to overcome this error we use DEEP copy.
#/**************************************************************\
from copy import *
x = [1,2,[3,4]]
y = deepcopy(x)
y[0] = 12
y[2][0] = 5 # change value of first element of List [3,4].
print x #print -> [1,2,[3,4]]
print y #print -> [12,2,[5,4]]
| true |
00c319cb96b7c226943266109c4e48c723fc4ff5 | bhargavpydimalla/100-Days-of-Python | /Day 1/band_generator.py | 487 | 4.5 | 4 | #1. Create a greeting for your program.
print("Hello there! Welcome to Band Generator.")
#2. Ask the user for the city that they grew up in.
city = input("Please tell us your city name. \n")
#3. Ask the user for the name of a pet.
pet = input("Please tell us your pet's name. \n")
#4. Combine the name of their city and pet and show them their band name.
band_name = f"{city} {pet}"
#5. Make sure the input cursor shows on a new line.
print(f"Your band name should be {band_name}.")
| true |
67dcf2f90962af4a64ae3e0907e051f558755771 | realme1st/Data-structurePython | /linkedlist3.py | 720 | 4.28125 | 4 | # 파이썬 객체지향 프로그래밍으로 링크드 리스트 구현
class Node:
def __init__(self,data,next=None):
self.data=data
self.next = next
class NodeMgmt:
def __init__(self,data):
self.head = Node(data)
def add(self,data):
if self.head == "":
self.head =Node(data)
else:
node = self.head
while node.next:
node = node.next
node.next = Node(data)
def desc(self):
node = self.head
while node:
print(node.data)
node = node.next
linkedlist1 = NodeMgmt(0)
linkedlist1.desc()
for data in range(1,10):
linkedlist1.add(data)
linkedlist1.desc()
| false |
7a183fdbe4e63ee69c2c204bfaa69be6e7e29933 | demelziraptor/misc-puzzles | /monsters/monsters.py | 2,634 | 4.125 | 4 | import argparse
from random import randint
"""
Assumptions:
- Two monsters can start in the same place
- If two monsters start in the same place, they ignore eachother and start by moving!
- All monsters move at each iteration
- For some reason, the monsters always move in the same order...
- This monster world runs python 2.7
"""
class Main:
monsters = {}
cities = {}
def __init__(self):
self._parse_args()
self._setup_monsters_and_cities()
def _parse_args(self):
""" get cli arguments and add to arg variable """
parser = argparse.ArgumentParser(description='Monsters, destroying stuff!')
parser.add_argument('map_file', metavar='M', type=file, help='the map file')
parser.add_argument('--num', metavar='n', type=int, default=6, help='number of monsters to add to the map (default: 6)', dest='num_monsters')
self.args = parser.parse_args()
print self.args
def _setup_monsters_and_cities(self):
""" read map file, add map and monster dictionaries """
for line in args.map_file:
self._parse_map(line)
for num in range(args.num_monsters):
self.monsters[num] = random.choice(list(self.cities.keys()))
def run_iterations(self):
""" do an iteration until all monsters die or each monster moves 10,000 times """
self._move()
self._destroy()
def print_map(self):
""" print out remaining map in correct format """
for city in city_map:
#format and print stuff
pass
def _move(self):
""" moves the monsters! """
for monster, location in self.monsters.iteritems():
options = self.cities[location]
direction = random.choice(list(options.keys()))
new_location = options[direction]
self.monsters[monster] = new_location
print "Monster #{n} has moved {d} to {l}".format(n = monster, d = direction, l = new_location)
def _destroy(self):
pass
def _parse_map(self, line):
""" put map lines into cities dictionary """
line_list = line.split()
location = line_list.pop[0]
location_dict = {}
for road in line_list:
position = road.find('=')
direction = road[:position]
city = road[position+1:]
location_dict[direction] = city
self.cities[location] = location_dict
if __name__ == "__main__":
main = Main
main.run_iteration()
main.print_map()
| true |
349cb6b10ae1affa50838b3d88d634101c5553c0 | kwohl/python-multiple-inheritance | /flower-shop.py | 2,628 | 4.125 | 4 | class Arrangement:
def __init__(self):
self.flowers = []
def enhance(self, flower):
self.flowers.append(flower)
class MothersDay(Arrangement):
def __init__(self):
super().__init__()
def enhance(self, flower):
if isinstance(flower, IOrganic):
self.flowers.append(flower)
else:
print(f"This {flower.name} does not belong in the Mother's Day Arrangement.")
def trim(self, length = 4):
for flower in self.flowers:
flower.stem_length = length
print(f"The stem on the {flower.name} is now {flower.stem_length} inches.")
class ValentinesDay(Arrangement):
def __init__(self):
super().__init__()
def enhance(self, flower):
if isinstance(flower, INotOrganic):
self.flowers.append(flower)
else:
print(f"This {flower.name} does not belong in the Valentine's Day Arrangement.")
# Override the `enhance` method to ensure only
# roses, lillies, and alstroemeria can be added
def trim(self, length = 7):
for flower in self.flowers:
flower.stem_length = length
print(f"The stem on the {flower.name} is now {flower.stem_length} inches.")
class IOrganic:
def __init__(self):
self.isOrganic = True
class INotOrganic:
def __init__(self):
self.isOrganic = False
class Flower:
def __init__(self):
self.stem_length = 10
class Rose(Flower, INotOrganic):
def __init__(self):
Flower.__init__(self)
INotOrganic.__init__(self)
self.name = "rose"
class Lily(Flower, INotOrganic):
def __init__(self):
Flower.__init__(self)
INotOrganic.__init__(self)
self.name = "lily"
class Alstroemeria(Flower, INotOrganic):
def __init__(self):
Flower.__init__(self)
INotOrganic.__init__(self)
self.name = "alstroemeria"
class Daisy(Flower, IOrganic):
def __init__(self):
Flower.__init__(self)
IOrganic.__init__(self)
self.name = "daisy"
class Baby_Breath(Flower, IOrganic):
def __init__(self):
Flower.__init__(self)
IOrganic.__init__(self)
self.name = "baby's breath"
class Poppy(Flower, IOrganic):
def __init__(self):
Flower.__init__(self)
IOrganic.__init__(self)
self.name = "poppy"
red_rose = Rose()
pink_rose = Rose()
white_lily = Lily()
white_daisy = Daisy()
for_beth = ValentinesDay()
for_beth.enhance(red_rose)
for_beth.enhance(pink_rose)
for_beth.enhance(white_lily)
for_beth.enhance(white_daisy)
for_beth.trim()
| false |
d927fecd196dab0383f022b4a5669a47e7f9fb37 | Oyelowo/GEO-PYTHON-2017 | /assignment4/functions.py | 2,671 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 27 11:15:48 2017
@author: oyeda
"""
##You should do following (also criteria for grading):
#Create a function called fahrToCelsius in functions.py
#The function should have one input parameter called tempFahrenheit
#Inside the function, create a variable called convertedTemp to which you should
#assign the conversion result (i.e., the input Fahrenheit temperature converted to Celsius)
#The conversion formula from Fahrenheit to Celsius is:
#Return the converted value from the function back to the user
#Comment your code and add a docstring that explains how to use your fahrToCelsius function
#(i.e., you should write the purpose of the function, parameters, and returned values)
def fahrToCelsius(tempFahrenheit): #define function to convert parameter(tempFahrenheit)
"""
Function for converting temperature in Fahrenheit to Celsius.
Parameters
----------
tempFahrenheit: <numerical>
Temperature in Fahrenheit
convertedTemp: <numerical>
Target temperature in Celsius
Returns
-------
<float>
Converted temperature.
"""
convertedTemp = (tempFahrenheit - 32)/1.8 #assign the conversion to convertedTemp variable
return convertedTemp #return the converted temperature variable
#What is 48° Fahrenheit in Celsius? ==> Add your answer here:
fahrToCelsius(48)
#What about 71° Fahrenheit in Celsius? ==> Add your answer here:
fahrToCelsius(71)
print ("32 degrees Fahrenheit in Celsius is:", fahrToCelsius(32))
#check what the function does by using help function which returns the docstring comments
help(fahrToCelsius)
#0 temperatures below -2 degrees (Celsius)
#1 temperatures from -2 up to +2 degrees (Celsius) [1]
#2 temperatures from +2 up to +15 degrees (Celsius) [2]
#3 temperatures above +15 degrees (Celsius)
def tempClassifier(tempCelsius): #define the function of the parameter(tempCelsius)
"""
Function for classifying temperature in celsius.
Parameters
----------
tempCelsius: <numerical>
Temperature in Celsius
Returns
-------
<integer>
Classified temperature.
"""
#conditional statements to assign temperatues to different values/classes
if tempCelsius < -2: return 0
elif tempCelsius >= -2 and tempCelsius<=2: return 1
elif tempCelsius >= 2 and tempCelsius<=15: return 2
else: return 3
#What is class value for 16.5 degrees (Celsius)? ==> Add your answer here:
tempClassifier(16.5)
#What is the class value for +2 degrees (Celsius)? ==> Add your answer here:
tempClassifier(2)
tempClassifier(15)
| true |
ca0d0d446cbc2a2cbf3f0f99a4ce6358cb913ccf | PiaNgg/t08.chunga_huatay | /iteracion.chunga.py | 1,211 | 4.15625 | 4 | #EJERCIOIO 1
fruta="Pera"
for i in fruta:
print(i)
print("-----")
#EJERCIOIO 2
fruta="Manzana"
for i in fruta:
print(i)
print("-----")
#EJERCIOIO 3
fruta="platano"
for i in fruta:
print(i)
print("-----")
#EJERCIOIO 4
fruta="Mango"
for i in fruta:
print(i)
print("-----")
#EJERCIOIO 5
fruta="Sandia"
for i in fruta:
print(i)
print("-----")
#EJERCIOIO 6
fruta="Arandano"
for i in fruta:
print(i)
print("-----")
#EJERCIOIO 7
fruta="Mandarina"
for i in fruta:
print(i)
print("-----")
#EJERCIOIO 8
fruta="Uva"
for i in fruta:
print(i)
print("-----")
#EJERCIOIO 9
fruta="Naranja"
for i in fruta:
print(i)
print("-----")
#EJERCIOIO 10
pais="Peru"
for i in pais:
print(i)
print("-----")
#EJERCIOIO 11
pais="Argentina"
for i in pais:
print(i)
print("-----")
#EJERCIOIO 12
pais="Brasil"
for i in pais:
print(i)
print("-----")
#EJERCIOIO 13
pais="Chile"
for i in pais:
print(i)
print("-----")
#EJERCIOIO 14
pais="Ecuador"
for i in pais:
print(i)
print("-----")
#EJERCIOIO 15
pais="Venezuela"
for i in pais:
print(i)
print("-----")
| false |
14265fcb05c67d2b45d8bfe5ccb5f97c8b28295d | Dartnimus/for-Andersen | /name_Vyacheslav.py | 420 | 4.375 | 4 | '''
Составить алгоритм: если введенное имя совпадает с Вячеслав,
то вывести “Привет, Вячеслав”, если нет, то вывести "Нет такого имени"
'''
name = input("Введите имя ")
if name == 'Вячеслав':
print("Привет, {}".format(name))
else:
print("Нет такого имени") | false |
8913aa3c08840276a068ebe6b6d6d69afe519167 | AndrewKalil/holbertonschool-machine_learning | /unsupervised_learning/0x02-hmm/1-regular.py | 2,114 | 4.28125 | 4 | #!/usr/bin/env python3
""" Regular Markov chain """
import numpy as np
def markov_chain(P, s, t=1):
"""determines the probability of a markov chain being in a
particular state after a specified number of iterations
Args:
P is a square 2D numpy.ndarray of shape (n, n)
representing the transition matrix
P[i, j] is the probability of transitioning from state
i to state j
n is the number of states in the markov chain
s is a numpy.ndarray of shape (1, n) representing the
probability of starting in each state
t is the number of iterations that the markov chain has
been through
"""
if (not isinstance(P, np.ndarray) or not isinstance(s, np.ndarray)):
return None
if (not isinstance(t, int)):
return None
if ((P.ndim != 2) or (s.ndim != 2) or (t < 1)):
return None
n = P.shape[0]
if (P.shape != (n, n)) or (s.shape != (1, n)):
return None
while (t > 0):
s = np.matmul(s, P)
t -= 1
return s
def regular(P):
"""determines the steady state probabilities of a regular markov chain
Args:
P is a is a square 2D numpy.ndarray of shape (n, n) representing
the transition matrix
P[i, j] is the probability of transitioning from state i to
state j
n is the number of states in the markov chain
"""
np.warnings.filterwarnings('ignore')
# Avoid this warning: Line 92. np.linalg.lstsq(a, b)[0]
if (not isinstance(P, np.ndarray)):
return None
if (P.ndim != 2):
return None
n = P.shape[0]
if (P.shape != (n, n)):
return None
if ((np.sum(P) / n) != 1):
return None
if ((P > 0).all()): # checks to see if all elements of P are posistive
a = np.eye(n) - P
a = np.vstack((a.T, np.ones(n)))
b = np.matrix([0] * n + [1]).T
regular = np.linalg.lstsq(a, b)[0]
return regular.T
return None
| true |
d9d934e204e8a0503d96f17fc16433cc2ba42a2e | oscarhscc/algorithm-with-python | /LeetCode/538. 把二叉搜索树转换为累加树.py | 984 | 4.125 | 4 | '''
给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
例如:
输入: 原始二叉搜索树:
5
/ \
2 13
输出: 转换为累加树:
18
/ \
20 13
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.val = 0
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return None
self.convertBST(root.right)
root.val, self.val = self.val + root.val, self.val + root.val
self.convertBST(root.left)
return root | false |
26144b4784b9602b473a8d1da19fe8b568fdc662 | blackdragonbonu/ctcisolutions | /ArrayStringQ3.py | 948 | 4.4375 | 4 | '''
The third question is as follows
Write a method to decide if two strings are anagrams or not.
We solve this by maintaining counts of letters in both strings and checking if they are equal, if they are they are anagrams. This can be implemented using a dictionary of byte array of size 26
'''
from collections import defaultdict
def hash_solution(str1,str2):
dict1=defaultdict(int)
dict2=defaultdict(int)
if len(str1)==len(str2):
for i,letter in enumerate(str1):
dict1[letter]+=1
dict2[str2[i]]+=1
for key in dict1:
if dict1[key]!=dict2[key]:
return False
else:
return False
return True
def solutions(str1,str2,method):
if method=="hash_solution":
check=hash_solution(str1,str2)
if check:
print("The string are anagrams")
else:
print("The strigs are not anagrams")
if __name__=="__main__":
str1=input("Enter first string \n")
str2=input("Enter second string \n")
solutions(str1,str2,"hash_solution")
| true |
6aa56313f436099121db045261afc16dbcac9595 | Adrianbaldonado/learn_python_the_hard_way | /exercises/exercise_11.py | 304 | 4.25 | 4 | """Asking Qestions
The purpose of this exercise is to utilize all ive learned so far
"""
print("How old are you?", end=' ')
age = (' 22 ')
print("How tall are you?", end=' ')
height = ( 5 )
print("How do you weigh?", end=' ')
weight = ('160')
print(f"So, you're{age} old, {height} tall and {weight}") | true |
18b210811e067834d980f7b80b886d36e060d65b | deepikaasharma/unpacking-list | /main.py | 310 | 4.34375 | 4 | # Create a list
some_list = ['man', 'bear', 'pig']
# Unpack the list
man, bear, pig = some_list
'''
The statement above is equivalent to:
man = some_list[0]
bear = some_list[1]
pig = some_list[2]
'''
# Show that the variables represent the values of the original list
print(man, bear, pig)
print(some_list) | true |
1a6dfa2fb7db6a3d0d4c349afc09c7868dc3af5e | micha-wirth/Lecturio | /loops.py | 422 | 4.15625 | 4 | # for x in list
for x in [1, 2, 3]:
print(x)
# for c in string
for c in 'abc':
print(c)
# for i in range(0, 3, 1):
for i in range(3):
print(i)
print(list(range(3)))
# while-loop
x = 0
while x < 3:
print(x)
x += 1
# break-statement
while True:
if x == 3:
print('End of while-loop')
break
# continue-statement
for x in range(3):
if x == 1:
continue
print(x)
| false |
eb0ba706baa251c56bbaaaafa25110ae5b7d18db | micha-wirth/Lecturio | /sequences.py | 248 | 4.1875 | 4 | text = 'abcdefghiklm'
print('a' in text)
print('x' in text)
t = tuple(range(3))
print(0 in t)
print(3 in t)
# Last element of a sequence.
print(text[len(text) - 1])
print(text[-1])
print(max(text))
print(t[len(t)-1])
print(t[-1])
print(max(t))
| false |
9ee2d6ea090f939e7da651d7a44b204ff648168a | ShumbaBrown/CSCI-100 | /Programming Assignment 3/guess_the_number.py | 874 | 4.21875 | 4 | def GuessTheNumber(mystery_num):
# Continually ask the user for guesses until they guess correctly.
# Variable to store the number of guesses
guesses = 0
# loop continually ask the user for a guess until it is correct
while (True):
# Prompt the user of a guess
guess = int(input('Enter a guess: '))
guesses += 1
# Update the user as to whether the guess is too high, too low or correct
if (guess > mystery_num):
print('Too high!')
elif (guess < mystery_num):
print('Too low!')
else:
if (guesses == 1):
print('You\'re correct! It took you 1 guess')
else:
print('You\'re correct! It took you %d guesses' % (guesses))
# If the guess is correct exit the loop
break
GuessTheNumber(100)
| true |
d02467d8e5ec22b8daf6e51b007280d3f4c8a245 | malav-parikh/python_programming | /string_formatting.py | 474 | 4.4375 | 4 | # leaning python the hard way
# learnt the basics
# string formatting using f
first_name = 'Malav'
last_name = 'Parikh'
middle_name = 'Arunkumar'
print(f"My first name is {first_name}")
print(f"My last name is {last_name}")
print(f"My middle name is {middle_name}")
print(f"My full name is {first_name} {middle_name} {last_name}")
# string formatting using format function
sentence = "My full name is {} {} {}"
print(sentence.format(first_name,middle_name,last_name)) | true |
e4e80522ce19e03c1c6bceee954741d324d79b44 | ffabiorj/desafio_fullstack | /desafio_parte_1/question_1.py | 504 | 4.1875 | 4 | def sum_two_numbers(arr, target):
"""
The function receives two parameters, a list and a target.
it goes through the list and checks if the sum of two numbers
is equal to the target and returns their index.
"""
number_list = []
for index1, i in enumerate(arr):
for index2, k in enumerate(arr[index1+1:]):
if i + k == target:
number_list.append(arr.index(i))
number_list.append(arr.index(k))
return number_list
| true |
836b0ef11b1e389e78b91511b9fcbfe167b3d420 | AnhVuH/vuhonganh-fundamental-c4e16 | /session05/homework/ex3.py | 258 | 4.15625 | 4 | bacterias = int(input('How many B bacterias arer there? '))
minutes = int(input('How much time in minutes will we wait? '))
for time in range(1,minutes,2):
bacterias *= 2
print("After {} minutes, we would have {} bacterias".format(minutes, bacterias))
| false |
e3c20aa1677c13d4c0ccf63d2f7180e717a39cb4 | AnhVuH/vuhonganh-fundamental-c4e16 | /session02/yob.py | 259 | 4.125 | 4 | yob = int(input("Your year of birth: \n"))
age = 2018 - yob
print("Your age: ",age)
if age < 10: #conditional statement
print("Baby")
elif age <= 18:
print("teenager")
elif age ==24:
print("asfsdfsdf")
else:
print("Not baby")
print("Bye")
| false |
58f0290c093677400c5a85267b1b563140feda85 | FrancescoSRende/Year10Design-PythonFR | /FileInputOutput1.py | 1,512 | 4.53125 | 5 | # Here is a program that shows how to open a file and WRITE information TO it.
# FileIO Example 3
# Author: Francesco Rende
# Upper Canada College
# Tell the user what the program will do...
print ("This program will open a file and write information to it")
print ("It will then print the contents to the screen for you to see")
# So as before we will still have to open a file, but this time we specify for the parameter either "w" or "a"
# "w" means we are going to "write" information which overwrite everything that was in the file from before.
# "a" means that we "append" which will add to the end of existing information.
def addSong():
song = str(input("What is your favorite song?"))
file = open("FileInfo1.txt", "a")
file.write ("\n"+song)
file.close()
file = open("FileInfo1.txt", "r")
print (file.read())
addMore = input("Would you like to add another song? (y/n) \n")
if addMore.lower() == "y":
addSong()
else:
print("Thanks for your time!")
def giveSongs():
file = open("FileInfo1.txt", "r")
print(file.read())
def doSomething():
choice = int(input("Would you like to:\n1. Add a new song or\n2. Get the list of songs\n"))
if choice == 1:
addSong()
elif choice == 2:
giveSongs()
else:
print("Invalid choice.")
doItAgain = input("Would you like to try again? (y/n) \n")
if doItAgain.lower() == "y":
doSomething()
else:
print("Thanks for your time!")
doSomething()
# This is a way to gracefully exit the program
input("Press ENTER to quit the program") | true |
2306ffb05eecd0dc048f36c8359b7684178f0634 | MuhammadRehmanRabbani/Python | /Average of 2D Array python/average.py | 1,260 | 4.28125 | 4 |
# defining the average function
def average(matrix,matrix_size):
my_sum = 0 # declaring variable to store sum
count = 0 # declaring variable to count total elements of 2D array
# this for loop is calculating the sum
for i in range(0, matrix_size):
for j in range(0, matrix_size):
my_sum = my_sum+ int(matrix[i][j])
count = count+1
# calculating the average
average = my_sum/count
return average;
# defining the main function
def main():
matrix = [] #declaring matrix
ave = 0
matrix_size=int(input("Enter N for N x N matrix : ")) #prompt
print("Enter {} Elements in Square Matrix:".format(matrix_size)) # prompt
#this for loop is taking elements from user and storing them to 2D array
for i in range(0, matrix_size):
row = []
for j in range(0, matrix_size):
row.append(input())
matrix.append(row)
print("You entered:") #prompt
#printing 2D array
for i in range(0, matrix_size):
print(" ".join(matrix[i]))
# calling the average function to find average of matrix elements
ave = average(matrix,matrix_size)
# printing average
print('Average is: ',ave)
if __name__ == "__main__": main() | true |
356a8c8ecc88afd964c5a83dc438890a3326b483 | girishsj11/Python_Programs_Storehouse | /Daily_coding_problems/daily_coding_2.py | 737 | 4.125 | 4 | '''
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]
'''
print("Enter the list elements with space : ")
input_list = list(map(int, input().split()))
output_list=list()
temp=1
for i in input_list:
temp*=i
print("multiplication of all the elements in a given list is:\n",temp)
for i in input_list:
output_list.append(temp//i)
print("input given user list is:\n",input_list)
print("output list is:\n",output_list) | true |
9d3dad6f365a6e73d00d90411f80a1a6e165f0cf | girishsj11/Python_Programs_Storehouse | /codesignal/strstr.py | 1,378 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 12:33:18 2021
@author: giri
"""
'''
Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview.
Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1.
Example
For s = "CodefightsIsAwesome" and x = "IA", the output should be
strstr(s, x) = -1;
For s = "CodefightsIsAwesome" and x = "IsA", the output should be
strstr(s, x) = 10.
Input/Output
[execution time limit] 4 seconds (py3)
[input] string s
A string containing only uppercase or lowercase English letters.
Guaranteed constraints:
1 ≤ s.length ≤ 106.
[input] string x
String, containing only uppercase or lowercase English letters.
Guaranteed constraints:
1 ≤ x.length ≤ 106.
[output] integer
An integer indicating the index of the first occurrence of the string x in s, or -1 if s does not contain x.
'''
def strstr(s, x):
try:
return (s.index(x))
except ValueError:
return -1
if __name__ == "__main__":
print(strstr('CodefightsIsAwesome','IA'))
print(strstr('CodefightsIsAwesome','IsA')) | true |
1f75ec5d58684cd63a770bd63c7aab3ee7b26de6 | girishsj11/Python_Programs_Storehouse | /codesignal/largestNumber.py | 569 | 4.21875 | 4 | '''
For n = 2, the output should be
largestNumber(n) = 99.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer n
Guaranteed constraints:
1 ≤ n ≤ 9.
[output] integer
The largest integer of length n.
'''
def largestNumber(n):
reference = '9'
if(n==1):
return int(reference)
elif(n>1 and n<=10):
return int(reference*n)
else:
return ("Exceeded/below the range value")
if __name__ == "__main__":
n = int(input("Enter the number to get its largest number of digits : "))
print(largestNumber(n))
| true |
478ed1b0685ac4fda3e3630472b2c05155986d50 | girishsj11/Python_Programs_Storehouse | /codesignal/Miss_Rosy.py | 2,510 | 4.15625 | 4 | '''
Miss Rosy teaches Mathematics in the college FALTU and is noticing for last few lectures that the turn around in class is not equal to the number of attendance.
The fest is going on in college and the students are not interested in attending classes.
The friendship is at its peak and students are taking turns for classes and arranging proxy for their friends.
They have been successful till now and have become confident. Some of them even call themselves pro.
One fine day, the proxy was called in class as usual but this time Miss Rosy recognized the student with his voice.
When caught, the student disagreed and said that it was a mistake and Miss Rosy has interpreted his voice incorrectly.
Miss Rosy let it go but thought of an idea to give attendance to the students present in class only.
In the next lecture, Miss Rosy brought a voice recognition device which would save the voice of students as per their roll number and
when heard again will present the roll number on which it was heard earlier.
When the attendance process is complete, it will provide a list which would consist of the number of distinct voices.
The student are unaware about this device and are all set to call their proxies as usual. Miss Rosy starts the attendance process and the device is performing its actions. After the attendance is complete, the device provides a list.
Miss Rosy presents the list to you and asks for the roll numbers of students who were not present in class.
Can you provide her with the roll number of absent students in increasing order.
Note: There is at least one student in the class who is absent.
Input Format
The first line of input consists of the actual number of students in the class, N.
The second line of input consists of the list (N space-separated elements) presented to you by Miss Rosy as recorded by the voice recognition device.
Constraints
1<= N <= 100
1<= List_elements <=N
Output Format
Print the roll number of students who were absent in class separated by space.
Example :
Input
7
1 2 3 3 4 6 4
Output
5 7
'''
def main(N,List_elements):
List_elements.sort()
k = List_elements[0]
out_elements = list()
for i in List_elements:
if(k not in List_elements):
out_elements.append(k)
k +=1
for element in out_elements:
print(element,end=' ')
if __name__ == "__main__":
N = int(input())
List_elements = list(map(lambda x:int(x) , input().split(' ')))
main(N,List_elements)
| true |
b986d60ff29d4cf7ff66d898b5f0f17a29a168cb | girishsj11/Python_Programs_Storehouse | /prime_numbers_generations.py | 577 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 16:00:24 2021
@author: giri
"""
def is_prime(num):
"""Returns True if the number is prime
else False."""
if num == 0 or num == 1:
return False
for x in range(2, num):
if num % x == 0:
return False
else:
return True
if __name__ == "__main__":
lower = int(input("Enter the lower range to generate prime numbers : "))
upper = int(input("Enter the upper range to generate prime numbers : "))
list(filter(is_prime,range(lower,upper)))
| true |
8b6aad04e70312c2323d1a8392cef1bc10587b2e | Stone1231/py-sample | /loop_ex.py | 413 | 4.125 | 4 | for i in [0, 1, 2, 3, 4]:
print(i)
for i in range(5):
print(i)
for x in range(1, 6):
print(x)
for i in range(3):
print(i)
else:
print('done')
#A simple while loop
current_value = 1
while current_value <= 5:
print(current_value)
current_value += 1
#Letting the user choose when to quit
msg = ''
while msg != 'quit':
msg = input("What's your message? ")
print(msg)
| true |
ded47265e7eda94698d63b24bd4665b2e8afb16e | mikvikpik/Project_Training | /whitespace.py | 308 | 4.1875 | 4 | """Used in console in book"""
# Print string
print("Python")
# Print string with whitespace tab: \t
print("\tPython")
# Print multiple whitespaces and strings
print("Languages:\nPython\nC\nJavaScript")
# variable set to string and call variable without print
favorite_language = "python"
favorite_language
| true |
7791023ad7a3561d91401b22faeff3fce3a1c7c8 | EoinMcKeever/Test | /doublyLinkedListImplemention.py | 1,028 | 4.4375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
#insert at tail(end) of linked list
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
new_node.previous = self.tail
self.tail.next = new_node
self.tail = new_node
# we can traverse a doubly linked list in both directions
def traverse_forward(self):
actual_node = self.head
while actual_node is not None:
print("%d" % actual_node.data)
actual_node = actual_node.next
def traverse_backward(self):
actual_node = self.tail
while actual_node is not None:
print("%d" % actual_node.data)
actual_node = actual_node.previous
if __name__ == '__main__':
linked_list = DoublyLinkedList()
linked_list.insert(1)
linked_list.insert(2)
linked_list.insert(3)
linked_list.traverse_forward()
linked_list.traverse_backward()
| true |
d795bad87b7b902d05ee026e5f280a131aa15a89 | trajeshmca21/rajesht | /assignent/assignment4/usecase2.py | 279 | 4.15625 | 4 | even = [ x for x in range(20) if x % 2 == 0]
odd= [ x for x in range(20) if x %2 != 0]
square=[x*x for x in range(20) ]
cube=[x*x*x for x in range(20)
print("print square of list",square)
print"odd numbers",(odd)
print("print even numbers",even)
print("print cube",cube) | false |
1da86b9c0e953787d0ae33850015e6f3aea85f7b | rekhinnvs/learnPython | /HackerRank/codes/Conditional.py | 435 | 4.40625 | 4 | # Given an integer, , perform the following conditional actions:
#
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
N = int(raw_input().strip())
if N%2 != 0:
print 'Weird'
elif (N>=2 and N<=5) or N>20:
print 'Not Weird'
elif N>=6 and N<=20:
print 'Weird'
| false |
5edf8cb2a9e0e25df4d2ce8e76c143b7b43e4f91 | scheffeltravis/Python | /Fractals/Tree.py | 761 | 4.25 | 4 | """
Tree.py
Simple fractal program which draws a tree based on bifurcation in terms
of 'branch' length.
"""
import turtle
# Draw a tree recursively
def drawTree (ttl, length):
if length > 5:
ttl.forward (length)
ttl.right (20)
drawTree (ttl, length - 15)
ttl.left (40)
drawTree (ttl, length - 15)
ttl.right (20)
ttl.backward (length)
def main():
# Prompt the user to enter a branch length
length = int (input ('Enter branch length: '))
turtle.setup (800, 800, 0, 0)
turtle.title ('Recursive Tree')
ttl = turtle.Turtle()
ttl.pen(shown = False, speed = 0)
ttl.penup()
ttl.goto (0, -100)
ttl.pendown()
ttl.left (90)
ttl.pendown()
drawTree (ttl, length)
ttl.penup()
turtle.done()
main()
| false |
6eb48816205257b528b1aefd8f03fa8206716aa9 | sayee2288/python-mini-projects | /blackjack/src/Deck.py | 1,401 | 4.1875 | 4 | '''
The deck class simulates a deck of cards and
returns one card back to the player or the dealer randomly.
'''
import random
class Deck:
'''
The deck class creates the cards
and has functions to return a card or shuffle all cards
'''
def __init__(self):
print('Deck is ready for the game')
self.card = ''
self.shape = ''
self.deck = {
0: [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 'ace'],
1: [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 'ace'],
2: [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 'ace'],
3: [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 'ace']
}
self.suit = {
0: 'Spades',
1: 'Hearts',
2: 'clubs',
3: 'diamonds'
}
def pick_card(self):
while True:
a = random.randint(0, 3)
b = random.randint(0, len(self.deck[a])-1)
self.card = self.deck[a][b]
if self.card in self.deck[a]:
del self.deck[a][b]
break
else:
continue
print('You retrieved this card: {} of {}' .format(self.card, self.suit[a]))
return self.card, self.suit[a]
def shuffle(self):
print('Deck has been shuffled')
self.__init__()
if __name__ == "__main__":
my_deck = Deck()
my_deck.pick_card()
| true |
0240991d2a500c398cfd17ea1ac3616d00dd09dd | Spandan-Madan/python-tutorial | /8_while_loops.py | 2,147 | 4.40625 | 4 | import random
# ** While Loops **
# What if you want your code to do something over and over again until some
# condition is met?
# For instance, maybe you're writing code for a timer
# and you want to keep checking how much time has passed until you have waited
# the correct amount of time.
# Then you should use a while loop. Check out the example:
time_to_count = 10
seconds_passed = 0
while seconds_passed < time_to_count: # this is called the condition
print("ticks_passed:", seconds_passed)
seconds_passed += 1 # increase seconds_passed by 1
print("Timer done!")
print("\n")
# At the beginning of the loop, the condition (`seconds_passed < time_to_count`)
# is evaluated. If the condition is `True`, then the body of the loop--the
# indented block that follows the while condition--is run. If the condition
# is `False`, then it continues with the rest of the code.
# A really important thing to consider when writing a while loop is
# "termination": making sure that at some point, the condition will evaluate to
# `False`. Otherwise, the loop will run forever!
# ** Break **
# There is one exception to the idea of termination. Consider this while loop:
n_tries = 0
while True:
n_tries += 1
n = random.randint(1, 10) # chooses a random number between 1 and 10
if n == 10:
break
print("Outside of loop; took", n_tries, "tries")
# Clearly, the condition here will never be `False`! They key here is the word
# `break`. This keyword causes Python to "break" out of the loop and continue
# with the next line of code. Note that writing a "while True" loop can be
# dangerous, because it is not clear when the loop will terminate. If possible,
# state the condition explicitly. You should reserve "while True" for
# situations where you really do have to continue doing something forever, or
# where it is not clear how many times you will have to do something.
# ** Exercises **
# 1. Write a while loop that prints all the numbers from 1 to 10.
# Your code here.
# 2. What is wrong with this code?
# count = 10
# while (count < 100):
# print(count)
# count = count - 1
| true |
e6bed67b87876e59d12ad8a0e2776649b169f3bf | Spandan-Madan/python-tutorial | /5_booleans.py | 1,334 | 4.40625 | 4 | # ** Boolean Comparisons **
print("Examples of boolean comparisons")
# Python also supports logical operations on booleans. Logical operations take
# booleans as their operands and produce boolean outputs. Keep reading to learn
# what boolean operations Python supports.
# And
# The statement `a and b` evaluates to True only if both a and b are `True`.
# Use the keyword `and` to perform this operation
print("True and True is", True and True)
print("False and False is", False and False)
print("True and False is", True and False)
# Or
# The statement `a or b` evaluates to True if a is `True` or b is `True`.
# use the keyword `or` to perform this operation
print("True or True is", True or True)
print("False or False is", False or False)
print("True or False is", True or False)
# Not
# The keyword `not` flips a boolean from True to False or vice versa
print("not True is", not True)
print("not False is", not False)
print("\n")
# ** Exercises **
print("Output of exercises")
# 1. Modify line 38 below so that it only prints `True` if all of a, b, and c
# are True. Modify the three values to test your code.
a = True
b = True
c = True
print(False)
# 2. Modify line 42 so that it only prints `True` if x is less than 10 or
# greater than 100. Change the value of x to test your code.
x = 0
print(False)
| true |
b6965d0d5ebe028780d4ba63d10d1c159fab97c7 | jasonwee/asus-rt-n14uhp-mrtg | /src/lesson_text/re_groups_individual.py | 407 | 4.1875 | 4 | import re
text = 'This is some text -- with punctuation.'
print('Input text :', text)
# word starting with 't' then another word
regex = re.compile(r'(\bt\w+)\W+(\w+)')
print('Pattern :', regex.pattern)
match = regex.search(text)
print('Entire match :', match.group(0))
print('Word starting with "t":', match.group(1))
print('Word after "t" word :', match.group(2))
| true |
8025c47447a18c0f93b4c59c6c1191c6b0c6454a | shail0804/Shail-Project | /word_series.py | 2,137 | 4.125 | 4 | def Character_to_number():
""" This function converts a given (User Defined) Character to Number\
as per the given Pattern (2*(Previous Character) + counter) """
nb = input('please enter the character: ')
nb = nb.upper()
count = 1
sum = 0
for s in range(65,ord(nb)+1):
sum = sum*2+count
count = count+1
print ('The Value of ',chr(s),':',sum,' \n')
def String_to_number():
""" This function converts a given (User Defined) String to Number\
as per the given Pattern (2*(Previous Character) + counter)\
This function calculates the individual value of the letters of the String\
and then gives us the Sum of all the letters, which is the Numeric Value of the String. """
alpha = input('Please enter a word: ')
alpha = alpha.upper()
final_sum = 0
for s in alpha:
count = 1
sum = 0
for i in range(65,ord(s)+1):
sum = sum*2 + count
count = count+1
print('for',s,'value is',sum)
final_sum = final_sum+sum
print('The sum of given words is: ', final_sum,' \n')
def Digit_to_string():
"""This function Converts a given Number into String :/
with character value calculated as per the given pattern (2*(Previous Character) + counter) """
numb = int(input('Enter the number: '))
temp = numb
while (temp >= 1):
sum = 0
i = 1
prev_char = ''
prev = 0
l=0
while (temp >= sum):
prev = sum
if (prev == 0):
prev_char = ''
elif(prev ==1):
prev_char= 'A'
else:
l= i-2
prev_char = chr(ord('A') + l)
sum = sum *2 + i
i=i+1
if (temp==numb):
word = prev_char
else:
word = word + prev_char
temp = temp -prev
print('The Word is: ',word, ' \n')
if __name__=='__main__':
Character_to_number()
String_to_number()
Digit_to_string()
| true |
e8596535535979655079184dbf2d61899b8610b3 | diptaraj23/TextStrength | /TextStrength.py | 324 | 4.25 | 4 | #Calculating strength of a text by summing all the ASCII values of its characters
def strength (text):
List=[char for char in text] # storing each character in a list
sum=0
for x in List:
sum=sum+ord(x) #Extracting ASCII values using ord() function and then adding it in a loop
return sum | true |
1775f4ecf0c6270b6209dd68358899fa92c8387c | jasonchuang/python_coding | /27_remove_element.py | 897 | 4.40625 | 4 | '''
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
'''
def removeElement(nums, val):
index = 0
for i in range(0, len(nums)):
print "inside range val: {} {}:".format(val, nums[i])
if nums[i] != val:
print "index: {} :".format(index)
nums[index] = nums[i]
index += 1
return index
#given = [3,2,2,3]
given = [0,1,2,2,3,0,4,2]
#target = 3
target = 2
print removeElement(given, target)
print given
| true |
ce6f6114512ae2682c8902999118c08474da92fd | alanamckenzie/advent-of-code | /advent2017/code/utils.py | 403 | 4.15625 | 4 | def read_file(filename, line_delimiter='\n'):
"""Read the contents of a file
:param str filename: full path to the text file to open
:param line_delimiter: line delimiter used in the file
:return: contents of the file, with one list item per line
:rtype: list
"""
with open(filename, 'r') as fin:
text = fin.read().strip()
return text.split(line_delimiter)
| true |
36ac8905679118a796c0ea1e073b8f4c035f3246 | campbellerickson/CollatzConjecture | /Collatz.py | 540 | 4.25 | 4 | print "Type '123' to start the program::",
check = input()
if check == 123:
print "To what number would you like to prove the Collatz Conejecture?::"
limit = input()
int(limit)
for x in xrange(1,limit+1):
num=x
original=x
iterations=0
while num > 1:
if (num % 2 == 0):
num = num/2
iterations = iterations + 1
elif (num % 2 != 0):
num = (num * 3) + 1
iterations = iterations + 1
print original, "is proven through", iterations, "iterations."
print "The Collatz Conjecture is proven!"
| true |
a3ce178e270557e7711aa92a860f2d6820531dcc | KSSwimmy/python-problems | /csSumOfPostitive/main.py | 776 | 4.125 | 4 | # Given an array of integers, return the sum of all positive integers in an array
def csSumOfPositive(input_arr):
# Solution 1
sum = 0
for key, value in enumerate(input_arr):
if value <= 0:
continue
else:
sum += value
return sum
# Solution 2
'''
This uses a lambda function. It's like an anonymous JS function.
lambda x is the argument and to the right side of : is the expression. input_arr is asking for numbers that are greate than
zero, then create a list of numbers greater than zero. From there
we sum the result and return the answer
'''
result = list(filter(lambda x: x > 0, input_arr))
return sum(result)
input_arr = ([1,2,3,-4,5])
print(csSumOfPositive(input_arr)) | true |
8c99e5d3a112f865f0d8c90f98be43ce6c1e7e01 | moorea4870/CTI110 | /P5HW2_GuessingGame_AvaMoore.py | 817 | 4.28125 | 4 | # Using random to create simple computer guessing game
# July 5, 2018
# CTI-110 P5HW2 - Random Number Guessing Game
# Ava Moore
# use random module
import random
# set minimum and maximum values (1-100)
MIN = 1
MAX = 100
def main():
#variable to control loop
again = 'y'
#until the user is finished, repeat
while again == 'y' or again == 'Y':
guess = int(input("Guess what the secret number is: "))
number = random.randint(1,100)
#print("The number is",number)
if guess < number:
print("Too low, try again.")
elif guess > number:
print("Too high, try again.")
else:
print("Congratulations! You guess correctly!")
again = input("Play again? (y for yes): ")
main()
| true |
444179e90b2b2cffdf645e97c8e48cd9c86d2923 | dmunozbarras/Practica-6-Python | /ej6-6.py | 649 | 4.21875 | 4 | # -*- coding: cp1252 -*-
"""DAVID MUÑOZ BARRAS - 1º DAW - PRACTICA 6 - EJERCICIO 6
Escribe un programa que permita crear una lista de palabras y que, a continuación,
cree una segunda lista igual a la primera, pero al revés (no se trata de escribir
la lista al revés, sino de crear una lista distinta).
"""
num=input("Dime cuantas palabras tiene la lista: ")
lista1=[]
contador= 0
for i in range (num):
contador= contador+1
palabra=(raw_input("Introduce una palabra %d: " % (contador) ))
lista1.append(palabra)
print "La lista creada es: ", (lista1)
lista2= (lista1)
lista2.reverse ()
print "La lista inversa es: ", (lista2)
| false |
c565083b6d11e6bb8403b0e4c3083ea695a4f5fa | Hanjyy/python_practice | /conditional2.py | 1,677 | 4.1875 | 4 | '''
purchase_price = int(input("What is the purchase price: "))
discount_price_10 = (10 /100 )* (purchase_price)
final_price_10 = purchase_price - discount_price_10
discount_price_20 = (20/100) * (purchase_price)
final_price_20 = purchase_price - discount_price_20
if purchase_price < 10:
print("10%", final_price_10, discount_price_10)
else:
print("20%",final_price_20, discount_price_20)
user_gender = input("Enter your gender: ")
if user_gender == "M":
print("You are not eligible")
else:
print("You are eligible")
user_age = int(input("How old are you: "))
if user_age >= 10 and user_age <= 12:
print("You are eligible to play on the team")
else:
print("You are not eligible to play on the team")
gas_tank =int(input("What is your tank size in litres: "))
tank_percentage = int(input("What is the percentage of your tank: "))
km_litre = int(input("How many km/litre does your car get: "))
current_litre = (tank_percentage/100) * (gas_tank)
distance_litre_can_go = (current_litre * km_litre) + 5
if distance_litre_can_go < 200:
print(f"You can go another {distance_litre_can_go} km")
print("The next gas station is 200 km away")
print("Get gas now")
else:
print(f"You can go another {distance_litre_can_go} km")
print("The next gas sation is 200 km away")
print("You can wait for the next station")
'''
password = "Anjola"
pin = input("Enter a secret password: ")
if pin == password:
print("You're in")
else:
print("Ask the owner")
print("Learn enough python to look at the code and figure out")
'''Q = input("Enter any word: ")
if Q.isupper() or Q.islower():
print("It is a fact")'''
| true |
20a497f0e1df4edff5d710df5b8fa4839998ca18 | hihasan/Design-Patterns | /Python In these Days/practice_windows/com/hihasan/ListPractice.py | 786 | 4.25 | 4 | number=[1,2,3,4]
#print list
print(number)
#Accessing Elements In A List
print(number[0])
print(number[-1])
print(number[-2])
print(number[0]+number[2])
#changing, adding & removing elements
names=["Hasan","Mamun","Al","Nadim"]
names.append("Tasmiah") #When we append an item in the list, it will store in last
print(names)
names.insert(0,"Khan") #while inserting we need to specify the input postion then the stored value
names.insert(0,"Hiumu")
print(names)
print("First Input Value in the List is: " +names[0].title())
print("Last Input Value in the List is : "+names[-1].title())
del names[4]
print(names)
del_name=names.pop()
number.append(del_name)
print("You add delete value in number list: "+int(number))
#delete an item and stored in other list. Need to study firther | true |
fe0a64036e5a1317c0dcaaded3a332a6d33594a7 | axecopfire/Pthw | /Exercises/Ex15_Reading_FIles/Reading_Files.py | 1,392 | 4.5625 | 5 | # Importing argv from the system module
from sys import argv
# argv takes two variables named filename and script
script, filename = argv
# The variable txt opens filename, which is an argv variable
txt = open(filename)
# filename is entered after this prompt, which is then assigned to the variable txt. At the same time this has to be a valid filename. In a better program we would add an exception saying something like can not find your file try again instead of exiting the program.
print(f"Here's your file {filename}:")
# The newly formed variable txt is then printed into the shell environment
print(txt.read())
# The program continues with another prompting statement
print("Type the filename again:")
# This time instead of using argv we are using a custom input, which makes it look like it is in the python program also we are assigning file_again to this input
file_again = input("> ")
# That input then has the method open operated on it and assigned to the variable txt_again, so in actuality the file has not been opened. But instead just assigned to a variable
txt_again = open(file_again)
# This is where python reads the opened txt_again file and prints its contents.
print(txt_again.read())
# In summary the process to print the contents of a file to the command shell is to open the file, read the file, then print what was read.
txt.close()
txt_again.close()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.